qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,338,875 | <p>I am studying C (self-study, not in an educational institution) and have been trying to build a hashtable data structure as part of my learning.</p>
<p>Please refer to this hopefully reproducible example:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
struct table_item {
char *name;
char gender;
char *birthdate;
char *address;
};
struct list_node {
struct table_item *data;
struct list_node *next;
unsigned long long hash_key;
};
struct hashtable {
int table_size;
int num_entries;
struct list_node **entries;
};
struct hashtable* init_hashtable(int size);
void free_hashtable(struct hashtable *table);
int main(void)
{
struct hashtable *hashtable = NULL;
int size_entry = 0;
printf("Input hashtable array size: ");
while (size_entry < 1) {
scanf(" %d", &size_entry);
}
hashtable = init_hashtable(size_entry);
free_hashtable(hashtable);
return 0;
}
struct hashtable* init_hashtable(int size) {
struct hashtable* new_table;
if ((new_table = malloc(sizeof(struct hashtable))) == NULL) {
perror("Error: failed to allocate memory for hash table\n");
exit(EXIT_FAILURE);
}
new_table->table_size = size;
new_table->num_entries = 0;
if ((new_table->entries = malloc(size*sizeof(struct list_node))) == NULL) {
perror("Error: failed to allocate memory for hash table array\n");
exit(EXIT_FAILURE);
}
return new_table;
}
void free_hashtable(struct hashtable *table) {
for (int i = 0; i < table->table_size; i++) {
if (table->entries[i] != NULL) {
free_list(table->entries[i]);
table->entries[i] = NULL;
}
}
free(table->entries);
free(table);
}
</code></pre>
<p>My issue is that trying to free the table always fails, even if I have not added anything to it.</p>
<p>I used GDB to check the issue. It seems that, in the above for loop, <code>if (table->entries[i] != NULL)</code> always fires (such as when i=0) even when I haven't added anything. This results in my <code>free_list</code> function trying to free inappropriate memory, which is why I get the stack dump.</p>
<p>Somehow it seems that <code>table->entries[i]</code> is actually not NULL but rather has a <code>struct list_node *</code> type, causing the if condition to fire inappropriately. Could somebody please explain to me why this is?</p>
<p>I was hoping that I could use this for loop to go through the entries array and only free memory where <code>malloc</code>ed nodes exist, but as it stands this will just crash my program. I am not sure how I can alter this to behave as I'd like it to.</p>
| [
{
"answer_id": 74339009,
"author": "Xəyal Şərifli",
"author_id": 20432696,
"author_profile": "https://Stackoverflow.com/users/20432696",
"pm_score": 0,
"selected": false,
"text": "data class User(var name: String, var age: Int) {\n\n var size: String\n\n init {\n size = \"size\"\n }\n\nconstructor(name: String, age: Int, size: String) : this(name, age) {\n this.size = size\n }\n}\n"
},
{
"answer_id": 74340197,
"author": "Hubert Grzeskowiak",
"author_id": 2445864,
"author_profile": "https://Stackoverflow.com/users/2445864",
"pm_score": 2,
"selected": false,
"text": "\ndata class User(val name: String, val age: Int, val size: String = \"M\")\n"
},
{
"answer_id": 74343932,
"author": "aSemy",
"author_id": 4161471,
"author_profile": "https://Stackoverflow.com/users/4161471",
"pm_score": 0,
"selected": false,
"text": "MountDetails"
},
{
"answer_id": 74346751,
"author": "David Soroko",
"author_id": 239101,
"author_profile": "https://Stackoverflow.com/users/239101",
"pm_score": 0,
"selected": false,
"text": "data class OneDetails(val c: Int)\ndata class TwoDetails(val c: String)\ndata class MountOptions(val a: String, val b: String)\n\ndata class User(\n val mountOptions: MountOptions,\n val detailsOne: OneDetails? = null,\n val detailsTwo: TwoDetails? = null\n)\n\nfun main() {\n fun anotherCaller(user: User) = println(user)\n \n val mt = MountOptions(\"foo\", \"bar\")\n val one = OneDetails(1)\n val two = TwoDetails(\"2\")\n\n val switch = \"0\"\n when (switch) {\n \"0\" -> anotherCaller(User(mt))\n \"1\" -> anotherCaller(User(mt, detailsOne = one))\n \"2\" -> anotherCaller(User(mt, detailsTwo = two))\n \"12\" -> anotherCaller(User(mt, detailsOne = one, detailsTwo = two))\n else -> throw IllegalArgumentException(switch)\n }\n}\n\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74338875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14608372/"
] |
74,338,878 | <p>For example, let's say there is a array of items each equally likely to be chosen, and the output of this random function will tell which item to be chosen, but I want the function to be split into multiple steps so that along each step the list of potential items is narrowed in giving better insight on the result probabilities.</p>
<p>Here's a step by step example of how it might work:</p>
<p>Step 1: Every item is 1/1000 chance.</p>
<p>Step 2: Random subset of half the original set is removed, so each remaining item is 1/500 now.</p>
<p>Step 3: Repeat step 2 until narrowed down to a single item.</p>
<p>The requirements I'd like for the algorithm is < O(n) time complexity and at each step the distribution is still uniformly random.</p>
<hr />
<p>Initially I though to have an algorithm which:</p>
<ol>
<li>Start with variables <code>min</code> and <code>max</code> describing the current range of values left.</li>
<li>Shrink the range by generating random float number between [-1, 1] which is applied to the range to shrink it proportionally. If random number is negative then lower the max, otherwise raise the min. So 50% of the time it is shifting the min up, and shifting the max down, and the range is shrinking by a factor between [0,1].</li>
<li>Repeat 2. until range converges on a single number.</li>
</ol>
<p>But I noticed this doesn't have a uniform distribution, and instead it is more common for the chosen result to be closer to starting min and max values. So to fix this I think one could add a preliminary step where the starting range is offset by another random value. But this would only fix in making the starting distribution uniformly random, and it still doesn't fit my requirement of making it uniformly random at every step.</p>
<p>The naive solution is to generate random numbers and remove those from the list until at each step, but that is a O(n) solution so I hope there is something better.</p>
| [
{
"answer_id": 74339696,
"author": "btilly",
"author_id": 585411,
"author_profile": "https://Stackoverflow.com/users/585411",
"pm_score": 1,
"selected": false,
"text": "p"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74338878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9865950/"
] |
74,338,927 | <p>Ok So For Example let's say this is My Object.</p>
<pre><code>const myObj = {
cf_retryAttempts:0,
cf_amount:1,
cf_event:"SUBSCRIPTION_NEW_PAYMENT",
cf_eventTime:"2022-01-10 10:03:50",
cf_paymentId:1,
cf_referenceId:2,
cf_subReferenceId:3,
}
</code></pre>
<p>If I use JSON.stringify(myObj) it returns something like <code>{"cf_retryAttempts":"0"...}</code> But I don't want that what I want is a complete string without any doubleQuotes, commas or colon separators between key value. so what I'm expecting is something like:</p>
<pre><code>const string = cf_amount1cf_eventSUBSCRIPTION_NEW_PAYMENTcf_eventTime2022-01-10 10:51:02cf_paymentId1cf_referenceId2cf_retryAttempts0cf_subReferenceId3
</code></pre>
<p>If you want to understand more please check the docs as to understand what I'm trying to achieve.</p>
<p>Link: <a href="https://docs.cashfree.com/docs/webhooks-1#verify-signature" rel="nofollow noreferrer">https://docs.cashfree.com/docs/webhooks-1#verify-signature</a></p>
<p>Language: JS</p>
| [
{
"answer_id": 74338998,
"author": "IT goldman",
"author_id": 3807365,
"author_profile": "https://Stackoverflow.com/users/3807365",
"pm_score": 2,
"selected": false,
"text": "const myObj = {\n cf_retryAttempts: 0,\n cf_amount: 1,\n cf_event: \"SUBSCRIPTION_NEW_PAYMENT\",\n cf_eventTime: \"2022-01-10 10:03:50\",\n cf_paymentId: 1,\n cf_referenceId: 2,\n cf_subReferenceId: 3,\n cf_inner: {\n 'this': 'that'\n }\n}\n\nfunction iterate(obj) {\n var result = \"\"\n Object.entries(obj).forEach(function([key, value]) {\n if (typeof value === 'object' && value !== null) {\n result += (key + iterate(value))\n } else {\n result += (key + value)\n }\n })\n return result;\n}\nconsole.log(iterate(myObj))"
},
{
"answer_id": 74339097,
"author": "Mister Jojo",
"author_id": 10669010,
"author_profile": "https://Stackoverflow.com/users/10669010",
"pm_score": 0,
"selected": false,
"text": "cf_"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74338927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18705314/"
] |
74,338,942 | <p>Got a question regarding regex matching in Java.
Given is a string with a defined length.
Now I want to check with a matcher if every char contained in that String is different.</p>
<p>For example (only pass of length = 8):</p>
<pre><code>String a = "abcdefgz" -> pass
String b = "aacdefgz" -> fail
String c = "abcdefghz" -> fail
</code></pre>
<p>So matching the length would simply be:</p>
<pre><code>"^[a-zA-Z]{8}$"
</code></pre>
<p>But to get it working in combination with the condition that every contained char needs to be unique is quite tough.</p>
| [
{
"answer_id": 74338998,
"author": "IT goldman",
"author_id": 3807365,
"author_profile": "https://Stackoverflow.com/users/3807365",
"pm_score": 2,
"selected": false,
"text": "const myObj = {\n cf_retryAttempts: 0,\n cf_amount: 1,\n cf_event: \"SUBSCRIPTION_NEW_PAYMENT\",\n cf_eventTime: \"2022-01-10 10:03:50\",\n cf_paymentId: 1,\n cf_referenceId: 2,\n cf_subReferenceId: 3,\n cf_inner: {\n 'this': 'that'\n }\n}\n\nfunction iterate(obj) {\n var result = \"\"\n Object.entries(obj).forEach(function([key, value]) {\n if (typeof value === 'object' && value !== null) {\n result += (key + iterate(value))\n } else {\n result += (key + value)\n }\n })\n return result;\n}\nconsole.log(iterate(myObj))"
},
{
"answer_id": 74339097,
"author": "Mister Jojo",
"author_id": 10669010,
"author_profile": "https://Stackoverflow.com/users/10669010",
"pm_score": 0,
"selected": false,
"text": "cf_"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74338942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14607533/"
] |
74,338,950 | <p>I trying to add quotation mark at the start of first line and then at the end of every 50th line I have like 500 plus lines in notepad++ can anyone help</p>
<p>This is what my file look like</p>
<pre><code>your text
your text
your text
</code></pre>
<p>and I want it to look like</p>
<pre><code>"your text
your text
your text"
</code></pre>
| [
{
"answer_id": 74339049,
"author": "Toto",
"author_id": 372239,
"author_profile": "https://Stackoverflow.com/users/372239",
"pm_score": 2,
"selected": true,
"text": "(?:.+\\R){2}.+"
},
{
"answer_id": 74339345,
"author": "TheAnalogyGuy",
"author_id": 6317990,
"author_profile": "https://Stackoverflow.com/users/6317990",
"pm_score": 0,
"selected": false,
"text": "Ctrl + H"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74338950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20434394/"
] |
74,338,986 | <p>I want to get the player whos name matches the name of the block which was placed and updated this players gamemode to survival. But this just gives me gibberish in the console:</p>
<pre><code>@EventHandler
public void onPlace(BlockPlaceEvent blockPlaceEvent){
//Player ded = Bukkit.getPlayer(String.valueOf(blockPlaceEvent.getItemInHand().displayName()));- not important
//gives just the item name
blockPlaceEvent.getPlayer().sendMessage(blockPlaceEvent.getItemInHand().displayName());
//gibberish
System.out.println(Bukkit.getPlayer(String.valueOf(blockPlaceEvent.getItemInHand().displayName())));
}
</code></pre>
<pre><code>[19:15:09 INFO]: [Immortality] [STDOUT] TranslatableComponentImpl{key="chat.square_brackets", args=[TextComponentImpl{content="", style=StyleImpl{obfuscated=not_set, bold=not_set, strikethrough=not_set, underlined=not_set, italic=true, color=null, clickEvent=null, hoverEvent=null, insertion=null, font=null}, children=[TextComponentImpl{content="Windows_Paride", style=StyleImpl{obfuscated=not_set, bold=not_set, strikethrough=not_set, underlined=not_set, italic=not_set, color=null, clickEvent=null, hoverEvent=null, insertion=null, font=null}, children=[]}]}], style=StyleImpl{obfuscated=not_set, bold=not_set, strikethrough=not_set, underlined=not_set, italic=not_set, color=NamedTextColor{name="yellow", value="#ffff55"}, clickEvent=null, hoverEvent=HoverEvent{action=show_item, value=ShowItem{item=KeyImpl{namespace="minecraft", value="player_head"}, count=1, nbt={SkullOwner:{Id:[I;1311740293,1907444130,-1719123357,-1000482567],Name:"Windows_Paride",Properties:{textures:[{Signature:"x3tHAiXrUDBYofKatE+CaD46u0lyjkxlab+Xg+zKNEO1GMGnjPHXsfRSl9CVp9bBLJLu3aMcd8qI/bcm+E8mqJlbHRxjzRi/7W/JOTbsWWurf32i4fgO1VqxoSWsGb6PGbtCVKI7LXm0nPu+lreVHKWbgAqaw8koadUZIu+XhS8hTeqwpuNMLcrS5Wh7ODdf7hBK/BDT67RC3y6pjmDNeznrH6k8YEHQVZszJ/RCicP9AyQmbwCppjzjubYdwwIOi7r+jLmsCVL4r03svzOuugtGoMNgDFj/Gm/dLrvsN+Hy7lggltApbUFkxnewrkvTq+/ZQVACjsVEphwd6kMnzq8lRiUjtsqpcJpmhIttyAR0y+kgWX6L9zWP/z8FOACsXjf7OJfPPOVBs3LHLrBjDKuD9fTvbhZwdzW4Nonpmqk8M9Z+Y/tXbGyINzCdbs5lbNQYRwH7ACzjUQwHi93e5dwN622VP/vBzv0Uz7g9quohzlZKyogDuiSJUpPRBzyMhxWrVneMEOzj6fGIuN/Qxx6XVi6ZfoH0WRCvYeOjOqcR426rbXzoXV6vDHV0OxvKkCv7Md1TqO9zb3jaB7ekEVY2mWiJitNMuyT8CGATMCKhimCuP+RFu1leQXVFdnaFtbviQ6HxDoVxndODzrSRfz2GJ2ZCN4atQb4MuqMUdg0=",Value:"ewogICJ0aW1lc3RhbXAiIDogMTY2Nzc2MDM5NTYwNCwKICAicHJvZmlsZUlkIiA6ICI0ZTJmOTE4NTcxYjE0OWEyOTk4ODQyNjNjNDVkZDhmOSIsCiAgInByb2ZpbGVOYW1lIiA6ICJXaW5kb3dzX1BhcmlkZSIsCiAgInNpZ25hdHVyZVJlcXVpcmVkIiA6IHRydWUsCiAgInRleHR1cmVzIiA6IHsKICAgICJTS0lOIiA6IHsKICAgICAgInVybCIgOiAiaHR0cDovL3RleHR1cmVzLm1pbmVjcmFmdC5uZXQvdGV4dHVyZS83MzI1ODg2Y2JlZDQ3ZWI5MDk0ZWQyY2YxN2QyZWMyNGQzYzZhYmJlYzFlNDU3YjIyOTU1NzkxZjI2ZjkyZjZkIiwKICAgICAgIm1ldGFkYXRhIiA6IHsKICAgICAgICAibW9kZWwiIDogInNsaW0iCiAgICAgIH0KICAgIH0sCiAgICAiQ0FQRSIgOiB7CiAgICAgICJ1cmwiIDogImh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjlhNzY1Mzc2NDc5ODlmOWEwYjZkMDAxZTMyMGRhYzU5MWMzNTllOWU2MWEzMWY0Y2UxMWM4OGYyMDdmMGFkNCIKICAgIH0KICB9Cn0="}]}},Unbreakable:1b,display:{Name:'{"text":"Windows_Paride"}'}}}}, insertion=null, font=null}, children=[]}
</code></pre>
<p>I tried doing ComponentLike etc but it returned null when I did that.</p>
| [
{
"answer_id": 74342660,
"author": "Shivam Puri",
"author_id": 11226302,
"author_profile": "https://Stackoverflow.com/users/11226302",
"pm_score": 1,
"selected": true,
"text": "Player player = Bukkit.getPlayer(String.valueOf(blockPlaceEvent.getItemInHand().displayName()));\n\nplayer.getName();\n"
},
{
"answer_id": 74342928,
"author": "Christoph Dahlen",
"author_id": 20370596,
"author_profile": "https://Stackoverflow.com/users/20370596",
"pm_score": 1,
"selected": false,
"text": "\n@EventHandler\npublic void onPlace(BlockPlaceEvent blockPlaceEvent){\n blockPlaceEvent.getPlayer()\n .sendMessage(blockPlaceEvent.getItemInHand().displayName());\n System.out.println(blockPlaceEvent.getPlayer().getName());\n}\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74338986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13994905/"
] |
74,338,996 | <p>Hi I<code>ve got basic html file + external css file. css file contain font-size class and text-align class but only font-size class actually work. I try VS Studio code, Pycharm, and use .centered class on body, header, footer - still don</code>t work</p>
<p>Html code:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" >
<link href="styles.css" rel="stylesheet">
<title>Title</title>
</head>
<body class="centered">
<header class="large" >
John Harvard
</header>
<main class="medium">
Welcome to my page!
</main>
<footer class="small" >
Copyright &#169 John Harvard 1636
</footer>
</body>
</html>
</code></pre>
<p>CSS code:</p>
<pre><code><style>
.centered {
text-align: center;
}
.large {
font-size: 70px;
}
.medium {
font-size: medium;
}
.small {
font-size: 3px;
}
</style>
</code></pre>
<p>I try VS Studio code, Pycharm, and use .centered class on body, header, footer - still don`t work
Can you explain why?</p>
<p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
| [
{
"answer_id": 74339174,
"author": "liquidot",
"author_id": 20400911,
"author_profile": "https://Stackoverflow.com/users/20400911",
"pm_score": -1,
"selected": false,
"text": "<center> Your text here </center>\n"
},
{
"answer_id": 74339273,
"author": "Anye",
"author_id": 16752210,
"author_profile": "https://Stackoverflow.com/users/16752210",
"pm_score": 2,
"selected": true,
"text": "CSS"
},
{
"answer_id": 74339418,
"author": "KnightTheLion",
"author_id": 20432259,
"author_profile": "https://Stackoverflow.com/users/20432259",
"pm_score": 0,
"selected": false,
"text": "body {\n text-align: center;\n}\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74338996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20434413/"
] |
74,339,000 | <p>Having different UI versions for Desktop and Mobile, I'm struggling with targeting certain tests specifically for the mobile while forcing the rest run only for Desktop.
In addition to existing browsers I've added a mobile target like this:</p>
<pre class="lang-js prettyprint-override"><code>{
name: 'mobile',
use: {
...devices['iPhone 12'],
viewport: {
width: 390,
height: 844
},
headless: false,
video: 'on-first-retry'
},
},
</code></pre>
<p>Which is properly running the tests emulating the specified mobile target. The problem is that it tries every single test with this config while I need it to run only specified tests for the mobile.</p>
<p>The only way I can think of achieving the goal is to create two separate projects. Is there a better 'configurable' way for that?</p>
| [
{
"answer_id": 74339174,
"author": "liquidot",
"author_id": 20400911,
"author_profile": "https://Stackoverflow.com/users/20400911",
"pm_score": -1,
"selected": false,
"text": "<center> Your text here </center>\n"
},
{
"answer_id": 74339273,
"author": "Anye",
"author_id": 16752210,
"author_profile": "https://Stackoverflow.com/users/16752210",
"pm_score": 2,
"selected": true,
"text": "CSS"
},
{
"answer_id": 74339418,
"author": "KnightTheLion",
"author_id": 20432259,
"author_profile": "https://Stackoverflow.com/users/20432259",
"pm_score": 0,
"selected": false,
"text": "body {\n text-align: center;\n}\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/400745/"
] |
74,339,012 | <p>I use Table in my CoreData app for macOS</p>
<pre><code>@FetchRequest(sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)]) private var categories: FetchedResults<Categories>
@State private var selectedCategoryID: Categories.ID?
</code></pre>
<p>and I'm wondering how I could catch change of selected row. If I try .onChange() as shown below then code can't be compiled due to error "Cannot call value of non-function type 'Categories.ID?' (aka 'Optional<Optional>')"</p>
<pre><code>Table(categories, selection: $selectedCategoryID) {
TableColumn("Name", value \.name!)
TableColumn("Type", value: \.type!)
}.onChange(of: selectedCategoryID {
print("Selected row changed.")
}
</code></pre>
<p>Thank you.</p>
| [
{
"answer_id": 74339597,
"author": "Dawy",
"author_id": 6723756,
"author_profile": "https://Stackoverflow.com/users/6723756",
"pm_score": 0,
"selected": false,
"text": ".onChange(of: selectedCategoryID) { selected in\n print(\"Selected row is \\(selected)\")\n}\n"
},
{
"answer_id": 74347158,
"author": "malhal",
"author_id": 259521,
"author_profile": "https://Stackoverflow.com/users/259521",
"pm_score": 1,
"selected": false,
"text": "onChange"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6723756/"
] |
74,339,032 | <p>I'm slightly confused about how <code>blazor-error-ui</code> works in practice. I understand that it's hidden by default because of CSS (via <code>display: none</code>), but I can't seem to get it to appear by causing errors in the application.</p>
<p>According to the <a href="https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/handle-errors?view=aspnetcore-6.0#detailed-errors-during-development" rel="nofollow noreferrer">Blazor docs</a>:</p>
<blockquote>
<p>The <code>blazor-error-ui</code> element is normally hidden due to the presence of the <code>display: none</code> style of the <code>blazor-error-ui</code> CSS class in the site's stylesheet [...] <strong>When an error occurs, the framework applies <code>display: block</code> to the element.</strong></p>
</blockquote>
<p>Emphasis mine.</p>
<p>The docs say that an error should cause the <code>blazor-error-ui</code> div to have its <code>display</code> property set to <code>block</code>, but throwing an exception takes me to an developer exception page, and doesn't actually display the div at all. If I set the environment to <code>Release</code>, it takes me to the <code>/Error</code> page, instead.</p>
<p>So, when does the <code>blazor-error-ui</code> div actually get shown? When Blazor itself has an internal error?</p>
| [
{
"answer_id": 74339560,
"author": "otets_dmitriy",
"author_id": 17393877,
"author_profile": "https://Stackoverflow.com/users/17393877",
"pm_score": 0,
"selected": false,
"text": "blazor-error-ui"
},
{
"answer_id": 74341188,
"author": "micka190",
"author_id": 7321499,
"author_profile": "https://Stackoverflow.com/users/7321499",
"pm_score": 1,
"selected": false,
"text": "blazor-error-ui"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7321499/"
] |
74,339,099 | <p>I have these two test cases:</p>
<pre><code>calc1 = [['print', 5]] # 5
calc2 = [['print', 2], ['print', 4], ['print', 8]] # 2 4 8
</code></pre>
<p>And I can print them correctly with this function:</p>
<pre><code>def exec_program(p):
if len(p) == 1:
print(p[0][1])
else:
for i in p:
print(i[1])
print(exec_program(calc2))
>>> 2
>>> 4
>>> 8
</code></pre>
<p>But how can I solve this recursively? The number of items in calc can be 1 or many. All help appreciated</p>
<p>Edit:
My current try. Looking for a solution</p>
<pre><code>def exec_program(p):
if len(p) == 1:
print(p[0][1])
else:
print(exec_program[1:] - 1)
</code></pre>
| [
{
"answer_id": 74339132,
"author": "Ghazi",
"author_id": 16589029,
"author_profile": "https://Stackoverflow.com/users/16589029",
"pm_score": 0,
"selected": false,
"text": "calc2 = [['print', 2], ['print', 4], ['print', 8]]\ndef print_me(calc2):\n if not calc2:\n return #once calc2 is empty, we stop the recursion.\n print(calc2[0][1])\n return print_me(calc2[1::])\nprint_me(calc2)\n"
},
{
"answer_id": 74339173,
"author": "I'mahdi",
"author_id": 1740577,
"author_profile": "https://Stackoverflow.com/users/1740577",
"pm_score": 0,
"selected": false,
"text": "lst = [['print', 2], ['print', 4], ['print', 8] ]# 2 4 8\n\ndef rec_print(lst):\n if not lst: return lst\n return([lst[0][1]] + rec_print(lst[1:]))\n\nprint(*rec_print(lst))\n"
},
{
"answer_id": 74339182,
"author": "Chris",
"author_id": 447939,
"author_profile": "https://Stackoverflow.com/users/447939",
"pm_score": 2,
"selected": false,
"text": "def do_print(calc):\n if not calc:\n return\n if calc[0] == 'print':\n print(calc[1])\n else:\n for subcalc in calc:\n do_print(subcalc)\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7793969/"
] |
74,339,138 | <p>I have a field that I'm displaying on a report that is a combination of text and codes that represent an image. Some of those icons have ascii symbols that I've used a replace formula to display them as their ascii version. For two or three of the images, I have no luck and have to display a mini picture for the representation.</p>
<p>The codes being sent are something like:</p>
<p><code>^he^ = ♥ ^st^ = ⭐ ^cl^ = etc...</code></p>
<p>So for the clover leaf, there is no emoji support in my version of Crystal for clover leaves, and the ascii icon I found online for it just shows the empty square icon when an emoji isn't supported.</p>
<p>My workaround for this is to have a formula that converts all my icons to the appropriate ascii where supported, and to leave two blank spaces for the unsupported icons.</p>
<pre><code>>stringvar gift_msg;
>gift_msg:= {DataTable1.gift_field};
>gift_msg := replace(gift_msg,"^CL^"," ");
>gift_msg := replace(gift_msg,"^HE^","♥");
>gift_msg := replace(gift_msg,"^ST^","★");
>gift_msg
</code></pre>
<p>I then put a suppression formula on each image that looks like this:</p>
<pre><code>>mid({DataTable1.gift_field},2,4)<>"^CL^"
</code></pre>
<p>So I duplicated the image along the length of the field and increment the mid formula to match the field. I also set the font to Consolas so that it's fixed width to remove any surprises in spacing. My issue is that this still creates very strange spacing, and I'm almost certain there's a much easier way to do this.</p>
| [
{
"answer_id": 74339132,
"author": "Ghazi",
"author_id": 16589029,
"author_profile": "https://Stackoverflow.com/users/16589029",
"pm_score": 0,
"selected": false,
"text": "calc2 = [['print', 2], ['print', 4], ['print', 8]]\ndef print_me(calc2):\n if not calc2:\n return #once calc2 is empty, we stop the recursion.\n print(calc2[0][1])\n return print_me(calc2[1::])\nprint_me(calc2)\n"
},
{
"answer_id": 74339173,
"author": "I'mahdi",
"author_id": 1740577,
"author_profile": "https://Stackoverflow.com/users/1740577",
"pm_score": 0,
"selected": false,
"text": "lst = [['print', 2], ['print', 4], ['print', 8] ]# 2 4 8\n\ndef rec_print(lst):\n if not lst: return lst\n return([lst[0][1]] + rec_print(lst[1:]))\n\nprint(*rec_print(lst))\n"
},
{
"answer_id": 74339182,
"author": "Chris",
"author_id": 447939,
"author_profile": "https://Stackoverflow.com/users/447939",
"pm_score": 2,
"selected": false,
"text": "def do_print(calc):\n if not calc:\n return\n if calc[0] == 'print':\n print(calc[1])\n else:\n for subcalc in calc:\n do_print(subcalc)\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1154619/"
] |
74,339,140 | <p>I am working with a huge dataset, but just to simplify what I'd like to do, I will use the following one.</p>
<pre><code>testDF <- data.frame(v1 = rep(c('a', 'b', 'c', 'd', 'e', 'f'), 2),
v2 = rep(c(1,0),6))
</code></pre>
<p>Let's assume you could subset it like this.</p>
<pre><code> v1 v2
1 a 1
2 b 0
3 c 1
4 d 0
5 e 1
6 f 0
7 a 1
8 b 0
9 c 1
10 d 0
11 e 1
12 f 0
</code></pre>
<p>When the first value of v1 assumes the same value (for example in the I would like to add a third column reporting sum of the second column values. The output will be like this:</p>
<pre><code> testDF
v1 v2 tc
1 a 1 2
2 b 0 0
3 c 1 2
4 d 0 0
5 e 1 2
6 f 0 0
7 a 1 2
8 b 0 0
9 c 1 2
10 d 0 0
11 e 1 2
</code></pre>
<p>Which operation I could by perpetuating the dplyr code?</p>
<p>Thanks</p>
| [
{
"answer_id": 74339132,
"author": "Ghazi",
"author_id": 16589029,
"author_profile": "https://Stackoverflow.com/users/16589029",
"pm_score": 0,
"selected": false,
"text": "calc2 = [['print', 2], ['print', 4], ['print', 8]]\ndef print_me(calc2):\n if not calc2:\n return #once calc2 is empty, we stop the recursion.\n print(calc2[0][1])\n return print_me(calc2[1::])\nprint_me(calc2)\n"
},
{
"answer_id": 74339173,
"author": "I'mahdi",
"author_id": 1740577,
"author_profile": "https://Stackoverflow.com/users/1740577",
"pm_score": 0,
"selected": false,
"text": "lst = [['print', 2], ['print', 4], ['print', 8] ]# 2 4 8\n\ndef rec_print(lst):\n if not lst: return lst\n return([lst[0][1]] + rec_print(lst[1:]))\n\nprint(*rec_print(lst))\n"
},
{
"answer_id": 74339182,
"author": "Chris",
"author_id": 447939,
"author_profile": "https://Stackoverflow.com/users/447939",
"pm_score": 2,
"selected": false,
"text": "def do_print(calc):\n if not calc:\n return\n if calc[0] == 'print':\n print(calc[1])\n else:\n for subcalc in calc:\n do_print(subcalc)\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14712320/"
] |
74,339,143 | <p>I have the following JSON data</p>
<pre class="lang-json prettyprint-override"><code>{
"docker_compose_init_result": {
"changed": true,
"failed": false,
"services": {
"grafana": {
"docker-compose_grafana_1": {
"cmd": [],
"image": "grafana/grafana:8.5.14",
"labels": {
"com.docker.compose.config-hash": "4d0b5dd6e697a8fe5bf5074192770285e54da43ad32cc34ba9c56505cb709431",
"com.docker.compose.container-number": "1",
"com.docker.compose.oneoff": "False",
"com.docker.compose.project": "docker-compose",
"com.docker.compose.project.config_files": "/appl/docker-compose/docker-compose-init.yml",
"com.docker.compose.project.working_dir": "/appl/docker-compose",
"com.docker.compose.service": "grafana",
"com.docker.compose.version": "1.29.2"
},
"networks": {
"docker-compose_homeserver-net": {
"IPAddress": "172.20.0.2",
"IPPrefixLen": 16,
"aliases": [
"3d19f54271b2",
"grafana"
],
"globalIPv6": "",
"globalIPv6PrefixLen": 0,
"links": null,
"macAddress": "02:42:ac:14:00:02"
}
},
"state": {
"running": true,
"status": "running"
}
}
},
"node-red": {
"docker-compose_node-red_1": {
"cmd": [],
"image": "nodered/node-red:2.2.2",
"labels": {
"authors": "Dave Conway-Jones, Nick O'Leary, James Thomas, Raymond Mouthaan",
"com.docker.compose.config-hash": "5610863d4b28b11645acb5651e7bab174125743dc86a265969788cc8ac782efe",
"com.docker.compose.container-number": "1",
"com.docker.compose.oneoff": "False",
"com.docker.compose.project": "docker-compose",
"com.docker.compose.project.config_files": "/appl/docker-compose/docker-compose-init.yml",
"com.docker.compose.project.working_dir": "/appl/docker-compose",
"com.docker.compose.service": "node-red",
"com.docker.compose.version": "1.29.2",
"org.label-schema.arch": "",
"org.label-schema.build-date": "2022-02-18T21:01:04Z",
"org.label-schema.description": "Low-code programming for event-driven applications.",
"org.label-schema.docker.dockerfile": ".docker/Dockerfile.alpine",
"org.label-schema.license": "Apache-2.0",
"org.label-schema.name": "Node-RED",
"org.label-schema.url": "https://nodered.org",
"org.label-schema.vcs-ref": "",
"org.label-schema.vcs-type": "Git",
"org.label-schema.vcs-url": "https://github.com/node-red/node-red-docker",
"org.label-schema.version": "2.2.2"
},
"networks": {
"docker-compose_homeserver-net": {
"IPAddress": "172.20.0.4",
"IPPrefixLen": 16,
"aliases": [
"fc56e973c98d",
"node-red"
],
"globalIPv6": "",
"globalIPv6PrefixLen": 0,
"links": null,
"macAddress": "02:42:ac:14:00:04"
}
},
"state": {
"running": true,
"status": "running"
}
}
},
"organizr": {
"docker-compose_organizr_1": {
"cmd": [],
"image": "organizr/organizr:linux-amd64",
"labels": {
"base.maintainer": "christronyxyocum,Roxedus",
"base.s6.arch": "amd64",
"base.s6.rel": "2.2.0.3",
"com.docker.compose.config-hash": "430b338b0c0892a25522e1b641a9e3a08eedd255309b1cd275b22a3362dcac58",
"com.docker.compose.container-number": "1",
"com.docker.compose.oneoff": "False",
"com.docker.compose.project": "docker-compose",
"com.docker.compose.project.config_files": "/appl/docker-compose/docker-compose-init.yml",
"com.docker.compose.project.working_dir": "/appl/docker-compose",
"com.docker.compose.service": "organizr",
"com.docker.compose.version": "1.29.2",
"maintainer": "christronyxyocum,Roxedus",
"org.label-schema.description": "Baseimage for Organizr",
"org.label-schema.name": "organizr/base",
"org.label-schema.schema-version": "1.0",
"org.label-schema.url": "https://organizr.app/",
"org.label-schema.vcs-url": "https://github.com/organizr/docker-base",
"org.opencontainers.image.created": "2022-05-08_15",
"org.opencontainers.image.source": "https://github.com/Organizr/docker-organizr/tree/master",
"org.opencontainers.image.title": "organizr/base",
"org.opencontainers.image.url": "https://github.com/Organizr/docker-organizr/blob/master/README.md"
},
"networks": {
"docker-compose_homeserver-net": {
"IPAddress": "172.20.0.3",
"IPPrefixLen": 16,
"aliases": [
"organizr",
"f3f61d8938fe"
],
"globalIPv6": "",
"globalIPv6PrefixLen": 0,
"links": null,
"macAddress": "02:42:ac:14:00:03"
}
},
"state": {
"running": true,
"status": "running"
}
}
},
"prometheus": {
"docker-compose_prometheus_1": {
"cmd": [
"--config.file=/etc/prometheus/prometheus.yml",
"--storage.tsdb.path=/prometheus",
"--web.console.libraries=/etc/prometheus/console_libraries",
"--web.console.templates=/etc/prometheus/consoles",
"--web.enable-lifecycle"
],
"image": "prom/prometheus:v2.35.0",
"labels": {
"com.docker.compose.config-hash": "7d2ce7deba1a152ebcf4fe5494384018c514f6703b5e906aef6f2e8820733cb2",
"com.docker.compose.container-number": "1",
"com.docker.compose.oneoff": "False",
"com.docker.compose.project": "docker-compose",
"com.docker.compose.project.config_files": "/appl/docker-compose/docker-compose-init.yml",
"com.docker.compose.project.working_dir": "/appl/docker-compose",
"com.docker.compose.service": "prometheus",
"com.docker.compose.version": "1.29.2",
"maintainer": "The Prometheus Authors <prometheus-developers@googlegroups.com>"
},
"networks": {
"docker-compose_homeserver-net": {
"IPAddress": "172.20.0.5",
"IPPrefixLen": 16,
"aliases": [
"04f346e6694f",
"prometheus"
],
"globalIPv6": "",
"globalIPv6PrefixLen": 0,
"links": null,
"macAddress": "02:42:ac:14:00:05"
}
},
"state": {
"running": true,
"status": "running"
}
}
}
}
}
}
</code></pre>
<p>And I need an output similar to</p>
<pre class="lang-yaml prettyprint-override"><code>- docker-compose_grafana_1
- docker-compose_node-red_1
- docker-compose_organizr_1
- docker-compose_prometheus_1
</code></pre>
<p>I can do that with jq easy-peasy:</p>
<pre class="lang-bash prettyprint-override"><code>jq --raw-output '.docker_compose_init_result.services\[\] | keys | .\[\]' jsondata.json
</code></pre>
<p>But I am not able to do it with Ansible and especially <code>json_query</code> (and thus JMESPath).</p>
<p>I was able to get one key with</p>
<pre class="lang-bash prettyprint-override"><code>jp -f jsondata.json "keys(docker_compose_init_result.services.grafana)"
</code></pre>
<pre class="lang-json prettyprint-override"><code>[
"docker-compose_grafana_1"
]
</code></pre>
<p>But have no idea how to get all four. Also sometimes expressions that worked with jp did not work in Ansible with <code>json_query</code>, which additionally made me mad.</p>
<p>If anyone can give me a solution for this (wether its with <code>json_query</code> or not) in the best case explains how it works, I would be very glad.</p>
| [
{
"answer_id": 74339337,
"author": "Vladimir Botka",
"author_id": 6482561,
"author_profile": "https://Stackoverflow.com/users/6482561",
"pm_score": 2,
"selected": false,
"text": "docker_compose_list: \"{{ docker_compose_init_result|\n json_query(_query) }}\"\n_query: 'services.*.keys(@)'\n"
},
{
"answer_id": 74339561,
"author": "Zeitounator",
"author_id": 9401096,
"author_profile": "https://Stackoverflow.com/users/9401096",
"pm_score": 2,
"selected": false,
"text": "docker_compose_list: \"{{ docker_compose_init_result.services | dict2items\n | map(attribute='value') | map('dict2items')\n | flatten | map(attribute='key') }}\"\n"
},
{
"answer_id": 74345312,
"author": "β.εηοιτ.βε",
"author_id": 2123530,
"author_profile": "https://Stackoverflow.com/users/2123530",
"pm_score": 3,
"selected": true,
"text": "docker_compose_init_result.services.*.keys(@)[]\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7888757/"
] |
74,339,176 | <p>I am trying to use <code><TKey></code> in a function. I don't know how to use it properly as I discovered that recently.</p>
<p>Here is what I tried :</p>
<pre><code>private void filterContour()
{
if (this.geometryRepToDraw.Profile.Famille == "FLAT")
{
filterContour2(x => x[0].Face == 0);
}
else
{
filterContour2(x => x[0].Face == 0 || x[0].Face==1);
}
}
private void filterContour2<TKey>(Func<List<Contour>, TKey> selector)
{
this.internalContours = this.internalContours.Where(selector).ToList();
}
</code></pre>
<p>But cannot decompile, as I have the error <code>cannot convert from <List<Contour>,Tkey> to <List<Contour>,bool></code></p>
<p>For information, <code>this.internalContours</code> is a <code>List<List<Contour>></code></p>
<p>I also tried to replace <code>Func<List<Contour>, TKey></code> by <code>Func<List<Contour>, bool></code>, but error is when calling the function (and I don't think this is the good one)?</p>
| [
{
"answer_id": 74339337,
"author": "Vladimir Botka",
"author_id": 6482561,
"author_profile": "https://Stackoverflow.com/users/6482561",
"pm_score": 2,
"selected": false,
"text": "docker_compose_list: \"{{ docker_compose_init_result|\n json_query(_query) }}\"\n_query: 'services.*.keys(@)'\n"
},
{
"answer_id": 74339561,
"author": "Zeitounator",
"author_id": 9401096,
"author_profile": "https://Stackoverflow.com/users/9401096",
"pm_score": 2,
"selected": false,
"text": "docker_compose_list: \"{{ docker_compose_init_result.services | dict2items\n | map(attribute='value') | map('dict2items')\n | flatten | map(attribute='key') }}\"\n"
},
{
"answer_id": 74345312,
"author": "β.εηοιτ.βε",
"author_id": 2123530,
"author_profile": "https://Stackoverflow.com/users/2123530",
"pm_score": 3,
"selected": true,
"text": "docker_compose_init_result.services.*.keys(@)[]\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7310000/"
] |
74,339,181 | <p>I am trying to use python recursion in order to draw a box, but have a hard time finding where to start. In principle I want to pass two numbers as arguments which will be the amount of '*''s that are printed both vertically and horizontally like this:</p>
<pre><code>>>> drawRectangle(4, 4)
****
* *
* *
****
</code></pre>
| [
{
"answer_id": 74339337,
"author": "Vladimir Botka",
"author_id": 6482561,
"author_profile": "https://Stackoverflow.com/users/6482561",
"pm_score": 2,
"selected": false,
"text": "docker_compose_list: \"{{ docker_compose_init_result|\n json_query(_query) }}\"\n_query: 'services.*.keys(@)'\n"
},
{
"answer_id": 74339561,
"author": "Zeitounator",
"author_id": 9401096,
"author_profile": "https://Stackoverflow.com/users/9401096",
"pm_score": 2,
"selected": false,
"text": "docker_compose_list: \"{{ docker_compose_init_result.services | dict2items\n | map(attribute='value') | map('dict2items')\n | flatten | map(attribute='key') }}\"\n"
},
{
"answer_id": 74345312,
"author": "β.εηοιτ.βε",
"author_id": 2123530,
"author_profile": "https://Stackoverflow.com/users/2123530",
"pm_score": 3,
"selected": true,
"text": "docker_compose_init_result.services.*.keys(@)[]\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18021751/"
] |
74,339,192 | <p>I have a problem pretty similiar to the below:</p>
<p>I need to store the data of studentIDs along with 10 of their favourite foods in an RPG variable.
The best option would be obviously a data structure array.</p>
<p>But as a standard, all DS definitions must reference an external DS (File structure) which obviously can be done using EXTNAME and EXTFLD.</p>
<p>So, the file structure (STUDREF) I create would look like this:</p>
<pre><code>STUDENTID INTEGER
FOOD CHAR(10)
</code></pre>
<p>And the DS would look like this:</p>
<pre><code>dcl-ds StudentData EXTNAME('STUDREF') qualified;
StudentID EXTFLD('STUDENTID');
FavoriteFoods LIKE(StudentData.FOOD) DIM(10); --> Note that I cant use EXTFLD here as this is an array.
end-ds;
</code></pre>
<p>Considering that the standard mandates to have all Datastructures be defined externally, this should work.</p>
<p>But the problem is, if I do an EVAL StudentData in Debug, I see the array elements like this:</p>
<pre><code>StudentData(1).StudentID = 123
StudentData(1).FOOD = ' ' ----> This is the problem!!
StudentData(1).FavoriteFoods(1) = 'Burger'
StudentData(1).FavoriteFoods(2) = 'PIZZA'
StudentData(1).FavoriteFoods(3) = 'CANDY'
.
.
.
StudentData(1).FavoriteFoods(10) = 'ICE CREAM'
</code></pre>
<p>The FOOD variable obviously "inherited" from the STUDREF structure is really unwanted for me.</p>
<p>Is there any simple way to get rid of this but using EXTNAME at the same time?</p>
<p>Now coming to the actual situation I am facing in my production code, similiar to above, I need to add a new array (similiar to FavoriteFoods above) to an existing DS.
The DS is used as a one of the parms (in dcl-pi) of an RPG API program.</p>
<p>So the coding standard mandates that the DCL-PI Data structures should be defined externally.</p>
<p>So, What I did was to add a new field to the Structure Table (FOOD variable in STUDREF in example above) and declared the new variable in the DS
similiar to FavoriteFoods <code>LIKE(StudentData.FOOD) DIM(10).</code></p>
<p>But as I noted, there was the variable "FOOD" also added to each instance of the DS array which I dont want.</p>
<p>Any good solutions to achieve this or any other general comments ?</p>
| [
{
"answer_id": 74339711,
"author": "bvstone",
"author_id": 2296644,
"author_profile": "https://Stackoverflow.com/users/2296644",
"pm_score": 2,
"selected": false,
"text": "dcl-ds STUDREFDS EXTNAME('STUDREF'); \nEnd-ds;\n"
},
{
"answer_id": 74352396,
"author": "Theju112",
"author_id": 19539055,
"author_profile": "https://Stackoverflow.com/users/19539055",
"pm_score": 0,
"selected": false,
"text": "FavoriteFoods like(StudRef.Food) DIM(10)"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19539055/"
] |
74,339,198 | <p>I have a configuration file that the user can modify.</p>
<p>In this configuration file there exists a <code>#define ListOfWords</code> with a list of words to which the user can add or remove any custom words. For example: <code>#define ListOfWords black,bear,Mouse</code>.</p>
<p>User then also defines, using <code>#define SequenceOfWords</code>, an arbitrary sequence of words. For example: <code>#define SequenceOfWords In a forest, a brown-bear saw a black mouse</code>.</p>
<p>I want to extract every word from <code>#define ListOfWords</code> that appears in <code>#SequenceOfWords</code> and create a compile-time string array of extracted words <code>const char* extractedWords[] = {bear, black}</code>.</p>
<p><em>Note:</em> Instead of <code>#define SequenceOfWords</code> being a define it can also be a compile-time string constant if it makes it easier to solve this problem. The important thing is that this must be solved at the compile-time or preprocessing time.</p>
| [
{
"answer_id": 74339711,
"author": "bvstone",
"author_id": 2296644,
"author_profile": "https://Stackoverflow.com/users/2296644",
"pm_score": 2,
"selected": false,
"text": "dcl-ds STUDREFDS EXTNAME('STUDREF'); \nEnd-ds;\n"
},
{
"answer_id": 74352396,
"author": "Theju112",
"author_id": 19539055,
"author_profile": "https://Stackoverflow.com/users/19539055",
"pm_score": 0,
"selected": false,
"text": "FavoriteFoods like(StudRef.Food) DIM(10)"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1806687/"
] |
74,339,214 | <p>I'm trying to get data from an external API and then render it into a flatlist.</p>
<p>I'm very new to React Native so this may be easy to solve.</p>
<p>I'm trying to use the following data: <a href="https://www.nationaltrust.org.uk/search/data/all-places" rel="nofollow noreferrer">https://www.nationaltrust.org.uk/search/data/all-places</a></p>
<p>I want to fetch it from the URL, and render the 'title' and 'imageUrl' fields into a flatlist component.</p>
<p>This is what I have so far:</p>
<pre><code>const placesURL = "https://www.nationaltrust.org.uk/search/data/all-places";
const [isLoading, setLoading] = useState(true);
const [places, setPlaces] = useState([]);
useEffect(() => {
fetch(placesURL)
.then((response) => response.json())
.then((json) => setPlaces(json))
.catch((error) => alert(error))
.finally(setLoading(false));
})
</code></pre>
<p>And in the flatlist:</p>
<pre><code>
export default function App() {
return (
<View style={styles.container}>
<FlatList
data={places}
renderItem={({ item }) => (
<Text>{item.title}</Text>
)}
keyExtractor={(item) => item.id}
/>
<StatusBar style="auto" />
</View>
);
}
</code></pre>
<p>If anyone could tell me what to do I would really appreciate it.</p>
| [
{
"answer_id": 74339711,
"author": "bvstone",
"author_id": 2296644,
"author_profile": "https://Stackoverflow.com/users/2296644",
"pm_score": 2,
"selected": false,
"text": "dcl-ds STUDREFDS EXTNAME('STUDREF'); \nEnd-ds;\n"
},
{
"answer_id": 74352396,
"author": "Theju112",
"author_id": 19539055,
"author_profile": "https://Stackoverflow.com/users/19539055",
"pm_score": 0,
"selected": false,
"text": "FavoriteFoods like(StudRef.Food) DIM(10)"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16529639/"
] |
74,339,255 | <p>I want to write a function that will add a constant to each list element. The list can be Doubles or Integers or something similar. I write:</p>
<pre><code>static <T> List<T> forEachIndexChange(List<T> list,
Function<Integer, T> cb) {
for (int i = 0; i < list.size(); ++i) {
list.set(i, cb.apply(i));
}
return list;
}
static <T extends Number> List divide(List<T> list, int val) {
return forEachIndexChange(list, i -> list.get(i) / val);
}
</code></pre>
<p>And then the compiler spills out that I can't call <code>/</code> on class <code>Number</code>:</p>
<pre><code>error: bad operand types for binary operator '/'
return forEachIndexChange(list, i -> list.get(i) / val);
^
first type: T
second type: int
where T is a type-variable:
T extends Number declared in method <T>divide(List<T>,int,T)
</code></pre>
<p>Great, then let me overload depending on type:</p>
<pre><code>static <T extends Number> List divide(List<T> list, int val, T type) {
if (type instanceof Double) {
return forEachIndexChange(list, i -> list.get(i).doubleValue() / val);
}
return null;
}
static <T extends Number> List divide(List<T> list, int val) {
if (list.size() == 0) return list;
return divide(list, val, list.get(0));
}
</code></pre>
<p>But this spills out an error message that I do not understand:</p>
<pre><code>error: incompatible types: inference variable T#1 has incompatible bounds
return forEachIndexChange(list, i -> list.get(i).doubleValue() / val);
^
equality constraints: T#2
lower bounds: Double
where T#1,T#2 are type-variables:
T#1 extends Object declared in method <T#1>forEachIndexChange(List<T#1>,Function<Integer,T#1>)
T#2 extends Number declared in method <T#2>divide(List<T#2>,int,T#2)
</code></pre>
<p>Overloading on multiple <code>T</code> separately also doesn't work, because, as I understand, <code>List</code> erases the information about <code>T</code> when overloading a function. It looks like I am basically forced to write a separate function name for each type.</p>
<p>How do I write a generic algorithm to permute each list element in Java? Is there a better way to approach such problems in Java?</p>
| [
{
"answer_id": 74339348,
"author": "Sweeper",
"author_id": 5133585,
"author_profile": "https://Stackoverflow.com/users/5133585",
"pm_score": 2,
"selected": false,
"text": "static <T extends Number> List<T> divide(List<T> list, int val) {\n if (list.isEmpty()) return list;\n\n if (list.get(0) instanceof Double) {\n return forEachIndexChange(list, i -> (T)(Object)(list.get(i).doubleValue() / val));\n }\n\n if (list.get(0) instanceof Integer) {\n return forEachIndexChange(list, i -> (T)(Object)(list.get(i).intValue() / val));\n }\n\n // other types you want to support...\n\n throw new UnsupportedOperationException();\n}\n"
},
{
"answer_id": 74339616,
"author": "Gobanit",
"author_id": 4106800,
"author_profile": "https://Stackoverflow.com/users/4106800",
"pm_score": 2,
"selected": false,
"text": " private static <T extends Number> List<T> divide(List<T> orig, int divisor) {\n return orig.stream()\n .map(it -> divide(it, divisor))\n .toList();\n }\n\n private static <T extends Number> T divide(T num, int divisor) {\n if (num instanceof Double) return (T) Double.valueOf(num.doubleValue() / divisor);\n if (num instanceof Float) return (T) Float.valueOf(num.floatValue() / divisor);\n if (num instanceof Long) return (T) Long.valueOf(num.longValue() / divisor);\n if (num instanceof Integer) return (T) Integer.valueOf(num.intValue() / divisor);\n if (num instanceof Byte) return (T) Byte.valueOf((byte) (num.byteValue() / divisor)); // this might be problem if divisor is greater than 127\n throw new IllegalStateException(\"Cannot divide class of \" + num.getClass());\n }\n"
},
{
"answer_id": 74340212,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "forEachIndexChange()"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9072753/"
] |
74,339,256 | <p>I have two arrays :</p>
<pre><code>a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
[13, 14, 15]]
b = [[1, 2, 3],
[4, 5, 6],
[13, 14, 15]]
</code></pre>
<p>And I want to find out which rows of first array are represented in second array</p>
<pre><code>desired_output = [1, 1, 0, 0, 1]
</code></pre>
<p>I have tried this code :</p>
<pre><code>x = a == b[:, None]
row_sums = da.sum(x, axis=2)
output = np.sum(np.where(row_sums == 6,1,0),axis=0)
</code></pre>
<p>But it creates a massive 3D array - x - which is shaped (a(rows), b(rows), a (or b) (columns)).</p>
<pre><code>x.shape() = [5,3,3]
</code></pre>
<p>And taking into account that my arrays are large, my computer will take a long time to compute it.
Does someone have ideas how to improve my code?</p>
| [
{
"answer_id": 74339348,
"author": "Sweeper",
"author_id": 5133585,
"author_profile": "https://Stackoverflow.com/users/5133585",
"pm_score": 2,
"selected": false,
"text": "static <T extends Number> List<T> divide(List<T> list, int val) {\n if (list.isEmpty()) return list;\n\n if (list.get(0) instanceof Double) {\n return forEachIndexChange(list, i -> (T)(Object)(list.get(i).doubleValue() / val));\n }\n\n if (list.get(0) instanceof Integer) {\n return forEachIndexChange(list, i -> (T)(Object)(list.get(i).intValue() / val));\n }\n\n // other types you want to support...\n\n throw new UnsupportedOperationException();\n}\n"
},
{
"answer_id": 74339616,
"author": "Gobanit",
"author_id": 4106800,
"author_profile": "https://Stackoverflow.com/users/4106800",
"pm_score": 2,
"selected": false,
"text": " private static <T extends Number> List<T> divide(List<T> orig, int divisor) {\n return orig.stream()\n .map(it -> divide(it, divisor))\n .toList();\n }\n\n private static <T extends Number> T divide(T num, int divisor) {\n if (num instanceof Double) return (T) Double.valueOf(num.doubleValue() / divisor);\n if (num instanceof Float) return (T) Float.valueOf(num.floatValue() / divisor);\n if (num instanceof Long) return (T) Long.valueOf(num.longValue() / divisor);\n if (num instanceof Integer) return (T) Integer.valueOf(num.intValue() / divisor);\n if (num instanceof Byte) return (T) Byte.valueOf((byte) (num.byteValue() / divisor)); // this might be problem if divisor is greater than 127\n throw new IllegalStateException(\"Cannot divide class of \" + num.getClass());\n }\n"
},
{
"answer_id": 74340212,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "forEachIndexChange()"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20387248/"
] |
74,339,257 | <p>I have a parent repository having branches <code>master</code> <code>stage</code> & <code>develop</code> along with child repository say as <strong>submodule</strong> which has same branches <code>master</code> <code>stage</code> & <code>develop</code>, I made commits in <code>stage</code> branch in child repository(<strong>submodule</strong>) and try to push the changes to <code>stage</code> branch in parent repository but still the changes are not reflecting in the GitHub.</p>
<p>note:- Its working for parent repo's <code>master</code> to child repo's <code>master</code> .
**script used for master
**</p>
<pre><code>#!/bin/bash
git init
git clone --recurse-submodules https://github.com/username/file.git
cd file
git submodule update --remote
git commit -a -m "commit in both submodule"
git push -u origin
</code></pre>
<p>above script work for for parent repo's <code>master</code> to child repo's <code>master</code> like wise
I want for parent repo's <code>stage</code> to child repo's <code>stage</code> as well.</p>
<p>**I even tried using multiple commands :-
git push -u origin stage
git config push.default current
git config push.default upstream</p>
<p>none of them were working
**</p>
| [
{
"answer_id": 74339348,
"author": "Sweeper",
"author_id": 5133585,
"author_profile": "https://Stackoverflow.com/users/5133585",
"pm_score": 2,
"selected": false,
"text": "static <T extends Number> List<T> divide(List<T> list, int val) {\n if (list.isEmpty()) return list;\n\n if (list.get(0) instanceof Double) {\n return forEachIndexChange(list, i -> (T)(Object)(list.get(i).doubleValue() / val));\n }\n\n if (list.get(0) instanceof Integer) {\n return forEachIndexChange(list, i -> (T)(Object)(list.get(i).intValue() / val));\n }\n\n // other types you want to support...\n\n throw new UnsupportedOperationException();\n}\n"
},
{
"answer_id": 74339616,
"author": "Gobanit",
"author_id": 4106800,
"author_profile": "https://Stackoverflow.com/users/4106800",
"pm_score": 2,
"selected": false,
"text": " private static <T extends Number> List<T> divide(List<T> orig, int divisor) {\n return orig.stream()\n .map(it -> divide(it, divisor))\n .toList();\n }\n\n private static <T extends Number> T divide(T num, int divisor) {\n if (num instanceof Double) return (T) Double.valueOf(num.doubleValue() / divisor);\n if (num instanceof Float) return (T) Float.valueOf(num.floatValue() / divisor);\n if (num instanceof Long) return (T) Long.valueOf(num.longValue() / divisor);\n if (num instanceof Integer) return (T) Integer.valueOf(num.intValue() / divisor);\n if (num instanceof Byte) return (T) Byte.valueOf((byte) (num.byteValue() / divisor)); // this might be problem if divisor is greater than 127\n throw new IllegalStateException(\"Cannot divide class of \" + num.getClass());\n }\n"
},
{
"answer_id": 74340212,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "forEachIndexChange()"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19868763/"
] |
74,339,261 | <p>I want to know what models are children of a model to retrieve their <code>on_delete</code> property. As I know, like below, if we have <code>ownerModel</code> which is parent of <code>childModel1</code> and <code>check1Model</code>:</p>
<pre><code>import uuid
from django.db import models
class ownerModel(models.Model):
ownerId = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False, blank=True)
class check1Model(models.Model):
checkId = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False, blank=True)
owner=models.ForeignKey(ownerModel,on_delete=models.CASCADE)
class childModel1(models.Model):
childId = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False, blank=True)
check2=models.ForeignKey(ownerModel,on_delete=models.CASCADE)
</code></pre>
<p>Then we can get what models are children of <code>ownerModel</code> with a code like this:</p>
<pre><code>class myView(views.APIView):
def get(self, request, format=None):
for f in ownerModel._meta.get_fields():
if 'field' in f.__dict__.keys():
print('***childModels***')
print(f.__dict__)
print()
return Response({'0000'}, status=status.HTTP_200_OK)
</code></pre>
<p>I mean by checking if the <code>field</code> key is in <code>__dict__.keys()</code> in items of <code>ownerModel._meta.get_fields()</code>.</p>
<p>Of course, here we get extended info about children models:</p>
<pre><code>***childModels***
{'field': <django.db.models.fields.related.ForeignKey: owner>, 'model': <class 'Users.models.ownerModel'>, 'related_name': None, 'related_query_name': None, 'limit_choices_to': {}, 'parent_link': False, 'on_delete': <function
CASCADE at 0x00000286550848B0>, 'symmetrical': False, 'multiple': True, 'field_name': 'ownerId', 'related_model': <class 'Users.models.check1Model'>, 'hidden': False}
***childModels***
{'field': <django.db.models.fields.related.ForeignKey: check2>, 'model': <class 'Users.models.ownerModel'>, 'related_name': None, 'related_query_name': None, 'limit_choices_to': {}, 'parent_link': False, 'on_delete': <function CASCADE at 0x00000286550848B0>, 'symmetrical': False, 'multiple': True, 'field_name': 'ownerId', 'related_model': <class 'Users.models.childModel1'>, 'hidden': False}
</code></pre>
<p>So I find these 2 conditions necessary to get child models info:</p>
<ol>
<li>In child models, making sure child relationship is set up with a line like below:</li>
</ol>
<pre><code>models.ForeignKey(ownerModel,on_delete=models.CASCADE)
</code></pre>
<ol start="2">
<li>As said "if the <code>field</code> key is in <code>__dict__.keys()</code> in items of <code>ownerModel._meta.get_fields()</code>" to get children info.</li>
</ol>
<p>But the problem is that in some cases I can't get the children info from parent model. So:</p>
<ol>
<li>It makes me wonder if these 2 conditions are enough to find out which models are children of a model?</li>
<li>Are there other similar ways to get which models are children of a model?</li>
</ol>
<p>By the way, I want to have <code>on_delete</code> also and having <code>on_delete</code> is the only reason I am using <code>_meta.get_fields()</code> over <code>_meta.fields</code> because <code>_meta.fields</code> doesn't provide <code>on_delete</code> property.</p>
<p>This is <a href="https://easyupload.io/ou93pt" rel="nofollow noreferrer">my code</a> if you wanna have a look. Note that in full answer I also wanna know what has made problem. So in this case, that <code>__dict__.keys()</code> doesn't provide items which don't have <code>field</code> in their keys (doesn't provide child model details). Because generally those 2 conditions provide child model details. So later I can get child model details in all codes.</p>
<p>the problem is that even with <code>for f in ownerModel._meta.get_fields(include_hidden=True)</code> and without any further <code>if</code>s doesnt retrieve lines including <code>on_delete</code> properties in this project. but in the other projects <code>ownerModel._meta.get_fields()</code> provides them. and I don't whats the cause that sometimes <code>ownerModel._meta.get_fields()</code> provides these relationships infos and other times doesnt.</p>
| [
{
"answer_id": 74340467,
"author": "Zkh",
"author_id": 19235697,
"author_profile": "https://Stackoverflow.com/users/19235697",
"pm_score": 1,
"selected": false,
"text": "Model._meta.related_objects"
},
{
"answer_id": 74450673,
"author": "Antoine Pinsard",
"author_id": 1529346,
"author_profile": "https://Stackoverflow.com/users/1529346",
"pm_score": 0,
"selected": false,
"text": "ownerModel._meta.related_objects"
},
{
"answer_id": 74461268,
"author": "Antoine Pinsard",
"author_id": 1529346,
"author_profile": "https://Stackoverflow.com/users/1529346",
"pm_score": 1,
"selected": true,
"text": "models"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11692124/"
] |
74,339,328 | <p>I have got the Recyclerview working with findViewById but cant get it working with View bindings.</p>
<p>This Works</p>
<pre><code>val tdList: RecyclerView = findViewById(R.id.td_list);
tdList.layoutManager = LinearLayoutManager(this)
tdList.setHasFixedSize(true);
tdList.adapter = reportAdapter
</code></pre>
<p>But this does not work</p>
<pre><code>tdBinding.tdList.layoutManager = LinearLayoutManager(this)
tdBinding.tdList.setHasFixedSize(true);
tdBinding.tdList.adapter = reportAdapter
</code></pre>
<p>onCreateViewHolder or onBindViewHolder are never called and I get an error 'No adapter attached; skipping layout' so no data is shown in the RecyclerView.</p>
<p>I've been trying to get this working for a few days with View Bindings and finally found the code to get it working with findViewById and part of me thinks I should just be glad I got it working but would like to understand why (also as findViewById is quite expensive).</p>
<p>The full code is</p>
<p><strong>DurationsReport.kt</strong></p>
<pre><code>package com.funkytwig.tasktimer
import android.database.Cursor
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.funkytwig.tasktimer.databinding.ActivityDurationsReportBinding
import com.funkytwig.tasktimer.databinding.TaskDurationsBinding
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
private const val TAG = "DurationsReportXX"
enum class SortColumns { NAME, DESCRIPTION, START_DATE, DURATION }
class DurationsReport : AppCompatActivity() {
private val reportAdapter by lazy { DurationsRVAdapter(this, null) }
var databaseCursor: Cursor? = null
var sortOrder = SortColumns.NAME
private val selection = "${DurationsContract.Columns.START_TIME} BETWEEN ? AND ?"
private var selectionArgs = arrayOf("0", "1559347199")
private lateinit var binding: ActivityDurationsReportBinding
private lateinit var tdBinding: TaskDurationsBinding
override fun onCreate(savedInstanceState: Bundle?) {
val func = "onCreate"
Log.d(TAG, func)
super.onCreate(savedInstanceState)
binding = ActivityDurationsReportBinding.inflate(layoutInflater)
tdBinding = TaskDurationsBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
Log.d(TAG, "$func: Setup adapter")
val tdList: RecyclerView = findViewById(R.id.td_list);
tdList.layoutManager = LinearLayoutManager(this)
tdList.setHasFixedSize(true);
tdList.adapter = reportAdapter
// This does not work
// tdBinding.tdList.layoutManager = LinearLayoutManager(this)
// tdBinding.tdList.setHasFixedSize(true);
// tdBinding.tdList.adapter = reportAdapter
loadData()
}
private fun loadData() {
val func = "loadData"
Log.d(TAG, func)
val order = when (sortOrder) {
SortColumns.NAME -> DurationsContract.Columns.NAME
SortColumns.DESCRIPTION -> DurationsContract.Columns.DESCRIPTION
SortColumns.START_DATE -> DurationsContract.Columns.START_DATE
SortColumns.DURATION -> DurationsContract.Columns.DURATION
}
Log.d(TAG, "order=$order")
GlobalScope.launch {
val cursor = application.contentResolver.query(
DurationsContract.CONTENT_URI, null, selection, selectionArgs, order
)
Log.d(TAG, "$func: cursor.count=${cursor?.count}")
databaseCursor = cursor
reportAdapter.swapCursor(cursor)?.close()
}
}
}
</code></pre>
<p><strong>DurationsRVAdapter.kt</strong></p>
<pre><code>package com.funkytwig.tasktimer
import android.content.Context
import android.database.Cursor
import android.text.format.DateFormat
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.funkytwig.tasktimer.databinding.TaskDurationItemsBinding
import java.util.Locale
import java.lang.IllegalStateException
private const val TAG = "DurationsRVAdapterXX"
class DurationsRVAdapter(context: Context, private var cursor: Cursor?) :
RecyclerView.Adapter<DurationsRVAdapter.DurationsViewHolder>() {
inner class DurationsViewHolder(val bindings: TaskDurationItemsBinding) :
RecyclerView.ViewHolder(bindings.root)
private val dateFormat = DateFormat.getDateFormat(context)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DurationsViewHolder {
Log.d(TAG, "onCreateViewHolder")
val view =
TaskDurationItemsBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return DurationsViewHolder(view)
}
override fun onBindViewHolder(holder: DurationsViewHolder, position: Int) {
val func = "onBindViewHolder"
Log.d(TAG, "$func: position = $position")
val cursor = cursor
if (cursor != null && cursor.count != 0) {
if (!cursor.moveToPosition(position)) {
throw IllegalStateException("Couldn't move cursor to position $position")
}
val name = cursor.getString(cursor.getColumnIndex(DurationsContract.Columns.NAME))
val description =
cursor.getString(cursor.getColumnIndex(DurationsContract.Columns.DESCRIPTION))
val startTime =
cursor.getLong(cursor.getColumnIndex(DurationsContract.Columns.START_TIME))
val totalDuration =
cursor.getLong(cursor.getColumnIndex(DurationsContract.Columns.DURATION))
val userDate =
dateFormat.format(startTime * 1000) // The database stores seconds, we need milliseconds
val totalTime = formatDuration(totalDuration)
holder.bindings.tdName.text = name
holder.bindings.tdDescription?.text = description
holder.bindings.tdStart.text = userDate
holder.bindings.tdDuration.text = totalTime
}
}
private fun formatDuration(duration: Long): String {
// convert duration Long to hours:mins:secs String (can be > 24 hours so cant use dateFormat)
val hours = duration / 3600
val remainder = duration - hours * 3600
val minutes = remainder / 60
val seconds = remainder % 60
return String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, seconds)
}
override fun getItemCount(): Int {
val func = "getItemCount"
val count = cursor?.count ?: 0
Log.d(TAG, "$func: count=$count")
return count
}
fun swapCursor(newCursor: Cursor?): Cursor? {
val func = "swapCursor"
Log.d(TAG, func)
if (newCursor === cursor) return null
val numItems = itemCount
val oldCursor = cursor
cursor = newCursor
Log.d(TAG, "$func: cursor.count=${cursor?.count}")
Log.d(TAG, "$func newCursor.count=${newCursor?.count}, oldCursor.cont=${oldCursor?.count}")
if (newCursor != null) {
Log.d(TAG, "$func notify the observers about the new cursor")
// notify the observers about the new cursor
this.notifyDataSetChanged()
Log.d(TAG, "$func: notifyDataSetChanged")
} else {
Log.d(TAG, "$func Notify observer about lack of dataset")
// Notify observer about lack of dataset, all of it from 0 to newItems,
// i.e. whole range of records has gone
this.notifyItemRangeChanged(0, numItems)
Log.d(TAG, "$func: notifyItemRangeChanged(0, $numItems)")
}
return oldCursor
}
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
val func = "onAttachedToRecyclerView"
Log.d(TAG, "$func: ${recyclerView.adapter.toString()}")
super.onAttachedToRecyclerView(recyclerView)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
val func = "onDetachedFromRecyclerView"
Log.d(TAG, "$func: ${recyclerView.adapter.toString()}")
super.onDetachedFromRecyclerView(recyclerView)
}
}
</code></pre>
<p><strong>task_durations.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
app:layout_constraintHorizontal_chainStyle="spread">
<TextView
android:id="@+id/td_name_heading"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_marginTop="4dp"
android:background="?attr/colorButtonNormal"
android:padding="4dp"
android:text="@string/td_text_name"
android:textAlignment="viewStart"
android:textStyle="bold"
app:layout_constraintHorizontal_weight="2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="spread" />
<TextView
android:id="@+id/td_start_heading"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_marginEnd="4dp"
android:background="?attr/colorButtonNormal"
android:padding="4dp"
android:text="@string/td_text_date"
android:textAlignment="viewStart"
android:textStyle="bold"
app:layout_constraintBaseline_toBaselineOf="@+id/td_name_heading"
app:layout_constraintEnd_toStartOf="@+id/td_duration_heading"
app:layout_constraintHorizontal_weight="1"
app:layout_constraintStart_toEndOf="@+id/td_name_heading" />
<TextView
android:id="@+id/td_duration_heading"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_marginEnd="4dp"
android:background="?attr/colorButtonNormal"
android:padding="4dp"
android:text="@string/td_text_duration"
android:textAlignment="viewStart"
android:textStyle="bold"
app:layout_constraintBaseline_toBaselineOf="@+id/td_start_heading"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_weight="1"
app:layout_constraintStart_toEndOf="@+id/td_start_heading" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/td_list"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:scrollbars="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/td_name_heading"
tools:listitem="@layout/task_duration_items" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code></pre>
<p><strong>task_duration_itesm.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:showIn="@layout/task_durations">
<TextView
android:id="@+id/td_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:padding="4dp"
android:textAlignment="viewStart"
app:layout_constraintHorizontal_weight="2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="spread"
tools:text="@string/td_text_name" />
<TextView
android:id="@+id/td_start"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_marginEnd="4dp"
android:padding="4dp"
android:textAlignment="viewStart"
app:layout_constraintBaseline_toBaselineOf="@+id/td_name"
app:layout_constraintEnd_toStartOf="@+id/td_duration"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintHorizontal_weight="1"
app:layout_constraintStart_toEndOf="@+id/td_name"
tools:text="@string/td_text_date" />
<TextView
android:id="@+id/td_duration"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_marginEnd="4dp"
android:padding="4dp"
android:textAlignment="viewStart"
app:layout_constraintBaseline_toBaselineOf="@+id/td_start"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintHorizontal_weight="1"
app:layout_constraintStart_toEndOf="@+id/td_start"
tools:text="@string/td_text_duration" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code></pre>
| [
{
"answer_id": 74339705,
"author": "Tenfour04",
"author_id": 506796,
"author_profile": "https://Stackoverflow.com/users/506796",
"pm_score": 2,
"selected": false,
"text": "findViewById"
},
{
"answer_id": 74434352,
"author": "Ben Edwards",
"author_id": 8423250,
"author_profile": "https://Stackoverflow.com/users/8423250",
"pm_score": 0,
"selected": false,
"text": " <include\n android:id=\"@+id/items\"\n layout=\"@layout/task_durations\" />\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8423250/"
] |
74,339,362 | <p>Lets say I have a function like this:</p>
<pre><code>Function Hello(){
Write-Host "Hello, World"}
</code></pre>
<p>when used on its own it works perfect but I would also like for it to receive pipeline input:</p>
<pre><code>$MyString = "Something Else please"
$MyString | Hello
</code></pre>
<p>In the second example, <code>Something Else please</code> should be printed instead of the default value of <code>Hello, World</code>.</p>
<p>I have searched and searched and have turned up empty handed. everything out there keeps mentioning default parameters. I am not looking to use parameters.</p>
<p>Someone please point me in the right direction.</p>
| [
{
"answer_id": 74339593,
"author": "RetiredGeek",
"author_id": 13702221,
"author_profile": "https://Stackoverflow.com/users/13702221",
"pm_score": 2,
"selected": false,
"text": "Clear-Host\n\nFunction Hello {\n\n Param (\n [Parameter(Mandatory=$False,ValueFromPipeline=$True)]\n [String] $MyText = \"Hello\"\n )\n Write-Host \"$MyText, World\"\n}\n\nHello\n\n\"It's A Wonderful\" | Hello\n"
},
{
"answer_id": 74339834,
"author": "hellen_dorandt89",
"author_id": 17841256,
"author_profile": "https://Stackoverflow.com/users/17841256",
"pm_score": 1,
"selected": false,
"text": "Function Hello {\n Param (\n [Parameter(Mandatory=$False,ValueFromPipeline=$True)]\n [PSObject[]] $InputObject,\n )\n if ($PSCmdlet.MyInvocation.ExpectingInput) {\n \"Data received from pipeline input: '$($InputObject)'\"\n }\n \n else {\n Write-host \"Hello World\"\n }\n }\n"
},
{
"answer_id": 74339888,
"author": "mklement0",
"author_id": 45375,
"author_profile": "https://Stackoverflow.com/users/45375",
"pm_score": 3,
"selected": true,
"text": "process"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17841256/"
] |
74,339,385 | <p>Is it okay to create a list like this?</p>
<pre><code><ul>
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
<li><a href="#">Item 4</a></li>
</ul>
</code></pre>
<p>Or should I always add a <code><p></code>?</p>
<pre><code><ul>
<li><p><a href="#">Item 1</a></p></li>
<li><p><a href="#">Item 2</a></p></li>
<li><p><a href="#">Item 3</a></p></li>
<li><p><a href="#">Item 4</a></p></li>
</ul>
</code></pre>
| [
{
"answer_id": 74339391,
"author": "Tamás Sengel",
"author_id": 3151675,
"author_profile": "https://Stackoverflow.com/users/3151675",
"pm_score": 2,
"selected": false,
"text": "<p>"
},
{
"answer_id": 74339416,
"author": "Milkmannetje",
"author_id": 2815350,
"author_profile": "https://Stackoverflow.com/users/2815350",
"pm_score": 3,
"selected": true,
"text": "<p>"
},
{
"answer_id": 74339663,
"author": "liquidot",
"author_id": 20400911,
"author_profile": "https://Stackoverflow.com/users/20400911",
"pm_score": 0,
"selected": false,
"text": "<p>"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2986930/"
] |
74,339,390 | <p>I am asked to extract the dates of dictionary in which the values exceed the input threshold.</p>
<p>See code beneath:</p>
<pre><code>def get_dates(prices,threshold):
{k:v for k,v in prices if threshold>130}
prc = [
{ 'price': 1279.79, 'date': '2020-01-01' },
{ 'price': 139.01, 'date': '2020-01-02' },
{ 'price': 134.3, 'date': '2020-01-03' },
{ 'price': 120.99, 'date': '2020-01-04' }
]
get_dates(prc, 130.0)
</code></pre>
<p>Ideally, the function should return the respective date on which the price is beyond the threshold (130). My code does not however return anything.</p>
| [
{
"answer_id": 74339423,
"author": "I'mahdi",
"author_id": 1740577,
"author_profile": "https://Stackoverflow.com/users/1740577",
"pm_score": 1,
"selected": false,
"text": "list comprehensions"
},
{
"answer_id": 74339466,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 1,
"selected": true,
"text": "date"
},
{
"answer_id": 74339483,
"author": "Dante ",
"author_id": 16320430,
"author_profile": "https://Stackoverflow.com/users/16320430",
"pm_score": 1,
"selected": false,
"text": "def get_dates(prices, threshold) :\n dates=[]\n for dict in prices:\n if dict['price']>threshold:\n dates.append(dict['date'])\n return dates\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18072226/"
] |
74,339,404 | <p>Im facing a problem with assigning a value to a variable that its name is stored in other variable or a file</p>
<p>cat ids.txt</p>
<pre><code>ID1
ID2
ID3
</code></pre>
<p>What i want to do is:</p>
<pre><code>for i in `cat ids.txt'; do $i=`cat /proc/sys/kernel/random/uuid`
</code></pre>
<p>or</p>
<pre><code>for i in ID1 ID2 ID3; do $i=`cat /proc/sys/kernel/random/uuid`
</code></pre>
<p>But its not working.
What i would like to have, its something like:</p>
<pre><code>echo $ID1
5dcteeee-6abb-4agg-86bb-948593020451
echo $ID2
5dcteeee-6abb-4agg-46db-948593322990
echo $ID3
5dcteeee-6abb-4agg-86cb-948593abcd45
</code></pre>
| [
{
"answer_id": 74339423,
"author": "I'mahdi",
"author_id": 1740577,
"author_profile": "https://Stackoverflow.com/users/1740577",
"pm_score": 1,
"selected": false,
"text": "list comprehensions"
},
{
"answer_id": 74339466,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 1,
"selected": true,
"text": "date"
},
{
"answer_id": 74339483,
"author": "Dante ",
"author_id": 16320430,
"author_profile": "https://Stackoverflow.com/users/16320430",
"pm_score": 1,
"selected": false,
"text": "def get_dates(prices, threshold) :\n dates=[]\n for dict in prices:\n if dict['price']>threshold:\n dates.append(dict['date'])\n return dates\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13428400/"
] |
74,339,446 | <p>I'm trying to create a simple vscode extension that will insert some default text into a newly created file. What I want is for the <code>vscode.workspace.createFileSystemWatcher</code> to call a function that gets the <code>activeTextEditor</code> and writes to the new file. Here is what I've tried:</p>
<pre><code>import * as vscode from "vscode";
export function activate(context: vscode.ExtensionContext) {
let disposable = vscode.commands.registerCommand(
"default-text-generator.generate",
() => {
function _watcherChangeApplied(editor?: vscode.TextEditor) {
if (editor) {
editor.edit((editBuilder) => {
editBuilder.insert(editor.selection.active, "Hello World");
});
}
}
const editor = vscode.window.activeTextEditor;
let uri: vscode.Uri | undefined = editor?.document.uri;
if (uri) {
let watcher = vscode.workspace.createFileSystemWatcher(
new vscode.RelativePattern(
vscode.workspace.getWorkspaceFolder(uri)!,
"**/*.ts"
),
false,
false,
false
);
watcher.onDidCreate(() => _watcherChangeApplied(editor));
}
}
);
context.subscriptions.push(disposable);
}
// this method is called when your extension is deactivated
export function deactivate(): void {
//deactivate
}
</code></pre>
<p>Here's what's happening. The editor seems to insert the text, then immediately gets overwritten back to a blank page. I can't seem to figure out why.</p>
| [
{
"answer_id": 74339423,
"author": "I'mahdi",
"author_id": 1740577,
"author_profile": "https://Stackoverflow.com/users/1740577",
"pm_score": 1,
"selected": false,
"text": "list comprehensions"
},
{
"answer_id": 74339466,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 1,
"selected": true,
"text": "date"
},
{
"answer_id": 74339483,
"author": "Dante ",
"author_id": 16320430,
"author_profile": "https://Stackoverflow.com/users/16320430",
"pm_score": 1,
"selected": false,
"text": "def get_dates(prices, threshold) :\n dates=[]\n for dict in prices:\n if dict['price']>threshold:\n dates.append(dict['date'])\n return dates\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2782124/"
] |
74,339,450 | <p>Can't printout the indexes for all the elements with the same value from an array list. Only the index for the first element found in the array list is printed out.</p>
<p>Current output when list = 5,5,4,5:
Number 5 can be found in the following indexes [0, 0, 0, 0]</p>
<p>The desired output would be:
Number 5 can be found in the following indexes [0, 1, 3]</p>
<p>How I would want the code to work is that the user has to enter integers to an array list until the value -1 is entered. After that system prints out "What number are you looking for?". User enters the number for the element(s) that is wanted to be fetched from the array list. After that system prints out "Number 5 can be found in the following indexes [0, 1, 3].</p>
<p>Here's my code so far:</p>
<pre><code>import java.util.ArrayList;
import java.util.Scanner;
public class sandbox{
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
while (true) {
int read = Integer.valueOf(reader.nextLine());
if (read == -1) {
break;
}
list.add(read);
}
System.out.print("What number are you looking for? ");
int requestednumb = Integer.valueOf(reader.nextLine());
int count = 0;
ArrayList<Integer> index = new ArrayList<>();
while ((list.size() > count)) {
if (list.contains(requestednumb))
;
index.add(list.indexOf(requestednumb));
count++;
}
System.out.println("Number " + requestednumb + " can be found in the following indexes " + index);
}
}
</code></pre>
<p>`</p>
<p>I'm pretty sure that it's an silly beginner mistake I have made, but after being stuck with this problem for multiple hours, I hope you can find the time to help me with this.</p>
| [
{
"answer_id": 74339423,
"author": "I'mahdi",
"author_id": 1740577,
"author_profile": "https://Stackoverflow.com/users/1740577",
"pm_score": 1,
"selected": false,
"text": "list comprehensions"
},
{
"answer_id": 74339466,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 1,
"selected": true,
"text": "date"
},
{
"answer_id": 74339483,
"author": "Dante ",
"author_id": 16320430,
"author_profile": "https://Stackoverflow.com/users/16320430",
"pm_score": 1,
"selected": false,
"text": "def get_dates(prices, threshold) :\n dates=[]\n for dict in prices:\n if dict['price']>threshold:\n dates.append(dict['date'])\n return dates\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20434565/"
] |
74,339,452 | <p>I'm fairly new to Python and coding in general so please bare with me. Overall, what im attempting is to create a script to open up my monthly fire department training, go to the monthly training video's, make a list of the potential videos in that data pod that change monthly and vary in how many video's we have for that month, and then play the video's. I've used Selenium to access the webpage and login. Im currently trying to make the list of possible monthly video's that'll ill be able to pull from and play. Show in the pic's are the "Assigments" and the code layout of the inspect video elements. Below is my code that I've come up with to pull the video links but everytime I run it it comes up with email obfuscation. Not sure what's causing this or how to get around it. Any help would be appreciated.</p>
<p><a href="https://i.stack.imgur.com/xluJk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xluJk.png" alt="Assignment block" /></a></p>
<p><a href="https://i.stack.imgur.com/30CCe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/30CCe.png" alt="Code snippet" /></a></p>
<p>###Edit added all of my code</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options #for maximize, disabling pop ups, enabling/disabling ext, etc..
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import requests
from bs4 import BeautifulSoup
import httplib2
import re
#Target Solutions Credentials
username = "#"
password = "#"
#opening web page
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
s = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=s, options=chrome_options)
#open window in maximize
driver.maximize_window()
#website
driver.get('https://www.targetsolutions.com/')
driver.implicitly_wait(10)
#login screen button
lms_login_button = driver.find_element(by=By.XPATH, value='//*[@id="riverbend-ButtonElement--oouR2NYdw9Ns5lb2VrED"]')
lms_login_button.click()
#username & password
username = driver.find_element(by=By.XPATH, value='//*[@id="username"]').send_keys("#")
password = driver.find_element(by=By.XPATH, value ='//*[@id="password"]').send_keys("#")
#Login button
login_screen_button = driver.find_element(by=By.XPATH, value='//*[@id="form-login"]/ul/li[3]/input')
login_screen_button.click()
# Assignments page
my_assignments = driver.find_element(by=By.XPATH, value ='//*[@id="navLeft"]/ul/li[2]/a')
my_assignments.click()
# EMAIL OBFUSCATION===============
def email(string):
r = int(string[:2], 16)
email = ''.join([chr(int(string[i:i+2], 16) ^ r)
for i in range(2, len(string), 2)])
return email
print(email('d0a3a5a0a0bfa2a490a4b1a2b7b5a4a3bfbca5a4b9bfbea3feb3bfbd'))
# WEBSCRAPER====================
url = 'https://app.targetsolutions.com/tsapp/dashboard/pl_fb/index.cfm?fuseaction=c_pro_assignments.showHome'
links = []
website = requests.get(url)
website_text = website.text
soup = BeautifulSoup(website_text, features='html.parser')
for link in soup.find_all('a'):
links.append(link.get('href'))
for link in links:
print(link)
</code></pre>
<p>Results: ====== WebDriver manager ======
Current google-chrome version is 107.0.5304
Get LATEST chromedriver version for 107.0.5304 google-chrome
Driver [C:\Users\Wrd_3.wdm\drivers\chromedriver\win32\107.0.5304.62\chromedriver.exe] found in cache</p>
<p>DevTools listening on ws://127.0.0.1:55154/devtools/browser/d4e0b939-a7c4-4cfb-b828-1187823a031e
support@targetsolutions.com
/cdn-cgi/l/email-protection#3a494f4a4a55484e7a4e5b485d5f4e4955564f4e5355544914595557</p>
<p>Which I understand to be some form of CloudFare Email Obfuscation.</p>
| [
{
"answer_id": 74339677,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "js2py"
},
{
"answer_id": 74339693,
"author": "holy",
"author_id": 20411925,
"author_profile": "https://Stackoverflow.com/users/20411925",
"pm_score": 2,
"selected": false,
"text": "support@targetsolutions.com"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19004472/"
] |
74,339,455 | <p>I have two files from these website:
<a href="https://sedac.ciesin.columbia.edu/data/set/gpw-v4-population-count-rev11/data-download" rel="nofollow noreferrer">https://sedac.ciesin.columbia.edu/data/set/gpw-v4-population-count-rev11/data-download</a></p>
<p>And a shapefile of China from these website
<a href="https://gadm.org/download_country_v3.html" rel="nofollow noreferrer">https://gadm.org/download_country_v3.html</a></p>
<p>I would like to compute the difference between the raster population layers, that I can show a map where each pixel represents the change in the population in China.</p>
<p>I used this code</p>
<pre><code>library(raster)
library(sf)
library(tmap)
p_15 <- terra::rast("gpw-v4-population-count-rev11_2015_2pt5_min_tif/gpw_v4_population_count_rev11_2015_2pt5_min.tif")
p_20 <- terra::rast("gpw-v4-population-count-rev11_2020_2pt5_min_tif/gpw_v4_population_count_rev11_2020_2pt5_min.tif")
CHN <- sf::read_sf("gadm36_CHN_shp/gadm36_CHN_1.shp")
CHN <- sf::st_transform(CHN, crs="epsg:4490")|> terra::vect()
p_15<- terra::project(p_15,'EPSG:4490')
p_20 <- terra::project(p_20,'EPSG:4490')
p_15_crop <- terra::crop(p_15, CHN)
p_20_crop <- terra::crop(p_20, CHN)
p_15_mask <- mask(p_15_crop, CHN)
p_20_mask <- mask(p_2_crop, CHN)
</code></pre>
<p>The code above everything works fine.</p>
<p>Now I used overlay from the raster package to calculate the difference between the population layers to show the change in each pixel.</p>
<p>I gave these code</p>
<pre><code>diff1520 <- overlay(p_15_mask, p_20_mask, fun=function(x,y){return(y-x)})
</code></pre>
<p>But I got the error message method not applicable??? What is wrong with the code?</p>
<p>By the way, I also used geodata package, but did not solve my problem</p>
| [
{
"answer_id": 74339677,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "js2py"
},
{
"answer_id": 74339693,
"author": "holy",
"author_id": 20411925,
"author_profile": "https://Stackoverflow.com/users/20411925",
"pm_score": 2,
"selected": false,
"text": "support@targetsolutions.com"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,339,464 | <p>When I do <code>Math.pow(3, num)/num</code>, it is giving me the value if <code>Infinity</code> and when I do <code>modulus</code> of that with <code>2</code> it is giving me <code>NaN</code>. I understand NaN is due to Infinity. I am using <code>300530164787</code> as the num and am expecting to do a modulus on the above formulae.</p>
<p>Any way I can avoid this?</p>
<p><code>Math.pow(3, num)/num = Infinity</code>
<code>(Math.pow(3, num)/num)%2 = NaN</code></p>
<p>Second which is faster?</p>
<ol>
<li><code>Math.pow(3, num)</code> OR</li>
<li><code>for</code> loop for 3x3x....</li>
</ol>
| [
{
"answer_id": 74339588,
"author": "Girardi",
"author_id": 488229,
"author_profile": "https://Stackoverflow.com/users/488229",
"pm_score": -1,
"selected": false,
"text": "(3^x)/x>1"
},
{
"answer_id": 74340150,
"author": "Bergi",
"author_id": 1048572,
"author_profile": "https://Stackoverflow.com/users/1048572",
"pm_score": 2,
"selected": false,
"text": "(a/b) % 2 ≡ (a % 2b) / b\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3204942/"
] |
74,339,499 | <p>This is a DataFrame sample:</p>
<pre><code> Folder Model
0 123 A
1 123 A
2 123 A
3 4541 A
4 4541 B
5 4541 C
6 4541 A
7 11 B
8 11 C
9 222 D
10 222 D
11 222 B
12 222 A
</code></pre>
<p>I need to separate <code>Folders</code> that have items with <code>Model</code> <code>A</code> and also another <code>Model</code> (<code>B</code>, <code>C</code> or <code>D</code>). The final DataFrame should look like that.</p>
<pre><code> Folder Model
3 4541 A
4 4541 B
5 4541 C
6 4541 A
9 222 D
10 222 D
11 222 B
12 222 A
</code></pre>
<p>I suppose it is something in the <code>groupby</code> universe, but couldn't get to a conclusion. Any suggestions?</p>
| [
{
"answer_id": 74339566,
"author": "Panda Kim",
"author_id": 20430449,
"author_profile": "https://Stackoverflow.com/users/20430449",
"pm_score": 2,
"selected": true,
"text": "filter"
},
{
"answer_id": 74339832,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "set"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5606352/"
] |
74,339,502 | <p>I am working on a small Laravel application, the problem is with the login, it works fine, but I just found out that the password can be seen if you have the basic knowledge to inspect the request payload. I want to know how can I encrypt the password or what solution can there be for this.</p>
<p>Blade file:</p>
<pre><code><form role="form" method="POST" action="{{ route('Login') }}">
@csrf
<div class="form-group{{ $errors->has('email') ? ' has-danger' : '' }} mb-3">
<div class="input-group input-group-alternative">
<div class="input-group-prepend">
<span class="input-group-text"><i class="ni ni-email-83"></i></span>
</div>
<input class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" placeholder="{{ __('Correo') }}" type="email" name="email" value="{{ old('email') }}" value="admin@argon.com" required autofocus>
</div>
@if ($errors->has('email'))
<span class="invalid-feedback" style="display: block;" role="alert">
<strong>{{ $errors->first('email') }}</strong>
</span>
@endif
</div>
<div class="form-group{{ $errors->has('password') ? ' has-danger' : '' }}">
<div class="input-group input-group-alternative">
<div class="input-group-prepend">
<span class="input-group-text"><i class="ni ni-lock-circle-open"></i></span>
</div>
<input class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" placeholder="{{ __('Contraseña') }}" type="password" required>
</div>
@if ($errors->has('password'))
<span class="invalid-feedback" style="display: block;" role="alert">
<strong>{{ $errors->first('password') }}</strong>
</span>
@endif
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary my-4">{{ __('Iniciar sesión') }} </button>
</div>
</form>
</code></pre>
<p>Login controller:</p>
<pre><code>public function Login(Request $request)
{
$credentials = $this->validate(request(),[
'email'=>'email|required|string',
'password'=>'required|string'
]);
try
{
if(Auth::attempt($credentials))
{
$roleStdClass = DB::table('users')->where('email', $credentials['email'])->select('role_idrole')->first();
$role = current((array) $roleStdClass);
session(['rol'=> $role]);
$id = DB::table('users')->where('email', $credentials['email'])->select('id')->first();
$imgRoute = DB::table('users')->where('email', $credentials['email'])->select('photo')->first();
$idConvert = current((array) $id);
$userPhoto = current((array) $imgRoute);
session(['id'=> $idConvert]);
session(['userEmail' => $credentials['email']]);
session(['userPhoto' => $userPhoto]);
if($role == 3)
{
return redirect()->route('main');
}
return redirect()->route('home');
}
else
{
return back()->withErrors(['email' => trans('auth.failed')]);
}
}catch(Exception $ex)
{
return back()->withErrors(['email' => trans('auth.failed')]);
}
}
</code></pre>
<p>I really don't know how to solve this, any help would be appreciated.</p>
| [
{
"answer_id": 74339556,
"author": "Albert Wijaya",
"author_id": 19570048,
"author_profile": "https://Stackoverflow.com/users/19570048",
"pm_score": 0,
"selected": false,
"text": "'password' => Hash::make($request->yourpassword)\n"
},
{
"answer_id": 74339559,
"author": "Tural Rzaxanov",
"author_id": 9922647,
"author_profile": "https://Stackoverflow.com/users/9922647",
"pm_score": 1,
"selected": false,
"text": "use Illuminate\\Support\\Facades\\Hash;\n\n$userValidated = DB::table('users')->where(['email' => $credentials['email'],'password'=> Hash::make($credentials['password'])])->first();\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13600579/"
] |
74,339,512 | <p>I wanted to ask how to create channels in discord.js 14 (i tried to researched but found nothing) I want to make a simple text channel! :)) Also, with the stuff i found, it worked ( no errors) it just didnt create anything / post errors in debug log</p>
| [
{
"answer_id": 74339567,
"author": "str1ng",
"author_id": 12826055,
"author_profile": "https://Stackoverflow.com/users/12826055",
"pm_score": 1,
"selected": false,
"text": " guild.channels.create({\n name: \"hello\",\n type: ChannelType.GuildText,\n parent: cat[0].ID,\n // your permission overwrites or other options here\n });\n"
},
{
"answer_id": 74344127,
"author": "FlameQuard",
"author_id": 20438436,
"author_profile": "https://Stackoverflow.com/users/20438436",
"pm_score": 0,
"selected": false,
"text": "//If the command is slash type\n\nconst { Permissions } = require(\"discord.js\")\n\ninteraction.guild.channels.create({\n name: \"new-channel\",\n type: 'GUILD_TEXT',\n permissionOverwrites: [\n {\n id: interaction.guild.id,\n accept: [Permissions.FLAGS.VIEW_CHANNEL],\n },\n ],\n});\n\n//If the command is message type\n\nconst { Permissions } = require(\"discord.js\")\n\nmessage.guild.channels.create({\n name: \"new-channel\",\n type: 'GUILD_TEXT',\n permissionOverwrites: [\n {\n id: message.guild.id,\n accept: [Permissions.FLAGS.VIEW_CHANNEL],\n },\n ],\n});\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18269108/"
] |
74,339,518 | <p>I need to extract all email addresses from all text files within a directory with a lot of subdirectories. It is to much work to do this manually. I wrote the python script below to automate this task. However, when I execute the script I end up with an empty array printed. No errors shown. Can one please indicate what I'm doing wrong</p>
<pre><code># Import Module
import os
import re
# Folder Path
path = "pat to the root directory"
# Change the directory
os.chdir(path)
#create list and index to add the emails
new_list = []
idx = 0
# I create a method to add all email address from within the subdirectories to add
them to an array
def read_text_file(file_path):
with open(file_path, 'r') as f:
emails = re.findall(r"[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+", str(f))
new_list.insert(idx, emails)
idx + 1
# iterate through all file and call the method from above
for file in os.listdir():
# Check whether file is in text format or not
if file.endswith(".txt"):
p = f"{path}\{file}"
# call read text file function
read_text_file(p)
#print the array
print (new_list)
</code></pre>
| [
{
"answer_id": 74339613,
"author": "Danielle M.",
"author_id": 3434388,
"author_profile": "https://Stackoverflow.com/users/3434388",
"pm_score": -1,
"selected": false,
"text": "list.insert()"
},
{
"answer_id": 74339704,
"author": "Omer Dagry",
"author_id": 15010874,
"author_profile": "https://Stackoverflow.com/users/15010874",
"pm_score": 1,
"selected": true,
"text": "os.listdir()"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5953578/"
] |
74,339,552 | <p>So I am doing some graphics rendering and have gotten to a point where the data being used is too high and run/loading time takes way too long. Completely my fault as I am copying a massive chucks (2+ gig) of data all over the place. Naturally I need to transition to pointers and here is the problem I face.</p>
<p>We have main data "vector data" and I need to access random areas (xyz points) in it.</p>
<pre><code>vector<float> data{1, 2, 3, ... , 101, 102, 103, ...};
float* point1 = &data[0] //points to beginning of array (1,2,3,...)
float* point2 = &data[100] //points to middle of array (101, 102, 103,...)
</code></pre>
<p>Now I need to make an output array that uses both pointers, but I'm not sure how to do this. In essence I want the following.</p>
<pre><code>float* outputList = point1;
outputList+3 = point2;
</code></pre>
<p>Such that output List = {1,2,3,101,102,103};
This wont work because I am trying to reassign the actual pointer address in the second line. The second major issue is that output list would go on after 103, and keep going till the end of the data vector. I know there are a few issues with this, but hopefully I got the idea across. Thank you for any advice.</p>
| [
{
"answer_id": 74339613,
"author": "Danielle M.",
"author_id": 3434388,
"author_profile": "https://Stackoverflow.com/users/3434388",
"pm_score": -1,
"selected": false,
"text": "list.insert()"
},
{
"answer_id": 74339704,
"author": "Omer Dagry",
"author_id": 15010874,
"author_profile": "https://Stackoverflow.com/users/15010874",
"pm_score": 1,
"selected": true,
"text": "os.listdir()"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5776660/"
] |
74,339,594 | <p>I have 3 data frame. 2 of them are only one column, another one is two columns.
3 dataframe looks like this</p>
<pre><code>Itemcode Itemcode2 Itemcode count
AAC AAC AAC 2
AAB AAB AAB 1
AAG AAF AAT 0
AAD AAD AAD 1
AAC AAF 1
</code></pre>
<p>If I want to check how many occurence of Itemcode and Itemcode2, I can use <code>value_counts()</code>.
Then if I want to combine them, I can not use pd.concat ([]) for the 3rd (it works if for 1 and 2 dataframe) because number of column is different.
How do I join these 3 data frame ?</p>
<p>This is the result I expected.</p>
<pre><code> df df2 df3
AAC 2 1 2
AAB 1 1 1
AAT 0 0 0
AAD 1 1 1
AAF 0 1 1
</code></pre>
<p>Thanks</p>
| [
{
"answer_id": 74339754,
"author": "Bushmaster",
"author_id": 15415267,
"author_profile": "https://Stackoverflow.com/users/15415267",
"pm_score": 0,
"selected": false,
"text": "df3 = df3.set_index('Itemcode').rename(columns={'count':'df3'})\na=df1.Itemcode.value_counts().rename('df1').to_frame()\nb=df2.Itemcode2.value_counts().rename('df2').to_frame()\nfinal=a.join(b).join(df3,how='right').fillna(0)\nfinal\n\nItemcode df1 df2 df3\nAAC 2.0 1.0 2\nAAB 1.0 1.0 1\nAAT 0.0 0.0 0\nAAD 1.0 1.0 1\nAAF 0.0 0.0 1\n\n"
},
{
"answer_id": 74340002,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "pandas.concat"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20434497/"
] |
74,339,694 | <p>I'm styling a <a href="https://moodle.org/?lang=pt_br" rel="nofollow noreferrer">moodle theme</a> and put this effect on nav:</p>
<p><img src="https://i.imgur.com/INjP5em.gif" alt="" /></p>
<p>But i don't want it to appear on "Active" nav: Only appearing on <strong>server</strong> and not on <strong>appeareance</strong></p>
<p>CSS:</p>
<pre class="lang-css prettyprint-override"><code>.nav-item .nav-link {
position: relative;
}
.nav-item .nav-link::after {
content: '';
position: absolute;
bottom: 0;
left: 50%;
width: 0%;
height: 1px;
background: #FFFFFF;
transition: 0.4s ease-out;
}
.nav-item .nav-link:hover::after {
left: 0;
width: 100%;
}
</code></pre>
<p>The "tree" of menu element:</p>
<p><img src="https://i.imgur.com/hPXTVnG.png" alt="" /></p>
| [
{
"answer_id": 74342178,
"author": "Sampat Aheer",
"author_id": 10835518,
"author_profile": "https://Stackoverflow.com/users/10835518",
"pm_score": 0,
"selected": false,
"text": ".active.nav-link:hover::after {\n width: 0;\n}\n"
},
{
"answer_id": 74344133,
"author": "reptofrog",
"author_id": 16909741,
"author_profile": "https://Stackoverflow.com/users/16909741",
"pm_score": 1,
"selected": false,
"text": ":not()"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10832965/"
] |
74,339,698 | <pre><code>import React, { useState } from "react";
import { v4 as uuidv4 } from 'uuid';
const ReturantInfo = ()=>{
const data = [
{
name: "Haaland Restaurant's",
stars: 5,
price:"100$",
ranking:"top 1 in england",
ids:[
{id:uuidv4(),key:uuidv4(),visibility:false},
{id:uuidv4(),key:uuidv4(),visibility:false},
{id:uuidv4(),key:uuidv4(),visibility:false},
]
}
]
const [restaurantData,setRestaurantData] = useState(data)
const CardElement = restaurantData.map((data)=>{
return(
<div style={{color:"white"}}>
<h1>{data.name}</h1>
<div>
<div>
<h1>Stars</h1>
<p
id={data.ids[0].id}
onClick={()=>toggleVisibility(data.ids[0].id)}
>show</p>
</div>
{ data.ids[0].visibility ? <p>{data.stars}</p> : ""}
</div>
<div>
<div>
<h1>Price</h1>
<p
id={data.ids[1].id}
onClick={()=>toggleVisibility(data.ids[1].id)}
>show</p>
</div>
{ data.ids[1].visibility ? <p>{data.price}</p> : ""}
</div>
<div>
<div>
<h1>Ranking</h1>
<p
id={data.ids[2].id}
onClick={()=>toggleVisibility(data.ids[2].id)}
>show</p>
</div>
{ data.ids[2].visibility ? <p>{data.ranking}</p> : ""}
</div>
</div>
)
})
function toggleVisibility(id) {
setRestaurantData((prevData) =>
prevData.map((data) => {
data.ids.map(h=>{
return h.id === id ? {...data,ids:[{...h,visibility:!h.visibility}]} : data
})
})
);
}
return(
<div>
{CardElement}
</div>
)
}
export default ReturantInfo
</code></pre>
<p>that's a small example from my project I want to toggle visibility property by depending on the id of the clicked element and then if it equals to the id in the array then change the visibility to the opposite.</p>
| [
{
"answer_id": 74342178,
"author": "Sampat Aheer",
"author_id": 10835518,
"author_profile": "https://Stackoverflow.com/users/10835518",
"pm_score": 0,
"selected": false,
"text": ".active.nav-link:hover::after {\n width: 0;\n}\n"
},
{
"answer_id": 74344133,
"author": "reptofrog",
"author_id": 16909741,
"author_profile": "https://Stackoverflow.com/users/16909741",
"pm_score": 1,
"selected": false,
"text": ":not()"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19786784/"
] |
74,339,729 | <p>I need to open multiple txt (all have the same number of variables and variables names, see picture[<a href="https://i.stack.imgur.com/1oz2n.jpg" rel="nofollow noreferrer">1</a>]); to each, add multiple columns with specific parts of their file name; then save a CSV resulting from merging all txts, with the added columns corresponding to each txt unique file name.</p>
<p>The file name looks like:</p>
<pre><code>NVR_ch2_main_20220505140000_20220505150000
</code></pre>
<p>and I need three columns:</p>
<pre><code>Month (05, the first of the two after 2022),
Day (05) and
hour (14).
</code></pre>
<p>Example of one of the txt sources of datawould</p>
<pre><code>dput(head('NVR_ch2_main_20220505132105_20220505140000.txt'))
# A tibble: 41 x 8
Selection View Channel Begin Time (s) End Time (s) Low Freq (Hz) High Freq (Hz)
type <dbl> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <lgl>
1 1 Waveform 1 1 790. 792. 0 4000 NA
# ... with 37 more rows
</code></pre>
<p>I managed the process with the whole file name for one file:</p>
<pre><code>read_tsv('NVR_ch2_main_20220505132105_20220505140000.txt') %>%
mutate(filename = 'NVR_ch2_main_20220505132105_20220505140000.txt') %>%
select(filename, everything ()) %>%
write_csv('C:/Users/marta/Documents/R/Crete/NVR_ch2_main_20220505132105_20220505140000.csv')
</code></pre>
| [
{
"answer_id": 74342178,
"author": "Sampat Aheer",
"author_id": 10835518,
"author_profile": "https://Stackoverflow.com/users/10835518",
"pm_score": 0,
"selected": false,
"text": ".active.nav-link:hover::after {\n width: 0;\n}\n"
},
{
"answer_id": 74344133,
"author": "reptofrog",
"author_id": 16909741,
"author_profile": "https://Stackoverflow.com/users/16909741",
"pm_score": 1,
"selected": false,
"text": ":not()"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20434880/"
] |
74,339,733 | <p>I am building a custom Keras layer that it is essentially the softmax function with a base parameter which is trainable. While the layer works on its own, when placed inside a sequential model, <code>model.summary()</code> determines its output shape as <code>None</code> and <code>model.fit()</code> raises a presumably linked exception:</p>
<blockquote>
<p>ValueError: as_list() is not defined on an unknown TensorShape.</p>
</blockquote>
<p>In other custom layers (including obviously the <a href="https://keras.io/guides/making_new_layers_and_models_via_subclassing/" rel="nofollow noreferrer">Linear example from keras</a>) the output shape can be determined after <code>.build()</code> is called. By looking at <code>model.summary()</code>'s source code, as well as <a href="https://keras.io/api/layers/base_layer/#layer-class" rel="nofollow noreferrer"><code>keras.layers.Layer</code></a>, there is this @property <code>Layer.output_shape</code> that fails to automatically determine the output shape.</p>
<p>Then I tried overwriting the property and manually returning the <code>input_shape</code> argument passed to my layer's <code>.build()</code> method after saving it (softmax does not change the shape of the input), but this didn't work either: If i make a call to <code>super().output_shape before returning my value, </code>model.summary() determines the shape as <code>?</code>, while if I don't, the value may be shown seemingly correct, but in both cases, I get the exact same error during .fit().</p>
<p>Is there something special about the code iside call() that prevents keras from understanding the shape of the output?<br />
Alteratively, is there a piece of documentation I have missed?</p>
<p>My layer:</p>
<pre class="lang-py prettyprint-override"><code>class B_Softmax(keras.layers.Layer):
def __init__(self, b_init_mean=10, b_init_var=0.001):
super(B_Softmax, self).__init__()
self.b_init = tf.random_normal_initializer(b_init_mean, b_init_var)
self._out_shape = None
def build(self, input_shape):
self.b = tf.Variable(
initial_value = self.b_init(shape=(1,), dtype='float32'),
trainable=True
)
self._out_shape = input_shape
def call(self, inputs):
# This is an implementation of Softmax for batched inputs
# where the factor b is added to the exponents
nominators = tf.math.exp(self.b * inputs)
denominator = tf.reduce_sum(nominators, axis=1)
denominator = tf.squeeze(denominator)
denominator = tf.expand_dims(denominator, -1)
s = tf.divide(nominators, denominator)
return s
@property
def output_shape(self): # If I comment out this function, summary prints 'None'
self.output_shape # If I leave this line, summary prints '?'
return self._out_shape # If the above line is commented out, summary prints '10' (correctly)
# but the same error is triggered in all three cases
</code></pre>
<p>The layer works on its own:</p>
<pre class="lang-py prettyprint-override"><code>>>> A = tf.constant([[1,2,3], [7,5,6]], dtype="float32")
>>> layer = B_Softmax(1.0)
>>> layer(A)
<tf.Tensor: shape=(2, 3), dtype=float32, numpy=
array([[0.08991686, 0.24461554, 0.6654676 ],
[0.6654677 , 0.08991687, 0.24461551]], dtype=float32)>
</code></pre>
<p>But when I try to include it inside a model, the summary doesn't look right:</p>
<pre class="lang-py prettyprint-override"><code>input_dim = 5
model = keras.Sequential([
Dense(32, activation='relu', input_shape=(input_dim,)),
Dense(num_classes, activation="softmax"),
B_Softmax(1.0)
])
model.summary()
</code></pre>
<pre><code>Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense_10 (Dense) (None, 32) 192
dense_11 (Dense) (None, 10) 330
b__softmax_18 (B_Softmax) None <-------------------1-------- "None", "?", or "10" (in a hacky way) may be printted
=================================================================
Total params: 523
Trainable params: 523
Non-trainable params: 0
</code></pre>
<p>And training fails:</p>
<pre class="lang-py prettyprint-override"><code>batch_size = 128
epochs = 15
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1)
</code></pre>
<pre><code>ValueError: in user code:
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1051, in train_function *
return step_function(self, iterator)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1040, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1030, in run_step **
outputs = model.train_step(data)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 894, in train_step
return self.compute_metrics(x, y, y_pred, sample_weight)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 987, in compute_metrics
self.compiled_metrics.update_state(y, y_pred, sample_weight)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/compile_utils.py", line 480, in update_state
self.build(y_pred, y_true)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/compile_utils.py", line 398, in build
y_pred)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/compile_utils.py", line 526, in _get_metric_objects
return [self._get_metric_object(m, y_t, y_p) for m in metrics]
File "/usr/local/lib/python3.7/dist-packages/keras/engine/compile_utils.py", line 526, in <listcomp>
return [self._get_metric_object(m, y_t, y_p) for m in metrics]
File "/usr/local/lib/python3.7/dist-packages/keras/engine/compile_utils.py", line 548, in _get_metric_object
y_p_rank = len(y_p.shape.as_list())
ValueError: as_list() is not defined on an unknown TensorShape.
</code></pre>
| [
{
"answer_id": 74340277,
"author": "Dr. Snoopy",
"author_id": 349130,
"author_profile": "https://Stackoverflow.com/users/349130",
"pm_score": 1,
"selected": false,
"text": "compute_output_shape"
},
{
"answer_id": 74340439,
"author": "xdurch0",
"author_id": 9393102,
"author_profile": "https://Stackoverflow.com/users/9393102",
"pm_score": 3,
"selected": true,
"text": "squeeze"
},
{
"answer_id": 74340612,
"author": "Jirayu Kaewprateep",
"author_id": 7848579,
"author_profile": "https://Stackoverflow.com/users/7848579",
"pm_score": 0,
"selected": false,
"text": "import tensorflow as tf\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Class / Definition\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nclass B_Softmax(tf.keras.layers.Layer):\n def __init__(self, b_init_mean=10, b_init_var=0.001):\n super(B_Softmax, self).__init__()\n self.b_init = tf.random_normal_initializer(b_init_mean, b_init_var)\n self._out_shape = None\n \n def build(self, input_shape):\n self.b = tf.Variable(\n initial_value = self.b_init(shape=(1,), dtype='float32'),\n trainable=True\n )\n self._out_shape = input_shape\n\n def call(self, inputs):\n # This is an implementation of Softmax for batched inputs\n # where the factor b is added to the exponents\n nominators = tf.math.exp(self.b * inputs)\n denominator = tf.reduce_sum(nominators, axis=1)\n denominator = tf.squeeze(denominator)\n denominator = tf.expand_dims(denominator, -1)\n s = tf.divide(nominators, denominator)\n return s\n\n # @property\n # def output_shape(self): # If I comment out this function, summary prints 'None'\n # self.output_shape # If I leave this line, summary prints '?' \n # return self._out_shape # If the above line is commented out, summary prints '10' (correctly)\n # but the same error is triggered in all three cases\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Variables\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" \nA = tf.constant([[1,2,3], [7,5,6]], dtype=\"float32\")\n\nbatch_size = 128\nepochs = 15\ninput_dim = 5\nnum_classes = 1\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Dataset\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nstart = 3\nlimit = 16\ndelta = 3\nsample = tf.range( start, limit, delta )\nsample = tf.cast( sample, dtype=tf.float32 )\nsample = tf.constant( sample, shape=( 1, 1, 1, 5 ) )\ndataset = tf.data.Dataset.from_tensor_slices(( sample, tf.constant( [0], shape=( 1, 1, 1, 1 ), dtype=tf.int64)))\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Model Initialize\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" \nlayer = B_Softmax(1.0)\nprint( layer(A) )\n\nmodel = tf.keras.Sequential([\n tf.keras.layers.Dense(32, activation='relu', input_shape=(1, input_dim)),\n tf.keras.layers.Dense(num_classes, activation=\"softmax\"),\n B_Softmax(1.0)\n])\nmodel.summary()\n\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Working\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" \nmodel.fit(dataset, batch_size=batch_size, epochs=epochs, validation_data=dataset)\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6942918/"
] |
74,339,734 | <pre><code> df1:
Customer Manager Time Period Amount
Samsung Rosalie 90D 46726190
Samsung Rosalie 18M 46726190
Samsung Rosalie 18M 46726190
Samsung Rosalie 18M 46726190
Samsung Rosalie 30D 46726190
Samsung Rosalie 30D 46726190
Apple Abir 24M 359233179
Apple Abir 30D 359233179
Apple Abir 30D 25000000
Nokia Abir 90D 571711209
Nokia Abir 24M 571711209
Nokia Abir 24M -284461
Nokia Abir 1M 571711209
Nokia Abir 1M 49715539
Google Michael 90D 49850165
Google Michael 12M 49850165
Google Michael 12M 49850165
Google Michael 12M 33048028
Google Michael 12M 49850165
Google Michael 12M 33048028
Blackberry Zec 90D 27975518
Blackberry Zec 18M 27975518
Blackberry Zec 30D 27975518
Blackberry Zec 30D 27975518
Expected Output
df1:
Customer Manager Time Period Amount
Samsung Rosalie Navarrete 90D 46726190
Samsung Rosalie Navarrete 18M 46726190
Samsung Rosalie Navarrete 18M 46726190
Samsung Rosalie Navarrete 18M 46726190
Samsung Rosalie Navarrete 30D 46726190
Samsung Rosalie Navarrete 30D 46726190
Apple Abir Paul 24M 359233179
Apple Abir Paul 30D 359233179
Apple Abir Paul 30D 25000000
Nokia Abir Paul 90D 571711209
Nokia Abir Paul 24M 571711209
Nokia Abir Paul 24M -284461
Nokia Abir Paul 1M 571711209
Nokia Abir Paul 1M 49715539
Google MichaelZec 90D 49850165
Google MichaelZec 12M 49850165
Google MichaelZec 12M 49850165
Google MichaelZec 12M 33048028
Google MichaelZec 12M 49850165
Google MichaelZec 12M 33048028
How to add a blank row after each of the customer in dataframe, as shown in expected output?
</code></pre>
<p>Tried Code:</p>
<p>for index, row in df.iterrrows():
if df.loc[index,'Customer Code'] != df.loc[index+1,'Customer Code'] and not(pd.isna(df.iloc[index,'Customer Code'])) and not(pd.isna(df.iloc[index+1,'Type']))
df.loc[index+1] = pd.Series([np.nan,np.nan, np.nan, np.nan])</p>
| [
{
"answer_id": 74340277,
"author": "Dr. Snoopy",
"author_id": 349130,
"author_profile": "https://Stackoverflow.com/users/349130",
"pm_score": 1,
"selected": false,
"text": "compute_output_shape"
},
{
"answer_id": 74340439,
"author": "xdurch0",
"author_id": 9393102,
"author_profile": "https://Stackoverflow.com/users/9393102",
"pm_score": 3,
"selected": true,
"text": "squeeze"
},
{
"answer_id": 74340612,
"author": "Jirayu Kaewprateep",
"author_id": 7848579,
"author_profile": "https://Stackoverflow.com/users/7848579",
"pm_score": 0,
"selected": false,
"text": "import tensorflow as tf\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Class / Definition\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nclass B_Softmax(tf.keras.layers.Layer):\n def __init__(self, b_init_mean=10, b_init_var=0.001):\n super(B_Softmax, self).__init__()\n self.b_init = tf.random_normal_initializer(b_init_mean, b_init_var)\n self._out_shape = None\n \n def build(self, input_shape):\n self.b = tf.Variable(\n initial_value = self.b_init(shape=(1,), dtype='float32'),\n trainable=True\n )\n self._out_shape = input_shape\n\n def call(self, inputs):\n # This is an implementation of Softmax for batched inputs\n # where the factor b is added to the exponents\n nominators = tf.math.exp(self.b * inputs)\n denominator = tf.reduce_sum(nominators, axis=1)\n denominator = tf.squeeze(denominator)\n denominator = tf.expand_dims(denominator, -1)\n s = tf.divide(nominators, denominator)\n return s\n\n # @property\n # def output_shape(self): # If I comment out this function, summary prints 'None'\n # self.output_shape # If I leave this line, summary prints '?' \n # return self._out_shape # If the above line is commented out, summary prints '10' (correctly)\n # but the same error is triggered in all three cases\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Variables\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" \nA = tf.constant([[1,2,3], [7,5,6]], dtype=\"float32\")\n\nbatch_size = 128\nepochs = 15\ninput_dim = 5\nnum_classes = 1\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Dataset\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nstart = 3\nlimit = 16\ndelta = 3\nsample = tf.range( start, limit, delta )\nsample = tf.cast( sample, dtype=tf.float32 )\nsample = tf.constant( sample, shape=( 1, 1, 1, 5 ) )\ndataset = tf.data.Dataset.from_tensor_slices(( sample, tf.constant( [0], shape=( 1, 1, 1, 1 ), dtype=tf.int64)))\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Model Initialize\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" \nlayer = B_Softmax(1.0)\nprint( layer(A) )\n\nmodel = tf.keras.Sequential([\n tf.keras.layers.Dense(32, activation='relu', input_shape=(1, input_dim)),\n tf.keras.layers.Dense(num_classes, activation=\"softmax\"),\n B_Softmax(1.0)\n])\nmodel.summary()\n\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Working\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" \nmodel.fit(dataset, batch_size=batch_size, epochs=epochs, validation_data=dataset)\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19446467/"
] |
74,339,763 | <p>I want to store several <strong>general extension settings and specific website settings</strong>.</p>
<p>I need to save a website name if it's not yet saved and according to its number retrieve the individual settings.</p>
<p>Would the below setup be the best approach using an object with object for websites number & name (key/value) while for website settings array with objects that use the number of the arrays of the website?</p>
<p>And how can I do a check if a website is saved and then return its settings?
Do i need to use indexof or findIndex?</p>
<pre><code>const extensionsettings = {
websites: {
1: 'website 1',
2: 'website 2',
3: 'website 3'
},
websitesettings: [
{
1: {
color: 'green',
size: '12'
},
},
{
2: {
color: 'red',
size: '10'
}
},
{
3: {
color: 'blue',
size: '20'
}
}
],
general: {
optionalsetting1: 'yes',
optionalsetting2: 'no'
},
};
</code></pre>
| [
{
"answer_id": 74339937,
"author": "Dakeyras",
"author_id": 1857909,
"author_profile": "https://Stackoverflow.com/users/1857909",
"pm_score": 3,
"selected": true,
"text": "websiteSettings"
},
{
"answer_id": 74340181,
"author": "Cat",
"author_id": 8223070,
"author_profile": "https://Stackoverflow.com/users/8223070",
"pm_score": 1,
"selected": false,
"text": "// Demonstates info retrieval\nconst settingsGlobal = getExtensionSettings();\nlogSiteInfo('website 3');\nlogSiteInfo('website 42');\n\nfunction logSiteInfo(website){\n const siteInfo = getSiteInfo(website, settingsGlobal);\n console.log(`${website}:`);\n console.log(siteInfo ?? \" ...not found\");\n}\n\n// For each stored website: if value matches needle, uses key to get settings\nfunction getSiteInfo(needle, haystack){\n const entries = Object.entries(haystack.websites); // entries are len-2 arrays\n for(const [key, value] of entries){ // Destructures each entry\n if(value === needle){\n return haystack.websiteSettings[key];\n }\n }\n return null; // Desired website value was not found\n}\n\n// Provides storage object\nfunction getExtensionSettings(){\n const extensionSettings = {\n websites: { 1: 'website 1', 2: 'website 2', 3: 'website 3' },\n websiteSettings: {\n 1: { color: 'green', size: '12' },\n 2: { color: 'red', size: '10' },\n 3: { color: 'blue', size: '20' }\n },\n general: { optionalsetting1: 'yes', optionalsetting2: 'no' }\n };\n return extensionSettings;\n}"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8719001/"
] |
74,339,765 | <p>We are trying to use one single <code>.gradle</code> cache among our multiple build workers (in jenkins) by creating <code>.gradle</code> in <strong>NFS</strong> mount which is shared with all the workers.</p>
<p>Now when we run multiple projects using gradle builds, they get failed with following errors:</p>
<pre><code>Timeout waiting to lock artifact cache (/common/user/.gradle/caches/modules-2). It is currently in use by another Gradle instance.
Owner PID: 1XXXX
Our PID: 1XXXX
Owner Operation: resolve configuration ':classpath’
Our operation: resolve configuration ':classpath’
Lock file: /common/user/.gradle/caches/modules-2/modules-2.lock
</code></pre>
<p>What is the suggestive method to use <code>.gradle</code> cache sharing among multiple users. This model works fine for maven <code>.m2</code> cache.</p>
<p>We cannot have .gradle for each workers as it occupies lot of space to store the jars in cache.</p>
| [
{
"answer_id": 74339937,
"author": "Dakeyras",
"author_id": 1857909,
"author_profile": "https://Stackoverflow.com/users/1857909",
"pm_score": 3,
"selected": true,
"text": "websiteSettings"
},
{
"answer_id": 74340181,
"author": "Cat",
"author_id": 8223070,
"author_profile": "https://Stackoverflow.com/users/8223070",
"pm_score": 1,
"selected": false,
"text": "// Demonstates info retrieval\nconst settingsGlobal = getExtensionSettings();\nlogSiteInfo('website 3');\nlogSiteInfo('website 42');\n\nfunction logSiteInfo(website){\n const siteInfo = getSiteInfo(website, settingsGlobal);\n console.log(`${website}:`);\n console.log(siteInfo ?? \" ...not found\");\n}\n\n// For each stored website: if value matches needle, uses key to get settings\nfunction getSiteInfo(needle, haystack){\n const entries = Object.entries(haystack.websites); // entries are len-2 arrays\n for(const [key, value] of entries){ // Destructures each entry\n if(value === needle){\n return haystack.websiteSettings[key];\n }\n }\n return null; // Desired website value was not found\n}\n\n// Provides storage object\nfunction getExtensionSettings(){\n const extensionSettings = {\n websites: { 1: 'website 1', 2: 'website 2', 3: 'website 3' },\n websiteSettings: {\n 1: { color: 'green', size: '12' },\n 2: { color: 'red', size: '10' },\n 3: { color: 'blue', size: '20' }\n },\n general: { optionalsetting1: 'yes', optionalsetting2: 'no' }\n };\n return extensionSettings;\n}"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19513849/"
] |
74,339,774 | <p>I am new on Node.js and I have app.js file like:</p>
<pre><code>const express = require('express');
const app = express();
const port = 8080;
app.get('/', (req, res) => res.send('Hello World'));
app.listen(port);
console.log(`App running on http://localhost:${port}`);
</code></pre>
<p>I also have index.html file in the same folder with app.js. Here there is a HTML5 website.
When I run the project I can see Hello World text in browser, How can I show this HTML file from my app.js so when I deploy it, it should show me responsive HTML file instead of Hello World?</p>
<p>I tried</p>
<pre><code>app.get('/',function(req,res) {
res.sendFile('index.html');
});
</code></pre>
<p>But didn't see a difference.</p>
| [
{
"answer_id": 74339937,
"author": "Dakeyras",
"author_id": 1857909,
"author_profile": "https://Stackoverflow.com/users/1857909",
"pm_score": 3,
"selected": true,
"text": "websiteSettings"
},
{
"answer_id": 74340181,
"author": "Cat",
"author_id": 8223070,
"author_profile": "https://Stackoverflow.com/users/8223070",
"pm_score": 1,
"selected": false,
"text": "// Demonstates info retrieval\nconst settingsGlobal = getExtensionSettings();\nlogSiteInfo('website 3');\nlogSiteInfo('website 42');\n\nfunction logSiteInfo(website){\n const siteInfo = getSiteInfo(website, settingsGlobal);\n console.log(`${website}:`);\n console.log(siteInfo ?? \" ...not found\");\n}\n\n// For each stored website: if value matches needle, uses key to get settings\nfunction getSiteInfo(needle, haystack){\n const entries = Object.entries(haystack.websites); // entries are len-2 arrays\n for(const [key, value] of entries){ // Destructures each entry\n if(value === needle){\n return haystack.websiteSettings[key];\n }\n }\n return null; // Desired website value was not found\n}\n\n// Provides storage object\nfunction getExtensionSettings(){\n const extensionSettings = {\n websites: { 1: 'website 1', 2: 'website 2', 3: 'website 3' },\n websiteSettings: {\n 1: { color: 'green', size: '12' },\n 2: { color: 'red', size: '10' },\n 3: { color: 'blue', size: '20' }\n },\n general: { optionalsetting1: 'yes', optionalsetting2: 'no' }\n };\n return extensionSettings;\n}"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3226924/"
] |
74,339,807 | <p>I previously used datagridview but now changed it to use a datatable
`</p>
<pre><code> private void table()
{
//create a data set
DataSet ds = new DataSet();
//create a data table for the data set
DataTable dt = new DataTable();
//create some columns for the datatable
DataColumn dc = new DataColumn("Name");
DataColumn dc2 = new DataColumn("Entry");
DataColumn dc3 = new DataColumn("SL");
DataColumn dc4 = new DataColumn("SL%");
DataColumn dc5 = new DataColumn("TP");
DataColumn dc6 = new DataColumn("TP%");
DataColumn dc7 = new DataColumn("Position");
DataColumn dc8 = new DataColumn("Day");
DataColumn dc9 = new DataColumn("Notes");
//add the columns to the datatable
dt.Columns.Add(dc);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
dt.Columns.Add(dc4);
dt.Columns.Add(dc5);
dt.Columns.Add(dc6);
dt.Columns.Add(dc7);
dt.Columns.Add(dc8);
dt.Columns.Add(dc9);
//add the datatable to the datasource
ds.Tables.Add(dt);
//make this data the datasource of our gridview
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.AutoSize = true;
}
</code></pre>
<p>`</p>
<p>When using datagridview i used this code on a button click event to add a row
<code>dataGridView1.Rows.Add(name, EntryPrice.Text, StopPrice.Text, slper, ProfitPrice.Text, tpper, pos, day, NotesTB.Text);</code></p>
<p>How do I add a row to the datatable with the same values using a button click event?</p>
<p>Using
<code>dt.Rows.Add</code>
isnt recognising the dt within my button click</p>
| [
{
"answer_id": 74339937,
"author": "Dakeyras",
"author_id": 1857909,
"author_profile": "https://Stackoverflow.com/users/1857909",
"pm_score": 3,
"selected": true,
"text": "websiteSettings"
},
{
"answer_id": 74340181,
"author": "Cat",
"author_id": 8223070,
"author_profile": "https://Stackoverflow.com/users/8223070",
"pm_score": 1,
"selected": false,
"text": "// Demonstates info retrieval\nconst settingsGlobal = getExtensionSettings();\nlogSiteInfo('website 3');\nlogSiteInfo('website 42');\n\nfunction logSiteInfo(website){\n const siteInfo = getSiteInfo(website, settingsGlobal);\n console.log(`${website}:`);\n console.log(siteInfo ?? \" ...not found\");\n}\n\n// For each stored website: if value matches needle, uses key to get settings\nfunction getSiteInfo(needle, haystack){\n const entries = Object.entries(haystack.websites); // entries are len-2 arrays\n for(const [key, value] of entries){ // Destructures each entry\n if(value === needle){\n return haystack.websiteSettings[key];\n }\n }\n return null; // Desired website value was not found\n}\n\n// Provides storage object\nfunction getExtensionSettings(){\n const extensionSettings = {\n websites: { 1: 'website 1', 2: 'website 2', 3: 'website 3' },\n websiteSettings: {\n 1: { color: 'green', size: '12' },\n 2: { color: 'red', size: '10' },\n 3: { color: 'blue', size: '20' }\n },\n general: { optionalsetting1: 'yes', optionalsetting2: 'no' }\n };\n return extensionSettings;\n}"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20432584/"
] |
74,339,815 | <p>Define a function convert(input str) to return a list of characters based on the input
string input str. Specifically, each character in input str will be included as a separate element of
the returned list, while any spaces in input str will be ignored</p>
<pre><code>def convert(input_str):
newlist = []
reallist = [char for char in input_str]
for k in input_str:
if k:
newlist.append(k)
return newlist
print(convert("Hi You"))
</code></pre>
<p>this gives output</p>
<pre><code>['H', 'i', ' ', 'Y', 'o', 'u']
</code></pre>
<p>but I do not want the empty space between i and y</p>
| [
{
"answer_id": 74339842,
"author": "Omer Dagry",
"author_id": 15010874,
"author_profile": "https://Stackoverflow.com/users/15010874",
"pm_score": 0,
"selected": false,
"text": "if char != \" \":"
},
{
"answer_id": 74339846,
"author": "Jimpsoni",
"author_id": 18195201,
"author_profile": "https://Stackoverflow.com/users/18195201",
"pm_score": 0,
"selected": false,
"text": "def convert(input_str):\n # Replace whitespaces with nothing\n input_str = input_str.replace(\" \", \"\")\n\n new_list = [char for char in input_str]\n return new_list\n\n\nprint(convert(\"Hi You\"))\n"
},
{
"answer_id": 74339848,
"author": "Shen",
"author_id": 16037571,
"author_profile": "https://Stackoverflow.com/users/16037571",
"pm_score": 0,
"selected": false,
"text": "def convert(input_str):\n newstr = \"\".join(input_str.split())\n reallist = [char for char in newstr]\n return reallist\n\nprint(convert(\"Hi You\"))\n\n"
},
{
"answer_id": 74339895,
"author": "j1-lee",
"author_id": 11450820,
"author_profile": "https://Stackoverflow.com/users/11450820",
"pm_score": 2,
"selected": false,
"text": "if"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20430206/"
] |
74,339,843 | <p>I am facing this for the first time and I have no options on how to do it. I read many forums and did not find anything like this anywhere. I need to do as in the picture, how can I do it<br />
This is a sample of how it should turn out:
<a href="https://i.stack.imgur.com/VpRua.png" rel="nofollow noreferrer">enter image description here</a></p>
<pre><code> Padding(padding: const EdgeInsets.only(top: 15),
child: Row(
children: const [
CircleAvatar(
backgroundColor: Colors.white,
radius: 18,
child: CircleAvatar(
radius: 16,
backgroundImage: AssetImage('lib/assets/avatar-410658-028235png.png'),
),
),
CircleAvatar(
backgroundColor: Colors.white,
radius: 18,
child: CircleAvatar(
radius: 16,
backgroundImage: AssetImage('lib/assets/avatar-410658-028235png.png'),
),
),
CircleAvatar(
backgroundColor: Colors.white,
radius: 18,
child: CircleAvatar(
radius: 16,
backgroundImage: AssetImage('lib/assets/avatar-410658-028235png.png'),
),
),
CircleAvatar(
backgroundColor: Colors.white,
radius: 20,
child: CircleAvatar(
radius: 18,
backgroundColor: Colors.black,
child: Text('28', style: TextStyle(fontSize: 12.5, color: Colors.white ),),
)
),
Padding(padding: EdgeInsets.only(left: 70) ,
child: Text('6 Hours Ago', style: TextStyle(fontSize: 12.5),)
),
],
),
),
</code></pre>
| [
{
"answer_id": 74339842,
"author": "Omer Dagry",
"author_id": 15010874,
"author_profile": "https://Stackoverflow.com/users/15010874",
"pm_score": 0,
"selected": false,
"text": "if char != \" \":"
},
{
"answer_id": 74339846,
"author": "Jimpsoni",
"author_id": 18195201,
"author_profile": "https://Stackoverflow.com/users/18195201",
"pm_score": 0,
"selected": false,
"text": "def convert(input_str):\n # Replace whitespaces with nothing\n input_str = input_str.replace(\" \", \"\")\n\n new_list = [char for char in input_str]\n return new_list\n\n\nprint(convert(\"Hi You\"))\n"
},
{
"answer_id": 74339848,
"author": "Shen",
"author_id": 16037571,
"author_profile": "https://Stackoverflow.com/users/16037571",
"pm_score": 0,
"selected": false,
"text": "def convert(input_str):\n newstr = \"\".join(input_str.split())\n reallist = [char for char in newstr]\n return reallist\n\nprint(convert(\"Hi You\"))\n\n"
},
{
"answer_id": 74339895,
"author": "j1-lee",
"author_id": 11450820,
"author_profile": "https://Stackoverflow.com/users/11450820",
"pm_score": 2,
"selected": false,
"text": "if"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20350574/"
] |
74,339,844 | <p>I have this class:</p>
<pre><code>public class user
{
public string FirstName { get; set; }
public string LastName { get; set; }
public EyeColor EyeColor { get; set; }
}
public enum EyeColor
{
Brown,
Black
}
</code></pre>
<p>I can use <code>user.GetType().GetProperties();</code> to get properties and then get values of them. <br>
But for enums is different, all I want to do is: getting Enum index, for example brown is <code>0</code> and black is <code>1</code> for dynamic search on enum fields.<br />
But I have a generic method to get index and I can't use <code>int enumIndex = (EyeColor)user.EyeColor;</code> because I don't know what kind of enum will be pass to the generic method.</p>
<pre><code>public static IQueryable<T> CreateEqualExpressions<T>(IQueryable<T> query, object model)
{
var result = query;
var propertiesToSearch = model.GetType().GetProperties()
.Where(x => Attribute.IsDefined(x, typeof(EqualSearchAttribute)))
.ToList();
if (propertiesToSearch.Count > 0)
{
foreach (var propertyInfo in propertiesToSearch)
{
var propertyValue = propertyInfo.GetValue(model);
if (!string.IsNullOrWhiteSpace(propertyValue?.ToString()))
{
var parameter = Expression.Parameter(typeof(T));
var property = Expression.Property(parameter, propertyInfo.Name);
if (propertyValue is string)
propertyValue = propertyValue.ToString()?.Trim();
var constantValue = Expression.Constant(propertyValue);
var equal = Expression.Equal(property, constantValue);
var exp = Expression.Lambda<Func<T, bool>>(equal, parameter);
result = result.Where(exp);
}
}
}
return result;
}
</code></pre>
<p>Everything is ok for strings but for enums not works because <code>propertyValue</code> is: <code>Brown</code> or <code>Black</code>, but for dynamic search, I need to index of them like <code>0</code> or <code>1</code>.
Any suggestion ?</p>
| [
{
"answer_id": 74339842,
"author": "Omer Dagry",
"author_id": 15010874,
"author_profile": "https://Stackoverflow.com/users/15010874",
"pm_score": 0,
"selected": false,
"text": "if char != \" \":"
},
{
"answer_id": 74339846,
"author": "Jimpsoni",
"author_id": 18195201,
"author_profile": "https://Stackoverflow.com/users/18195201",
"pm_score": 0,
"selected": false,
"text": "def convert(input_str):\n # Replace whitespaces with nothing\n input_str = input_str.replace(\" \", \"\")\n\n new_list = [char for char in input_str]\n return new_list\n\n\nprint(convert(\"Hi You\"))\n"
},
{
"answer_id": 74339848,
"author": "Shen",
"author_id": 16037571,
"author_profile": "https://Stackoverflow.com/users/16037571",
"pm_score": 0,
"selected": false,
"text": "def convert(input_str):\n newstr = \"\".join(input_str.split())\n reallist = [char for char in newstr]\n return reallist\n\nprint(convert(\"Hi You\"))\n\n"
},
{
"answer_id": 74339895,
"author": "j1-lee",
"author_id": 11450820,
"author_profile": "https://Stackoverflow.com/users/11450820",
"pm_score": 2,
"selected": false,
"text": "if"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16180500/"
] |
74,339,864 | <p>I am currently experimenting with tkinter in python, but I couldnt figure out how to turn the string that is written inside an Entry to an integer.</p>
<pre><code>from tkinter import *
window = Tk()
erstertext = Label(window, text="Hi! You have to enter your information for this program.")
erstertext.pack()
agetext = Label(window, text="Age:")
agetext.pack()
ageinput = Entry(window,)
ageinput.pack()
nametext = Label(window, text="First Name:")
nametext.pack()
nameinput = Entry(window,)
nameinput.pack()
x = ageinput.get()
def callback():
if x >= 18:
Text1 = Label(window, text="Hi " + nameinput.get() + " , you are " + ageinput.get() + "or older")
Text1.pack()
else:
Text2 = Label(window, text="Hi " + nameinput.get() + " ur younger than 18")
Text2.pack()
button1 = Button(window, text="Done",command=callback)
button1.pack()
window.mainloop()
</code></pre>
<p>The relevant part:</p>
<pre><code>from tkinter import *
agetext = Label(window, text="Age:")
agetext.pack()
ageinput = Entry(window,)
ageinput.pack()
x = ageinput.get()
def callback():
if x >= 18:
Text1 = Label(window, text="Hi " + nameinput.get() + " , you are " + ageinput.get() + "or older")
Text1.pack()
</code></pre>
<p>I currently use Python 3.9</p>
<p>I tried turning x into an integer in the callback section</p>
<pre><code>def callback():
if int(x) >= 18:
Text1 = Label(window, text="Hi " + nameinput.get() + " , you are " + ageinput.get() + "or older")
Text1.pack()
</code></pre>
<p>still didnt work. Then I tried putting the ageinput.get directly into a int</p>
<pre><code>def callback():
if int(ageinput.get) >= 18:
Text1 = Label(window, text="Hi " + nameinput.get() + " , you are " + ageinput.get() + "or older")
Text1.pack()
</code></pre>
<p>and it doesnt work either.</p>
| [
{
"answer_id": 74339842,
"author": "Omer Dagry",
"author_id": 15010874,
"author_profile": "https://Stackoverflow.com/users/15010874",
"pm_score": 0,
"selected": false,
"text": "if char != \" \":"
},
{
"answer_id": 74339846,
"author": "Jimpsoni",
"author_id": 18195201,
"author_profile": "https://Stackoverflow.com/users/18195201",
"pm_score": 0,
"selected": false,
"text": "def convert(input_str):\n # Replace whitespaces with nothing\n input_str = input_str.replace(\" \", \"\")\n\n new_list = [char for char in input_str]\n return new_list\n\n\nprint(convert(\"Hi You\"))\n"
},
{
"answer_id": 74339848,
"author": "Shen",
"author_id": 16037571,
"author_profile": "https://Stackoverflow.com/users/16037571",
"pm_score": 0,
"selected": false,
"text": "def convert(input_str):\n newstr = \"\".join(input_str.split())\n reallist = [char for char in newstr]\n return reallist\n\nprint(convert(\"Hi You\"))\n\n"
},
{
"answer_id": 74339895,
"author": "j1-lee",
"author_id": 11450820,
"author_profile": "https://Stackoverflow.com/users/11450820",
"pm_score": 2,
"selected": false,
"text": "if"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20435019/"
] |
74,339,867 | <p>So I have faced an interesting thing in my React Native Code. Can you guys explain why it ' s happening like that?</p>
<pre><code>import React, { useState, useEffect } from "react";
import { SafeAreaView, Text, FlatList } from "react-native";
import config from "../../../config";
import axios from "axios";
import ProductCard from "../../components/ProductCard/ProductCard";
const Products = () => {
const [data, setData] = useState([]);
useEffect(() => {
fetchData();
}, []);
const fetchData = async () => {
const { data: productData } = await axios.get(config.API_URL);
setData(productData);
};
const renderProduct = ({ item }) => <ProductCard product={item} />;
return (
<SafeAreaView>
<FlatList data={data} renderItem={renderProduct} />
</SafeAreaView>
);
};
export default Products;
</code></pre>
<p>İn the ProductCard component I am basically formating output to look nice like below. There is no magic over there.</p>
<p><a href="https://i.stack.imgur.com/9rac9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9rac9.jpg" alt="enter image description here" /></a></p>
<p>Then I want you to guys look at renderProduct function
when I code it like that with curly braces :</p>
<pre><code> const renderProduct = ({ item }) => {
<ProductCard product={item} />;
};
</code></pre>
<p>the output is being like below :
<a href="https://i.stack.imgur.com/g2a8l.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g2a8l.jpg" alt="enter image description here" /></a></p>
<p>I couldn't understand why Honestly. what is the magic with curly braces?</p>
<p>İf this explanation is not enough just tell me to add other things:)</p>
| [
{
"answer_id": 74339842,
"author": "Omer Dagry",
"author_id": 15010874,
"author_profile": "https://Stackoverflow.com/users/15010874",
"pm_score": 0,
"selected": false,
"text": "if char != \" \":"
},
{
"answer_id": 74339846,
"author": "Jimpsoni",
"author_id": 18195201,
"author_profile": "https://Stackoverflow.com/users/18195201",
"pm_score": 0,
"selected": false,
"text": "def convert(input_str):\n # Replace whitespaces with nothing\n input_str = input_str.replace(\" \", \"\")\n\n new_list = [char for char in input_str]\n return new_list\n\n\nprint(convert(\"Hi You\"))\n"
},
{
"answer_id": 74339848,
"author": "Shen",
"author_id": 16037571,
"author_profile": "https://Stackoverflow.com/users/16037571",
"pm_score": 0,
"selected": false,
"text": "def convert(input_str):\n newstr = \"\".join(input_str.split())\n reallist = [char for char in newstr]\n return reallist\n\nprint(convert(\"Hi You\"))\n\n"
},
{
"answer_id": 74339895,
"author": "j1-lee",
"author_id": 11450820,
"author_profile": "https://Stackoverflow.com/users/11450820",
"pm_score": 2,
"selected": false,
"text": "if"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15648347/"
] |
74,339,868 | <p>I am creating a div in css with two elements split into two columns. My goal is to have one element be two-thirds of the page, and another to be a third. The columns will also collapse when the page size reaches a certain minimum width, and have each element take up the entire width of the page.</p>
<p>When I use the following:</p>
<pre class="lang-css prettyprint-override"><code>grid-template-columns: repeat(auto-fill,minmax(570px,1fr));
</code></pre>
<p>CSS divides the two elements into equal size columns which collapse under 570 px</p>
<p>When I attempt to resize the first column to be larger:</p>
<pre class="lang-css prettyprint-override"><code>grid-template-columns: minmax(570px,1fr) 1fr;
</code></pre>
<p>neither column is responsive to the page, and do not collapse under any size. Instead the page can go over the elements and cover them.</p>
<p>How can I allow for the responsive page without the repeat function causing both grid elements to be of equal size?</p>
| [
{
"answer_id": 74339842,
"author": "Omer Dagry",
"author_id": 15010874,
"author_profile": "https://Stackoverflow.com/users/15010874",
"pm_score": 0,
"selected": false,
"text": "if char != \" \":"
},
{
"answer_id": 74339846,
"author": "Jimpsoni",
"author_id": 18195201,
"author_profile": "https://Stackoverflow.com/users/18195201",
"pm_score": 0,
"selected": false,
"text": "def convert(input_str):\n # Replace whitespaces with nothing\n input_str = input_str.replace(\" \", \"\")\n\n new_list = [char for char in input_str]\n return new_list\n\n\nprint(convert(\"Hi You\"))\n"
},
{
"answer_id": 74339848,
"author": "Shen",
"author_id": 16037571,
"author_profile": "https://Stackoverflow.com/users/16037571",
"pm_score": 0,
"selected": false,
"text": "def convert(input_str):\n newstr = \"\".join(input_str.split())\n reallist = [char for char in newstr]\n return reallist\n\nprint(convert(\"Hi You\"))\n\n"
},
{
"answer_id": 74339895,
"author": "j1-lee",
"author_id": 11450820,
"author_profile": "https://Stackoverflow.com/users/11450820",
"pm_score": 2,
"selected": false,
"text": "if"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16752502/"
] |
74,339,891 | <p>I am trying to create a folder structure for audit logs that gets generated by the AIX system and Database</p>
<p>Below is a simple example of a file in a folder:</p>
<pre><code>ls -l /opt/audit/move/
</code></pre>
<p>Output:</p>
<pre><code>-rw-r--r-- 1 gl_user user 0 18 Aug 2019 test1.txt
-rw-r--r-- 1 gl_user user 0 06 Nov 18:55 test2.txt
</code></pre>
<p>The problem with the above ls -l command is that recent files in column 8 displays time instead of the year. I could of used awk and a for loop to get the month and year for the file, but this is not an option as seen above</p>
<p>The idea is to move the files in the below folder structure:</p>
<pre><code># ls -l /opt/audit/2019/August/test1.txt
-rw-r--r-- 1 gl_user user 0 18 Aug 2019 test1.txt
# ls -l /opt/audit/2022/November/test2.txt
-rw-r--r-- 1 gl_user user 0 06 Nov 18:55 test2.txt
</code></pre>
| [
{
"answer_id": 74339907,
"author": "Christopher Karsten",
"author_id": 5607499,
"author_profile": "https://Stackoverflow.com/users/5607499",
"pm_score": 0,
"selected": false,
"text": "INFORLOG_BKP=\"/opt/audit\"\nfor i in `ls ${INFORLOG_BKP}/move`\ndo\nFILE_MONTH=`istat ${INFORLOG_BKP}/move/$i | grep -w \"Last modified:\" | awk '{print $5}'`\nFILE_YEAR=`istat ${INFORLOG_BKP}/move/$i | grep -w \"Last modified:\" | awk '{print $6}'`\n\ncase $FILE_MONTH\nin\n Jan) MONTH_STRING=January\n ;;\n Feb) MONTH_STRING=February\n ;;\n Mar) MONTH_STRING=March\n ;;\n Apr) MONTH_STRING=April\n ;;\n May) MONTH_STRING=May\n ;;\n Jun) MONTH_STRING=June\n ;;\n Jul) MONTH_STRING=July\n ;;\n Aug) MONTH_STRING=August\n ;;\n Sep) MONTH_STRING=September\n ;;\n Oct) MONTH_STRING=October\n ;;\n Nov) MONTH_STRING=November\n ;;\n Dec) MONTH_STRING=December\n ;;\nesac\n\n#\n# Create directory if it does not exist\n#\n[ -d ${INFORLOG_BKP}/${FILE_YEAR}/${MONTH_STRING}/ ] || mkdir -p ${INFORLOG_BKP}/${FILE_YEAR}/${ MONTH_STRING}/\n\nmv ${INFORLOG_BKP}/move/$i ${INFORLOG_BKP}/${FILE_YEAR}/${MONTH_STRING}/\n\ndone \n"
},
{
"answer_id": 74340362,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 2,
"selected": false,
"text": "ksh93"
},
{
"answer_id": 74343101,
"author": "Christopher Karsten",
"author_id": 5607499,
"author_profile": "https://Stackoverflow.com/users/5607499",
"pm_score": 1,
"selected": true,
"text": "FILE_MONTH=`istat $i | grep -w \"Last modified:\" | awk '{print $5}' | sed 's/Jan/January/g' | sed 's/Feb/February/g' | sed 's/Mar/March/g' | sed 's/Apr/April/g' | sed 's/Jun/June/g' | sed 's/Jul/July/g' | sed 's/Aug/August/g' | sed 's/Sep/September/g' | sed 's/Oct/October/g' | sed 's/Nov/November/g' | sed 's/Dec/December/g'`\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5607499/"
] |
74,339,916 | <p>I am trying to get the ELB name using Ansible dig, but it is returning DNS name. Is there a way I can match the DNS name pattern and get the ELB name out of DNS. For example, I am trying to get ELB name from below DNS name in Ansible get fact.</p>
<p><code>internal-synergy-so-synergyin-883nxyin6e2o-278193237.us-west-2.elb.amazonaws.com. </code></p>
<p>should return:</p>
<p><code>synergy-so-synergyin-883NXYIN6E2O </code></p>
<p>the current code I am using is:</p>
<pre><code> set_fact:
input: "{{ elb_name }}"
target: "{{ input | regex_findall('^[a-zA-Z]+-[a-zA-Z]+-[a-zA-Z]+-[A-Za-z0-9]+')}}"
tags:
- always
</code></pre>
| [
{
"answer_id": 74340628,
"author": "D1__1",
"author_id": 17194645,
"author_profile": "https://Stackoverflow.com/users/17194645",
"pm_score": 1,
"selected": false,
"text": "^[^-]+-\\K[^.]+(?=-)\n"
},
{
"answer_id": 74340754,
"author": "Vladimir Botka",
"author_id": 6482561,
"author_profile": "https://Stackoverflow.com/users/6482561",
"pm_score": 3,
"selected": true,
"text": "input: internal-synergy-so-synergyin-883nxyin6e2o-278193237.us-west-2.elb.amazonaws.com.\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3388058/"
] |
74,339,931 | <p>My HTML elements are not changing size when the screen size changes, width is set at 100% for all elements. it works for my header but not my background image on the main part of the page. nor does it work with any of the elements below the header with the exception of the map picture under locations. code below, not sure what to do.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Brick Brigade</title>
<link rel="stylesheet" href="./companyhomecss/companyhome.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro&display=swap" rel="stylesheet">
</head>
<body>
<header>
<div class="title">
<h1>Bricks Brigade</h1>
</div>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Shop</a></li>
<li><a href="#">Contact Us</a></li>
<li><a href="#">Review</a></li>
</ul>
</nav>
</header>
<main>
<div class="titlepic1">
<div class="titlepic">
<div class="box">
<h2>Find the perfect fit for your house.</h2>
<p>Browse our brick selection today!</p>
<a href="#">Browse Bricks</a>
</div>
</div>
</div>
<div class="options">
<h2>Bricks</h2>
<h2>Lumber</h2>
<h2>Shingles</h2>
</div>
<div class="location">
<h2>Locations</h2>
<img src="./companyhomepics/GoogleMapTA.webp" alt="Locations">
</div>
<footer>
<div class="footer"></div>
<ul>
<li>Home</li>
<li>Contact</li>
<li>Shop</li>
<li>Leave Review</li>
</ul>
</footer>
</main>
</body>
</html>
</code></pre>
<p>CSS</p>
<pre><code>/* Universal */
html {font-size: 16px;}
body {margin: 0px; padding: 0px; font-family: 'Source Code Pro', monospace;}
/* Header */
header {background-color: black; display: flex; justify-content: space-between; align-items: center; position: fixed; width: 100%; z-index: 1; border-bottom: 1px solid gray;}
.title {color:whitesmoke; position: relative; left: 50px; font-size: 1rem;}
nav ul {color: whitesmoke; position: relative; right: 50px;}
nav li {display: inline; background-color: gray; padding: 5px 10px;}
nav a {text-decoration: none; color: whitesmoke;}
nav li:hover {background-color: lightgray; color: gray;}
nav a:hover {color: gray;}
/* Main picture */
.titlepic1 {width: 100%}
.titlepic {display: flex;
position: relative;
top: 83.276px;
background-image: url(../companyhomepics/brickangle.gif);
background-repeat: no-repeat;
background-position: center;
background-size: cover;
height: 35rem;
width: 100%;
justify-content: center;
align-items: center; border-bottom: 2px solid black; flex-direction: column;}
.titlepic .box {background-color: black; padding: 12px; height: 200px; width: 400px; position: relative; right: 350px; bottom: 45px;
border-radius: 5px; border: 2px solid gray; text-align: center;}
.titlepic h2 {color: whitesmoke; }
.titlepic a {color: whitesmoke; text-decoration: none; background-color: gray; padding: 20px 15px; position: relative; top: 15px;}
.titlepic a:hover {color: gray; background-color: whitesmoke;}
.titlepic p {color: whitesmoke; }
/* Options */
.options {position: relative; top: 70px; display: flex; justify-content: space-around;}
.options h2 {padding: 50px; background-color: gray; color: white; display: inline-block; border: 2px solid black; }
/* Locations */
.location {position: relative; top: 50px; display: flex; flex-direction: column; }
.location h2 {background-color: black; color: white; padding-left: 25px; padding-right: 25px; margin-left: 8px; margin-right: 8px;}
.location img {align-self: center;}
footer {position: relative; top: 60px; padding-bottom: 20px;}
footer .footer {background-color: black; display: block; width: 100%; height: 30px; margin-left: 8px; margin-right: 8px;}
</code></pre>
<pre><code>
Tried width at 100%.
</code></pre>
| [
{
"answer_id": 74340032,
"author": "liquidot",
"author_id": 20400911,
"author_profile": "https://Stackoverflow.com/users/20400911",
"pm_score": 0,
"selected": false,
"text": "body{\nwidth: 100%;\n}\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20435058/"
] |
74,339,966 | <p>For a wordpress website that I am developing I am trying to order a list of objects in SQL by price and would like to have the order descending but have prices that are not numbers (Price on demand for example) on top.</p>
<p>Here's an example of the list I need:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>List of objects (DESCENDING PRICE ORDER)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Price on demand</td>
</tr>
<tr>
<td>Price on demand</td>
</tr>
<tr>
<td>10000</td>
</tr>
<tr>
<td>5000</td>
</tr>
<tr>
<td>300</td>
</tr>
</tbody>
</table>
</div>
<p>Right now if the order is DESC the text prices are on the bottom of the list. And with ASC they are on top but after that it's the lowest prices.I also tried to sort them as text but then it's alphabetically and looks at all digits independently.</p>
| [
{
"answer_id": 74340284,
"author": "ORGPEV",
"author_id": 20085325,
"author_profile": "https://Stackoverflow.com/users/20085325",
"pm_score": 0,
"selected": false,
"text": "SELECT fieldName FROM tableName\nORDER BY\nCASE\n WHEN SUBSTR(fieldName, 1, 1) BETWEEN '0' AND '9' THEN 'B'\n ELSE 'A'\nEND ASC, fieldName DESC\n"
},
{
"answer_id": 74342305,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 2,
"selected": true,
"text": "CASE WHEN"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13626048/"
] |
74,339,990 | <p>I want a reflection of a ray but only in the X-Z axis, while the Y-axis should only allow me to adjust the height of the reflection, but have no impact on the reflection itself;</p>
<p>Here's the regular reflection:<a href="https://i.stack.imgur.com/DCSD9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DCSD9.png" alt="enter image description here" /></a></p>
<pre><code>
if (Physics.Raycast(ray.origin, ray.direction, out hit, remainingLength))
{
lineRenderer.positionCount += 1;
lineRenderer.SetPosition(lineRenderer.positionCount - 1, hit.point);
remainingLength -= Vector3.Distance(ray.origin, hit.point);
//temp_normal.x = ray_new.x;
ray = new Ray(hit.point, Vector3.Reflect(ray.direction, hit.normal));
</code></pre>
<p>Here's my attempt, I tried making the ray origin's y the same as the hit point's y in hopes that it would automatically give me a X-Z reflection, alas to no avail:<a href="https://i.stack.imgur.com/u3334.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u3334.png" alt="enter image description here" /></a>
Code:</p>
<pre><code>var hit_2 = hit ;
//Make a new ray with the same y position as the hit point so it doesn't reflect in y
var ray_2= new Ray(new Vector3(transform.position.x,hit.point.y,transform.position.z), transform.forward);
Physics.Raycast(ray_2.origin, ray_2.direction, out hit_2, remainingLength);
lineRenderer.positionCount += 1;
lineRenderer.SetPosition(lineRenderer.positionCount - 1, hit.point);
remainingLength -= Vector3.Distance(ray.origin, hit.point);
//temp_normal.x = ray_new.x;
ray = new Ray(hit.point, Vector3.Reflect(ray_2.direction, hit.normal));
if (hit.collider.tag == "Totem")
{
//lineRenderer.material.color = new Color(0.4f, 0.9f, 0.7f, 1.0f);
break;
}
</code></pre>
| [
{
"answer_id": 74340284,
"author": "ORGPEV",
"author_id": 20085325,
"author_profile": "https://Stackoverflow.com/users/20085325",
"pm_score": 0,
"selected": false,
"text": "SELECT fieldName FROM tableName\nORDER BY\nCASE\n WHEN SUBSTR(fieldName, 1, 1) BETWEEN '0' AND '9' THEN 'B'\n ELSE 'A'\nEND ASC, fieldName DESC\n"
},
{
"answer_id": 74342305,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 2,
"selected": true,
"text": "CASE WHEN"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14757786/"
] |
74,339,992 | <p>I have component A where I want to set variable using useQuery instead of useState</p>
<pre><code>function A() {
let varA= useQuery(['objA'], '');
</code></pre>
<p>then inside A I have dropDown list where I set varA using callback function</p>
<pre><code> const handleDropDownSelect = (e) => {
varA= e.value;
}
</code></pre>
<p>Till this moment everything works fine.
Also the whole app is enclosed in <code><QueryClientProvider client={queryClient}></code></p>
<p>Now I have component B.jsx</p>
<pre><code>function B() {
</code></pre>
<p>Where I want to use that varA.
I've tried this thing but it won' work.</p>
<pre><code>const queryClient = useQueryClient();
const varA= queryClient.getQueryData('objA');
</code></pre>
<p>I get error</p>
<blockquote>
<p>queryCache.ts:171 Uncaught TypeError: Cannot create property 'exact'
on string 'objA'</p>
</blockquote>
<p>How can I fix this problem ?</p>
| [
{
"answer_id": 74340284,
"author": "ORGPEV",
"author_id": 20085325,
"author_profile": "https://Stackoverflow.com/users/20085325",
"pm_score": 0,
"selected": false,
"text": "SELECT fieldName FROM tableName\nORDER BY\nCASE\n WHEN SUBSTR(fieldName, 1, 1) BETWEEN '0' AND '9' THEN 'B'\n ELSE 'A'\nEND ASC, fieldName DESC\n"
},
{
"answer_id": 74342305,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 2,
"selected": true,
"text": "CASE WHEN"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/678855/"
] |
74,339,995 | <p>I have a table like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Student_1</th>
<th>Student_2</th>
<th>lesson_id</th>
</tr>
</thead>
<tbody>
<tr>
<td>352-03-3624</td>
<td>805-17-4143</td>
<td>27</td>
</tr>
<tr>
<td>352-03-3624</td>
<td>805-17-4144</td>
<td>27</td>
</tr>
<tr>
<td>352-03-3624</td>
<td>805-17-4144</td>
<td>49</td>
</tr>
<tr>
<td>352-03-3624</td>
<td>805-17-4144</td>
<td>50</td>
</tr>
<tr>
<td>805-17-4143</td>
<td>352-03-3624</td>
<td>27</td>
</tr>
<tr>
<td>805-17-4143</td>
<td>805-17-4144</td>
<td>27</td>
</tr>
<tr>
<td>805-17-4143</td>
<td>805-17-4144</td>
<td>68</td>
</tr>
<tr>
<td>805-17-4144</td>
<td>352-03-3624</td>
<td>27</td>
</tr>
<tr>
<td>805-17-4144</td>
<td>352-03-3624</td>
<td>49</td>
</tr>
<tr>
<td>805-17-4144</td>
<td>352-03-3624</td>
<td>50</td>
</tr>
<tr>
<td>805-17-4144</td>
<td>805-17-4143</td>
<td>27</td>
</tr>
<tr>
<td>805-17-4144</td>
<td>805-17-4143</td>
<td>68</td>
</tr>
</tbody>
</table>
</div>
<p>I am looking for a query that returns only these values:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Student_1</th>
<th>Student_2</th>
<th>lesson_id</th>
</tr>
</thead>
<tbody>
<tr>
<td>352-03-3624</td>
<td>805-17-4144</td>
<td>27</td>
</tr>
<tr>
<td>352-03-3624</td>
<td>805-17-4144</td>
<td>49</td>
</tr>
<tr>
<td>352-03-3624</td>
<td>805-17-4144</td>
<td>50</td>
</tr>
<tr>
<td>805-17-4143</td>
<td>805-17-4144</td>
<td>27</td>
</tr>
<tr>
<td>805-17-4143</td>
<td>805-17-4144</td>
<td>68</td>
</tr>
</tbody>
</table>
</div>
<p>I expect only those couple of students_1 and student_2 with all lesson_id of student_1.
I am looking for those pairs (student_1, student_2) in which all the lesson_id of student_1 are present. In the example above, the pair (352-03-3624 and 805-17-4144) is ok because it's present with lesson_id 27,49 and 50, but the pair 352-03-3624 and 805-17-4143 isn't ok beacuse there is only lesson_id 27 while the lesson_id 49 e 50 are missing.</p>
<p>I hope I was clear.</p>
| [
{
"answer_id": 74340070,
"author": "MT0",
"author_id": 1509264,
"author_profile": "https://Stackoverflow.com/users/1509264",
"pm_score": 1,
"selected": false,
"text": "SELECT *\nFROM table_name\nWHERE (Student_1, Student_2, lesson_id) IN (\n ('352-03-3624', '805-17-4144', 27),\n ('352-03-3624', '805-17-4144', 49),\n ('352-03-3624', '805-17-4144', 50),\n ('805-17-4143', '805-17-4144', 27),\n ('805-17-4143', '805-17-4144', 68)\n );\n"
},
{
"answer_id": 74357231,
"author": "Thorsten Kettner",
"author_id": 2270762,
"author_profile": "https://Stackoverflow.com/users/2270762",
"pm_score": 0,
"selected": false,
"text": "select student_1, student_2, lesson_id\nfrom\n(\n select \n student_1, student_2, lesson_id,\n count (distinct lesson_id) over (partition by student_1) as s1_lesson_count,\n count (*) over (partition by student_1, student_2) as s1_s2_lesson_count\n from mytable\n)\nwhere s1_lesson_count = s1_s2_lesson_count\norder by student_1, student_2, lesson_id;\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74339995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20360789/"
] |
74,340,008 | <p>I am iterating through a list of dicts and want to update another dict that may have a key with the same name. Instead of overwriting the key I would like to increment the key with suffix '<code>_[num]</code>'. The problem is I don't know what the last incremented value is so I need to loop through all keys every time.</p>
<p>I can accomplish this with the below but is very inefficient with larger data sets. Is there a more efficient way to accomplish this task?</p>
<p><strong>My Code:</strong></p>
<pre><code>from pprint import pprint
my_dict = {
'key': 'A',
'key_1': 'B',
'key_2': 'C',
'key_3': 'D',
'key_4': 'E',
'key_5': 'F',
}
my_dict_list = [
{'key': 'G'},
{'key': 'H'},
{'key': 'I'},
{'key': 'J'},
{'key': 'K'},
]
for i in my_dict_list:
for k, v in i.items():
if k in my_dict:
for num in range(2, 100):
incremented_k = k + '_{}'.format(num + 1)
if incremented_k not in my_dict:
my_dict.update({incremented_k: v})
break
pprint(my_dict)
</code></pre>
<p><strong>Desired Output:</strong></p>
<pre><code> {'key': 'A',
'key_1': 'B',
'key_10': 'K',
'key_2': 'C',
'key_3': 'D',
'key_4': 'E',
'key_5': 'F',
'key_6': 'G',
'key_7': 'H',
'key_8': 'I',
'key_9': 'J'}
</code></pre>
| [
{
"answer_id": 74342819,
"author": "joquicho",
"author_id": 19889819,
"author_profile": "https://Stackoverflow.com/users/19889819",
"pm_score": 0,
"selected": false,
"text": "# Max index of all the different keys, ex: {\"keyA\": 5, \"keyB\": 21, \"keyC\": 44}\nmax_index_dict = {}\n\n# Get all the max indexes of all the keys in my_dict\nfor keys in my_dict.keys():\n split_key = keys.split(\"_\")\n key = split_key[0]\n if key not in max_index_dict:\n max_index_dict[key] = 0\n else:\n val = int(split_key[1])\n last_max_index = max_index_dict[key]\n if val > last_max_index:\n max_index_dict[key] = val\n\n# When running through my_dict_list, find and increment from the max_index_dict\nfor item in my_dict_list:\n for key, val in item.items():\n if key in my_dict:\n max_index_dict[key] += 1\n incremented_k = key + '_{}'.format(max_index_dict[key])\n my_dict.update({incremented_k: val})\n else:\n my_dict.update(item)\n max_index_dict[key] = 0\n\n"
},
{
"answer_id": 74342939,
"author": "Roland Smith",
"author_id": 1219295,
"author_profile": "https://Stackoverflow.com/users/1219295",
"pm_score": 2,
"selected": true,
"text": "key_"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5525619/"
] |
74,340,026 | <p>I had some vector icons that were converted from SVG and I need to customize the tint colors for them based on some conditions, I'm trying to change the tint color programmatically</p>
<pre><code>Image(
modifier = Modifier.size(128.dp),
painter = painterResource(id = R.drawable.icon_1),
contentDescription = null,
colorFilter = ColorFilter.tint(Color.Red)
)
</code></pre>
<p>it gave me the following result</p>
<p><a href="https://i.stack.imgur.com/hUWYU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hUWYU.png" alt="result" /></a></p>
<p>also, When I tried to do it by using</p>
<pre><code>Image(
modifier = Modifier.size(128.dp),
painter = painterResource(id = R.drawable.icon_1),
contentDescription = null,
colorFilter = ColorFilter.tint(Color.Red, blendMode = BlendMode.Multiply)
)
</code></pre>
<p>I got the same result as well. but, when I tried to change the icon tint from the XML file by adding</p>
<pre><code>android:tint="@color/red"
android:tintMode="multiply"
</code></pre>
<p>it gave me the desired result correctly like the following</p>
<p><a href="https://i.stack.imgur.com/Yd7X1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Yd7X1.png" alt="enter image description here" /></a></p>
<p>So how can I achieve the same result programmatically as I need to change the color programmatically to different colors based on some conditions?</p>
| [
{
"answer_id": 74340460,
"author": "cd1",
"author_id": 38333,
"author_profile": "https://Stackoverflow.com/users/38333",
"pm_score": 0,
"selected": false,
"text": "Icon"
},
{
"answer_id": 74393341,
"author": "MARK ",
"author_id": 5368454,
"author_profile": "https://Stackoverflow.com/users/5368454",
"pm_score": 2,
"selected": true,
"text": "blendMode = BlendMode.Modulate"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5368454/"
] |
74,340,035 | <p>The following code first defines the protocol <code>Proto</code> and then define a function that takes a variable follows that protocol. Then define classes <code>A</code> and <code>B</code> that I thought both follows the protocol, although only the argument name of <code>B.__call__</code> is different from the protocol (in <code>Proto</code> it's <code>x</code> and in <code>B</code> it'S <code>y</code>).</p>
<p>After checking the following code by mypy the following error was given</p>
<pre><code>main.py:20: error: Argument 1 to "func" has incompatible type "B"; expected "Proto"
</code></pre>
<p>It seems that, Protocol not only enforce the type but also the argument name. Is this intended behavior? Or something wrong with mypy?</p>
<pre class="lang-py prettyprint-override"><code>from typing import Protocol
class Proto(Protocol):
def __call__(self, x: int) -> int:
...
def func(f: Proto):
pass
class A:
def __call__(self, x: int) -> int:
return x
class B:
def __call__(self, y: int) -> int:
return y
func(A())
func(B())
</code></pre>
| [
{
"answer_id": 74340082,
"author": "joel",
"author_id": 5986907,
"author_profile": "https://Stackoverflow.com/users/5986907",
"pm_score": 3,
"selected": true,
"text": "Proto"
},
{
"answer_id": 74346603,
"author": "SUTerliakov",
"author_id": 14401160,
"author_profile": "https://Stackoverflow.com/users/14401160",
"pm_score": 1,
"selected": false,
"text": "__dunder_beginning"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7624196/"
] |
74,340,049 | <p>I have two arrays A, B with objects from the database. I want to merge the objects from array B into array A that have a relation: (A[n].id == B[n].a_id).</p>
<pre class="lang-js prettyprint-override"><code>const array_a = [
{
"id": 4,
"status": 0,
},
{
"id": 5,
"status": 1,
}
];
const array_b = [{
active: 1,
a_id: 5, // SELECTOR FOR MERGE
created_at: '2022-11-05 20:29:29',
firstname: 'user3',
lastname: ''
}];
</code></pre>
<p><strong>Expected result:</strong></p>
<pre class="lang-js prettyprint-override"><code>const result = [
{
"id": 4,
"status": 0,
},
{
"id": 5,
"status": 1,
"active": 1,
"user_id": 5,
"created_at": '2022-11-05 20:29:29',
"firstname": 'user3',
"lastname:" ''
}
];
</code></pre>
<p>I tried this approach from another SO answer and got nowhere.<br />
<a href="https://stackoverflow.com/a/53462680/18066399">https://stackoverflow.com/a/53462680/18066399</a> :-/</p>
| [
{
"answer_id": 74340094,
"author": "Asraf",
"author_id": 20361860,
"author_profile": "https://Stackoverflow.com/users/20361860",
"pm_score": 3,
"selected": true,
"text": "dict ={}"
},
{
"answer_id": 74340193,
"author": "Maik Lowrey",
"author_id": 14807111,
"author_profile": "https://Stackoverflow.com/users/14807111",
"pm_score": 0,
"selected": false,
"text": "map()"
},
{
"answer_id": 74340208,
"author": "Azzam Michel",
"author_id": 14568922,
"author_profile": "https://Stackoverflow.com/users/14568922",
"pm_score": 2,
"selected": false,
"text": "const array_a = [\n {\n \"id\": 4,\n \"status\": 0,\n },\n {\n \"id\": 5,\n \"status\": 1,\n }\n ];\n \n const array_b = [{\n active: 1,\n a_id: 5, // SELECTOR FOR MERGE\n created_at: '2022-11-05 20:29:29',\n firstname: 'user3',\n lastname: ''\n }];\n\n\n const merged = array_a.map((item) => {\n const found = array_b.find((i) => i.a_id === item.id);\n return found ? { ...item, ...found } : item;\n });\n\n\nconsole.log(\"merged\",merged);\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18066399/"
] |
74,340,051 | <p>I'm looking for a Regex to match the whole text of every sentence between the OR operators that contains one or more ANDs, if and only if, one or more ANDs is in the sentence between two ORs. For instance:</p>
<p>this should match</p>
<p><code>OR "Message:\"An Arm and a Leg \<Meaning\>: Something that is extremely expensive.\"" AND "Message:\"Jaws of Death \<Meaning\>: Being in a dangerous or very deadly situation.\"" OR</code></p>
<p><code>OR "Message:\"Know the Ropes \<Meaning\>: Having a familiarity or understanding of how something works.\"" AND "Message:\"Poke Fun At \<Meaning\>: Making fun of something or someone; ridicule.\"" AND "Message:\"Give a Man a Fish \<Meaning\>: It's better to teach a person how to do something than to do that something for them.\"" AND "Message:\"Money Doesn't Grow On Trees \<Meaning\>: Suggests that money is a resource that must be earned and is not one that's easily acquired.\"" AND "Message:\"There's No I in Team \<Meaning\>: To not work alone, but rather, together with others in order to achieve a certain goal.\"" AND "Message:\"A Busy Bee \<Meaning\>: An industrious person.\"" AND "Message:\"Wake Up Call \<Meaning\>: An occurance of sorts that brings a problem to somebody's attention and they realize it needs fixing.\"" AND "Message:\"A Lot on One\'s Plate \<Meaning\>: A lot \(or too much\) to do or cope with.\"" AND "Message:\"Under the Weather \<Meaning\>: Not feeling well, in health or mood.\"" OR</code></p>
<p>This shouldn't match:</p>
<p><code>OR "Message:\"Break The Ice \<Meaning\>: Breaking down a social stiffness.\"" OR</code></p>
<p>this is a placeholder/random text to use as example:</p>
<p><code>"Message:\"Knock Your Socks Off \<Meaning\>: To be taken by surprise.\"" AND "Message:\"Playing For Keeps \<Meaning\>: Said when things are about to get serious.\"" OR "Message:\"Break The Ice \<Meaning\>: Breaking down a social stiffness.\"" OR "Message:\"Right Out of the Gate \<Meaning\>: Right from the beginning; to do something from the start.\"" OR "Message:\"Birds of a Feather Flock Together \<Meaning\>: People tend to associate with others who share similar interests or values.\"" AND "Message:\"Up In Arms \<Meaning\>: Angry; being roused to the point that you are ready to fight.\"" OR "Message:\"Know the Ropes \<Meaning\>: Having a familiarity or understanding of how something works.\"" AND "Message:\"Poke Fun At \<Meaning\>: Making fun of something or someone; ridicule.\"" AND "Message:\"Give a Man a Fish \<Meaning\>: It's better to teach a person how to do something than to do that something for them.\"" AND "Message:\"Money Doesn't Grow On Trees \<Meaning\>: Suggests that money is a resource that must be earned and is not one that's easily acquired.\"" AND "Message:\"There's No I in Team \<Meaning\>: To not work alone, but rather, together with others in order to achieve a certain goal.\"" AND "Message:\"A Busy Bee \<Meaning\>: An industrious person.\"" AND "Message:\"Wake Up Call \<Meaning\>: An occurance of sorts that brings a problem to somebody's attention and they realize it needs fixing.\"" AND "Message:\"A Lot on One\'s Plate \<Meaning\>: A lot \(or too much\) to do or cope with.\"" AND "Message:\"Under the Weather \<Meaning\>: Not feeling well, in health or mood.\"" OR "Message:\"A Day Late and a Dollar Short \<Meaning\>: Too late. A missed opportunity.\"" OR "Message:\"Back to Square One \<Meaning\>: To go back to the beginning; back to the drawing board.\"" OR "Message:\"An Arm and a Leg \<Meaning\>: Something that is extremely expensive.\"" AND "Message:\"Jaws of Death \<Meaning\>: Being in a dangerous or very deadly situation.\"" OR "Message:\"Barking Up The Wrong Tree \<Meaning\>: To make a wrong assumption about something.\"" OR "Message:\"Swinging For the Fences \<Meaning\>: Giving something your all.\"" OR "Message:\"Talk the Talk \<Meaning\>: Supporting what you say, not just with words, but also through action or evidence.\"" OR "Message:\"Back To the Drawing Board \<Meaning\>: Starting over again on a new design from a previously failed attempt.\"" OR "Message:\"On the Ropes \<Meaning\>: Being in a situation that looks to be hopeless!\"" OR "Message:\"Tug of War \<Meaning\>: It can refer to the popular rope pulling game or it can mean a struggle for authority.\"" AND "Message:\"A Dime a Dozen \<Meaning\>: Something that is extremely common.\"" AND "Message:\"In a Pickle \<Meaning\>: Being in a difficult predicament; a mess; an undesirable situation.\"" AND "Message:\"Ring Any Bells? \<Meaning\>: Recalling a memory; causing a person to remember something or someone.\"" AND "Message:\"When the Rubber Hits the Road \<Meaning\>: When something is about to begin, get serious, or put to the test.\"" AND "Message:\"Burst Your Bubble \<Meaning\>: To ruin someone's happy moment.\"" AND "Message:\"No Ifs, Ands, or Buts \<Meaning\>: Finishing a task without making any excuses.\"" AND "Message:\"Tough It Out \<Meaning\>: To remain resillient even in hard times; enduring.\"" OR "Message:\"Curiosity Killed The Cat \<Meaning\>: Typically said to indicate that any further investigation into a situation may lead to harm.\"" OR "Message:\"A Chip on Your Shoulder \<Meaning\>: Being angry about something that happened in the past.\"" OR "Message:\"A Cold Day in July \<Meaning\>: Something that is highly unlikely to happen.\"" OR "Message:\"Cry Over Spilt Milk \<Meaning\>: It's useless to worry about things that already happened and cannot be changed.\"" OR "Message:\"A Leg Up \<Meaning\>: Someone who's given an advantage over others.\"" OR "Message:\"It's Not Brain Surgery \<Meaning\>: A task that's easy to accomplish, a thing lacking complexity.\"" OR "Message:\"You Can't Judge a Book By Its Cover \<Meaning\>: Don't judge someone or something only by the outward appearance.\"" AND "Message:\"Down For The Count \<Meaning\>: Someone or something that looks to be defeated, or nearly so.\"" OR "Message:\"Yada Yada \<Meaning\>: A way to notify a person that what they're saying is predictable or boring.\"" AND "Message:\"Let Her Rip \<Meaning\>: Permission to start, or it could mean 'go faster!'\"" OR "Message:\"Wouldn't Harm a Fly \<Meaning\>: Nonviolent; someone who is mild or gentle.\"" OR "Message:\"Off One's Base \<Meaning\>: A person that is crazy or behaving in idiotic ways\"" AND "Message:\"Close But No Cigar \<Meaning\>: Coming close to a successful outcome only to fall short at the end.\"" AND "Message:\"It's Not All It's Cracked Up To Be \<Meaning\>: Failing to meet expectations; not being as good as people say.\"" AND "Message:\"What Am I, Chopped Liver? \<Meaning\>: A rhetorical question used by a person who feels they are being given less consideration than someone else.\"" AND "Message:\"A Dog in the Manger \<Meaning\>: Someone who prevents others from using valuable items even though they have no need for them.\"" AND "Message:\"A Bite at the Cherry \<Meaning\>: An opportunity that's not available to most people.\"" OR "Message:\"Don't Count Your Chickens Before They Hatch \<Meaning\>: Do not rely on something you are not sure of.\"</code></p>
<p>I'm using Positive lookbehind at the beginning and Positive lookahead at the end to set boundaries, i tried with (.<em>?AND.</em>?) to match any character between zero and unlimited times and as few times as possible.
I tried with:</p>
<p><code>(?<=OR)(.*?AND.*?)(?=OR)</code></p>
<p><code>(?<=OR) (?:[\s\S])*? AND (?:[\s\S\w]+?)(?=OR)</code></p>
<p>They stop matching at the OR (after the AND), but the do not start matching at the first OR before the AND.</p>
| [
{
"answer_id": 74340145,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 3,
"selected": true,
"text": "AND"
},
{
"answer_id": 74340389,
"author": "Claudio",
"author_id": 7711283,
"author_profile": "https://Stackoverflow.com/users/7711283",
"pm_score": 1,
"selected": false,
"text": "' OR '"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5498926/"
] |
74,340,052 | <p>I have been breaking my head with this function.</p>
<pre><code>def snatch(data,threshold):
</code></pre>
<p>Given I have the following data:</p>
<pre><code>data = { 'x': [1, 2, 3, 7], 'y': [1, 3, 7, 2] }
threshold = { 'x': 3, 'y': 2 }
</code></pre>
<p>Briefly, the data dictionaries' values are supposed to merge as one list, if they are above or equal to the threshold's values.</p>
<p><code>i.e. [3,7,7,3,2]</code> for 'x' 3,7 are above or equal to threshold 'x'. And for 'y' 3,7,2 are above or equal to threshold 'y.' The mean is hence computed.</p>
<p>The second condition concerns the absence of a threshold. In that case, the respective letter key is excluded from the list and thus the product mean.</p>
<p>e.g. <code>thresh = { 'x': 3 }</code> hence the list from data is only <code>[3,7]</code></p>
| [
{
"answer_id": 74340089,
"author": "ShlomiF",
"author_id": 5024514,
"author_profile": "https://Stackoverflow.com/users/5024514",
"pm_score": 0,
"selected": false,
"text": "from itertools import chain\n\ndef snatch(data, threshold): return list(chain(*[[a for a in data[k] if a >= v] for k, v in threshold.items()])) \n\ndata = {'x': [1, 2, 3, 7], 'y': [1, 3, 7, 2]}\nthreshold = {'x': 3, 'y': 2}\n\nprint(snatch(data, threshold))\n# [3, 7, 3, 7, 2]\n \n"
},
{
"answer_id": 74340192,
"author": "pythonista",
"author_id": 20269454,
"author_profile": "https://Stackoverflow.com/users/20269454",
"pm_score": 3,
"selected": true,
"text": "def snatch(data, threshold):\n return [v for k in threshold for v in data[k] if v >= threshold[k]]\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18072226/"
] |
74,340,060 | <p>When I add a calendar event, it is off by 1 hour after DST changed.</p>
<p>I have been adding calendar events to my google calendar from google sheets in bulk, but after the daylight saving change, it become messed up. It appears in my Execution log that the time starts in "GMT-0400 (Eastern Daylight Time)", but later changes to "GMT-0500 (Eastern Standard Time)" which I believe messes it up, but I am unsure.</p>
<p>I was using this as a guide: <a href="https://developers.google.com/apps-script/advanced/calendar#reference" rel="nofollow noreferrer">https://developers.google.com/apps-script/advanced/calendar#reference</a></p>
<p>Explanation: Basically I am writing in my own timestamp and extracting the values from Google Sheets and making a calendar event for it.</p>
<p><a href="https://i.stack.imgur.com/Z2e9H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z2e9H.png" alt="enter image description here" /></a></p>
<p>To create a calendar event, you need a starting and ending date/time. For purposes of this thread, Here is a small snippet of just the STARTING date/time with the accompanying log output after it:</p>
<p><code>var startDate = sheet.getRange(i + 1,2).getValue()</code></p>
<ul>
<li>Label: #1</li>
<li>Log: Sun Nov 06 2022 00:00:00 GMT-0400 (Eastern Daylight Time)</li>
</ul>
<p><code>var startTimeHour = sheet.getRange(i + 1,3).getValue()</code></p>
<ul>
<li>Label: #2</li>
<li>Log: 5</li>
</ul>
<p><code>var startTimeMin = sheet.getRange (i + 1,4).getValue()</code>
<code>var startTimeMin = (startTimeMin / 60)</code></p>
<ul>
<li>Label: #3</li>
<li>Log: 0.9166666666666666</li>
<li>Notes: I am taking the value of 55 and dividing by 60 to convert it to hours</li>
</ul>
<p><code>var startTime = new Date(startDate.getTime() + ((startTimeHour + startTimeMin) * 60 * 60 * 1000))</code></p>
<ul>
<li>Log: Sun Nov 06 2022 04:55:00 GMT-0500 (Eastern Standard Time)</li>
<li>Notes:
startDate.getTime() = 1667707200000 and is milliseconds for time since 1/1/1970</li>
</ul>
<p>((startTimeHour + startTimeMin) * 60 * 60 * 1000)) = 21300000, the 5 hours 55 minutes I want, converted to milliseconds</p>
<p>This is where it gets tricky. I am adding 5 hours 55 minutes to essentially 12AM, which should be 5:55 AM, but it comes up as 4:55 AM, and somehow the timezone is now Eastern Standard Time instead of Eastern Daylight Time. So basically the command can be simplified to <code>new Date(1667728500000)</code>.</p>
<p><code>start: {dateTime: startTime.toISOString()}</code></p>
<ul>
<li>Log: startTime.toISOString() = 2022-11-06T09:55:00.000Z</li>
<li>Notes: This is what I use with the Calendar API to post it to my calendar</li>
</ul>
<p>And again, this will add to my calendar as <code>11/6/2022 4:55 AM</code>, which is incorrect. I need it to be 5:55 AM.</p>
| [
{
"answer_id": 74521406,
"author": "Gustavo",
"author_id": 17839041,
"author_profile": "https://Stackoverflow.com/users/17839041",
"pm_score": 0,
"selected": false,
"text": "Sunday, November 6, 2022 4:00:00 AM"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1009123/"
] |
74,340,112 | <p>I have a file where each line contains a person's name, occupation, and duties separated by commas.
How could I print the name of the people who have a specific occupation?
So far i have</p>
<p><code>awk -v val="barrister" '$0 ~ val' Occupation.txt</code></p>
<p>for printing the lines that contain the occupation</p>
<p>But I dont know how I could make it so it only prints the line until the first comma.</p>
| [
{
"answer_id": 74340183,
"author": "Christoph Dahlen",
"author_id": 20370596,
"author_profile": "https://Stackoverflow.com/users/20370596",
"pm_score": -1,
"selected": false,
"text": "grep barrister Occupation.txt | \\\n awk -F, '{ print $1 }'\n"
},
{
"answer_id": 74340383,
"author": "Dave Pritlove",
"author_id": 2005666,
"author_profile": "https://Stackoverflow.com/users/2005666",
"pm_score": 2,
"selected": true,
"text": "Awk"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20152389/"
] |
74,340,159 | <p>I am sending notification with firebase, when click on notification I want to redirect to a page in webview, how can I do that?</p>
<pre><code>FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessagemessage) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ,
));
});
</code></pre>
| [
{
"answer_id": 74340183,
"author": "Christoph Dahlen",
"author_id": 20370596,
"author_profile": "https://Stackoverflow.com/users/20370596",
"pm_score": -1,
"selected": false,
"text": "grep barrister Occupation.txt | \\\n awk -F, '{ print $1 }'\n"
},
{
"answer_id": 74340383,
"author": "Dave Pritlove",
"author_id": 2005666,
"author_profile": "https://Stackoverflow.com/users/2005666",
"pm_score": 2,
"selected": true,
"text": "Awk"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20435171/"
] |
74,340,266 | <p>I'm in the middle of taking an online C++ course, and I've been having issues with this homework problem. I tried reaching out to my professor twice, but he hasn't responded. I've sought out many solutions, but since I'm new in the course, many of the solutions involve using techniques I haven't learned yet (like character arrays.) I can get the conversion program to work, but I want the program to allow to process as many user inputs as the user wants.</p>
<p>When I run the program, the program accepts my first input that is 'y' or 'Y' to run the program. It then will ask for a string to convert to the telephone number. This works. However, I need the program to ask the user if they want to run the program again to convert another string to a telephone number or to terminate the program.</p>
<p>I put in another cin at the end of the first while loop to prompt for another input, but it gets skipped over everytime and keeps doing the while loop.</p>
<p>Question: Why is the last prompt to repeat the program get skipped every time I've run it? What am I missing?
Here's the problem and what I've done so far:</p>
<p>Problem:</p>
<blockquote>
<p>To make telephone numbers easier to remember, some companies use
letters to show their telephone number. For example, using letters,
the telephone number 438-5626 can be shown as GET LOAN.</p>
<p>In some cases, to make a telephone number meaningful, companies might
use more than seven letters. For example, 225-5466 can be displayed as
CALL HOME, which uses eight letters. Instructions</p>
<p>Write a program that prompts the user to enter a telephone number
expressed in letters and outputs the corresponding telephone number in
digits.</p>
<p>If the user enters more than seven letters, then process only the
first seven letters.</p>
<p>Also output the - (hyphen) after the third digit.</p>
<p>Allow the user to use both uppercase and lowercase letters as well as
spaces between words.</p>
<p>Moreover, your program should process as many telephone numbers as the
user wants.</p>
</blockquote>
<p>My code so far:</p>
<pre><code>#include <iostream>
using namespace std;
int main()
{
char letter, runLetter;
int counter = 0;
cout << "Enter Y/y to convert a telephone number from letters to digits"
<< endl;
cout << "Enter any other key to terminate the program." << endl;
cin >> runLetter;
while (runLetter == 'y' || runLetter == 'Y')
{
cout << "Enter in a telephone number as letters: " << endl;
while (cin.get(letter) && counter < 7 )
{
if (letter != ' ' && letter >= 'A' && letter <= 'z')
{
counter++;
if (letter > 'Z')
{
letter = (int)letter-32;
}
if (counter == 4)
cout << "-";
switch (letter)
{
case 'A':
case 'B':
case 'C':
{
cout << "2";
break;
}
case 'D':
case 'E':
case 'F':
{
cout << "3";
break;
}
case 'G':
case 'H':
case 'I':
{
cout << "4";
break;
}
case 'J':
case 'K':
case 'L':
{
cout << "5";
break;
}
case 'M':
case 'N':
case 'O':
{
cout << "6";
break;
}
case 'P':
case 'Q':
case 'R':
case 'S':
{
cout << "7";
break;
}
case 'T':
case 'U':
case 'V':
{
cout << "8";
break;
}
case 'W':
case 'X':
case 'Y':
case 'Z':
{
cout << "9";
break;
}
default:
break;
}
}
}
cout << endl;
cout << "To process another telephone number, enter Y/y" << endl;
cout << "Enter any other key to terminate the program." << endl;
cin >> runLetter;
}
cout << "Goodbye. " << endl;
return 0;
}
</code></pre>
<p>Thanks in advance for any help. I know this might be an easy solution, but I've been tinkering with this program for a couple of days now.</p>
<p>Tried moving the last user prompt in and out of each if/else structure and different while loops. Not sure what I can do to make the program take a new input after the first iteration.</p>
| [
{
"answer_id": 74340768,
"author": "guivi",
"author_id": 1856251,
"author_profile": "https://Stackoverflow.com/users/1856251",
"pm_score": 1,
"selected": false,
"text": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main()\n{\n char letter;\n std::string runLetter;\n std::string number;\n\n cout << \"Enter Y/y to convert a telephone number from letters to digits\"\n << endl;\n cout << \"Enter any other key to terminate the program.\" << endl;\n std::getline( std::cin, runLetter);\n\n\n while (runLetter == \"y\" || runLetter == \"Y\")\n { \n int counter = 0;\n cout << \"Enter in a telephone number as letters: \" << endl;\n std::getline(std::cin, number);\n for (int i = 0; i < number.size(); i++)\n {\n letter = number[i];\n if (counter < 7)\n if (letter != ' ' && letter >= 'A' && letter <= 'z')\n {\n counter++;\n\n if (letter > 'Z')\n {\n letter = (int)letter - 32;\n }\n\n if (counter == 4)\n cout << \"-\";\n\n switch (letter)\n {\n case 'A':\n case 'B':\n case 'C':\n {\n cout << \"2\";\n break;\n }\n case 'D':\n case 'E':\n case 'F':\n {\n cout << \"3\";\n break;\n }\n case 'G':\n case 'H':\n case 'I':\n {\n cout << \"4\";\n break;\n }\n case 'J':\n case 'K':\n case 'L':\n {\n cout << \"5\";\n break;\n }\n case 'M':\n case 'N':\n case 'O':\n {\n cout << \"6\";\n break;\n }\n case 'P':\n case 'Q':\n case 'R':\n case 'S':\n {\n cout << \"7\";\n break;\n }\n case 'T':\n case 'U':\n case 'V':\n {\n cout << \"8\";\n break;\n }\n case 'W':\n case 'X':\n case 'Y':\n case 'Z':\n {\n cout << \"9\";\n break;\n }\n default:\n break;\n }\n }\n }\n\n cout << endl;\n\n cout << \"To process another telephone number, enter Y/y\" << endl;\n cout << \"Enter any other key to terminate the program.\" << endl;\n std::getline(std::cin, runLetter);\n }\n\n cout << \"Goodbye. \" << endl;\n return 0;\n} \n"
},
{
"answer_id": 74355446,
"author": "Andreas Wenzel",
"author_id": 12149471,
"author_profile": "https://Stackoverflow.com/users/12149471",
"pm_score": 0,
"selected": false,
"text": "counter"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20435305/"
] |
74,340,271 | <p>Here is the code of the (My)SQL function (it works outside of the function),
but I can't manage to save it as a function for further reuse...</p>
<p>This is an example of the working query:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
(
SUM(Items_Available * Store_Sales) - (SUM(Items_Available) * SUM(Store_Sales)) / COUNT(*)
) / (
SQRT(
SUM(Items_Available * Items_Available) - (SUM(Items_Available) * SUM(Items_Available)) / COUNT(*)
) * SQRT(
SUM(Store_Sales * Store_Sales) - (SUM(Store_Sales) * SUM(Store_Sales)) / COUNT(*)
)
) as pearson_r
FROM
store_sales
</code></pre>
<p>I've extracted the business logic into this UDF:</p>
<pre class="lang-sql prettyprint-override"><code>DELIMITER $$
DROP FUNCTION IF EXISTS PEARSON_R $$
CREATE FUNCTION PEARSON_R(X INT, Y INT) RETURNS FLOAT DETERMINISTIC
BEGIN
RETURN (SUM(X * Y) - (SUM(X) * SUM(Y)) / COUNT(*)) / (SQRT(SUM(X * X) - (SUM(X) * SUM(X)) / COUNT(*)) * SQRT(SUM(Y * Y) - (SUM(Y) * SUM(Y)) / COUNT(*)));
END$$
DELIMITER ;
</code></pre>
<p>When I try to execute this code in command line, I get this useless error message:</p>
<pre><code>> SELECT PEARSON_R(Items_Available, Store_Sales) FROM store_sales;
ERROR 1111 (HY000): Invalid use of group function
</code></pre>
<p>Do you have any idea?</p>
<p>I tried to simplify a lot the function but once I use a group function, I have this error.</p>
| [
{
"answer_id": 74340332,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 2,
"selected": true,
"text": "COUNT"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1986681/"
] |
74,340,280 | <p>My Calculator is half working. I really put my brain in it but I cant figure out why its not working. Can someone help me?</p>
<pre><code>number1 = input("Enter first number: ")
number2 = input("Enter second number: ")
operator = input("Enter the operation character: ")
result = number1 + operator + number2
if operator == '+':
result = int(number1) + int(number2)
elif operator == '-':
result = int(number1) - int(number2)
elif operator == '*':
result = int(number1) * int(number2)
elif operator == '/':
result = int(number1) / int(number2)
if number1.isdigit() == True:
print (result)
elif number2.isdigit() == True:
print(result)
else:
print("Enter a number.")
</code></pre>
<p>It's printing the calculated value, but if you enter a letter instead of a number.
For example:
Enter a first number: 5
Enter a second number: f
Now it should print "enter a number". But im getting this message istead
ValueError: invalid literal for int() with base 10: 'a'</p>
<pre><code>if number1.isdigit() == True:
print (result)
elif number2.isdigit() == True:
print(result)
**else:
print("Enter a number.")**
</code></pre>
| [
{
"answer_id": 74340332,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 2,
"selected": true,
"text": "COUNT"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20435309/"
] |
74,340,317 | <p>Somehow i managed to stop getting the 400 POST error on the Login and Register Components in my app, but now for some reason they shoot me the "Formik.tsx:824 Warning: An unhandled error was caught from submitForm() TypeError: onSubmit is not a function" problem when i click the submit button (they both pretty much have the same code, maybe that's not the best way to do it though)</p>
<p>Anyway, here's the Register Component (since at the very least i want that one to work to move on to the Login one and as i said they're pretty much the same)</p>
<pre><code>import React from "react";
import { View, TextInput, TouchableOpacity,Text } from "react-native";
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
import {createUsuario} from '../../CRUD';
const SignupSchema = Yup.object().shape({
email: Yup.string().email('El email ingresado no es valido.').required('Por favor ingrese su email.'),
contrasenia: Yup.string()
.min(6, 'La contrasenia es muy corta.')
.max(20, 'La contrasenia es demasiado larga.')
.required('Por favor ingrese su contrasenia.')
});
export default function RegisterForm () {
return(
<Formik initialValues={{
email: '',
contrasenia: ''
}}
validationSchema={SignupSchema}
handleSubmit={(values=>(createUsuario()))}>
{({values,errors,touched, handleChange, setFieldTouched, isValid, handleSubmit}) =>(
<View>
<TextInput
placeholder="Email"
value={values.email}
onChangeText={handleChange('email')}
onBlur={()=> setFieldTouched('email')}/>
{touched.email && errors.email && (
<Text>{errors.email}</Text>
)}
<TextInput
placeholder="Contraseña"
value={values.contrasenia}
onChangeText={handleChange('contrasenia')}
onBlur={()=> setFieldTouched('contrasenia')}
secureTextEntry={true}/>
{touched.contrasenia && errors.contrasenia && (
<Text>{errors.contrasenia}</Text>
)}
<TouchableOpacity disabled={!isValid} style={{backgroundColor: isValid? '#289D8C': '#808080'}} onPress={handleSubmit}>
<Text>Registrate</Text>
</TouchableOpacity>
</View>
)}
</Formik>
)
}
</code></pre>
<p>The CreateUsuario function which is on my CRUD.js file:</p>
<pre><code>export async function createUsuario(db,email, contrasenia){
await setDoc(doc(db, "Usuario"), {
email: email,
contrasenia: contrasenia
}).then(()=> {
console.log("Guardado exitosamente");
}).catch((error)=>{
console.log("Hubo fallos al guardar");
})
}
</code></pre>
<p>PS: i know there are some asked questions that were answered with similar or the same issue as mine but i'm not really sure <em>how</em> to apply those solutions to my own code</p>
<p>It could be the ValidationSchema as i've read in some places though.</p>
| [
{
"answer_id": 74340332,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 2,
"selected": true,
"text": "COUNT"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19840995/"
] |
74,340,337 | <p>Getting started with using Chrome webdrivers and selenium. When I execute the code:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
driver = webdriver.Chrome(executable_path = \
r"C:\Users\payto\Downloads\chromedriver_win32.zip\chromedriver.exe")
</code></pre>
<p>I keep getting this error:</p>
<p>WebDriverException: 'chromedriver.exe' executable needs to be in PATH. Please see <a href="https://sites.google.com/a/chromium.org/chromedriver/home" rel="nofollow noreferrer">https://sites.google.com/a/chromium.org/chromedriver/home</a></p>
<p>I've looked up how to solve it, but anything I see says to install a webdriver...which I've already done. My Chrome version is 107 and that's the one I downloaded, so it should be working but it's not. Any tips?</p>
| [
{
"answer_id": 74340332,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 2,
"selected": true,
"text": "COUNT"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18069825/"
] |
74,340,339 | <p>Good evening,</p>
<p>I'm wondering how i can exclude certain characters from a frequency table?</p>
<p>first i read the file, creates a frequency table. after this i change it to a tuple to be able to get a percentage of occourence for each letter.
however i am wondering how i can implement that it does not count certain letters.
ie. an exclude list.</p>
<pre><code>with open('test.txt', 'r') as file:
data = file.read().replace('\n', '')
frequency_table = {char : data.count(char) for char in set(data)}
x0= ("Character frequency table for '{}' is :\n {}".format(data, str(frequency_table)))
from collections import Counter
res = [(*key, val) for key, val in Counter(frequency_table).most_common()]
print("Frequency Tuple list : " + str(res))
print(res[1][1]/res[1][1])#
</code></pre>
| [
{
"answer_id": 74340386,
"author": "soyapencil",
"author_id": 12161501,
"author_profile": "https://Stackoverflow.com/users/12161501",
"pm_score": 1,
"selected": false,
"text": "if"
},
{
"answer_id": 74340400,
"author": "pythonista",
"author_id": 20269454,
"author_profile": "https://Stackoverflow.com/users/20269454",
"pm_score": 1,
"selected": true,
"text": "if"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9861217/"
] |
74,340,355 | <p>I'm new with HTML & JS and I face the following problem:</p>
<p>I have an input in html that creates a new li Element (in combination with JS); is it possible to give every newly-created li element its own id? For example to delete an specific element?</p>
<p>For Example:</p>
<pre><code><li id="one"> .. </li>
<li id="two"> .. </li>
</code></pre>
<p>So far it creates only <code><li> ... </li></code></p>
<p>I think it can be done with a <code>for</code> loop, but I have no idea how to use it in my case.</p>
<p>See my JS code below:</p>
<pre><code>function NewEntry() {
var Inputfield = document.getElementById("Inputfield");
var AddButton = document.getElementById("AddButton");
var ul = document.querySelector("ul");
var li = document.createElement("li");
li.appendChild(document.createTextNode(Input.value));
ul.appendChild(li);
Input.value = "";
</code></pre>
<p>I tried to insert a <code>for</code> loop into my code, but after that it doesn't add any elements.</p>
<pre><code>function NewEntry() {
var Inputfield = document.getElementById("Inputfield");
var AddButton = document.getElementById("AddButton");
var ul = document.querySelector("ul");
var li = document.createElement("li");
for (var i = 0; i < li.length; i++)
li[i].id = 'abc-' + i;
li.appendChild(document.createTextNode(Input.value));
ul.appendChild(li);
Input.value = "";
</code></pre>
| [
{
"answer_id": 74340386,
"author": "soyapencil",
"author_id": 12161501,
"author_profile": "https://Stackoverflow.com/users/12161501",
"pm_score": 1,
"selected": false,
"text": "if"
},
{
"answer_id": 74340400,
"author": "pythonista",
"author_id": 20269454,
"author_profile": "https://Stackoverflow.com/users/20269454",
"pm_score": 1,
"selected": true,
"text": "if"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16837874/"
] |
74,340,359 | <p>I am super new to SQL and am trying to figure out how to find the average by day. So YTD what were they averaging by day.</p>
<p>the table below is an example of the table I am working with</p>
<pre><code>Study Date | ID | Subject
01\01\2018 | 123 | Math
01\01\2018 | 456 | Science
01\02\2018 | 789 | Science
01\02\2018 | 012 | History
01\03\2018 | 345 | Science
01\03\2018 | 678 | History
01\03\2018 | 921 | Art
01\03\2018 | 223 | Science
01\04\2018 | 256 | English
</code></pre>
<p>For instance, If I filter on just 'Science' as the Subject, the output I am looking for is , out of the 4 science subject results, what is the daily average, min and max YTD.</p>
<p>So my max in a day would be 2 science subjects, my min would be 1 etc.</p>
<p>how can i configure a query to output this information?</p>
<p>So far I know to get the YTD total it would be</p>
<pre><code>select SUBJECT, count (ID)
from table
where SUBJECT='science' and year (Study_date)=2022
group by SUBJECT
</code></pre>
<p>what would be the next step I have to take?</p>
| [
{
"answer_id": 74340381,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 2,
"selected": false,
"text": "select subject, sum(cnt_daily) as cnt, \n min(cnt_daily) as min_cnt_daily, max(cnt_daily) as max_cnt_daily\nfrom (\n select study_date, subject, count(*) as cnt_daily\n from mytable\n where study_date >= '2022-01-01'\n group by study_date, subject\n) t\ngroup by subject\n"
},
{
"answer_id": 74341004,
"author": "DannySlor",
"author_id": 19174570,
"author_profile": "https://Stackoverflow.com/users/19174570",
"pm_score": 0,
"selected": false,
"text": "select Subject\n ,count(*) as total_count\n ,min(cnt) as min_daily_count\n ,max(cnt) as max_daily_count\n ,avg(cnt*1.0) as avg_daily_count\nfrom\n(\nselect *\n ,count(*) over(partition by Study_Date, Subject) as cnt\nfrom t \n) t\ngroup by Subject\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20435318/"
] |
74,340,365 | <p>This is my first time attempting to use APIs with Blazor, and I am struggling to save info from nested JSON objects into C# objects. I have been following these guides:
<a href="https://learn.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-6.0&pivots=server" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-6.0&pivots=server</a>
<a href="https://alexb72.medium.com/how-to-make-an-api-call-in-blazor-server-136e4154fca6" rel="nofollow noreferrer">https://alexb72.medium.com/how-to-make-an-api-call-in-blazor-server-136e4154fca6</a></p>
<p>My API returns this data:</p>
<pre><code>{
"page": 1,
"results": [
{
"adult": false,
"backdrop_path": "/c6OLXfKAk5BKeR6broC8pYiCquX.jpg",
"genre_ids": [
18,
53,
35
],
"id": 550,
"original_language": "en",
"original_title": "Fight Club",
"overview": "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \"fight clubs\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
"popularity": 100.28,
"poster_path": "/pB8BM7pdSp6B6Ih7QZ4DrQ3PmJK.jpg",
"release_date": "1999-10-15",
"title": "Fight Club",
"video": false,
"vote_average": 8.4,
"vote_count": 25110
},
{
"adult": false,
"backdrop_path": null,
"genre_ids": [
28
],
"id": 347807,
"original_language": "hi",
"original_title": "Fight Club: Members Only",
"overview": "Four friends head off to Bombay and get involved in the mother and father of all gang wars.",
"popularity": 2.023,
"poster_path": "/aXFmWfWYCCxQTkCn7K86RvDiMHZ.jpg",
"release_date": "2006-02-17",
"title": "Fight Club: Members Only",
"video": false,
"vote_average": 3.4,
"vote_count": 9
}
],
"total_pages": 2,
"total_results": 36
}
</code></pre>
<p>I have configured an API call that can correctly deserialze the page, total_pages, and total_results headers. If I try to display the results header on my page as a string, I get the error "Cannot get the value of a token type 'StartArray' as a string". I would like to save the results header into a list which I can iterate through on my page, but I am not sure how to handle this StartArray data type.</p>
<p>My C# code for this page (I have also tried List and IEnumerable for the results variable):</p>
<pre><code>@code {
public class MovieItem
{
public int id { get; set; }
public string title { get; set; }
}
public class APIItem
{
public int page { get; set; }
public IList<MovieItem> results { get; set; }
public int total_pages { get; set; }
public int total_results { get; set; }
}
public APIItem api_item = new APIItem();
protected override async Task OnInitializedAsync()
{
var request = new HttpRequestMessage(HttpMethod.Get, "https://api.themoviedb.org/3/search/movie?api_key=HIDDEN&query=fight%20club");
var client = ClientFactory.CreateClient();
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
await using var responseStream = await response.Content.ReadAsStreamAsync();
api_item = await JsonSerializer.DeserializeAsync<APIItem>(responseStream);
}
}
}
</code></pre>
<p>Finally, when I try to display the API results on my page using the following code, I get this error: System.NullReferenceException: 'Object reference not set to an instance of an object'. When I comment out the @foreach section then the rest of the data loads correctly:</p>
<pre><code> <p>@api_item.page</p>
<p>@api_item.total_pages</p>
<p>@api_item.total_results</p>
@foreach (var movie in api_item.results)
{
@movie.id
@movie.title
}
</code></pre>
<p>I am not sure what to try next from here. If there is a better way to handle this API call in general then I would appreciate any suggestions; I went with this method simply because it's how it was documented on Microsoft's Blazor API guide. Thanks for the help.</p>
| [
{
"answer_id": 74340381,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 2,
"selected": false,
"text": "select subject, sum(cnt_daily) as cnt, \n min(cnt_daily) as min_cnt_daily, max(cnt_daily) as max_cnt_daily\nfrom (\n select study_date, subject, count(*) as cnt_daily\n from mytable\n where study_date >= '2022-01-01'\n group by study_date, subject\n) t\ngroup by subject\n"
},
{
"answer_id": 74341004,
"author": "DannySlor",
"author_id": 19174570,
"author_profile": "https://Stackoverflow.com/users/19174570",
"pm_score": 0,
"selected": false,
"text": "select Subject\n ,count(*) as total_count\n ,min(cnt) as min_daily_count\n ,max(cnt) as max_daily_count\n ,avg(cnt*1.0) as avg_daily_count\nfrom\n(\nselect *\n ,count(*) over(partition by Study_Date, Subject) as cnt\nfrom t \n) t\ngroup by Subject\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18228665/"
] |
74,340,370 | <p>Fairly new to Flutter and have encountered an issue. I am trying to get the emulator (for both iOS and Android) of my app to connect to an API that is running on my local machine. I had it working up until I upgraded flutter null-safety and have not been able to get it back since. Any suggestions on how I can fix the error I am getting?</p>
| [
{
"answer_id": 74340381,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 2,
"selected": false,
"text": "select subject, sum(cnt_daily) as cnt, \n min(cnt_daily) as min_cnt_daily, max(cnt_daily) as max_cnt_daily\nfrom (\n select study_date, subject, count(*) as cnt_daily\n from mytable\n where study_date >= '2022-01-01'\n group by study_date, subject\n) t\ngroup by subject\n"
},
{
"answer_id": 74341004,
"author": "DannySlor",
"author_id": 19174570,
"author_profile": "https://Stackoverflow.com/users/19174570",
"pm_score": 0,
"selected": false,
"text": "select Subject\n ,count(*) as total_count\n ,min(cnt) as min_daily_count\n ,max(cnt) as max_daily_count\n ,avg(cnt*1.0) as avg_daily_count\nfrom\n(\nselect *\n ,count(*) over(partition by Study_Date, Subject) as cnt\nfrom t \n) t\ngroup by Subject\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1937987/"
] |
74,340,395 | <p>I am brushing up on my rails. I have a dead simple form. views -> genalg -> index.html.erb</p>
<pre><code><h1>Genalg#index</h1>
<p>Find me in app/views/genalg/index.html.erb</p>
<%= form_with url: "/calculate" do |form| %>
<%= form.text_field :query %>
<%= form.submit "calculate" %>
<% end %>
<% unless @query.nil? %>
<p><%=@query%></p>
<% end %>
</code></pre>
<p>I have a controller under controllers -> genalg_controller.rb</p>
<pre><code>class GenalgController < ApplicationController
def index
@query = "biznass"
end
def calculate
puts params
@query = (params[:query].to_i * 2).to_s
render :index
end
end
</code></pre>
<p>In routes.rb:</p>
<pre><code>Rails.application.routes.draw do
get 'genalg/index'
post '/calculate', to: 'genalg#index' , as: 'index'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
</code></pre>
<p>How, when I fill the from text :query and hit submit, can I get the text denoted at the very end of my view to display the value I put in times 2 (per the calculate function)? Seems like it should be easy but clearly I have forgotten some basic tenant of how forms and form submission works.</p>
| [
{
"answer_id": 74340381,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 2,
"selected": false,
"text": "select subject, sum(cnt_daily) as cnt, \n min(cnt_daily) as min_cnt_daily, max(cnt_daily) as max_cnt_daily\nfrom (\n select study_date, subject, count(*) as cnt_daily\n from mytable\n where study_date >= '2022-01-01'\n group by study_date, subject\n) t\ngroup by subject\n"
},
{
"answer_id": 74341004,
"author": "DannySlor",
"author_id": 19174570,
"author_profile": "https://Stackoverflow.com/users/19174570",
"pm_score": 0,
"selected": false,
"text": "select Subject\n ,count(*) as total_count\n ,min(cnt) as min_daily_count\n ,max(cnt) as max_daily_count\n ,avg(cnt*1.0) as avg_daily_count\nfrom\n(\nselect *\n ,count(*) over(partition by Study_Date, Subject) as cnt\nfrom t \n) t\ngroup by Subject\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1222564/"
] |
74,340,407 | <p>I have a structure like this:</p>
<pre><code>{
_id: new ObjectId("634aa49f98e3a05346dd2327"),
filmName: 'Film number 1',
episodes: [
{
episodeName: 'Testing 1',
slugEpisode: 'testing-1',
_id: new ObjectId("6351395c17f08335f1dabfc9")
},
{
episodeName: 'Testing 2',
slugEpisode: 'testing-2',
_id: new ObjectId("6351399d9a2533b9be1cbab0")
},
],
},
{
_id: new ObjectId("634aa4cc98e3a05346dd232a"),
filmName: 'Film number 2',
episodes: [
{
episodeName: 'Something 1',
slugEpisode: 'something-1',
_id: new ObjectId("6367cce66d6b85442f850b3a")
},
{
episodeName: 'Something 2',
slugEpisode: 'something-2',
_id: new ObjectId("6367cd0e6d6b85442f850b3e")
},
],
}
</code></pre>
<p>I received 3 fields:</p>
<ul>
<li><code>_id</code>: Film _id</li>
<li><code>episodeId</code>: Episode _id</li>
<li><code>episodeName</code>: The content I wish to update</li>
</ul>
<p>I tried to find a specific <code>Film ID</code> to get a specific film, and from then on, I pass an <code>Episode ID</code> to find the exact episode in the <code>episodes</code> array. Then, update the <code>episodeName</code> of that specific episode.</p>
<p>Here's my code in NodeJS:</p>
<pre><code>editEpisode: async (req, res) => {
const { _id } = req.params
const { episodeId, episodeName } = req.body
try {
const specificResult = await Films.findOneAndUpdate(
{ _id, 'episodes._id': episodeId },
{ episodeName }
)
console.log(specificResult)
res.json({ msg: "Success update episode name" })
} catch (err) {
return res.status(500).json({ msg: err.message })
}
},
</code></pre>
<p>But what <code>console.log</code> display to me is a whole document, and when I check in MongoDB, there was no update at all, does my way of using <code>findOneAndUpdate</code> incorrect?</p>
<p>I'm reading this document: <a href="https://mongoosejs.com/docs/tutorials/findoneandupdate.html" rel="nofollow noreferrer">MongooseJS - Find One and Update</a>, they said this one gives me the option to <code>filter</code> and <code>update</code>.</p>
| [
{
"answer_id": 74340381,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 2,
"selected": false,
"text": "select subject, sum(cnt_daily) as cnt, \n min(cnt_daily) as min_cnt_daily, max(cnt_daily) as max_cnt_daily\nfrom (\n select study_date, subject, count(*) as cnt_daily\n from mytable\n where study_date >= '2022-01-01'\n group by study_date, subject\n) t\ngroup by subject\n"
},
{
"answer_id": 74341004,
"author": "DannySlor",
"author_id": 19174570,
"author_profile": "https://Stackoverflow.com/users/19174570",
"pm_score": 0,
"selected": false,
"text": "select Subject\n ,count(*) as total_count\n ,min(cnt) as min_daily_count\n ,max(cnt) as max_daily_count\n ,avg(cnt*1.0) as avg_daily_count\nfrom\n(\nselect *\n ,count(*) over(partition by Study_Date, Subject) as cnt\nfrom t \n) t\ngroup by Subject\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16240395/"
] |
74,340,413 | <p>I was using replit (maybe because replit doesnt work?) tryoing to make some code for a Discord bot when I saw this:</p>
<p><code>Type error: __init__ missing 1 required keyword-only argument: "intents"</code></p>
<p>Im not really sure what is means</p>
<p>Heres my code (BTW i used <em><strong>pip install discord</strong></em> in shell)
`</p>
<pre><code>import discord
token = "mytoken (not revealing it i guess)"# but even with right token it doesnt work
client = discord.Client()
name = "MIIB.BOT_v1.0"
@client.event
async def on_ready():
print("Bot logged in as ", name, "!")
client.run(token)
on_ready()
#i did *****pip install discord****** in shell btw
</code></pre>
<p>`</p>
<p>I tried some variations but not much. I expected:
<code>Bot logged in as botname#6969</code></p>
| [
{
"answer_id": 74340422,
"author": "liquidot",
"author_id": 20400911,
"author_profile": "https://Stackoverflow.com/users/20400911",
"pm_score": 1,
"selected": false,
"text": "client = discord.Client()\n"
},
{
"answer_id": 74345719,
"author": "Carlos Mediavilla",
"author_id": 10592737,
"author_profile": "https://Stackoverflow.com/users/10592737",
"pm_score": 0,
"selected": false,
"text": "bot_intents = discord.Intents.default()\nclient = discord.Client(intents=bot_intents)\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20435438/"
] |
74,340,427 | <p>Windows 11.
I am not great at virtual environments, and I have bumped around between a half dozen different "solutions." I thought I had it solved with chocolatey, but I am trying to install python3.11, and not having success. Basically, choco says it is installed, but I can't find it anywhere.</p>
<pre class="lang-bash prettyprint-override"><code>C:\Windows\System32>choco install --force python --version=3.11
Chocolatey v1.2.0
Installing the following packages:
python
By installing, you accept licenses for the packages.
python v3.11.0 already installed. Forcing reinstall of version '3.11.0'.
Please use upgrade if you meant to upgrade to a new version.
Progress: Downloading python 3.11.0... 100%
python v3.11.0 (forced) [Approved]
python package files install completed. Performing other installation steps.
The install of python was successful.
Software installed to 'C:\ProgramData\chocolatey\lib\python'
Chocolatey installed 1/1 packages.
See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log).
C:\Windows\System32>
</code></pre>
<p>This gives the impression that python would be in <code>C:\ProgramData\chocolatey\lib\python</code>, but the only files in that directory are python.nupkg<code>and</code>python.nuspec`</p>
<p>Where do I go to find my shiny new python?</p>
| [
{
"answer_id": 74340422,
"author": "liquidot",
"author_id": 20400911,
"author_profile": "https://Stackoverflow.com/users/20400911",
"pm_score": 1,
"selected": false,
"text": "client = discord.Client()\n"
},
{
"answer_id": 74345719,
"author": "Carlos Mediavilla",
"author_id": 10592737,
"author_profile": "https://Stackoverflow.com/users/10592737",
"pm_score": 0,
"selected": false,
"text": "bot_intents = discord.Intents.default()\nclient = discord.Client(intents=bot_intents)\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3112610/"
] |
74,340,457 | <p>Given this JSON,</p>
<pre><code>{
"token": {
"accessToken": "scrciFyGuLAQn6XgKkaBWOxdZA1",
"issuedAt": "2022-11-06T22:54:27Z",
"expiresIn": 1799
}
}
</code></pre>
<p>I can get the <code>DeserializeObject</code> to work if I define the model as this</p>
<pre><code> public class Root
{
public Token Token { get; set; }
}
public class Token
{
public string AccessToken { get; set; }
public DateTime IssuedAt { get; set; }
public int ExpiresIn { get; set; }
}
</code></pre>
<p>And use this call:</p>
<pre><code>Root myRoot = JsonConvert.DeserializeObject<Root>(apiResponse);
</code></pre>
<p>The third-party API I am calling has all methods returning a similar JSON response, in that it has a header object containing a single object of a specific type, such as:</p>
<pre><code>{
"user": {
"preferences": {},
"address": {},
"name": {},
"email": "string",
"segmentName": "string"
}
}
</code></pre>
<p>which requires a model looking like this:</p>
<pre><code> public class Address
{
}
public class Name
{
}
public class Preferences
{
}
public class Root
{
public User user { get; set; }
}
public class User
{
public Preferences preferences { get; set; }
public Address address { get; set; }
public Name name { get; set; }
public string email { get; set; }
public string segmentName { get; set; }
}
</code></pre>
<p>I do not want to be having to define a different <code>Root</code> class for every one of the JSON responses. Is there a way to avoid this?</p>
<p>EDIT 14/11.</p>
<p>Another JSON response looks like this:</p>
<pre><code>{
"provider": {
"TOTAL": {
"count": 0
}
}
}
</code></pre>
<p>Again, it's an "empty" root object containing the specific object I need.</p>
<p>As <strong>zaitsman</strong> indicated in his comment, by typing the <code>DeserializeObject</code> call to use a <code><Dictionary, T></code>, where <code>T</code> is the actual object I'm after (such as <code>Token</code> or <code>User</code> or <code>Provider</code>), it gets around the need for a root object.</p>
<p>EDIT 15/11.</p>
<p>Just one more example;</p>
<pre><code>{
"provider": [
{
"accountType": [],
"loginHelp": "string",
"baseUrl": "string",
"loginUrl": "string",
"name": "string",
"id": 0,
"lastModified": "string",
"status": "Supported"
}
]
}
</code></pre>
<p>In this case, the <em>C#</em> code to deserialize looks like this:</p>
<pre><code>providers = JsonConvert.DeserializeObject<Dictionary<string, List<Provider>>>(apiResponse)["provider"];
</code></pre>
<p>Using <code>Dictionary<string,T></code> removes the need to define a root class, and <code>T</code> has to be defined as a <code>List<T></code> since the content is an array.</p>
| [
{
"answer_id": 74340535,
"author": "Thorberg",
"author_id": 15638584,
"author_profile": "https://Stackoverflow.com/users/15638584",
"pm_score": 0,
"selected": false,
"text": "public class Response<T>\n{\n public User User { get; set; }\n public Token Token { get; set; }\n public Token AuthToken { get; set; }\n public XYZ XYZ { get; set; }\n\n public T Content => GetType().GetProperties().Where(p => p.Name != nameof(Content)).Select(p => p.GetValue(this)).Single(v => v != null) as T;\n}\n"
},
{
"answer_id": 74340623,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 1,
"selected": false,
"text": "Root"
},
{
"answer_id": 74439347,
"author": "zaitsman",
"author_id": 2057955,
"author_profile": "https://Stackoverflow.com/users/2057955",
"pm_score": 2,
"selected": true,
"text": "JsonConvert.DeserializeObject<Dictionary<string, User>>()[\"user\"] \n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1007906/"
] |
74,340,488 | <p>I am simply looking to get a count of the <strong>character</strong> (not the words) in a Google document. It cannot be in the active document for this use case, so would need to be post <code>getBody</code>.</p>
<p>Here is my very fragmented script so far. For context, I am looking to integrate a few features into a collaborator's document, at the end of the document. From what I can see so far I would need the character count (+1) to acheive this.</p>
<pre><code>function myFunction() {
var doc = DocumentApp.openById([ID]);
var bodyCount = doc.getBody().getText();
var body = doc.getBody();
//var numChildren = body.getNumChildren();
//var pos = doc.newPosition(body.getChild(numChildren - 1),0);
var text = body.editAsText();
var space = " ";
//var text = DocumentApp.getActiveDocument().getBody().getText();
var words = bodyCount.replace(/\s+/g, space).split(space);
Logger.log(words.length);
const characters = words.join('');
Logger.log(characters);
var charCount = characters.toString();
Logger.log(charCount);
var realCharCount = charCount.length();
//body.setCursor(pos);
text.insertText(words.length,"yadayadayada");
}
</code></pre>
<p>Just want to insert text, it needs to be the integer for the position AKA, +1 of the character count. I have most of the functions I need so far except getting that one number: the character count.</p>
<p><strong>This is NOT to count characters in a cell, nor is it related in any way to sheets. That would be nice because than I could just use the length function... but I cannot in this context so far.</strong></p>
| [
{
"answer_id": 74340535,
"author": "Thorberg",
"author_id": 15638584,
"author_profile": "https://Stackoverflow.com/users/15638584",
"pm_score": 0,
"selected": false,
"text": "public class Response<T>\n{\n public User User { get; set; }\n public Token Token { get; set; }\n public Token AuthToken { get; set; }\n public XYZ XYZ { get; set; }\n\n public T Content => GetType().GetProperties().Where(p => p.Name != nameof(Content)).Select(p => p.GetValue(this)).Single(v => v != null) as T;\n}\n"
},
{
"answer_id": 74340623,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 1,
"selected": false,
"text": "Root"
},
{
"answer_id": 74439347,
"author": "zaitsman",
"author_id": 2057955,
"author_profile": "https://Stackoverflow.com/users/2057955",
"pm_score": 2,
"selected": true,
"text": "JsonConvert.DeserializeObject<Dictionary<string, User>>()[\"user\"] \n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20426355/"
] |
74,340,497 | <p>I am wondering which is a better way of designing my data base.</p>
<p>Currently designing for Hospitals that advertise positions
which require specific skills (e.g., nursing, administrative, etc.). Candidates may be invited to
interviews for the positions.</p>
<p>For one of the requirments I have to include information of the hospital details such as:
hospital identifier, hospital name, address, and telephone number.
I also have to include details on candidate, position and interviews in other tables.</p>
<p>My question is, would it be better to include the address of the hospital in the column of the hospital table or is it better to create a separate table called address for the address of the hospital and create a one to one relationship with the hospital table ?</p>
<p>I tried putting the address in the column of hospital anyway but i'm wondering which is better practice and if it makes more sense to put address's in its separate table.</p>
| [
{
"answer_id": 74340535,
"author": "Thorberg",
"author_id": 15638584,
"author_profile": "https://Stackoverflow.com/users/15638584",
"pm_score": 0,
"selected": false,
"text": "public class Response<T>\n{\n public User User { get; set; }\n public Token Token { get; set; }\n public Token AuthToken { get; set; }\n public XYZ XYZ { get; set; }\n\n public T Content => GetType().GetProperties().Where(p => p.Name != nameof(Content)).Select(p => p.GetValue(this)).Single(v => v != null) as T;\n}\n"
},
{
"answer_id": 74340623,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 1,
"selected": false,
"text": "Root"
},
{
"answer_id": 74439347,
"author": "zaitsman",
"author_id": 2057955,
"author_profile": "https://Stackoverflow.com/users/2057955",
"pm_score": 2,
"selected": true,
"text": "JsonConvert.DeserializeObject<Dictionary<string, User>>()[\"user\"] \n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20425502/"
] |
74,340,512 | <p>How can you determine the amount of flip flops that will be generated during synthesis without using any tool?</p>
<p>This first code is supposed to create 5 flip flops</p>
<pre><code>module regdesp (PL, RST, ENSERIE, CLOCK, ENPARA, SALSERIE);
input PL;
input RST;
input ENSERIE;
input CLOCK;
input[3:0] ENPARA;
output SALSERIE;
logic SALSERIE;
logic [3:0] SHIFT;
always_ff @(posedge CLOCK or negedge RST)
if (!RST)
SHIFT <= 4'b0000 ;
else
if (!PL)
SHIFT <= ENPARA ;
else
begin
SHIFT[3] <= ENSERIE ;
begin : xhdl_0
integer i;
for(i = 2; i >= 0; i = i - 1)
begin : DESPLAZAR
SHIFT[i] <= SHIFT[i + 1] ;
end
end
SALSERIE=SHIFT[0];
end
endmodule
</code></pre>
<p>This second example creates 32 flip flops</p>
<pre><code>module SHIFTER2D(clock,reset,clear,shift,entrada_serie, salida_serie);
parameter tamanyo=4;
input clock;
input reset;
input [7:0] entrada_serie;
input clear;
input shift;
output [7:0] salida_serie ;
logic [tamanyo-1:0][7:0] aux;
always_ff @(posedge clock or negedge reset)
if (!reset)
aux<={tamanyo{8'b0}};
else
if (!clear)
if (shift==1'b1)
aux<={entrada_serie,aux[tamanyo-1:1]};
else
begin
aux[tamaño-1]<= entrada_serie;
aux<={tamanyo{8'b0}};
end
assign salida_serie=aux[0];
endmodule
</code></pre>
<p>I want to understand how can you tell from the code that 5 and 32 flip flops will be generated when the code is synthesized.</p>
| [
{
"answer_id": 74340645,
"author": "mkrieger1",
"author_id": 4621513,
"author_profile": "https://Stackoverflow.com/users/4621513",
"pm_score": 0,
"selected": false,
"text": "SHIFT"
},
{
"answer_id": 74349810,
"author": "Alberto Garcia",
"author_id": 15647384,
"author_profile": "https://Stackoverflow.com/users/15647384",
"pm_score": 2,
"selected": true,
"text": "="
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20435422/"
] |
74,340,534 | <pre><code>import random
money=int(0) # money starts at 0 always
bet=int(input("enter a bet.")) # user inputs a bet.
winningnumber=(random.randint(0,30)) # chooses random integer from 0 - 30, stores it as variable winningnumber
number = int(input("Pick a number 0-30"))
if number % 2 == 0: #checks if number is divisible by 2
print("The number was even, you get 2x your money.") #prints the users winnings
money = float(bet) * float(2) # multiplies the bet by 2
else:
money = bet+0 # doesnt add anyuthing to the bet
if number % 10 ==0: #checks if number is divisible by 10
print("The number was a multiple of 10, you get 3x your money.") #prints the users winnings
money = bet*3 # multiplies the bet by 3
else:
money = bet+0 # doesnt add anyuthing to the bet
primenum = ["3","5","7","11","13","17","19","23","29"] #list of prime numbers
if number == primenum ==0: #if number chosen by user = one of the numbers on the list, the user wins.
print("The number was a prime number, you get 5x your money.") #prints the users winnings
money = bet*5 # multiplies the bet by 5
else:
money=bet+0 # doesnt add anything to the bet
print("the winning number was",winningnumber) #shows the player the winning number
print("Your money for the end of the round is",money) #prints money at end of round
</code></pre>
<p>Why doesn't this code work? I have tried multiple different ways yet the bet doesn't seem to multiply.
I was expecting the code number to be multiplied at the end.</p>
| [
{
"answer_id": 74340647,
"author": "Vin",
"author_id": 7955271,
"author_profile": "https://Stackoverflow.com/users/7955271",
"pm_score": 1,
"selected": false,
"text": "if-else"
},
{
"answer_id": 74340705,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 0,
"selected": false,
"text": "if-else"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20435533/"
] |
74,340,550 | <p>For example, if I have two lists:</p>
<p><code>x <- data.frame(c('a', 'b', 'c'))</code>
<code>y <- data.frame(c('1', '2', '3'))</code></p>
<p>I want my output to look like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>x</th>
<th>y</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>1</td>
</tr>
<tr>
<td>a</td>
<td>2</td>
</tr>
<tr>
<td>a</td>
<td>3</td>
</tr>
<tr>
<td>b</td>
<td>1</td>
</tr>
<tr>
<td>b</td>
<td>2</td>
</tr>
<tr>
<td>b</td>
<td>3</td>
</tr>
<tr>
<td>c</td>
<td>1</td>
</tr>
<tr>
<td>c</td>
<td>2</td>
</tr>
<tr>
<td>c</td>
<td>3</td>
</tr>
</tbody>
</table>
</div>
<p>I sadly have no idea how such an operation is called, or where to start. Could anyone help me with a solution? Thanks!</p>
| [
{
"answer_id": 74340647,
"author": "Vin",
"author_id": 7955271,
"author_profile": "https://Stackoverflow.com/users/7955271",
"pm_score": 1,
"selected": false,
"text": "if-else"
},
{
"answer_id": 74340705,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 0,
"selected": false,
"text": "if-else"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20435521/"
] |
74,340,555 | <p>I need to read data from a JSON and there are some money data as shown below:</p>
<pre><code>$234,205,860
</code></pre>
<p>I thought to map this data to my DTO class as String, but I am not sure if there is a proper data type in Java. I look at on the web, but could not see any for this kind of data.</p>
<p>So, is there any data type for this money value? Or should I use String to keep this kind of data in Java?</p>
| [
{
"answer_id": 74340647,
"author": "Vin",
"author_id": 7955271,
"author_profile": "https://Stackoverflow.com/users/7955271",
"pm_score": 1,
"selected": false,
"text": "if-else"
},
{
"answer_id": 74340705,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 0,
"selected": false,
"text": "if-else"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20416459/"
] |
74,340,602 | <p>I have a chat collection.</p>
<p>each document has an array with two user id's.
my goal is to get the chat that has both user sys id's</p>
<p>I tried running the following but I got an error because we cant use two 'arrayContains' in one query.</p>
<p>Is there any way to perform such query?</p>
<p>here is an image of the data structure
<a href="https://i.stack.imgur.com/aovhw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aovhw.png" alt="data structure" /></a></p>
<pre><code> Future getChat({required List userIdsArr}) async {
var docId = '';
userIdsArr.sort((a, b) {
return a.compareTo(b);
});
var filter1 = userIdsArr[0];
var filter2 = userIdsArr[1];
await chat
.where(userIdsArrayColumn, arrayContains: userIdsArr[0])
.where(userIdsArrayColumn, arrayContains: userIdsArr[1])
.get()
.then((value) {
value.docs.forEach((element) {
docId = element.id;
});
});
return docId;
}
</code></pre>
<p>the goal is to get the chat that pertains to the users being passed in userIdsArr</p>
| [
{
"answer_id": 74340647,
"author": "Vin",
"author_id": 7955271,
"author_profile": "https://Stackoverflow.com/users/7955271",
"pm_score": 1,
"selected": false,
"text": "if-else"
},
{
"answer_id": 74340705,
"author": "ScottC",
"author_id": 20174226,
"author_profile": "https://Stackoverflow.com/users/20174226",
"pm_score": 0,
"selected": false,
"text": "if-else"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17281101/"
] |
74,340,633 | <p>I have a large csv file with consecutive repeated rows except for the time related columns (columns 1, 2, 3, 4) I want to skip except for the first occurence (non-consecutive repeated rows are ok).</p>
<p>Is there a more efficient way than the below code? (I also don't want to painfully hard code that condition, say when I have more than 9 columns)</p>
<pre class="lang-bash prettyprint-override"><code> awk -F"," -v OFS="," 'p[5]!=$5 || p[6]!=$6 || p[7]!=$7 || p[8]!=$8 || p[9]!=$9 {for (i = 5; i <= 9; i++) {p[i] = $i}; print $0}' file_path
</code></pre>
<hr />
<p>Example input:</p>
<pre><code>a,z,k,d,5,6,7,8,9
b,x,j,d,5,6,7,8,9
c,c,l,e,8,9,1,2,3
d,v,k,r,8,9,1,2,3
e,b,j,e,9,1,2,3,4
f,n,h,t,5,6,7,8,9
g,m,g,w,6,3,4,5,6
h,a,f,q,4,5,6,7,8
i,s,d,w,4,5,6,7,8
i,s,d,w,4,5,6,7,8
</code></pre>
<p>Desired output:</p>
<pre><code>a,z,k,d,5,6,7,8,9
c,c,l,e,8,9,1,2,3
e,b,j,e,9,1,2,3,4
f,n,h,t,5,6,7,8,9
g,m,g,w,6,3,4,5,6
h,a,f,q,4,5,6,7,8
</code></pre>
| [
{
"answer_id": 74340702,
"author": "Ed Morton",
"author_id": 1745001,
"author_profile": "https://Stackoverflow.com/users/1745001",
"pm_score": 3,
"selected": true,
"text": "$ awk '{prev=key; key=$0; sub(/([^,]*,){4}/,\"\",key)} key != prev' file\na,z,k,d,5,6,7,8,9\nc,c,l,e,8,9,1,2,3\ne,b,j,e,9,1,2,3,4\nf,n,h,t,5,6,7,8,9\ng,m,g,w,6,3,4,5,6\nh,a,f,q,4,5,6,7,8\n"
},
{
"answer_id": 74340706,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "awk"
},
{
"answer_id": 74340986,
"author": "karakfa",
"author_id": 1435869,
"author_profile": "https://Stackoverflow.com/users/1435869",
"pm_score": 2,
"selected": false,
"text": "$ sed 's/,/ /4' file | uniq -f1 | sed 's/ /,/'\n"
},
{
"answer_id": 74341536,
"author": "HatLess",
"author_id": 16372109,
"author_profile": "https://Stackoverflow.com/users/16372109",
"pm_score": 1,
"selected": false,
"text": "$ sed -En 'G;/^([^,]*,){4}([^\\n]*)\\n([^,]*,){4}\\2/d;h;P' input_file\na,z,k,d,5,6,7,8,9\nc,c,l,e,8,9,1,2,3\ne,b,j,e,9,1,2,3,4\nf,n,h,t,5,6,7,8,9\ng,m,g,w,6,3,4,5,6\nh,a,f,q,4,5,6,7,8\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5805389/"
] |
74,340,636 | <p>I was not sure if better to ask here, or on GameDev Stack Exchange. I believe it carries over to general programming.</p>
<p><strong>Context</strong></p>
<ul>
<li>I am using Unity3D and building an Online Multiplayer Game.</li>
<li>I would like to use Constructor Dependency Injection, so no "magic" reflection to keep things simple and be able to view my dependencies more clearly.</li>
<li>I would like to have Sub Injector Classes that will resolve dependencies.</li>
</ul>
<p>For example when I spawn a <code>Player</code> into the game world the root <code>PlayerScript</code> will be an injector that will resolve all of the players dependencies.</p>
<p>The <code>Player</code> will have a service collection and then it will construct each service the player needs to function.</p>
<p><strong>Problem</strong></p>
<p>The <code>Player</code> injector becomes a large list of constructing the services the player needs. I am trying to use SOLID principles, so by splitting my player services into many smaller services. This might mean having 20-30 services on the player. It just feels wrong to have 20-30 lines of code constructing each services and passing them their dependencies.</p>
<p>This is kind of what it is looking like if it wasn't in Unity3D.</p>
<p><strong>Outside of Unity Example</strong></p>
<pre><code>
//PlayerMovement
Services.Add<CharacterController>(new CharacterController(Inj 1,Inj 2, Inj 3));
//PlayerInputs
Services.Add<UIInputs>(new UIInputs(Inject 1,Inj 2, Inj 3));
Services.Add<InventoryInputs>(new InventoryInputs(Inject 1,Inj 2));
Services.Add<MovementInputs>(new MovementInputs(Inj 1,Inj 2, Inj 3));
Services.Add<InteractionInputs>(new CrossHair(Inj 1,Inj 2));
//PlayerInventory
Services.Add<InventoryStateManager>(new InventoryStateManager(Inj 1,Inj 2, Inj 3));
Services.Add<PlayerInventory>(new PlayerInventory(Inj 1,Inj 2, Inj 3));
Services.Add<CursorInventory>(new CursorInventory(Inj 1,Inj 2, Inj 3));
Services.Add<ActionBarInventory>(new ActionBarInventory(Inj 1,Inj 2, Inj 3));
//PlayerUI
Services.Add<PlayerUI>(new PlayerUI(Inj 1,Inj 2, Inj 3);
Services.Add<InventoryViewManager>(new InventoryViewManager(Inj 1,Inj 2, Inj 3));
Services.Add<PlayerInventoryView>(new PlayerInventoryView(Inj 1,Inj 2, Inj 3));
Services.Add<CursorInventoryView>(new CursorInventoryView(Inj 1,Inj 2));
Services.Add<ActionBarInventoryView>(new ActionBarInventoryView(Inj 1,Inj 2, Inj 3));
Services.Add<StorageInventoryView>(new StorageInventoryView(Inj 1,Inj 2));
Services.Add<ActionBarSelection>(new ActionBarSelection(Inj 1,Inj 2, Inj 3));
Services.Add<CrossHair>(new CrossHair(Inj 1,Inj 2, Inj 3));
</code></pre>
<p><strong>Unity Differences</strong></p>
<p>Only read if interested in how I implemented using Unity.</p>
<p>In unity you cannot construct monobehaviour classes. So instead you have to find all of your dependencies that already exist on the player.</p>
<p>I did that by adding <code>IService</code> interface to all Monobehaviours in the Scene. When Player Spawns into the server it will find all <code>IService</code>s, and then I will inject the dependencies by calling an initialization function on each service.</p>
<p><strong>Question</strong></p>
<p>Is it normal to have a lot of services constructed in one injector class?</p>
<p>Please correct me if I have a misunderstanding here.</p>
| [
{
"answer_id": 74340702,
"author": "Ed Morton",
"author_id": 1745001,
"author_profile": "https://Stackoverflow.com/users/1745001",
"pm_score": 3,
"selected": true,
"text": "$ awk '{prev=key; key=$0; sub(/([^,]*,){4}/,\"\",key)} key != prev' file\na,z,k,d,5,6,7,8,9\nc,c,l,e,8,9,1,2,3\ne,b,j,e,9,1,2,3,4\nf,n,h,t,5,6,7,8,9\ng,m,g,w,6,3,4,5,6\nh,a,f,q,4,5,6,7,8\n"
},
{
"answer_id": 74340706,
"author": "markp-fuso",
"author_id": 7366100,
"author_profile": "https://Stackoverflow.com/users/7366100",
"pm_score": 1,
"selected": false,
"text": "awk"
},
{
"answer_id": 74340986,
"author": "karakfa",
"author_id": 1435869,
"author_profile": "https://Stackoverflow.com/users/1435869",
"pm_score": 2,
"selected": false,
"text": "$ sed 's/,/ /4' file | uniq -f1 | sed 's/ /,/'\n"
},
{
"answer_id": 74341536,
"author": "HatLess",
"author_id": 16372109,
"author_profile": "https://Stackoverflow.com/users/16372109",
"pm_score": 1,
"selected": false,
"text": "$ sed -En 'G;/^([^,]*,){4}([^\\n]*)\\n([^,]*,){4}\\2/d;h;P' input_file\na,z,k,d,5,6,7,8,9\nc,c,l,e,8,9,1,2,3\ne,b,j,e,9,1,2,3,4\nf,n,h,t,5,6,7,8,9\ng,m,g,w,6,3,4,5,6\nh,a,f,q,4,5,6,7,8\n"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19204352/"
] |
74,340,665 | <p>I want to cut zeros from the beginning of the string in the calculation rules but don't want to make it a number.</p>
<p>I want something like this:</p>
<pre><code>'000' // '0'
'050' // '50'
'076' // '76'
'135' // '135'
'107' // '107'
</code></pre>
| [
{
"answer_id": 74340689,
"author": "acdcjunior",
"author_id": 1850609,
"author_profile": "https://Stackoverflow.com/users/1850609",
"pm_score": 2,
"selected": false,
"text": "Number('005').toString()"
},
{
"answer_id": 74340692,
"author": "Michael M.",
"author_id": 13376511,
"author_profile": "https://Stackoverflow.com/users/13376511",
"pm_score": 1,
"selected": false,
"text": "Number"
},
{
"answer_id": 74340766,
"author": "Michael Liu",
"author_id": 1127114,
"author_profile": "https://Stackoverflow.com/users/1127114",
"pm_score": 3,
"selected": true,
"text": "const trimLeadingZeros = s => s.replace(/^0+(?!$)/, '');\n\nconsole.log(trimLeadingZeros('000'));\nconsole.log(trimLeadingZeros('050'));\nconsole.log(trimLeadingZeros('076'));\nconsole.log(trimLeadingZeros('135'));\nconsole.log(trimLeadingZeros('107'));"
},
{
"answer_id": 74340993,
"author": "jsejcksn",
"author_id": 438273,
"author_profile": "https://Stackoverflow.com/users/438273",
"pm_score": 0,
"selected": false,
"text": "/**\n * @param {string} inputStr The input string\n * @param {string} char The character to trim\n * @returns {string}\n */\nfunction trimLeading (inputStr, char = ' ') {\n let index = 0;\n\n for (const s of inputStr) {\n if (s !== char) break;\n index += s.length;\n }\n\n return inputStr.slice(index);\n}\n\n/**\n * Special case behavior for an input with only zeroes\n *\n * @param {string} inputStr The input string\n * @returns {string}\n */\nfunction trimLeadingZeroes (inputStr) {\n const result = trimLeading(inputStr, '0');\n return result.length > 0 ? result : '0';\n}\n\nconst inputs = [\n '000', // '0'\n '050', // '50'\n '076', // '76'\n '135', // '135'\n '107', // '107'\n];\n\nconst results = inputs.map(trimLeadingZeroes);\nconsole.log(results);\n\n// Example with multi-byte unicode:\nconst blackCat = '⬛';\nconst cat = '';\nconst zeroWitdhJoinerAndBlackLargeSquare = trimLeading(blackCat, cat);\nconsole.log(`${blackCat} - ${cat} = ${zeroWitdhJoinerAndBlackLargeSquare}`);"
}
] | 2022/11/06 | [
"https://Stackoverflow.com/questions/74340665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17333112/"
] |
74,340,724 | <p>If I have a string like:</p>
<pre><code>query = """
SELECT
alias.column_one,
alias.column_two,
alias.column_three
FROM
table_name
"""
</code></pre>
<p>How do I just return the characters between "SELECT" and "FROM" in a list so I have a list like below which also accounts for line breaks:</p>
<pre><code>columns = ['alias.column_one', 'alias.column_two', 'alias.column_three']
</code></pre>
<p>I've tried importing re but I'm still stuck</p>
| [
{
"answer_id": 74340782,
"author": "Vin",
"author_id": 7955271,
"author_profile": "https://Stackoverflow.com/users/7955271",
"pm_score": 1,
"selected": false,
"text": "query = \"\"\"\nSELECT\n alias.column_one,\n alias.column_two,\n alias.column_three\nFROM\n table_name\n\"\"\"\n\ncolumns = query.split('\\n') # split the string at every line break - '\\n'\ncolumns = [column.strip() for column in columns] # strip out the leading spaces\n\n# take the slice of the list between 'SELECT' and 'FROM':\ncolumns = columns[columns.index('SELECT')+1:columns.index('FROM')] \n"
},
{
"answer_id": 74340849,
"author": "Sunny",
"author_id": 996565,
"author_profile": "https://Stackoverflow.com/users/996565",
"pm_score": 0,
"selected": false,
"text": ">>> s\n'\\nSELECT\\n alias.column_one,\\n alias.column_two,\\n \nalias.column_three\\nFROM\\n table_name\\n'\n\n>>> print((s.split('SELECT'))[1].split('FROM')[0])\n\nalias.column_one,\nalias.column_two,\nalias.column_three\n"
},
{
"answer_id": 74340968,
"author": "banzhe",
"author_id": 14520847,
"author_profile": "https://Stackoverflow.com/users/14520847",
"pm_score": 0,
"selected": false,
"text": " alias.column_one,\n alias.column_two,\n alias.column_three\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74340724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13621215/"
] |
74,340,727 | <p>CSS newbie here wondering if this is possible. If I have something like the code below, is it possible to override just the section that has the class itemtile AND data-id of ABC123? My goal is to hide that entire section from being displayed. I've reviewed some past comments about specifity but when it comes to wanting both values to exist I get a bit lost. I'm mucking with trying to override code for a site that is not mine using a personal plugin.</p>
<pre><code><div id="itemgrid" class="section">
<div class="itemtile" data-id="ABC123">
<div class="itemcontent"></div>
</div>
<div class="itemtile" data-id="DEF123">
<div class="itemcontent"></div>
</div>
</div>
</code></pre>
<p>I did some code examination in the debugger and can make the page do what I want by removing the div element for the data-id's I want to hide just not sure how to do it in CSS. I'm not asking for help on creating the plugin just if and how I can address an element that specifically.</p>
| [
{
"answer_id": 74340749,
"author": "Anye",
"author_id": 16752210,
"author_profile": "https://Stackoverflow.com/users/16752210",
"pm_score": 3,
"selected": true,
"text": "JavaScript"
},
{
"answer_id": 74340886,
"author": "liquidot",
"author_id": 20400911,
"author_profile": "https://Stackoverflow.com/users/20400911",
"pm_score": 0,
"selected": false,
"text": "style=\"\""
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74340727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10885761/"
] |
74,340,744 | <pre><code>lcolhead = ['ID', 'Name', 'Email']
lrow1 = [1, 'Jane Doe', 'janedoe@doemail.com']
lrow2 = [2, 'Jake Doe', 'jakedoe@doemail.com']
lrow3 = [3, 'Jane Fox', 'janefox@foxmail.com']
ltable1 = [lcolhead, lrow1, lrow2, lrow3]
for row in ltable1:
for item in row:
print(item, end=' | ')
</code></pre>
<p>output is each value on a single line separated by ' | '</p>
<pre class="lang-none prettyprint-override"><code>ID | Name | Email | 1 | Jane Doe | janedoe@doemail.com | 2 | John Doe | johndoe@doemail.com...
</code></pre>
<p>I want it to print:</p>
<pre class="lang-none prettyprint-override"><code>ID | Name | Email |
1 | Jane Doe | janedoe@doemail.com |
2 | John Doe | johndoe@doemail.com |
</code></pre>
<p>storing the column headers as a list as well as the row values in a list of lists but cannot figure out why it prints everything to a single line.</p>
| [
{
"answer_id": 74340959,
"author": "user3435121",
"author_id": 3435121,
"author_profile": "https://Stackoverflow.com/users/3435121",
"pm_score": -1,
"selected": false,
"text": "for row in ltable1:\n print( \" | \".join( row) + \" | \")\n"
},
{
"answer_id": 74340982,
"author": "Grismar",
"author_id": 4390160,
"author_profile": "https://Stackoverflow.com/users/4390160",
"pm_score": 1,
"selected": false,
"text": "print()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74340744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20435686/"
] |
74,340,759 | <p>I have a number of instance running under my app service in Azure. I need to get back all the id's of these instances.</p>
<p>I am currently using</p>
<pre><code>Get-AzureRmResource -ResourceGroupName $ResourceGroupName -ResourceType
Microsoft.Web/sites/instances -Name $WebAppName -ApiVersion 2016-03-01
</code></pre>
<p>But is there an equivalent command using the az cmdlets ?</p>
| [
{
"answer_id": 74340959,
"author": "user3435121",
"author_id": 3435121,
"author_profile": "https://Stackoverflow.com/users/3435121",
"pm_score": -1,
"selected": false,
"text": "for row in ltable1:\n print( \" | \".join( row) + \" | \")\n"
},
{
"answer_id": 74340982,
"author": "Grismar",
"author_id": 4390160,
"author_profile": "https://Stackoverflow.com/users/4390160",
"pm_score": 1,
"selected": false,
"text": "print()"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74340759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19592688/"
] |
74,340,763 | <p>I am currently developing a Discord bot for replit, and I am able to get it to post and even get it to send an intro message when joining a server, however whenever I try to get it to respond to a command I type it won't respond. The message for the first one client.on guild create works. However the client.on for async message will not work.</p>
<p>This is what I have so far.</p>
<pre><code>const { Client } = require('discord.js');
const client = new Client({ intents: 32767 });
//const Discord = require('discord.js');
const keepAlive = require('./server');
require("dotenv").config();
//const client = new Discord.Client();
//const fetch = require('node-fetch');
const config = require('./package.json');
const prefix = '!';
const guild = "";
client.once('ready', () => {
console.log('Jp Learn Online');
});
// let defaultChannel = "";
// guild.channels.cache.forEach((channel) => {
// if(channel.type == "text" && defaultChannel == "") {
// if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
// defaultChannel = channel;
// }
// }
// })
//defaultChannel.send("This is a test message I should say this message when I join");
//if(guild.systemChannelId != null) return guild.systemChannel.send("This is a test message I should say this message when I join"), console.log('Bot entered new Server.')
// client.on('guildCreate', (g) => {
// const channel = g.channels.cache.find(channel => channel.type === 'GUILD_TEXT' && channel.permissionsFor(g.me).has('SEND_MESSAGES'))
// channel.send("This is a test message I should say this message when I join");
// });
client.on('guildCreate', guild => {
guild.systemChannel.send('this message wil print')
});
client.on('message', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/); // This splits our code into to allow multiple commands.
const command = args.shift().toLowerCase();
if (command === 'jhelp') {
message.channel.send('こんにちは、私はDiscordロボットです。始めたいなら、!jhelp タイプしてください。 \n\n Hello I am a discord bot built to help learn the Japanese language! \n\n If you want to access a japanese dictionary type !dictionary \n\n If you would like to learn a random Japanese Phrase type !teachme \n\n If you would like to answer a challenge question type !challenge1 through 5 each different numbered challnege will ask a different question \n (ie. !challenge1) this will ask the first question.')
}
</code></pre>
<p>please note. the lower parts of the code are simply commands. That expand further from jhelp I want to know mainly why my second client.on with messages wont work specifically in the context of working with replit.</p>
<p>Thanks for the help in advance.</p>
<p>I expected that maybe changing intents might work, I even went into the discord developer portal, and enabled options, and am still not able to get it working.</p>
| [
{
"answer_id": 74342059,
"author": "Thunder",
"author_id": 16499723,
"author_profile": "https://Stackoverflow.com/users/16499723",
"pm_score": 0,
"selected": false,
"text": "const { Client } = require('discord.js');\nconst client = new Client({ intents: 131071 });\n\n//const Discord = require('discord.js');\nconst keepAlive = require('./server');\nrequire(\"dotenv\").config();\n//const client = new Discord.Client();\n//const fetch = require('node-fetch');\nconst config = require('./package.json');\nconst prefix = '!';\nconst guild = \"\";\n\n\nclient.once('ready', () => {\n console.log('Jp Learn Online');\n});\n\n// let defaultChannel = \"\";\n// guild.channels.cache.forEach((channel) => {\n// if(channel.type == \"text\" && defaultChannel == \"\") {\n// if(channel.permissionsFor(guild.me).has(\"SEND_MESSAGES\")) {\n// defaultChannel = channel;\n// }\n// }\n// })\n//defaultChannel.send(\"This is a test message I should say this message when I join\");\n\n\n//if(guild.systemChannelId != null) return guild.systemChannel.send(\"This is a test message I should say this message when I join\"), console.log('Bot entered new Server.')\n\n// client.on('guildCreate', (g) => {\n// const channel = g.channels.cache.find(channel => channel.type === 'GUILD_TEXT' && channel.permissionsFor(g.me).has('SEND_MESSAGES'))\n// channel.send(\"This is a test message I should say this message when I join\");\n// });\n\nclient.on('guildCreate', guild => {\n guild.systemChannel.send('this message wil print')\n});\n\nclient.on('messageCreate', async message => {\n if (!message.content.startsWith(prefix) || message.author.bot) return;\n\n const args = message.content.slice(prefix.length).split(/ +/); // This splits our code into to allow multiple commands.\n const command = args.shift().toLowerCase();\n\n if (command === 'jhelp') {\n message.channel.send('こんにちは、私はDiscordロボットです。始めたいなら、!jhelp タイプしてください。 \\n\\n Hello I am a discord bot built to help learn the Japanese language! \\n\\n If you want to access a japanese dictionary type !dictionary \\n\\n If you would like to learn a random Japanese Phrase type !teachme \\n\\n If you would like to answer a challenge question type !challenge1 through 5 each different numbered challnege will ask a different question \\n (ie. !challenge1) this will ask the first question.')\n\n\n }\n"
}
] | 2022/11/07 | [
"https://Stackoverflow.com/questions/74340763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20434076/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.