qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,625,578
|
<p>I'm trying to teach myself to use Google Apps Script, but somehow every function I try returns this error immediately. And since I'm a huge beginner, I don't know what I'm doing wrong.</p>
<p>Here's a simple example of a code I tried to run:</p>
<pre><code>function myFunction(){
//application
//file
var ad = DocumentApp.getActiveDocument();
var docBody = ad.getBody () ;
var paragraphs = docBody.getParagraphs();
//paragraphs[0]. setText ("MY NEW TEXT"):
//var attr = paragraphs[0].getAttributes() ;
//Logger.log(attr);
paragraphs[0].setAttributes({FONT_SIZE:40});
}
</code></pre>
<p>Yet no matter what I'm running really, I get this:</p>
<blockquote>
<p>TypeError: Cannot read property 'getBody' of null
myFunction @ Code.gs:5</p>
</blockquote>
<p>What am I doing wrong?</p>
<p>I have an open Google Doc, I've allowed permissions to run the script project. What else should I try? Thanks.</p>
|
[
{
"answer_id": 74625606,
"author": "Ashkan Sarlak",
"author_id": 2511775,
"author_profile": "https://Stackoverflow.com/users/2511775",
"pm_score": -1,
"selected": false,
"text": "final longestString = list.fold<String>('', \n (previousValue, element) => \n element.length > previousValue.length ? element : previousValue)\n"
},
{
"answer_id": 74625653,
"author": "Minato",
"author_id": 9977565,
"author_profile": "https://Stackoverflow.com/users/9977565",
"pm_score": 1,
"selected": false,
"text": "long_string(arr) {\n var longest = arr[0];\n for (var i = 1; i < arr.length; i++) {\n if (arr[i].length > longest.length) {\n longest = arr[i];\n }\n }\n return longest;\n }\n var arr = [\"Orebro\", \"Sundsvall\", \"Hudriksvall\", \"Goteborgsdsdsds\"];\n print(long_string(arr));\n"
},
{
"answer_id": 74625729,
"author": "Sparko Sol",
"author_id": 20407048,
"author_profile": "https://Stackoverflow.com/users/20407048",
"pm_score": 4,
"selected": true,
"text": "list.reduce((a, b) {\n return a.length > b.length ? a : b;\n})\n list.sort((a, b) {\n return b.length - a.length;\n});\nprint(list[0]);\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8137301/"
] |
74,625,602
|
<p>I am trying to query the following <code>Infoblox</code> data with Ansible and JMESPath <code>json_query</code>:</p>
<pre class="lang-json prettyprint-override"><code>{
"ip_records.json": {
"result": [
{
"_ref": "fixedaddress/blabla",
"ipv4addr": "10.10.10.10",
"network_view": "Bla"
},
{
"_ref": "record:host/blabla",
"ipv4addrs": [
{
"_ref": "record:host_ipv4addr/blabla",
"host": "bla.bla.com",
"ipv4addr": "10.10.10.10"
}
],
"name": "bla.bla.com",
"view": " "
},
{
"_ref": "record:a/blabla",
"ipv4addr": "10.10.10.10",
"name": "bla.bla.com",
"view": "bla"
}
]
}
}
</code></pre>
<p>I want to get only the <code>_ref</code> value for the item with <code>fixedaddress</code> in the <code>_ref</code> value.</p>
<p>Forgot to add that there might also be multiple records with fixedaddress but different IP's. So I also want to filter on a specific IP as the same time.</p>
<p>I have created queries to filter</p>
<ul>
<li>only on IP address given as input</li>
<li>the string <code>fixedaddress</code></li>
<li>a combination of both</li>
</ul>
<p>The first two work as expected. But, I want to combine both conditions and would expect to get the single item as output, but I get nothing. I tried using <code>&&</code> and <code>|</code> to combine both, as showed below.</p>
<pre class="lang-yaml prettyprint-override"><code>- name: "Search IP Record: Task 2.2: Filter Results."
vars:
jmesquery: "[] | [?ipv4addr==`{{ infoblox_ip }}`]._ref"
set_fact:
ip_records_refs: "{{ ip_records.json.result | json_query(jmesquery) }}"
- name: "Search IP Record: Task 2.4: Filter Results."
vars:
jmesquery: "[] | [?_ref.contains(@,`fixedaddress`)]._ref"
set_fact:
ip_records_refs: "{{ ip_records.json.result | to_json | from_json | json_query(jmesquery) }}"
- name: "Search IP Record: Task 2.6: Filter Results."
vars:
# jmesquery: "[] | ([?ipv4addr==`{{ infoblox_ip }}` && _ref.contains(@,`fixedaddress`)])._ref"
jmesquery: "[] | [?ipv4addr==`{{ infoblox_ip }}`].ref | [?_ref.contains(@,`fixedaddress`)]._ref"
set_fact:
ip_records_refs: "{{ ip_records.json.result | to_json | from_json | json_query(jmesquery) }}"
</code></pre>
<p>Output:</p>
<pre><code>TASK [Search IP Record: Task 2.3 Dump variable Content] ***********
ok: [localhost] => {
"ip_records_refs": [
"fixedaddress/blabla",
"record:a/blabla"
]
}
TASK [Search IP Record: Task 2.5 Dump variable Content] ***********
ok: [localhost] => {
"ip_records_refs": [
"fixedaddress/blabla"
]
}
TASK [Search IP Record: Task 2.7 Dump variable Content] ***********
ok: [localhost] => {
"ip_records_refs": []
}
</code></pre>
|
[
{
"answer_id": 74625606,
"author": "Ashkan Sarlak",
"author_id": 2511775,
"author_profile": "https://Stackoverflow.com/users/2511775",
"pm_score": -1,
"selected": false,
"text": "final longestString = list.fold<String>('', \n (previousValue, element) => \n element.length > previousValue.length ? element : previousValue)\n"
},
{
"answer_id": 74625653,
"author": "Minato",
"author_id": 9977565,
"author_profile": "https://Stackoverflow.com/users/9977565",
"pm_score": 1,
"selected": false,
"text": "long_string(arr) {\n var longest = arr[0];\n for (var i = 1; i < arr.length; i++) {\n if (arr[i].length > longest.length) {\n longest = arr[i];\n }\n }\n return longest;\n }\n var arr = [\"Orebro\", \"Sundsvall\", \"Hudriksvall\", \"Goteborgsdsdsds\"];\n print(long_string(arr));\n"
},
{
"answer_id": 74625729,
"author": "Sparko Sol",
"author_id": 20407048,
"author_profile": "https://Stackoverflow.com/users/20407048",
"pm_score": 4,
"selected": true,
"text": "list.reduce((a, b) {\n return a.length > b.length ? a : b;\n})\n list.sort((a, b) {\n return b.length - a.length;\n});\nprint(list[0]);\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20359148/"
] |
74,625,621
|
<p>I need to check <code>if not</code> a string starts with a substring. The substring is <code>any three digits</code> following by <code>-</code> .</p>
<p>so check string start with -> <code>digit digit digit space dash space</code>.</p>
<p>In my code below what should I write instead of <code>???</code></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>
$('button').on('click', function(){
$('.fi').each(function(){
let a = $(this).text().trim();
let b = "???"; // any three digits + " - "
if(!a.startsWith(b)){
console.log('uncorrect string');
}
});
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='fi'>005 - lorem</div>
<div class='fi'>ipsum</div>
<div class='fi'>999 - dolor</div>
<button>CLICK</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74625721,
"author": "TS97",
"author_id": 20643384,
"author_profile": "https://Stackoverflow.com/users/20643384",
"pm_score": 2,
"selected": true,
"text": "^[0-9]{3} \\- $('button').on('click', function(){\n$('.fi').each(function(){\n let a = $(this).text().trim();\n let b = /^[0-9]{3} \\- /i;\n if(!a.match(b)){\n console.log('uncorrect string');\n }\n });\n});\n"
},
{
"answer_id": 74625753,
"author": "raul g h",
"author_id": 7023619,
"author_profile": "https://Stackoverflow.com/users/7023619",
"pm_score": 0,
"selected": false,
"text": "if (a.indexOf(b) != 0)\n"
},
{
"answer_id": 74625909,
"author": "4b0",
"author_id": 965146,
"author_profile": "https://Stackoverflow.com/users/965146",
"pm_score": 1,
"selected": false,
"text": "test div $('button').on('click', function() {\n $('.fi').each(function() {\n let regex = /^\\d{3}\\s-\\s/i\n let str = $(this).text();\n let result = regex.test(str);\n if (result)\n $(this).show();\n else\n console.log('uncorrect string');\n\n });\n}); .fi {\n display: none\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<div class='fi'>005 - lorem</div>\n<div class='fi'>ipsum</div>\n<div class='fi'>999 - dolor</div>\n<button>CLICK</div>"
},
{
"answer_id": 74625989,
"author": "Sharad Kumar Yadav",
"author_id": 9336592,
"author_profile": "https://Stackoverflow.com/users/9336592",
"pm_score": 1,
"selected": false,
"text": "<div class='fi'>005 - lorem</div>\n<div class='fi'>ipsum</div>\n<div class='fi'>999 - dolor</div>\n<div class='fi'>20 - dolors</div>\n<button>CLICK</div>\n\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<script type=\"text/javascript\">\n $('button').on('click', function(){\n $('.fi').each(function(){\n let a = $(this).text().trim();\n let b = a.substring(0, 3);\n if(b.trim().length < 3) { \n alert(a);\n }\n });\n});\n</script>\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10983537/"
] |
74,625,639
|
<p>I have a problem with Entity Framework Core.</p>
<p>I made an admin panel for monitoring in "Blazor Server" with stardate and to date users choose and
every click search with from date && to date memory increment 200mb, 300mb, 400mb, 1gb..</p>
<p>I need don't increment memory after call dbcontext..</p>
<p>Method call:</p>
<pre><code>var data = await Task.Run(() => Service.GetJasminData(fromdate, todate)?.OrderBy(x => x.SendDate).ToList());
</code></pre>
<p>Method:</p>
<pre><code>protected readonly ApplicationDBContext _dBContext;
public SmsService(ApplicationDBContext _db)
{
_dBContext = _db;
}
public List<Sms> GetJasminData(DateTime fromdate, DateTime todate, int count = 30)
{
return _dBContext.Jasmin.Where(x => x.SendDate >= fromdate && x.SendDate <= todate).ToList();
}
</code></pre>
|
[
{
"answer_id": 74625721,
"author": "TS97",
"author_id": 20643384,
"author_profile": "https://Stackoverflow.com/users/20643384",
"pm_score": 2,
"selected": true,
"text": "^[0-9]{3} \\- $('button').on('click', function(){\n$('.fi').each(function(){\n let a = $(this).text().trim();\n let b = /^[0-9]{3} \\- /i;\n if(!a.match(b)){\n console.log('uncorrect string');\n }\n });\n});\n"
},
{
"answer_id": 74625753,
"author": "raul g h",
"author_id": 7023619,
"author_profile": "https://Stackoverflow.com/users/7023619",
"pm_score": 0,
"selected": false,
"text": "if (a.indexOf(b) != 0)\n"
},
{
"answer_id": 74625909,
"author": "4b0",
"author_id": 965146,
"author_profile": "https://Stackoverflow.com/users/965146",
"pm_score": 1,
"selected": false,
"text": "test div $('button').on('click', function() {\n $('.fi').each(function() {\n let regex = /^\\d{3}\\s-\\s/i\n let str = $(this).text();\n let result = regex.test(str);\n if (result)\n $(this).show();\n else\n console.log('uncorrect string');\n\n });\n}); .fi {\n display: none\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<div class='fi'>005 - lorem</div>\n<div class='fi'>ipsum</div>\n<div class='fi'>999 - dolor</div>\n<button>CLICK</div>"
},
{
"answer_id": 74625989,
"author": "Sharad Kumar Yadav",
"author_id": 9336592,
"author_profile": "https://Stackoverflow.com/users/9336592",
"pm_score": 1,
"selected": false,
"text": "<div class='fi'>005 - lorem</div>\n<div class='fi'>ipsum</div>\n<div class='fi'>999 - dolor</div>\n<div class='fi'>20 - dolors</div>\n<button>CLICK</div>\n\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<script type=\"text/javascript\">\n $('button').on('click', function(){\n $('.fi').each(function(){\n let a = $(this).text().trim();\n let b = a.substring(0, 3);\n if(b.trim().length < 3) { \n alert(a);\n }\n });\n});\n</script>\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20621511/"
] |
74,625,659
|
<p>I am wondering how can I delete a specific symbol for an entire column. Here is what the original data look like: <a href="https://i.stack.imgur.com/P1D12.png" rel="nofollow noreferrer">original data</a>.</p>
<p>The only element I want to get are the first words.</p>
<p>Here is what my full dataset look like:</p>
<p>Below are data background info</p>
<pre><code>library("dplyr")
library("stringr")
library("tidyverse")
library("ggplot2")
# load the .csv into R studio, you can do this 1 of 2 ways
#read.csv("the name of the .csv you downloaded from kaggle")
spotiify_origional <- read.csv("charts.csv")
spotiify_origional <- read.csv("https://raw.githubusercontent.com/info201a-au2022/project-group-1-section-aa/main/data/charts.csv")
View(spotiify_origional)
# filters down the data
# removes the track id, explicit, and duration columns
spotify_modify <- spotiify_origional %>%
select(name, country, date, position, streams, artists, genres = artist_genres)
#returns all the data just from 2022
#this is the data set you should you on the project
spotify_2022 <- spotify_modify %>%
filter(date >= "2022-01-01") %>%
arrange(date) %>%
group_by(date)
spotify_2022_global <- spotify_modify %>%
filter(date >= "2022-01-01") %>%
filter(country == "global") %>%
arrange(date) %>%
group_by(streams)
View(spotify_2022_global)
</code></pre>
<p>This is what I did,</p>
<pre><code>top_15 <- spotify_2022_global[order(spotify_2022_global$streams, decreasing = TRUE), ]
top_15 <- top_15[1:15,]
top_15$streams <- as.numeric(top_15$streams)
View(top_15)
top_15 <- top_15 %>%
separate(genres, c("genres"), sep = ',')
top_15$genres<-gsub("]","",as.character(top_15$genres))
View(top_15)
</code></pre>
<p>And now the name look like this:</p>
<p><a href="https://i.stack.imgur.com/Z92uM.png" rel="nofollow noreferrer">name now look like this</a></p>
<p>I tried use the same gsub function to remove the rest of the brackets and quotation marks, but it didn't work.</p>
<p>I wonder what should I do at this point? Any recommendations will be hugely help! Thank you!</p>
|
[
{
"answer_id": 74626003,
"author": "pluke",
"author_id": 948397,
"author_profile": "https://Stackoverflow.com/users/948397",
"pm_score": 0,
"selected": false,
"text": "top_15$genres <- gsub(\"]|\\\\[|[']\",\"\",as.character(top_15$genres))\n \"]|\\\\[|[']\" | ] \\\\[ ['] spotify_2022_global %>% \n arrange(desc(streams)) %>% \n head(15) %>%\n mutate(streams = as.numeric(streams),\n genres = gsub(\"]|\\\\[|[']|,\",\"\",genres), # remove brackets and quote marks\n genres = str_split(genres, \",\")[[1]][1])) # get first word from list\n"
},
{
"answer_id": 74626174,
"author": "MarBlo",
"author_id": 4282026,
"author_profile": "https://Stackoverflow.com/users/4282026",
"pm_score": 1,
"selected": false,
"text": "sub string::word() w <- \"[firstWord, secondWord, thirdWord]\"\n\nstringr::word(gsub('[\\\\[,\\']', '', w),1)\n#> [1] \"firstWord\"\n w <- \"['firstWord', 'secondWord', 'thirdWord']\""
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20353870/"
] |
74,625,694
|
<p>I have a base class A, which does some preliminary stuff. There are 2 subclasses B and C, whose behaviours are slightly different from each other. There is a function in A say <code>foo</code>, which is almost the same for both B and C, except one little step, which involves a function call to <code>bar</code>. <code>bar</code> is virtual in A and has definitions in B and C. The problem is <code>bar</code> has an extra input in C. How do i handle this in the most acceptable and clean way ?</p>
<pre><code>class A {
public:
A( int a, int b );
~A();
void foo( int a, int b );
virtual void bar( int a, int b );
};
class B : public A {
public:
B( int a, int b );
~B();
void bar( int a, int b );
};
class C: public A {
public:
C( int a, int b, int c );
~C();
void bar( int a, int b, int c );
}
void A::foo( int a, int b )
{
// Some code
bar( a, b );
// Some code
}
A::A( int a, int b )
{
// Some code
foo( a, b );
// Some code
}
</code></pre>
<p>The constructor and only the constructor calls <code>foo</code> which inturn is the only function that calls <code>bar</code>. I understand functions with a different signature than the base class doesnt override the virtual function in the base class. One way of doing it, is to have <code>c</code> as an argument to <code>A::foo</code> and <code>A::bar</code> also, but i want to avoid doing it, since <code>c</code> wont make much sense in case of <code>B</code>. Is there a better way of passing <code>c</code> cleanly to <code>bar</code> ?</p>
<p>Edit:</p>
<p>To give some context, class <code>A</code> is a FileReader class which reads from a file, and stores it in a <code>vector<unordered_map<int,int>></code>, where every index in the vector corresponds to a record.</p>
<p>For class <code>C</code>, instead of having just a single <code>vector<unordered_map<int,int>></code>, it was decided that it would be better if we had a <code>vector<unordered_map<int,int>></code> and a <code>vector<size_t></code>, because multiple records in the input, now belong to the same entity. Here every index in the first vector correspond to the <code>entity</code> and not the <code>record</code>. And the second vector maps the <code>record</code> to its corresponding <code>entity</code>. To find which records belong to which entity, there is an external input in the form of a big structure <code>c</code>, which maps one field of the record to the entity.</p>
<p>Class <code>B</code> was originally just class <code>A</code> itself. But now since there are 2 different behaviors of the similar thing, I decided to create a separate derived class for that, and make <code>A</code> a template.</p>
|
[
{
"answer_id": 74628001,
"author": "Petr",
"author_id": 3216312,
"author_profile": "https://Stackoverflow.com/users/3216312",
"pm_score": 1,
"selected": false,
"text": "void A::foo( int a, int b )\n{\n // Some code\n bar( a, b );\n // Some code\n}\n c void A::readAll() {\n int a, b;\n while (file >> a >> b) {\n // a, b is the raw record as stored on disk\n processRecord(a, b);\n }\n}\n\nvoid B::processRecord(int a, int b) {\n data_[a] = b;\n}\n\nvoid C::processRecord(int a, int b) {\n size_t entityId = vector_.size();\n vector_.push_back(b);\n // now vector[enityId] == b\n data_[a] = entityId;\n}\n A B C A Processor B C A B C A a b entityId entityId B"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7075416/"
] |
74,625,700
|
<p>I have 2 functions in ngOninit</p>
<pre><code>ngOnInit(){
this.getRowData();
this.getWrapperGridData();
}
</code></pre>
<p>GetRowData() is used to subscribe to a service and it looks like this</p>
<pre><code> getRowData() {
this.showDataServiceSubscription = this.heroService.showData().subscribe((data) => {
this.onlineData = data;
console.log('onlineData 1',this.onlineData);
})
}
</code></pre>
<p>In getWrapperGridData, I am calling this.onlineData again like this</p>
<pre><code> getWrapperGridData(){
console.log('onlineData',this.onlineData);
}
</code></pre>
<p>The problem is I am getting the result of onlineData inside getRowData method as it is written inside subscribe but I am getting undefined inside getWrapperGridData. How do we fix this?</p>
|
[
{
"answer_id": 74626069,
"author": "Eli Porush",
"author_id": 14598976,
"author_profile": "https://Stackoverflow.com/users/14598976",
"pm_score": 1,
"selected": false,
"text": "getWrapperGridData rxjs pipe showData getRowData() {\n this.showDataServiceSubscription = \n this.heroService.showData()\n .pipe(tap(data => {\n // here you can do what you plan to to do inside getWrapperGridData\n }))\n .subscribe((data) => {\n this.onlineData = data;\n console.log('onlineData 1',this.onlineData);\n\n })\n }\n subscribe .ts Observable this.onlineData$ = this.heroService.showData();\n async pipe"
},
{
"answer_id": 74626089,
"author": "Philipp Meissner",
"author_id": 3686898,
"author_profile": "https://Stackoverflow.com/users/3686898",
"pm_score": 0,
"selected": false,
"text": "getRowData getWrapperGridData getWrapperGridData getRowData getWrapperGridData getRowData switchMap getWrapperGridData tap switchMap import { switchMap } from 'rxjs/operators';\n\nexport class Foo implements OnInit {\n ngOnInit(){\n this.getData();\n }\n \n getData() {\n this.heroService.showData().pipe(\n switchMap((onlineData) => {\n this.onlineData = onlineData; // In case you need this globally\n\n return this.gridWrapperService.getData(onlineData);\n })\n ).subscribe((gridWrapperData) => {\n // Deal with the data.\n })\n }\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7816606/"
] |
74,625,770
|
<p>I want to give users the option to input a URL into an input field. At the moment it is really strict as it only accepts absolute URLs like this: <code>https://example.com/a.profile</code>.</p>
<p>The users gave feedback that they also want to be able to just type a relative URL like the following: <code>example.com/a.profile</code> or <code>www.example.com/a.profile</code>.</p>
<p>How do you take an arbitrarily relative or absolute URL and make sure that the output is an absolute URL? The <code>https:</code> protocol can be assumed for all URLs.</p>
|
[
{
"answer_id": 74626155,
"author": "user3691763",
"author_id": 3691763,
"author_profile": "https://Stackoverflow.com/users/3691763",
"pm_score": 0,
"selected": false,
"text": "const FULL_URL_REGEX =\n /(http|https):\\/\\/(\\w+:{0,1}\\w*@)?(\\S+)(:[0-9]+)?(\\.\\w\\w+)(\\/|\\/([\\w#!:.?+=&%@!\\-\\/]))?/;\nconst HALF_URL_REGEX =\n /(\\w+:{0,1}\\w*@)?(\\S+)(:[0-9]+)?(\\.\\w\\w+)(\\/|\\/([\\w#!:.?+=&%@!\\-\\/]))?/;\nconst ASSUME_PROTOCOL = 'https';\n\nexport class URLTools {\n public static urlIsValid(url: string): boolean {\n return FULL_URL_REGEX.test(url) || HALF_URL_REGEX.test(url);\n }\n\n public static guaranteeFullUrl(potentiallyHalfUrl: string) {\n if (HALF_URL_REGEX.test(potentiallyHalfUrl)) {\n return `${ASSUME_PROTOCOL}://${potentiallyHalfUrl}`;\n } else if (FULL_URL_REGEX.test(potentiallyHalfUrl)) {\n return potentiallyHalfUrl;\n } else {\n throw Error('Invalid URL');\n }\n }\n}\n"
},
{
"answer_id": 74626291,
"author": "Sebastian Simon",
"author_id": 4642212,
"author_profile": "https://Stackoverflow.com/users/4642212",
"pm_score": 2,
"selected": true,
"text": "URL // Solution:\n\nconst asAbsoluteURL = (url, base = location) => {\n let absoluteURL;\n \n try {\n absoluteURL = new URL(url);\n }\n catch {\n absoluteURL = new URL(`//${url}`, base);\n }\n \n return absoluteURL;\n };\n\n// Usage:\n\nconst absoluteURL1 = asAbsoluteURL(\"example.com\");\nconst absoluteURL2 = asAbsoluteURL(\"example.com\", \"http://something\");\nconst absoluteURL3 = asAbsoluteURL(\"https://example.com\");\n\nconsole.log({ // Run this snippet and look into your browser console\n absoluteURL1, // for the results (hit [F12]).\n absoluteURL2,\n absoluteURL3,\n \"1. If you want strings\": \"use concatenation: \" + absoluteURL1,\n \"2. Alternatively\": `use template literals: ${absoluteURL2}`,\n \"3. Or use the String function explicitly\": String(absoluteURL3)\n});\n\n// Interactive demonstration:\n\naddEventListener(\"input\", () => {\n const relativeURL = document.getElementById(\"relativeURL\").value,\n baseURL = document.getElementById(\"baseURL\").value || location;\n let result;\n \n try {\n result = formatCode`Relative URL ${relativeURL} is converted to absolute URL ${asAbsoluteURL(relativeURL, baseURL)}.`\n }\n catch {\n result = formatCode`Either the relative URL ${relativeURL} is not a valid relative URL or the base URL ${baseURL} is not a valid absolute URL itself.`;\n }\n \n document.getElementById(\"output\").replaceChildren(...result);\n});\n\nconst formatCode = (text, ...codeTexts) => text.flatMap((text, index) => [ text, Object.assign(document.createElement(\"code\"), { textContent: codeTexts[index] }) ]).slice(0, -1); #output { margin-top: 0.4em; line-height: 1.4em; white-space: pre-wrap; }\ncode { background: #ddd; padding: 0.2em 0.5em; border-radius: 0.2em; } <input id=\"relativeURL\" type=\"text\" placeholder=\"example.com\">\n<input id=\"baseURL\" type=\"text\" placeholder=\"https://example.com\">\n<div id=\"output\">Type a relative URL in the left input and an absolute URL as a base in the right input (or leave it blank to use the current location).</div> new URL(\" \") try catch new URL(\"// \", base) // base location \"https://stacksnippets.net/js\" \"http://example.com\" \"http://localhost\" \"ftp://anything\" asAbsoluteURL href asAbsoluteURL(\"example.com\") \"https://example.com/\" asAbsoluteURL(\"//example.com\") \"https://example.com/\" asAbsoluteURL(\"www.example.com\") \"https://www.example.com/\" asAbsoluteURL(\"https://example.com\") \"https://example.com/\" asAbsoluteURL(\"example.com\", \"http://localhost\") \"http://example.com/\" example.com https://example.net/path/file https://example.net/path/example.com /example.com https://example.net/path/file https://example.net/example.com //example.com https://example.net/path/file https://example.com"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3691763/"
] |
74,625,783
|
<p>I was learning <em>Scrapy framework</em>. I tried to use <strong>scrapy shell</strong>. There I was trying to <strong>fetch</strong> response from "https://quotes.toscrape.com/". The commands are below-</p>
<pre><code>python -m scrapy shell
</code></pre>
<p>Inside the <strong>shell</strong>-</p>
<pre><code>>> from scrapy import Request
>> req = Request("https://quotes.toscrape.com/")
>> fetch(req)
</code></pre>
<p>Then I found the <strong>error</strong> like this-</p>
<pre><code>PS D:\Projects\scrapyLearn\introSpider\introSpider> python -m scrapy shell
2022-11-30 15:04:52 [scrapy.utils.log] INFO: Scrapy 2.7.1 started (bot: introSpider)
2022-11-30 15:04:52 [scrapy.utils.log] INFO: Versions: lxml 4.9.0.0, libxml2 2.9.10, cssselect 1.2.0, parsel 1.7.0, w3lib 2.1.0, Twisted 22.10.0, Python 3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD64)], pyOpenSSL 22.1.0 (OpenSSL 3.0.7 1 Nov 2022), cryptography 38.0.4, Platform Windows-10-10.0.22000-SP0
2022-11-30 15:04:52 [scrapy.crawler] INFO: Overridden settings:
{'BOT_NAME': 'introSpider',
'DUPEFILTER_CLASS': 'scrapy.dupefilters.BaseDupeFilter',
'LOGSTATS_INTERVAL': 0,
'NEWSPIDER_MODULE': 'introSpider.spiders',
'REQUEST_FINGERPRINTER_IMPLEMENTATION': '2.7',
'ROBOTSTXT_OBEY': True,
'SPIDER_MODULES': ['introSpider.spiders'],
'TWISTED_REACTOR': 'twisted.internet.asyncioreactor.AsyncioSelectorReactor'}
2022-11-30 15:04:52 [asyncio] DEBUG: Using selector: SelectSelector
2022-11-30 15:04:52 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.asyncioreactor.AsyncioSelectorReactor
2022-11-30 15:04:52 [scrapy.utils.log] DEBUG: Using asyncio event loop: asyncio.windows_events._WindowsSelectorEventLoop2022-11-30 15:04:52 [scrapy.extensions.telnet] INFO: Telnet Password: 9ec5c326bbb22c54
2022-11-30 15:04:52 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
'scrapy.extensions.telnet.TelnetConsole']
2022-11-30 15:04:52 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
'scrapy.downloadermiddlewares.retry.RetryMiddleware',
'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
'scrapy.downloadermiddlewares.stats.DownloaderStats']
2022-11-30 15:04:52 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
'scrapy.spidermiddlewares.referer.RefererMiddleware',
'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
'scrapy.spidermiddlewares.depth.DepthMiddleware']
2022-11-30 15:04:52 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2022-11-30 15:04:52 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
[s] Available Scrapy objects:
[s] scrapy scrapy module (contains scrapy.Request, scrapy.Selector, etc)
[s] crawler <scrapy.crawler.Crawler object at 0x000002601B1B48D0>
[s] item {}
[s] settings <scrapy.settings.Settings object at 0x000002601B3EC550>
[s] Useful shortcuts:
[s] fetch(url[, redirect=True]) Fetch URL and update local objects (by default, redirects are followed)
[s] fetch(req) Fetch a scrapy.Request and update local objects
[s] shelp() Shell help (print this help)
[s] view(response) View response in a browser
>>> from scrapy import Request
>>> req = Request("https://quotes.toscrape.com/")
>>> fetch(req)
2022-11-30 15:05:46 [scrapy.core.engine] INFO: Spider opened
2022-11-30 15:05:47 [scrapy.core.engine] DEBUG: Crawled (404) <GET https://quotes.toscrape.com/robots.txt> (referer: None)
2022-11-30 15:05:47 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://quotes.toscrape.com/> (referer: None)
>>> 2022-11-30 15:05:47 [scrapy.core.scraper] ERROR: Spider error processing <GET https://quotes.toscrape.com/> (referer: None)
Traceback (most recent call last):
File "C:\Users\arnoLiono\AppData\Local\Programs\Python\Python311\Lib\site-packages\twisted\internet\defer.py", line 892, in _runCallbacks
current.result = callback( # type: ignore[misc]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\arnoLiono\AppData\Local\Programs\Python\Python311\Lib\site-packages\scrapy\utils\defer.py", line 285, in f
return deferred_from_coro(coro_f(*coro_args, **coro_kwargs))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\arnoLiono\AppData\Local\Programs\Python\Python311\Lib\site-packages\scrapy\utils\defer.py", line 272, in deferred_from_coro
event_loop = get_asyncio_event_loop_policy().get_event_loop()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\arnoLiono\AppData\Local\Programs\Python\Python311\Lib\asyncio\events.py", line 677, in get_event_loop
raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'Thread-1 (start)'.
2022-11-30 15:05:47 [py.warnings] WARNING: C:\Users\arnoLiono\AppData\Local\Programs\Python\Python311\Lib\site-packages\twisted\internet\defer.py:892: RuntimeWarning: coroutine 'SpiderMiddlewareManager.scrape_response.<locals>.process_callback_output' was never awaited
current.result = callback( # type: ignore[misc]
</code></pre>
<p>And the shell is still running. I don't know what is error is. And how to fix it.</p>
<p>I was just trying to get the response from "https://quotes.toscrape.com/" website.</p>
|
[
{
"answer_id": 74626719,
"author": "Victor Lozoya",
"author_id": 20644479,
"author_profile": "https://Stackoverflow.com/users/20644479",
"pm_score": -1,
"selected": true,
"text": "ROBOTSTXT_OBEY = False fetch fetch(\"https://quotes.toscrape.com/\")"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14497500/"
] |
74,625,810
|
<p>Up to now I used Apache Camel (JAVA) to route data from an Apache Kafka broker to an InfluxDB 1.8. Now I upgraded the database to InfluxDB 2.5.</p>
<p>The two InfluxDB-Versions are incompatible in terms of their read/write API. For example, it is not possible to inject the required security token required for reading/writing.</p>
<p>InfluxDB 1.8 requires a dependency to</p>
<pre><code><groupId>org.influxdb</groupId>
<artifactId>influxdb-java</artifactId>
<version>XXX</version>
</code></pre>
<p>InfluxDB 2.5 requires</p>
<pre><code><groupId>com.influxdb</groupId>
<artifactId>influxdb-client-java</artifactId>
<version>YYY</version>
</code></pre>
<p>In Apache Camel an InfluxDB component is available:</p>
<pre><code><groupId>org.apache.camel</groupId>
<artifactId>camel-influxdb</artifactId>
<version>ZZZ</version>
</code></pre>
<p>Which has a dependency to the <code>influx-client</code>library. Does that mean there is no InfluxDB 2.x component anymore? How do I build an InfluxDB 2.5 endpoint then?</p>
|
[
{
"answer_id": 74626719,
"author": "Victor Lozoya",
"author_id": 20644479,
"author_profile": "https://Stackoverflow.com/users/20644479",
"pm_score": -1,
"selected": true,
"text": "ROBOTSTXT_OBEY = False fetch fetch(\"https://quotes.toscrape.com/\")"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1552080/"
] |
74,625,846
|
<p>I'm creating elements dynamically based on SQL data server side.
I want to also edit some of those element's attributes after their creation.</p>
<p>They way I'm trying to go about this is by generating a string with the elements and inserting it into a div's innerHTML:</p>
<pre><code>client side:
<div id=master runat="server"></div>
server side:
string textToDiv = "<div id='" +num +"'><ul><li></li><li></li></ul></div>";
master.innerHTML = textToDiv;
</code></pre>
<p>Looks something like this in chrome:</p>
<pre><code><div id="master" runat="server">
<div id='1'>
<ul>
<li></li>
<li></li>
</ul>
</div>
<div id='2'>
<ul>
<li></li>
<li></li>
</ul>
</div>
</div>
</code></pre>
<p>Now, I want to change one of the child div's attributes. How do i go about doing that?</p>
<p>All I found on the internet is for more static uses using the method I applied when changing the 'master' div's innerHTML attribute. Is there a get() function or something similar <code>to document.getElementByID()</code> I can use?</p>
|
[
{
"answer_id": 74626041,
"author": "Grizou",
"author_id": 20068386,
"author_profile": "https://Stackoverflow.com/users/20068386",
"pm_score": 0,
"selected": false,
"text": "onload window.onload() => {\n element = document.createElement(\" \");\n element.setAttribute(\" \");\n element.innerHTML = ' ';\n document.getElementById(' ').appendChild(element);\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12532156/"
] |
74,625,847
|
<p>when I use my GET request and the parameters is null the client don't find the address route and return a 404 error (Not Found). I am sure this is an obvius mistake and I am missing something trivial, can someone guide me please ?</p>
<p>I am using JS in front and node.js/Express.js in back with the library <a href="https://www.npmjs.com/package/routing-controllers" rel="nofollow noreferrer">routing-controllers</a></p>
<p>Client</p>
<pre><code>let searchValue = ''
result = await fetch("http://localhost:3000/app/getRef/entitee/${searchValue}", {method:"GET"});
</code></pre>
<p>Server</p>
<pre><code>@Get('/getRef/entitee/:searchValue')
async getRefEntitee(@Req() req: any, @Res() res: any, @Param("searchValue") searchValue : string}: Promise<any> {
...
}
</code></pre>
|
[
{
"answer_id": 74625913,
"author": "Ahmad Alfy",
"author_id": 497828,
"author_profile": "https://Stackoverflow.com/users/497828",
"pm_score": 3,
"selected": true,
"text": "null getRef/entitee/:searchValue getRef/entitee/ result = await fetch(\"http://localhost:3000/app/getRef/entitee?q=${searchValue}\", {method:\"GET\"});\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17814297/"
] |
74,625,857
|
<p>I want to detect from inside a subroutine that a dummy argument passed with <code>intent(in)</code> is actually a null pointer:</p>
<pre><code>program testPTR
implicit none
integer, target :: ii
integer, pointer :: iPtr
iPtr => ii
iPtr = 2
print *, "passing ii"
call pointer_detect(ii)
print *, "passing iPtr"
call pointer_detect(iPtr)
iPtr => null()
print *, "passing iPtr => null()"
call pointer_detect(iPtr)
contains
subroutine pointer_detect(iVal)
implicit none
integer, intent(in), target :: iVal
integer, pointer :: iPtr
character(len = *), parameter :: sub_name = 'pointer_detect'
iPtr => iVal
if (associated(iPtr)) then
print *, "Pointer associated. Val=", iVal, ", iPtr = ", iPtr
else
print *, "Pointer not associated. Val=", iVal, ", iPtr = ", iPtr
endif
end subroutine pointer_detect
end program
</code></pre>
<p>To my surprise it works with gfortran-9 and gfortran-12. However I have got a couple of questions:</p>
<ol>
<li>How legitimate, portable and Fortran-ish the check is?</li>
<li>For some reason it does not segfault on the last print, but rather prints zeros and exits cleanly:</li>
</ol>
<pre><code>$ gfortan test.f90
$ ./a.out && echo ok
passing ii
Pointer associated. Val= 2 , iPtr = 2
passing iPtr
Pointer associated. Val= 2 , iPtr = 2
passing iPtr => null()
Pointer not associated. Val= 0 , iPtr = 0
ok
$
</code></pre>
<p>Any ideas? Thank you!</p>
|
[
{
"answer_id": 74627219,
"author": "PierU",
"author_id": 14778592,
"author_profile": "https://Stackoverflow.com/users/14778592",
"pm_score": 2,
"selected": false,
"text": "call pointer_detect(iPtr) pointer_detect() iPtr iPtr iPtr"
},
{
"answer_id": 74631282,
"author": "francescalus",
"author_id": 3157076,
"author_profile": "https://Stackoverflow.com/users/3157076",
"pm_score": 3,
"selected": true,
"text": " iPtr => null()\n print *, \"passing iPtr => null()\"\n call pointer_detect(iPtr)\n At line 19 of file brokenpointer.f90\nFortran runtime error: Pointer actual argument 'iptr' is not associated\n -fcheck=pointer forrtl: severe (408): fort: (7): Attempt to use pointer IPTR when it is not associated with a target\n -check pointers iPtr => iVal\n if (associated(iPtr)) then\n iVal iPtr iptr iVal PRESENT() subroutine pointer_detect(iVal)\n implicit none\n integer, intent(in), optional :: iVal\n character(len = *), parameter :: sub_name = 'pointer_detect'\n \n if (present(iVal)) then\n print *, \"Actual argument pointer was associated. Val=\", iVal\n else\n print *, \"Actual argument pointer was not associated.\"\n endif\n \n end subroutine pointer_detect\n iPtr"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/958841/"
] |
74,625,870
|
<p>So, the homework is: I need to write a code that will let the user to enter 3 numbers(this part is done.). Then my code should compare those numbers with each other(I think I know this too). But the hardest part is: if the first num is greater then code should print <em>1st: true</em>, if the second one is greater it should print <em>2nd: true</em> and so on. Also I can't use strings, if else and others the only thing I can use are operators,variables, input and typecasting.</p>
<p>I came up with this idea:</p>
<pre><code>first = int(input('Write first number: '))
second = int(input('Write second number: '))
third = int(input ('Write third number: '))
print (f'1st: {first > second and first> third}')
print (f'2nd: {second > first and second > third}')
print (f'3rd: { third > first and third > second}')
</code></pre>
|
[
{
"answer_id": 74627219,
"author": "PierU",
"author_id": 14778592,
"author_profile": "https://Stackoverflow.com/users/14778592",
"pm_score": 2,
"selected": false,
"text": "call pointer_detect(iPtr) pointer_detect() iPtr iPtr iPtr"
},
{
"answer_id": 74631282,
"author": "francescalus",
"author_id": 3157076,
"author_profile": "https://Stackoverflow.com/users/3157076",
"pm_score": 3,
"selected": true,
"text": " iPtr => null()\n print *, \"passing iPtr => null()\"\n call pointer_detect(iPtr)\n At line 19 of file brokenpointer.f90\nFortran runtime error: Pointer actual argument 'iptr' is not associated\n -fcheck=pointer forrtl: severe (408): fort: (7): Attempt to use pointer IPTR when it is not associated with a target\n -check pointers iPtr => iVal\n if (associated(iPtr)) then\n iVal iPtr iptr iVal PRESENT() subroutine pointer_detect(iVal)\n implicit none\n integer, intent(in), optional :: iVal\n character(len = *), parameter :: sub_name = 'pointer_detect'\n \n if (present(iVal)) then\n print *, \"Actual argument pointer was associated. Val=\", iVal\n else\n print *, \"Actual argument pointer was not associated.\"\n endif\n \n end subroutine pointer_detect\n iPtr"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20317113/"
] |
74,625,876
|
<p>trying to get all lines in a file and print them out</p>
<pre><code>topic = 1
if topic == 1:
allquestions = open("quizquestions1.txt","r")
allquestions = allquestions.read()
print(allquestions.readfile())
</code></pre>
|
[
{
"answer_id": 74625910,
"author": "Bhargav",
"author_id": 15358800,
"author_profile": "https://Stackoverflow.com/users/15358800",
"pm_score": 1,
"selected": false,
"text": "allquestions topic = 1\nif topic == 1:\n allquestions = open(\"quizquestions1.txt\",\"r\")\n allquestions = allquestions.read()\n print(allquestions)\n"
},
{
"answer_id": 74626053,
"author": "Amir reza Riahi",
"author_id": 12016688,
"author_profile": "https://Stackoverflow.com/users/12016688",
"pm_score": 0,
"selected": false,
"text": "read help read(size=-1, /) method of _io.TextIOWrapper instance\n Read at most n characters from stream.\n \n Read from underlying buffer until we have n characters or we hit EOF.\n If n is negative or omitted, read until EOF.\n topic = 1\nif topic == 1:\n with open(\"quizquestions1.txt\",\"r\") as file:\n allquestions = file.read()\n print(allquestions)\n readlines \\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20430376/"
] |
74,625,879
|
<p>I have three textboxes. If the value entered in textbox 3 (numeric) is between the values of textbox 1 (numeric) and textbox 2 (numeric), or between the values of textbox 2 and textbox 1 then the result is okay, else it is not okay.</p>
<p>How can this be done with VB.NET?</p>
|
[
{
"answer_id": 74626020,
"author": "swatsonpicken",
"author_id": 1185279,
"author_profile": "https://Stackoverflow.com/users/1185279",
"pm_score": 2,
"selected": false,
"text": "Return (z >= x And z <= y) Or (z >= y And z <= x)\n Function IsOk(ByVal firstValue As String, ByVal secondValue As String, ByVal thirdValue As String) As String\n If firstValue.IsInteger() And secondValue.IsInteger() And thirdValue.IsInteger() Then\n Dim x As Integer = Integer.Parse(firstValue)\n Dim y As Integer = Integer.Parse(secondValue)\n Dim z As Integer = Integer.Parse(thirdValue)\n\n If (z >= x And z <= y) Or (z >= y And z <= x) Then\n Return \"OK\"\n End If\n End If\n \n Return \"Not OK\"\nEnd Function\n\nPublic Module MyExtensions\n\n <System.Runtime.CompilerServices.Extension()> _\n Public Function IsInteger(ByVal value As String) As Boolean\n If String.IsNullOrEmpty(value) Then\n Return False\n Else\n Return Integer.TryParse(value, Nothing)\n End If\n End Function\n\nEnd Module\n"
},
{
"answer_id": 74637627,
"author": "Ray E",
"author_id": 12162657,
"author_profile": "https://Stackoverflow.com/users/12162657",
"pm_score": 0,
"selected": false,
"text": "Function IsOk(firstValue As String, secondValue As String, thisValue As String) As Boolean\n If IsNumeric(firstValue) And IsNumeric(secondValue) And IsNumeric(thisValue) Then\n Dim x As Integer = firstValue\n Dim y As Integer = secondValue\n Dim z As Integer = thisValue\n If (z >= x And z <= y) Or (z >= y And z <= x) Then\n Return True\n End If\n End If\n Return False\nEnd Function\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20589682/"
] |
74,625,894
|
<p>i have a line as below and all fields separated by comma:</p>
<p>I want to replace 2nd filed which is 11:50:21.444 with a value stored in variable "b"</p>
<pre><code>01-01-2022,11:50:21.444,1234543233443,0,0,0,0,1
</code></pre>
<p>I tried using sed
cat abc.csv| sed 's/$2/$b/'</p>
|
[
{
"answer_id": 74626020,
"author": "swatsonpicken",
"author_id": 1185279,
"author_profile": "https://Stackoverflow.com/users/1185279",
"pm_score": 2,
"selected": false,
"text": "Return (z >= x And z <= y) Or (z >= y And z <= x)\n Function IsOk(ByVal firstValue As String, ByVal secondValue As String, ByVal thirdValue As String) As String\n If firstValue.IsInteger() And secondValue.IsInteger() And thirdValue.IsInteger() Then\n Dim x As Integer = Integer.Parse(firstValue)\n Dim y As Integer = Integer.Parse(secondValue)\n Dim z As Integer = Integer.Parse(thirdValue)\n\n If (z >= x And z <= y) Or (z >= y And z <= x) Then\n Return \"OK\"\n End If\n End If\n \n Return \"Not OK\"\nEnd Function\n\nPublic Module MyExtensions\n\n <System.Runtime.CompilerServices.Extension()> _\n Public Function IsInteger(ByVal value As String) As Boolean\n If String.IsNullOrEmpty(value) Then\n Return False\n Else\n Return Integer.TryParse(value, Nothing)\n End If\n End Function\n\nEnd Module\n"
},
{
"answer_id": 74637627,
"author": "Ray E",
"author_id": 12162657,
"author_profile": "https://Stackoverflow.com/users/12162657",
"pm_score": 0,
"selected": false,
"text": "Function IsOk(firstValue As String, secondValue As String, thisValue As String) As Boolean\n If IsNumeric(firstValue) And IsNumeric(secondValue) And IsNumeric(thisValue) Then\n Dim x As Integer = firstValue\n Dim y As Integer = secondValue\n Dim z As Integer = thisValue\n If (z >= x And z <= y) Or (z >= y And z <= x) Then\n Return True\n End If\n End If\n Return False\nEnd Function\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19799105/"
] |
74,625,904
|
<p>I'm running mypy pre commit hook to check for any possible type issues and it's keep giving me this error <code>Argument 2 to "join" has incompatible type "Optional[str]"; expected "str"</code> for the code below:</p>
<pre class="lang-py prettyprint-override"><code>else:
renamed_paths_dict: CustomConnectorRenameDict = {
"old_path": os.path.join(
self.temp_dir, change["file_path"]
),
"new_path": os.path.join(
self.temp_dir,
change["new_file_path"], -> this is the line mypy is talking about
),
}
</code></pre>
<p><code>change["new_file_path"]</code> can be either a string or <code>None</code> but in this specific else block, it'll be never <code>None</code>.</p>
<p>How can I fix this issue?</p>
<p>Thanks</p>
|
[
{
"answer_id": 74626020,
"author": "swatsonpicken",
"author_id": 1185279,
"author_profile": "https://Stackoverflow.com/users/1185279",
"pm_score": 2,
"selected": false,
"text": "Return (z >= x And z <= y) Or (z >= y And z <= x)\n Function IsOk(ByVal firstValue As String, ByVal secondValue As String, ByVal thirdValue As String) As String\n If firstValue.IsInteger() And secondValue.IsInteger() And thirdValue.IsInteger() Then\n Dim x As Integer = Integer.Parse(firstValue)\n Dim y As Integer = Integer.Parse(secondValue)\n Dim z As Integer = Integer.Parse(thirdValue)\n\n If (z >= x And z <= y) Or (z >= y And z <= x) Then\n Return \"OK\"\n End If\n End If\n \n Return \"Not OK\"\nEnd Function\n\nPublic Module MyExtensions\n\n <System.Runtime.CompilerServices.Extension()> _\n Public Function IsInteger(ByVal value As String) As Boolean\n If String.IsNullOrEmpty(value) Then\n Return False\n Else\n Return Integer.TryParse(value, Nothing)\n End If\n End Function\n\nEnd Module\n"
},
{
"answer_id": 74637627,
"author": "Ray E",
"author_id": 12162657,
"author_profile": "https://Stackoverflow.com/users/12162657",
"pm_score": 0,
"selected": false,
"text": "Function IsOk(firstValue As String, secondValue As String, thisValue As String) As Boolean\n If IsNumeric(firstValue) And IsNumeric(secondValue) And IsNumeric(thisValue) Then\n Dim x As Integer = firstValue\n Dim y As Integer = secondValue\n Dim z As Integer = thisValue\n If (z >= x And z <= y) Or (z >= y And z <= x) Then\n Return True\n End If\n End If\n Return False\nEnd Function\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12828249/"
] |
74,625,940
|
<p>I am trying to implement a clear all button on a form that clears the textbox contents and unchecks all checkboxes. The issue is that the controls that need to be accessed are contained within Groupboxes and thus cannot be acessed via Me.Controls collection. I saw a similar post here: <a href="https://stackoverflow.com/questions/34720836/vb-uncheck-all-checked-checkboxes-in-forms">VB Uncheck all checked checkboxes in forms</a>, but the answer seems to be more complex than I would expect it should be. Is there any easier way other than in that post.</p>
<p>I tried this code, which logically to me should work but it does not:</p>
<pre><code>'Get textboes and clears them
For Each ctrGroupBoxes As Control In Me.Controls.OfType(Of GroupBox)
For Each ctrControls As Control In ctrGroupBoxes.Controls.OfType(Of TextBox)
ctrControls.Text = ""
Next
Next
'Get checkboxes and unchecks them
For Each ctrGroupBoxes As Control In Me.Controls.OfType(Of GroupBox)
For Each ctrControls As Control In ctrGroupBoxes.Controls.OfType(Of CheckBox)
DirectCast(ctrControls, CheckBox).Checked = False
Next
Next
</code></pre>
<p>I know the inner for loops work as I used it to clear each GroupBox individually for a different button on the form.</p>
<p>Any assistance would be appreciated.</p>
|
[
{
"answer_id": 74626020,
"author": "swatsonpicken",
"author_id": 1185279,
"author_profile": "https://Stackoverflow.com/users/1185279",
"pm_score": 2,
"selected": false,
"text": "Return (z >= x And z <= y) Or (z >= y And z <= x)\n Function IsOk(ByVal firstValue As String, ByVal secondValue As String, ByVal thirdValue As String) As String\n If firstValue.IsInteger() And secondValue.IsInteger() And thirdValue.IsInteger() Then\n Dim x As Integer = Integer.Parse(firstValue)\n Dim y As Integer = Integer.Parse(secondValue)\n Dim z As Integer = Integer.Parse(thirdValue)\n\n If (z >= x And z <= y) Or (z >= y And z <= x) Then\n Return \"OK\"\n End If\n End If\n \n Return \"Not OK\"\nEnd Function\n\nPublic Module MyExtensions\n\n <System.Runtime.CompilerServices.Extension()> _\n Public Function IsInteger(ByVal value As String) As Boolean\n If String.IsNullOrEmpty(value) Then\n Return False\n Else\n Return Integer.TryParse(value, Nothing)\n End If\n End Function\n\nEnd Module\n"
},
{
"answer_id": 74637627,
"author": "Ray E",
"author_id": 12162657,
"author_profile": "https://Stackoverflow.com/users/12162657",
"pm_score": 0,
"selected": false,
"text": "Function IsOk(firstValue As String, secondValue As String, thisValue As String) As Boolean\n If IsNumeric(firstValue) And IsNumeric(secondValue) And IsNumeric(thisValue) Then\n Dim x As Integer = firstValue\n Dim y As Integer = secondValue\n Dim z As Integer = thisValue\n If (z >= x And z <= y) Or (z >= y And z <= x) Then\n Return True\n End If\n End If\n Return False\nEnd Function\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661293/"
] |
74,625,950
|
<p>I've built a Wordpress Website and everything worked fine until I noticed that the CSS only works on my own computer but not on others.</p>
<p>Here is how I connected it.</p>
<pre><code><link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/style.min.css" type="text/css">
</code></pre>
<p>What could be the problem? Why does it only appear on my computer?</p>
<p>I tried to search why that happens but I couldn't find help</p>
|
[
{
"answer_id": 74626887,
"author": "Dileep Kuriyedath",
"author_id": 5518896,
"author_profile": "https://Stackoverflow.com/users/5518896",
"pm_score": -1,
"selected": false,
"text": "<link rel=\"stylesheet\" href=\"<?php echo get_template_directory_uri(); ?>/style.min.css\" type=\"text/css\">\n"
},
{
"answer_id": 74627071,
"author": "Lajos Arpad",
"author_id": 436560,
"author_profile": "https://Stackoverflow.com/users/436560",
"pm_score": 0,
"selected": false,
"text": "href href=\"<?php bloginfo('template_url'); ?>/style.min.css\"\n bloginfo('template_url) /style.min.css bloginfo('template_url') bloginfo('template_url') /style.min.css"
},
{
"answer_id": 74628296,
"author": "Sharad Kumar Yadav",
"author_id": 9336592,
"author_profile": "https://Stackoverflow.com/users/9336592",
"pm_score": 0,
"selected": false,
"text": "wp_enqueue_style ('custom-style-name', get_template_directory_uri().'/custom.css');\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20630424/"
] |
74,625,959
|
<p>I want to groupby my dataframe and concatenate the values/strings from the other columns together.</p>
<pre><code> Year Letter Number Note Text
0 2022 a 1 8 hi
1 2022 b 1 7 hello
2 2022 a 1 6 bye
3 2022 b 3 5 joe
</code></pre>
<p>To this:</p>
<pre><code> Column
Year Letter
2022 a 1|8|hi; 1|6|bye
b 1|7|hello; 3|5|joe
</code></pre>
<p>I tried some things with groupby, apply() and agg() but I can't get it work:</p>
<pre><code>df.groupby(['Year', 'Letter']).agg(lambda x: '|'.join(x))
</code></pre>
<p>Output:</p>
<pre><code> Text
Year Letter
2022 a hi|bye
b hello|joe
</code></pre>
|
[
{
"answer_id": 74625982,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "DataFrame.astype DataFrame.agg join GroupBy.agg df1 = (df.assign(Text= df[['Number','Note','Text']].astype(str).agg('|'.join, axis=1))\n .groupby(['Year', 'Letter'])['Text']\n .agg('; '.join)\n .to_frame())\nprint (df1)\n Text\nYear Letter \n2022 a 1|8|hi; 1|6|bye\n b 1|7|hello; 3|5|joe\n GroupBy.apply f = lambda x: '; '.join('|'.join(y) for y in x.astype(str).to_numpy())\ndf1 = (df.groupby(['Year', 'Letter'])[['Number','Note','Text']].apply(f)\n .to_frame(name='Text')\n )\nprint (df1)\n Text\nYear Letter \n2022 a 1|8|hi; 1|6|bye\n b 1|7|hello; 3|5|joe\n grouped = ['Year','Letter']\n\ndf1 = (df.assign(Text= df[df.columns.difference(grouped, sort=False)]\n .astype(str).agg('|'.join, axis=1))\n .groupby(['Year', 'Letter'])['Text']\n .agg('; '.join)\n .to_frame())\n grouped = ['Year','Letter']\n\nf = lambda x: '; '.join('|'.join(y) for y in x.astype(str).to_numpy())\ndf1 = (df.groupby(grouped)[df.columns.difference(grouped, sort=False)].apply(f)\n .to_frame(name='Text')\n )\n"
},
{
"answer_id": 74626055,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "groupby.apply cols = ['Year', 'Letter']\n(df.groupby(cols)\n .apply(lambda d: '; '.join(d.drop(columns=cols) # or slice the columns here\n .astype(str)\n .agg('|'.join, axis=1)))\n .to_frame(name='Column')\n)\n Column\nYear Letter \n2022 a 1|8|hi; 1|6|bye\n b 1|7|hello; 3|5|joe\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8814131/"
] |
74,625,968
|
<p>Assuming we have the following code:</p>
<pre class="lang-js prettyprint-override"><code>class Foo<T = number> {
foo: T;
constructor(foo: T) {
this.foo = foo;
}
}
const F: typeof Foo<number> = Foo;
let f: unknown;
if (f instanceof F) {
f.foo; // 'any', why is this not a 'number'?
}
</code></pre>
<p><a href="https://www.typescriptlang.org/play?#code/MYGwhgzhAEBiD28A8AVaBeaA7ArgWwCMBTAJwD5oBvAKGmgDNEAuaFAbmtumHiwgBcSOYP3gkAFI3gsUASipc6-ABYBLCADopGBog50AvtSPUeffnBb8AngAci8enERJchUhUwJ4HaiCIW9Cw4WADWWPAA7li+qk6S0KrmYFjADk6w8jR09Fp60AD0BdAA5CnWJQA00JHK1okwKurY8BZuxCQA-MZAA" rel="nofollow noreferrer">Playground</a></p>
<p>Why is <code>f</code> of type <code>Foo<any></code> and not <code>Foo<number></code>? And can I make this work only using <code>instanceof</code> or do I have to use a <a href="https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates" rel="nofollow noreferrer">type predicates function</a>?</p>
|
[
{
"answer_id": 74625982,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "DataFrame.astype DataFrame.agg join GroupBy.agg df1 = (df.assign(Text= df[['Number','Note','Text']].astype(str).agg('|'.join, axis=1))\n .groupby(['Year', 'Letter'])['Text']\n .agg('; '.join)\n .to_frame())\nprint (df1)\n Text\nYear Letter \n2022 a 1|8|hi; 1|6|bye\n b 1|7|hello; 3|5|joe\n GroupBy.apply f = lambda x: '; '.join('|'.join(y) for y in x.astype(str).to_numpy())\ndf1 = (df.groupby(['Year', 'Letter'])[['Number','Note','Text']].apply(f)\n .to_frame(name='Text')\n )\nprint (df1)\n Text\nYear Letter \n2022 a 1|8|hi; 1|6|bye\n b 1|7|hello; 3|5|joe\n grouped = ['Year','Letter']\n\ndf1 = (df.assign(Text= df[df.columns.difference(grouped, sort=False)]\n .astype(str).agg('|'.join, axis=1))\n .groupby(['Year', 'Letter'])['Text']\n .agg('; '.join)\n .to_frame())\n grouped = ['Year','Letter']\n\nf = lambda x: '; '.join('|'.join(y) for y in x.astype(str).to_numpy())\ndf1 = (df.groupby(grouped)[df.columns.difference(grouped, sort=False)].apply(f)\n .to_frame(name='Text')\n )\n"
},
{
"answer_id": 74626055,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "groupby.apply cols = ['Year', 'Letter']\n(df.groupby(cols)\n .apply(lambda d: '; '.join(d.drop(columns=cols) # or slice the columns here\n .astype(str)\n .agg('|'.join, axis=1)))\n .to_frame(name='Column')\n)\n Column\nYear Letter \n2022 a 1|8|hi; 1|6|bye\n b 1|7|hello; 3|5|joe\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8990411/"
] |
74,625,979
|
<p>I have a form that contains checkboxes, and from <strong>the script</strong> I check and uncheck them according to some requirements. at a certain point I reset the form <code>$("#formId")[0].reset()</code>, all inputs get reseted exept for checkboxes!!</p>
<p>I reseted the form but checkboxes didn't get reseted.</p>
|
[
{
"answer_id": 74625982,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "DataFrame.astype DataFrame.agg join GroupBy.agg df1 = (df.assign(Text= df[['Number','Note','Text']].astype(str).agg('|'.join, axis=1))\n .groupby(['Year', 'Letter'])['Text']\n .agg('; '.join)\n .to_frame())\nprint (df1)\n Text\nYear Letter \n2022 a 1|8|hi; 1|6|bye\n b 1|7|hello; 3|5|joe\n GroupBy.apply f = lambda x: '; '.join('|'.join(y) for y in x.astype(str).to_numpy())\ndf1 = (df.groupby(['Year', 'Letter'])[['Number','Note','Text']].apply(f)\n .to_frame(name='Text')\n )\nprint (df1)\n Text\nYear Letter \n2022 a 1|8|hi; 1|6|bye\n b 1|7|hello; 3|5|joe\n grouped = ['Year','Letter']\n\ndf1 = (df.assign(Text= df[df.columns.difference(grouped, sort=False)]\n .astype(str).agg('|'.join, axis=1))\n .groupby(['Year', 'Letter'])['Text']\n .agg('; '.join)\n .to_frame())\n grouped = ['Year','Letter']\n\nf = lambda x: '; '.join('|'.join(y) for y in x.astype(str).to_numpy())\ndf1 = (df.groupby(grouped)[df.columns.difference(grouped, sort=False)].apply(f)\n .to_frame(name='Text')\n )\n"
},
{
"answer_id": 74626055,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "groupby.apply cols = ['Year', 'Letter']\n(df.groupby(cols)\n .apply(lambda d: '; '.join(d.drop(columns=cols) # or slice the columns here\n .astype(str)\n .agg('|'.join, axis=1)))\n .to_frame(name='Column')\n)\n Column\nYear Letter \n2022 a 1|8|hi; 1|6|bye\n b 1|7|hello; 3|5|joe\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15557979/"
] |
74,625,993
|
<p>I have installed the cities_light library in Django and populated the db with the cities as instructed in the docs. I added the app in INSTALLED_APPS and I have been able to pull the data in this simple view. All cities load as expected:</p>
<pre><code>def index(request):
cities = City.objects.all()
context = {
'cities': cities
}
return render(request,'templates/index.html',context)
</code></pre>
<p>However, I am trying to create a model which has City as a foreign key, but when I run the app or try to make the migrations I get
'<strong>django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.'.</strong></p>
<pre><code>from cities_light.admin import City
from django.db import models
class Home(models.Model):
location = models.ForeignKey(City, on_delete=models.CASCADE)
</code></pre>
<p>I suspect I might need to override the model. Would that be the case?</p>
|
[
{
"answer_id": 74625982,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "DataFrame.astype DataFrame.agg join GroupBy.agg df1 = (df.assign(Text= df[['Number','Note','Text']].astype(str).agg('|'.join, axis=1))\n .groupby(['Year', 'Letter'])['Text']\n .agg('; '.join)\n .to_frame())\nprint (df1)\n Text\nYear Letter \n2022 a 1|8|hi; 1|6|bye\n b 1|7|hello; 3|5|joe\n GroupBy.apply f = lambda x: '; '.join('|'.join(y) for y in x.astype(str).to_numpy())\ndf1 = (df.groupby(['Year', 'Letter'])[['Number','Note','Text']].apply(f)\n .to_frame(name='Text')\n )\nprint (df1)\n Text\nYear Letter \n2022 a 1|8|hi; 1|6|bye\n b 1|7|hello; 3|5|joe\n grouped = ['Year','Letter']\n\ndf1 = (df.assign(Text= df[df.columns.difference(grouped, sort=False)]\n .astype(str).agg('|'.join, axis=1))\n .groupby(['Year', 'Letter'])['Text']\n .agg('; '.join)\n .to_frame())\n grouped = ['Year','Letter']\n\nf = lambda x: '; '.join('|'.join(y) for y in x.astype(str).to_numpy())\ndf1 = (df.groupby(grouped)[df.columns.difference(grouped, sort=False)].apply(f)\n .to_frame(name='Text')\n )\n"
},
{
"answer_id": 74626055,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "groupby.apply cols = ['Year', 'Letter']\n(df.groupby(cols)\n .apply(lambda d: '; '.join(d.drop(columns=cols) # or slice the columns here\n .astype(str)\n .agg('|'.join, axis=1)))\n .to_frame(name='Column')\n)\n Column\nYear Letter \n2022 a 1|8|hi; 1|6|bye\n b 1|7|hello; 3|5|joe\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15533897/"
] |
74,625,995
|
<p>My function is set to return a dictionary. When called, it returns the dictionary. However, if I call the function from within another function, it returns a list.</p>
<p>`</p>
<pre><code> def draw(self, num: int) -> dict:
drawn_dict = {}
if num > len(self.contents):
return self.contents
else:
while num >= 1:
drawn_num = self.contents.pop(random.randint(0, len(self.contents) - 1))
drawn_dict.setdefault(drawn_num, 0)
drawn_dict[drawn_num] +=1
num -= 1
return drawn_dict
def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
matches = 0
full_match = 0
count = 0
print(hat.draw(num_balls_drawn))
print(hat.draw(5))
</code></pre>
<p>`</p>
<p>When I call the draw function and print the result, I get the dictionary as expected. But when the draw function is called and result is printed within the experiment function, I get a list.</p>
|
[
{
"answer_id": 74625982,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "DataFrame.astype DataFrame.agg join GroupBy.agg df1 = (df.assign(Text= df[['Number','Note','Text']].astype(str).agg('|'.join, axis=1))\n .groupby(['Year', 'Letter'])['Text']\n .agg('; '.join)\n .to_frame())\nprint (df1)\n Text\nYear Letter \n2022 a 1|8|hi; 1|6|bye\n b 1|7|hello; 3|5|joe\n GroupBy.apply f = lambda x: '; '.join('|'.join(y) for y in x.astype(str).to_numpy())\ndf1 = (df.groupby(['Year', 'Letter'])[['Number','Note','Text']].apply(f)\n .to_frame(name='Text')\n )\nprint (df1)\n Text\nYear Letter \n2022 a 1|8|hi; 1|6|bye\n b 1|7|hello; 3|5|joe\n grouped = ['Year','Letter']\n\ndf1 = (df.assign(Text= df[df.columns.difference(grouped, sort=False)]\n .astype(str).agg('|'.join, axis=1))\n .groupby(['Year', 'Letter'])['Text']\n .agg('; '.join)\n .to_frame())\n grouped = ['Year','Letter']\n\nf = lambda x: '; '.join('|'.join(y) for y in x.astype(str).to_numpy())\ndf1 = (df.groupby(grouped)[df.columns.difference(grouped, sort=False)].apply(f)\n .to_frame(name='Text')\n )\n"
},
{
"answer_id": 74626055,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "groupby.apply cols = ['Year', 'Letter']\n(df.groupby(cols)\n .apply(lambda d: '; '.join(d.drop(columns=cols) # or slice the columns here\n .astype(str)\n .agg('|'.join, axis=1)))\n .to_frame(name='Column')\n)\n Column\nYear Letter \n2022 a 1|8|hi; 1|6|bye\n b 1|7|hello; 3|5|joe\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19870880/"
] |
74,625,997
|
<p>I want to scroll two SingleChildScrollView same time vertically.</p>
<p><a href="https://i.stack.imgur.com/dWaR4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dWaR4.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74626040,
"author": "Lars",
"author_id": 11708327,
"author_profile": "https://Stackoverflow.com/users/11708327",
"pm_score": 1,
"selected": false,
"text": "controller: SingleChildScrollView final ScrollController _scrollController = ScrollController(); \n"
},
{
"answer_id": 74626318,
"author": "Sparko Sol",
"author_id": 20407048,
"author_profile": "https://Stackoverflow.com/users/20407048",
"pm_score": 3,
"selected": true,
"text": "import 'package:flutter/material.dart';\n\nclass ScrollTestPage extends StatefulWidget {\n const ScrollTestPage({Key? key}) : super(key: key);\n\n @override\n State<ScrollTestPage> createState() => _ScrollTestPageState();\n}\n\nclass _ScrollTestPageState extends State<ScrollTestPage> {\n final _controller1 = ScrollController();\n final _controller2 = ScrollController();\n\n @override\n void initState() {\n super.initState();\n _controller1.addListener(listener1);\n _controller2.addListener(listener2);\n }\n\n var _flag1 = false;\n var _flag2 = false;\n\n void listener1() {\n if (_flag2) return;\n _flag1 = true;\n _controller2.jumpTo(_controller1.offset);\n _flag1 = false;\n }\n\n void listener2() {\n if (_flag1) return;\n _flag2 = true;\n _controller1.jumpTo(_controller2.offset);\n _flag2 = false;\n }\n\n @override\n void dispose() {\n super.dispose();\n _controller1.removeListener(listener1);\n _controller2.removeListener(listener2);\n _controller1.dispose();\n _controller2.dispose();\n }\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n body: Column(\n children: [\n Expanded(\n child: ListView.builder(\n controller: _controller1,\n itemBuilder: (context, i) {\n return Container(\n margin: const EdgeInsets.fromLTRB(10, 5, 10, 5),\n child: Text('First List View $i'),\n );\n },\n itemCount: 100,\n ),\n ),\n Expanded(\n child: ListView.builder(\n controller: _controller2,\n itemBuilder: (context, i) {\n return Container(\n margin: const EdgeInsets.fromLTRB(10, 5, 10, 5),\n child: Text('Second List View $i'),\n );\n },\n itemCount: 100,\n ),\n ),\n ],\n ),\n );\n }\n}\n"
},
{
"answer_id": 74653321,
"author": "Ramji",
"author_id": 20446596,
"author_profile": "https://Stackoverflow.com/users/20446596",
"pm_score": 0,
"selected": false,
"text": "import 'package:flutter/material.dart';\nimport 'package:linked_scroll_controller/linked_scroll_controller.dart';\n\nvoid main() => runApp(const MyApp());\n\nclass MyApp extends StatelessWidget {\n const MyApp({Key? key}) : super(key: key);\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n title: 'List',\n theme: ThemeData(\n primarySwatch: Colors.blue,\n ),\n debugShowCheckedModeBanner: false,\n home: const List(),\n );\n }\n}\n\nclass List extends StatefulWidget {\n const List({Key? key}) : super(key: key);\n @override\n _ListState createState() => _ListState();\n}\n\nclass _ListState extends State<List> {\n late LinkedScrollControllerGroup _controllers; // Declare link scroll Controller\n late ScrollController _letters; // Declare scroll controller for first list/widget\n late ScrollController _numbers; // Declare scroll controller for second list/widget\n\n @override\n void initState() {\n super.initState();\n _controllers = LinkedScrollControllerGroup(); // Initialize link scroll controller \n _letters = _controllers.addAndGet(); // Attach the first list/widget scroll controller to link scroll controller \n _numbers = _controllers.addAndGet(); // Attach the second list/widget scroll controller to link scroll controller\n }\n\n @override\n void dispose() {\n _letters.dispose();\n _numbers.dispose();\n super.dispose();\n }\n\n @override\n Widget build(BuildContext context) {\n return Material(\n child: Directionality(\n textDirection: TextDirection.ltr,\n child: Column(\n children: [\n Expanded(\n child: ListView.builder(\n controller: _letters, // First list/widget scroll controller\n itemBuilder: (context, i) {\n return Container(\n margin: const EdgeInsets.fromLTRB(10, 5, 10, 5),\n child: Text('First List View $i'),\n );\n },\n itemCount: 100,\n ),\n ),\n Expanded(\n child: ListView.builder(\n controller: _numbers, // Second list/widget scroll controller\n itemBuilder: (context, i) {\n return Container(\n margin: const EdgeInsets.fromLTRB(10, 5, 10, 5),\n child: Text('Second List View $i'),\n );\n },\n itemCount: 100,\n ),\n ),\n ],\n ),\n ),\n );\n }\n}\n\nclass _Tile extends StatelessWidget {\n final String caption;\n\n _Tile(this.caption);\n\n @override\n Widget build(_) => Container(\n margin: const EdgeInsets.all(8.0),\n padding: const EdgeInsets.all(8.0),\n height: 250.0,\n child: Center(child: Text(caption)),\n );\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74625997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8266094/"
] |
74,626,073
|
<p>I'm trying to build a structure like this :</p>
<ul>
<li>Parent 1
<ul>
<li>Child 1
<ul>
<li>Super child 1</li>
</ul>
</li>
<li>Child 2
<ul>
<li>Super Child 2
<ul>
<li>Super super Child 2</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>I don't know how many branches there will be.</p>
<p>I need to build my structure with an array of paths like this :</p>
<ul>
<li>Parent1/Child1/SuperChild1</li>
<li>Parent1/Child2/SuperChild2/SupersuperChild2</li>
</ul>
<p>I made a Model as following :</p>
<pre class="lang-c# prettyprint-override"><code>public class Person
{
public string Name { get; set; }
public string FullPath { get; set; }
public List<Person> Children { get; set; }
}
</code></pre>
<p>I split every paths to an array and then I interate inside with foreach :</p>
<pre class="lang-c# prettyprint-override"><code>string[] list =
{
"Parent1/Child1/SuperChild1/SupersuperChild1",
"Parent1/Child1/SuperChild1/SupersuperChild2",
"Parent2/Child2/SuperChild2/SupersuperChild3",
"Parent2/Child3/SuperChild3/SupersuperChild4",
"Parent2/Child3/SuperChild3/SupersuperChild5"
};
var branches = new List<Person>();
foreach (var tag in list)
{
var tagSlash = tag.Replace("[", "").Replace("]", "/").Split('/');
Person parent = null;
foreach (var step in tagSlash)
{
Person branch = null;
if (parent == null && branches.Find(b => b.Name.Equals(step)) == null)
{
branch = new Person
{
Name = step,
FullPath = tagSlash.Last().Equals(step) ? tag : null,
Children = new List<Person>()
};
branches.Add(branch);
}
else if (parent == null && branches.Find(b => b.Name.Equals(step)) != null)
{
branch = branches.Find(b => b.Name.Equals(step));
}
else if (parent.Children.Find(c => c.Name.Equals(step)) != null)
{
branch = parent.Children.Find(c => c.Name.Equals(step));
}
else
{
var ancestor =
branch = new Person
{
Name = step,
FullPath = tagSlash.Last().Equals(step) ? tag : null,
Children = new List<Person>()
};
}
parent = branch;
}
}
</code></pre>
<p>The previous code isn't finished because I'm stuck.</p>
<p>Do you have an idea on how to build that structure ?</p>
<p>Thank you.</p>
|
[
{
"answer_id": 74627084,
"author": "ufosnowcat",
"author_id": 1728208,
"author_profile": "https://Stackoverflow.com/users/1728208",
"pm_score": 2,
"selected": false,
"text": "string[] list =\n{\n \"Parent1/Child1/SuperChild1/SupersuperChild1\",\n \"Parent1/Child1/SuperChild1/SupersuperChild2\",\n \"Parent2/Child2/SuperChild2/SupersuperChild3\",\n \"Parent2/Child3/SuperChild3/SupersuperChild4\",\n \"Parent2/Child3/SuperChild3/SupersuperChild5\"\n};\n\nvar branches = new List<Person>();\n\nforeach (var tag in list)\n{\n var tagSlash = tag.Replace(\"[\", \"\").Replace(\"]\", \"/\").Split('/');\n\n var p1 = branches.FirstOrDefault(x => x.Name == tagSlash[0]);\n if (p1 == null)\n {\n p1 = new Person()\n {\n Name = tagSlash[0],\n FullPath = tagSlash[0]\n };\n branches.Add(p1);\n }\n\n MakeList.IterateListStep(p1, tagSlash, 1);\n}\n\npublic static class MakeList\n{\n public static void IterateListStep(Person parent, string[] tags, int level)\n {\n if(tags.Length <= level)\n return;\n\n var pers = parent.Children.FirstOrDefault(x => x.Name == tags[level]);\n\n if (pers == null)\n {\n pers = new Person()\n {\n Name = tags[level],\n FullPath = parent.FullPath + \"//\" + tags[level],\n };\n\n parent.Children.Add(pers);\n }\n\n IterateListStep(pers, tags, level + 1);\n\n }\n}\n public List<Person> Children { get; set; } = new List<Person>();\n"
},
{
"answer_id": 74627598,
"author": "jdweng",
"author_id": 5015238,
"author_profile": "https://Stackoverflow.com/users/5015238",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Xml;\nusing System.Xml.Linq;\nusing System.Data;\nnamespace ConsoleApplication51\n{\n class Program\n {\n static void Main(string[] args)\n {\n string[] list =\n {\n \"Parent1/Child1/SuperChild1/SupersuperChild1\",\n \"Parent1/Child1/SuperChild1/SupersuperChild2\",\n \"Parent2/Child2/SuperChild2/SupersuperChild3\",\n \"Parent2/Child3/SuperChild3/SupersuperChild4\",\n \"Parent2/Child3/SuperChild3/SupersuperChild5\"\n };\n\n List<List<string>> people = list.Select(x => x.Split(new char[] {'/'}).ToList()).ToList();\n\n Person root = Person.BuildTree(people);\n\n }\n }\n public class Person\n {\n public string Name { get; set; }\n public string FullPath { get; set; }\n public List<Person> Children { get; set; }\n\n public static Person BuildTree(List<List<string>> people)\n {\n Person root = new Person();\n root.Name = \"Root\";\n int level = 0;\n BuildTreeRecursive(root, people, level);\n\n return root;\n }\n public static void BuildTreeRecursive(Person parent, List<List<string>> people, int level)\n {\n var groups = people.GroupBy(x => x[level]).ToList();\n foreach (var group in groups)\n {\n if(parent.Children == null) parent.Children = new List<Person>();\n Person child = new Person();\n parent.Children.Add(child);\n child.Name = group.Key;\n child.FullPath = string.Join(\"/\", group.First().Take(level + 1));\n List<List<string>> descendnats = group.Where(x => x.Count() > level + 1).ToList();\n if (descendnats.Count > 0)\n {\n BuildTreeRecursive(child, descendnats, level + 1);\n }\n\n }\n\n }\n }\n \n \n}\n"
},
{
"answer_id": 74628465,
"author": "Jodrell",
"author_id": 659190,
"author_profile": "https://Stackoverflow.com/users/659190",
"pm_score": 0,
"selected": false,
"text": "INode public interface INode<T>\n{\n public string Name { get; }\n public string FullPath { get; }\n public IList<T> Children { get; }\n}\n\npublic static class Extensions\n{\n public static IEnumerable<T> BuildTrees<T>(\n this IEnumerable<string> paths,\n Func<string, string, T> nodeFactory,\n string delimiter = \"/\")\n where T : INode<T>\n {\n var nodes = new Dictionary<string, T>();\n var roots = new List<T>();\n \n foreach(var path in paths)\n {\n string fullPath = null;\n T parent = default;\n T node = default;\n \n foreach(var name in path.Split(delimiter))\n {\n var root = false;\n if (fullPath == null)\n {\n root = true;\n fullPath = name;\n }\n else\n {\n fullPath = $\"{fullPath}{delimiter}{name}\";\n parent = node;\n }\n \n if (nodes.ContainsKey(fullPath))\n {\n node = nodes[fullPath]; \n }\n else\n {\n node = nodeFactory(name, fullPath);\n nodes.Add(fullPath, node);\n \n if (root)\n {\n roots.Add(node);\n }\n else\n {\n parent.Children.Add(node); \n }\n }\n }\n }\n \n return roots; \n }\n}\n public class Person : INode<Person>\n{\n public string Name { get; set; }\n public string FullPath { get; set; }\n public IList<Person> Children { get; set; } = new List<Person>();\n}\n\npublic class Program\n{\n public static void Main()\n {\n string[] list =\n {\n \"Parent1/Child1/SuperChild1/SupersuperChild1\",\n \"Parent1/Child1/SuperChild1/SupersuperChild2\",\n \"Parent2/Child2/SuperChild2/SupersuperChild3\",\n \"Parent2/Child3/SuperChild3/SupersuperChild4\",\n \"Parent2/Child3/SuperChild3/SupersuperChild5\"\n };\n\n var roots = list.BuildTrees<Person>(\n (name, fullPath) => new Person { Name = name, FullPath = fullPath });\n }\n}\n roots |---> SupersuperChild1\nParent1 -------> Child1 -------> SuperChild1 ---|\n |---> SupersuperChild2\n\n |---> Child2 -------> SuperChild2 -------> SupersuperChild3\nParent2 ---|---> Child3 -------> SuperChild3 ---|---> SupersuperChild4\n |---> SupersuperChild5\n"
},
{
"answer_id": 74634248,
"author": "Enigmativity",
"author_id": 259769,
"author_profile": "https://Stackoverflow.com/users/259769",
"pm_score": 0,
"selected": false,
"text": "class Person : List<Person> public class Person : List<Person>\n{\n public string Name { get; private set; }\n private Person Parent { get; set; }\n public string FullPath => $\"{(this.Parent == null ? String.Empty : this.Parent.FullPath)}/{this.Name}\";\n private Person(string name, Person parent)\n {\n this.Name = name;\n this.Parent = parent;\n }\n public static IEnumerable<Person> Create(params string[] paths) => Person.Create(null, paths);\n\n private static IEnumerable<Person> Create(Person parent, params string[] paths)\n {\n var list = new List<Person>();\n var people = paths.Select(p => p.Split('/')).GroupBy(x => x[0], x => String.Join(\"/\", x.Skip(1)));\n foreach (var person in people)\n {\n var current = new Person(person.Key, parent);\n var children = Person.Create(parent, person.Where(x => x.Any()).ToArray());\n current.AddRange(children);\n yield return current;\n }\n }\n public override string ToString() =>\n String.Join(Environment.NewLine, this.Flatten(0));\n \n private IEnumerable<string> Flatten(int depth)\n {\n yield return $\"{new string('+', depth)}{this.Name}\";\n foreach (var x in this.SelectMany(y => y.Flatten(depth + 1)))\n {\n yield return x;\n }\n }\n}\n string[] list =\n{\n \"Parent1/Child1/SuperChild1/SupersuperChild1\",\n \"Parent1/Child1/SuperChild1/SupersuperChild2\",\n \"Parent2/Child2/SuperChild2/SupersuperChild3\",\n \"Parent2/Child3/SuperChild3/SupersuperChild4\",\n \"Parent2/Child3/SuperChild3/SupersuperChild5\"\n};\n\nvar people = Person.Create(list);\n\nforeach (var person in people)\n Console.WriteLine(person.ToString());\n Parent1\n+Child1\n++SuperChild1\n+++SupersuperChild1\n+++SupersuperChild2\nParent2\n+Child2\n++SuperChild2\n+++SupersuperChild3\n+Child3\n++SuperChild3\n+++SupersuperChild4\n+++SupersuperChild5\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20643903/"
] |
74,626,112
|
<p>Have a table where I want to go in range of two rows</p>
<pre><code>id | col b | message
1 | abc | hello |
2 | abc | world |
3 | abc 1| morning|
4 | abc | night |
...|... | .... |
100| abc1 | Monday |
101| abc1 | Tuesday|
</code></pre>
<p>How to I create below table that goes in a range of two and shows the first id with the second col b and message in spark.</p>
<p>Final table will look like this.</p>
<pre><code>id | full message
1 | 01:02,abc,world
3 | 03:04,abc,night
.. |................
100| 100:101,abc1,Tuesday
</code></pre>
|
[
{
"answer_id": 74627084,
"author": "ufosnowcat",
"author_id": 1728208,
"author_profile": "https://Stackoverflow.com/users/1728208",
"pm_score": 2,
"selected": false,
"text": "string[] list =\n{\n \"Parent1/Child1/SuperChild1/SupersuperChild1\",\n \"Parent1/Child1/SuperChild1/SupersuperChild2\",\n \"Parent2/Child2/SuperChild2/SupersuperChild3\",\n \"Parent2/Child3/SuperChild3/SupersuperChild4\",\n \"Parent2/Child3/SuperChild3/SupersuperChild5\"\n};\n\nvar branches = new List<Person>();\n\nforeach (var tag in list)\n{\n var tagSlash = tag.Replace(\"[\", \"\").Replace(\"]\", \"/\").Split('/');\n\n var p1 = branches.FirstOrDefault(x => x.Name == tagSlash[0]);\n if (p1 == null)\n {\n p1 = new Person()\n {\n Name = tagSlash[0],\n FullPath = tagSlash[0]\n };\n branches.Add(p1);\n }\n\n MakeList.IterateListStep(p1, tagSlash, 1);\n}\n\npublic static class MakeList\n{\n public static void IterateListStep(Person parent, string[] tags, int level)\n {\n if(tags.Length <= level)\n return;\n\n var pers = parent.Children.FirstOrDefault(x => x.Name == tags[level]);\n\n if (pers == null)\n {\n pers = new Person()\n {\n Name = tags[level],\n FullPath = parent.FullPath + \"//\" + tags[level],\n };\n\n parent.Children.Add(pers);\n }\n\n IterateListStep(pers, tags, level + 1);\n\n }\n}\n public List<Person> Children { get; set; } = new List<Person>();\n"
},
{
"answer_id": 74627598,
"author": "jdweng",
"author_id": 5015238,
"author_profile": "https://Stackoverflow.com/users/5015238",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Xml;\nusing System.Xml.Linq;\nusing System.Data;\nnamespace ConsoleApplication51\n{\n class Program\n {\n static void Main(string[] args)\n {\n string[] list =\n {\n \"Parent1/Child1/SuperChild1/SupersuperChild1\",\n \"Parent1/Child1/SuperChild1/SupersuperChild2\",\n \"Parent2/Child2/SuperChild2/SupersuperChild3\",\n \"Parent2/Child3/SuperChild3/SupersuperChild4\",\n \"Parent2/Child3/SuperChild3/SupersuperChild5\"\n };\n\n List<List<string>> people = list.Select(x => x.Split(new char[] {'/'}).ToList()).ToList();\n\n Person root = Person.BuildTree(people);\n\n }\n }\n public class Person\n {\n public string Name { get; set; }\n public string FullPath { get; set; }\n public List<Person> Children { get; set; }\n\n public static Person BuildTree(List<List<string>> people)\n {\n Person root = new Person();\n root.Name = \"Root\";\n int level = 0;\n BuildTreeRecursive(root, people, level);\n\n return root;\n }\n public static void BuildTreeRecursive(Person parent, List<List<string>> people, int level)\n {\n var groups = people.GroupBy(x => x[level]).ToList();\n foreach (var group in groups)\n {\n if(parent.Children == null) parent.Children = new List<Person>();\n Person child = new Person();\n parent.Children.Add(child);\n child.Name = group.Key;\n child.FullPath = string.Join(\"/\", group.First().Take(level + 1));\n List<List<string>> descendnats = group.Where(x => x.Count() > level + 1).ToList();\n if (descendnats.Count > 0)\n {\n BuildTreeRecursive(child, descendnats, level + 1);\n }\n\n }\n\n }\n }\n \n \n}\n"
},
{
"answer_id": 74628465,
"author": "Jodrell",
"author_id": 659190,
"author_profile": "https://Stackoverflow.com/users/659190",
"pm_score": 0,
"selected": false,
"text": "INode public interface INode<T>\n{\n public string Name { get; }\n public string FullPath { get; }\n public IList<T> Children { get; }\n}\n\npublic static class Extensions\n{\n public static IEnumerable<T> BuildTrees<T>(\n this IEnumerable<string> paths,\n Func<string, string, T> nodeFactory,\n string delimiter = \"/\")\n where T : INode<T>\n {\n var nodes = new Dictionary<string, T>();\n var roots = new List<T>();\n \n foreach(var path in paths)\n {\n string fullPath = null;\n T parent = default;\n T node = default;\n \n foreach(var name in path.Split(delimiter))\n {\n var root = false;\n if (fullPath == null)\n {\n root = true;\n fullPath = name;\n }\n else\n {\n fullPath = $\"{fullPath}{delimiter}{name}\";\n parent = node;\n }\n \n if (nodes.ContainsKey(fullPath))\n {\n node = nodes[fullPath]; \n }\n else\n {\n node = nodeFactory(name, fullPath);\n nodes.Add(fullPath, node);\n \n if (root)\n {\n roots.Add(node);\n }\n else\n {\n parent.Children.Add(node); \n }\n }\n }\n }\n \n return roots; \n }\n}\n public class Person : INode<Person>\n{\n public string Name { get; set; }\n public string FullPath { get; set; }\n public IList<Person> Children { get; set; } = new List<Person>();\n}\n\npublic class Program\n{\n public static void Main()\n {\n string[] list =\n {\n \"Parent1/Child1/SuperChild1/SupersuperChild1\",\n \"Parent1/Child1/SuperChild1/SupersuperChild2\",\n \"Parent2/Child2/SuperChild2/SupersuperChild3\",\n \"Parent2/Child3/SuperChild3/SupersuperChild4\",\n \"Parent2/Child3/SuperChild3/SupersuperChild5\"\n };\n\n var roots = list.BuildTrees<Person>(\n (name, fullPath) => new Person { Name = name, FullPath = fullPath });\n }\n}\n roots |---> SupersuperChild1\nParent1 -------> Child1 -------> SuperChild1 ---|\n |---> SupersuperChild2\n\n |---> Child2 -------> SuperChild2 -------> SupersuperChild3\nParent2 ---|---> Child3 -------> SuperChild3 ---|---> SupersuperChild4\n |---> SupersuperChild5\n"
},
{
"answer_id": 74634248,
"author": "Enigmativity",
"author_id": 259769,
"author_profile": "https://Stackoverflow.com/users/259769",
"pm_score": 0,
"selected": false,
"text": "class Person : List<Person> public class Person : List<Person>\n{\n public string Name { get; private set; }\n private Person Parent { get; set; }\n public string FullPath => $\"{(this.Parent == null ? String.Empty : this.Parent.FullPath)}/{this.Name}\";\n private Person(string name, Person parent)\n {\n this.Name = name;\n this.Parent = parent;\n }\n public static IEnumerable<Person> Create(params string[] paths) => Person.Create(null, paths);\n\n private static IEnumerable<Person> Create(Person parent, params string[] paths)\n {\n var list = new List<Person>();\n var people = paths.Select(p => p.Split('/')).GroupBy(x => x[0], x => String.Join(\"/\", x.Skip(1)));\n foreach (var person in people)\n {\n var current = new Person(person.Key, parent);\n var children = Person.Create(parent, person.Where(x => x.Any()).ToArray());\n current.AddRange(children);\n yield return current;\n }\n }\n public override string ToString() =>\n String.Join(Environment.NewLine, this.Flatten(0));\n \n private IEnumerable<string> Flatten(int depth)\n {\n yield return $\"{new string('+', depth)}{this.Name}\";\n foreach (var x in this.SelectMany(y => y.Flatten(depth + 1)))\n {\n yield return x;\n }\n }\n}\n string[] list =\n{\n \"Parent1/Child1/SuperChild1/SupersuperChild1\",\n \"Parent1/Child1/SuperChild1/SupersuperChild2\",\n \"Parent2/Child2/SuperChild2/SupersuperChild3\",\n \"Parent2/Child3/SuperChild3/SupersuperChild4\",\n \"Parent2/Child3/SuperChild3/SupersuperChild5\"\n};\n\nvar people = Person.Create(list);\n\nforeach (var person in people)\n Console.WriteLine(person.ToString());\n Parent1\n+Child1\n++SuperChild1\n+++SupersuperChild1\n+++SupersuperChild2\nParent2\n+Child2\n++SuperChild2\n+++SupersuperChild3\n+Child3\n++SuperChild3\n+++SupersuperChild4\n+++SupersuperChild5\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9390633/"
] |
74,626,179
|
<p>I have a excel file containing three columns as shown below,</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>117</td>
<td>Laspringe</td>
<td>2019-04-08</td>
</tr>
<tr>
<td>117</td>
<td>Laspringe (FT)</td>
<td>2020-06-16</td>
</tr>
<tr>
<td>117</td>
<td>Laspringe (Ftp)</td>
<td>2020-07-24</td>
</tr>
<tr>
<td>999</td>
<td>Angelo</td>
<td>2020-04-15</td>
</tr>
<tr>
<td>999</td>
<td>Angelo(FT)</td>
<td>2021-03-05</td>
</tr>
<tr>
<td>999</td>
<td>Angelo(Ftp)</td>
<td>2021-09-13</td>
</tr>
<tr>
<td>999</td>
<td>Angelo</td>
<td>2022-02-20</td>
</tr>
</tbody>
</table>
</div>
<p>I wanted to find out that based on each ID which has the name changed from original name and changed back to the same original name. For example <strong>Angelo</strong> is changed to <strong>Angelo(FT)</strong>, <strong>Angelo(Ftp)</strong> and changed back to original <strong>Angelo</strong>.</p>
<p>Whereas <strong>Laspringe</strong> is not changed back to the original name.</p>
<p>Is it possible to find out which of the ID's have changed the name back to original using python ??</p>
<p>Expecting the result to be like,</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>999</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74626271,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "s = df.duplicated(['ID', 'Name']).groupby(df['ID']).any()\nout = s[s].index.tolist()\n [999] s = (df\n .sort_values(by='Date')\n .groupby('ID')['Name']\n .agg(lambda s: s[s.ne(s.shift())].duplicated().any())\n)\nout = s[s].index.tolist()\n ID Name Date\n0 117 Laspringe 2019-04-08\n1 117 Laspringe 2019-04-09 # duplicated but no intermediate name\n2 117 Laspringe (FT) 2020-06-16\n3 117 Laspringe (Ftp) 2020-07-24\n4 999 Angelo 2020-04-15\n5 999 Angelo(FT) 2021-03-05\n6 999 Angelo(Ftp) 2021-09-13\n7 999 Angelo 2022-02-29\n"
},
{
"answer_id": 74626676,
"author": "bn_ln",
"author_id": 10535824,
"author_profile": "https://Stackoverflow.com/users/10535824",
"pm_score": 0,
"selected": false,
"text": "import openpyxl, collections\n\nws = openpyxl.load_workbook('Book1.xlsx').active\nname_dict = collections.defaultdict(list)\nids, names = ([cell.value for cell in col] for col in ws.iter_cols(1,2))\nfor id_, name in zip(ids[1:],names[1:]): # [1:] to ignore the header row\n name_dict[id_].append(name)\nprint(*[k for k,v in name_dict.items() if v[0]==v[-1]])\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16251356/"
] |
74,626,222
|
<p>Is it possible to use a wildcard on GoogleCloudStorageToBigQueryOperator?</p>
<p>So I have a collection of files inside a certain folder in GCS</p>
<pre><code>file_sample_1.json
file_sample_2.json
file_sample_3.json
...
file_sample_n.json
</code></pre>
<p>I want to ingest these files using airflow with GoogleCloudStorageToBigQueryOperator.</p>
<p>below is my code:</p>
<pre><code> def create_operator_write_init():
return GoogleCloudStorageToBigQueryOperator(
task_id = 'test_ingest_to_bq',
bucket = 'sample-bucket-dev-202211',
source_objects = 'file_sample_1.json',
destination_project_dataset_table = 'sample_destination_table',
create_disposition = "CREATE_IF_NEEDED",
write_disposition = "WRITE_TRUNCATE",
source_format = "NEWLINE_DELIMITED_JSON",
schema_fields = [
{"name": "id", "type": "INTEGER", "mode": "NULLABLE"},
{"name": "created_at", "type": "TIMESTAMP", "mode": "NULLABLE"},
{"name": "updated_at", "type": "TIMESTAMP", "mode": "NULLABLE"},
]
)
</code></pre>
<p>It can ingest 1 file just fine, but I need the source_object to have wild card, can I do something like 'file_sample_*.json' so that the * will act as a wild card?</p>
|
[
{
"answer_id": 74626271,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 3,
"selected": true,
"text": "s = df.duplicated(['ID', 'Name']).groupby(df['ID']).any()\nout = s[s].index.tolist()\n [999] s = (df\n .sort_values(by='Date')\n .groupby('ID')['Name']\n .agg(lambda s: s[s.ne(s.shift())].duplicated().any())\n)\nout = s[s].index.tolist()\n ID Name Date\n0 117 Laspringe 2019-04-08\n1 117 Laspringe 2019-04-09 # duplicated but no intermediate name\n2 117 Laspringe (FT) 2020-06-16\n3 117 Laspringe (Ftp) 2020-07-24\n4 999 Angelo 2020-04-15\n5 999 Angelo(FT) 2021-03-05\n6 999 Angelo(Ftp) 2021-09-13\n7 999 Angelo 2022-02-29\n"
},
{
"answer_id": 74626676,
"author": "bn_ln",
"author_id": 10535824,
"author_profile": "https://Stackoverflow.com/users/10535824",
"pm_score": 0,
"selected": false,
"text": "import openpyxl, collections\n\nws = openpyxl.load_workbook('Book1.xlsx').active\nname_dict = collections.defaultdict(list)\nids, names = ([cell.value for cell in col] for col in ws.iter_cols(1,2))\nfor id_, name in zip(ids[1:],names[1:]): # [1:] to ignore the header row\n name_dict[id_].append(name)\nprint(*[k for k,v in name_dict.items() if v[0]==v[-1]])\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20413423/"
] |
74,626,258
|
<p>I have an index spreadsheet, and not sure how to search and find Folder and File containing specific text related to values in column A and B.</p>
<p>In this spreadsheet, I create a product folder based on values from column A & B - <code>FolderName = ref + ' - ' + location</code> and store this inside one main parent folder.</p>
<p>Inside this new product folder, I then create a Google sheet with similar naming convention - <code>newDocName = ref + ' [Descriptions] - ' + location</code></p>
<p>ref = value from column A
location = value from column B</p>
<p>'- Parent Folder
'-- Product Folder
'--- Product Sheet File</p>
<p>However, inside the index spreadsheet, I would like to auto-fill column L & M with the link to the new Folder & File that relates to that product.</p>
<p>Column L = Folder Link (Product Folder)
Column M = Sheet Link (Product Sheet File)</p>
<p>Can this be done inside the index spreadsheet, or would it need to be done with Google app script with an On Open trigger? If so, How can I use Google app script to search and fill in the relevant Folder & File GD Link to column L & M?</p>
<p>Thanks.</p>
<p><a href="https://i.stack.imgur.com/6JoqI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6JoqI.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74626659,
"author": "Ricardas",
"author_id": 15058523,
"author_profile": "https://Stackoverflow.com/users/15058523",
"pm_score": 0,
"selected": false,
"text": "Drive.Files.list() Drive.Files.list({q: \"fullText contains 'Example One'\"});"
},
{
"answer_id": 74628596,
"author": "Iamblichus",
"author_id": 10612011,
"author_profile": "https://Stackoverflow.com/users/10612011",
"pm_score": 1,
"selected": false,
"text": "folderName sheetName L:M const SHEET_NAME = \"Sheet1\"; // Add your sheet name\nconst PARENT_FOLDER_ID = \"FOLDER_ID\"; // Add your parent folder id\nfunction writeUrls() {\n const parentFolder = DriveApp.getFolderById(PARENT_FOLDER_ID);\n const sheet = SpreadsheetApp.getActive().getSheetByName(SHEET_NAME);\n const lastRow = sheet.getLastRow();\n const values = sheet.getRange(\"A2:B\" + lastRow).getValues();\n const urls = values.map(([ref, location]) => {\n const folderName = `${ref} - ${location}`;\n const sheetName = `${ref} [Descriptions] - ${location}`;\n const foldersIter = parentFolder.getFoldersByName(folderName);\n let rowUrls = new Array(2);\n if (foldersIter.hasNext()) {\n const folder = foldersIter.next();\n rowUrls[0] = folder.getUrl();\n const filesIter = folder.getFilesByName(sheetName);\n if (filesIter.hasNext()) rowUrls[1] = filesIter.next().getUrl();\n }\n return rowUrls;\n });\n sheet.getRange(\"L2:M\" + lastRow).setValues(urls);\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10314266/"
] |
74,626,283
|
<p>I want to list some items so I used ul and li tags but when using different amount of li items the structure changes what would be the best solutions for this. Should I use table tag?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
display: inline-block;
margin-left: 10px;
list-style: none;
}
ul li:first-child {
font-weight: bold;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<ul class="box1">
<li>Usefull Links</li>
<li>Content</li>
<li>How it works</li>
<li>Create</li>
<li>Explore</li>
<li>Terms & Services</li>
</ul>
<ul class="box2">
<li>Community</li>
<li>Help center</li>
<li>Partners</li>
<li>Suggestions</li>
<li>Blog</li>
<li>News letters</li>
</ul>
<ul class="box3">
<li>Partner</li>
<li>Our Partner</li>
<li>Become a Partner</li>
</ul>
</body></code></pre>
</div>
</div>
</p>
<p>and the output is like this</p>
<p><a href="https://i.stack.imgur.com/ZlWtS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZlWtS.png" alt="enter image description here" /></a></p>
<p>what I actually want is this:-</p>
<p><a href="https://i.stack.imgur.com/SaMe9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SaMe9.png" alt="enter image description here" /></a></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
<tr>
<td>Cell 3</td>
<td>Cell 4</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74626385,
"author": "Fabrizio Calderan",
"author_id": 1098851,
"author_profile": "https://Stackoverflow.com/users/1098851",
"pm_score": 1,
"selected": false,
"text": "align-items .boxes {\n display: flex;\n justify-content: center;\n align-items: start;\n gap: 2rem;\n}\n\n.boxes ul {\n font: 1rem/1.6 system-ui;\n list-style: none;\n flex: 1;\n}\n\n.boxes li:first-child {\n margin-bottom: 1.6rem;\n} <div class=\"boxes\">\n <ul class=\"box1\">\n <li>Usefull Links</li>\n <li>Content</li>\n <li>How it works</li>\n <li>Create</li>\n <li>Explore</li>\n <li>Terms & Services</li>\n </ul>\n <ul class=\"box2\">\n <li>Community</li>\n <li>Help center</li>\n <li>Partners</li>\n <li>Suggestions</li>\n <li>Blog</li>\n <li>News letters</li>\n </ul>\n <ul class=\"box3\">\n <li>Partner</li>\n <li>Our Partner</li>\n <li>Become a Partner</li>\n </ul>\n</div>"
},
{
"answer_id": 74626650,
"author": "NAZIR HUSSAIN",
"author_id": 20587701,
"author_profile": "https://Stackoverflow.com/users/20587701",
"pm_score": 0,
"selected": false,
"text": "display: inline-block; ul display:flex body <html>\n<head>\n<style>\nul {\n margin-left: 10px;\n list-style: none;\n\n}\n\nul li:first-child {\n font-weight: bold;\n}\nbody{\ndisplay:flex\n}\n</style>\n</head>\n<body>\n <ul class=\"box1\">\n <li>Usefull Links</li>\n <li>Content</li>\n <li>How it works</li>\n <li>Create</li>\n <li>Explore</li>\n <li>Terms & Services</li>\n </ul>\n <ul class=\"box2\">\n <li>Community</li>\n <li>Help center</li>\n <li>Partners</li>\n <li>Suggestions</li>\n <li>Blog</li>\n <li>News letters</li>\n </ul>\n <ul class=\"box3\">\n <li>Partner</li>\n <li>Our Partner</li>\n <li>Become a Partner</li>\n </ul>\n</body>\n</html>\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20643092/"
] |
74,626,330
|
<p>I have got a list of Customers (Image1- unsorted) and displaying this list in a table.
Users able to sort this table by clicking table header.</p>
<p>If they click Customer Name the first time (Image2), the List is sorted by Customer Name from A-Z
Then they click the Customer Name a second time (Image3), List sorted by Customer Name from Z-A</p>
<p><strong>The issue is</strong>, when the user clicks the Customer Name the third time (Image4), I was expecting to see the list reordered like the first time(Image 2). But it is not. The list is ordered A-Z, but it is not in the same order
As you can see from the images i attached Second Image and 3rd image orders are not the same order.</p>
<pre class="lang-js prettyprint-override"><code>if (this.orderByColSide)
authList.sort((a, b) => a.customerCode.toLowerCase() > b.customerCode.toLowerCase() ? 1 : -1);
else
authList.sort((a, b) => a.customerCode.toLowerCase() > b.customerCode.toLowerCase() ? -1 : 1);
</code></pre>
<p><a href="https://i.stack.imgur.com/bnmxS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bnmxS.jpg" alt="UnSorted" /></a></p>
<p><a href="https://i.stack.imgur.com/S5nO8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S5nO8.jpg" alt="Sort by Customer" /></a></p>
<p><a href="https://i.stack.imgur.com/pvJhb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pvJhb.jpg" alt="Sort Customer again" /></a></p>
<p><a href="https://i.stack.imgur.com/MXp62.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MXp62.jpg" alt="Sort Customer again" /></a></p>
|
[
{
"answer_id": 74626791,
"author": "Steven Spungin",
"author_id": 5093961,
"author_profile": "https://Stackoverflow.com/users/5093961",
"pm_score": 1,
"selected": false,
"text": "localeCompare if (this.orderByColSide)\n authList.sort((a, b) => a.customerCode.toLowerCase().localCompare(b.customerCode.toLowerCase())\nelse\n authList.sort((a, b) => - a.customerCode.toLowerCase().localeCompare(b.customerCode.toLowerCase())\n "
},
{
"answer_id": 74627149,
"author": "AliAzra",
"author_id": 7520496,
"author_profile": "https://Stackoverflow.com/users/7520496",
"pm_score": 0,
"selected": false,
"text": "if (this.orderByColSide)\n authList.sort((a, b) => a.customerCode.toLowerCase() > b.customerCode.toLowerCase() ? 1 : a.customerCode.toLowerCase() < b.customerCode.toLowerCase()? -1: 0); \n else\n authList.sort((a, b) => a.customerCode.toLowerCase() > b.customerCode.toLowerCase() ? -1 : a.customerCode.toLowerCase() < b.customerCode.toLowerCase()? 1:0);\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7520496/"
] |
74,626,341
|
<p>I have created myscript.sh file in one of local linux server. I am trying to pass the variables and functions defined in(myscript.sh) to remote machine.</p>
<pre><code>my_var="Myvar Value"
getIPAddress()
{
echo $my_var
ip_address=$(hostname -i)
echo $ip_address
}
ssh user@remote "$(typeset -f getIPAddress); getIPAddress"
</code></pre>
<p>I am only getting the ip_address but not getting the value of $my_var. Is there a way to handle this.</p>
|
[
{
"answer_id": 74626791,
"author": "Steven Spungin",
"author_id": 5093961,
"author_profile": "https://Stackoverflow.com/users/5093961",
"pm_score": 1,
"selected": false,
"text": "localeCompare if (this.orderByColSide)\n authList.sort((a, b) => a.customerCode.toLowerCase().localCompare(b.customerCode.toLowerCase())\nelse\n authList.sort((a, b) => - a.customerCode.toLowerCase().localeCompare(b.customerCode.toLowerCase())\n "
},
{
"answer_id": 74627149,
"author": "AliAzra",
"author_id": 7520496,
"author_profile": "https://Stackoverflow.com/users/7520496",
"pm_score": 0,
"selected": false,
"text": "if (this.orderByColSide)\n authList.sort((a, b) => a.customerCode.toLowerCase() > b.customerCode.toLowerCase() ? 1 : a.customerCode.toLowerCase() < b.customerCode.toLowerCase()? -1: 0); \n else\n authList.sort((a, b) => a.customerCode.toLowerCase() > b.customerCode.toLowerCase() ? -1 : a.customerCode.toLowerCase() < b.customerCode.toLowerCase()? 1:0);\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11733503/"
] |
74,626,345
|
<p>I want to fill multiple columns with different values.</p>
<p>I have a df that looks as such:</p>
<pre><code>df
'A' 'B' 'C'
0 1 dog red
1 5 cat yellow
2 4 moose blue
</code></pre>
<p>I would like to overwrite the columns based upon list values and so would look like this:</p>
<pre><code>overwrite = [0, cat, orange]
df
'A' 'B' 'C'
0 0 cat orange
1 0 cat orange
2 0 cat orange
</code></pre>
<p>Is there an easy way to do this?</p>
<p>Thanks</p>
|
[
{
"answer_id": 74626367,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "overwrite = [0, 'cat', 'orange']\ndf[['A', 'B', 'C']] = overwrite\n df.iloc[:, :len(overwrite)] = overwrite\n\n# or\ndf[df.columns[:len(overwrite)]] = overwrite\n A B C\n0 0 cat orange\n1 0 cat orange\n2 0 cat orange\n"
},
{
"answer_id": 74626374,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": -1,
"selected": false,
"text": "DataFrame.assign df = df.assign(**dict(zip(df.columns, overwrite)))\nprint (df)\n 'A' 'B' 'C'\n0 0 cat orange\n1 0 cat orange\n2 0 cat orange\n DataFrame df = pd.DataFrame([overwrite], index=df.index, columns=df.columns)\nprint (df)\n 'A' 'B' 'C'\n0 0 cat orange\n1 0 cat orange\n2 0 cat orange\n"
},
{
"answer_id": 74626498,
"author": "John Collins",
"author_id": 20590267,
"author_profile": "https://Stackoverflow.com/users/20590267",
"pm_score": -1,
"selected": false,
"text": "df = pd.DataFrame({'A':[1,2,3],'B':['cat','dog','bird']})\noverwrite = [0,'Elk']\nfor index,row in df.iterrows():\n df.iloc[index,:] = overwrite\ndf\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10574250/"
] |
74,626,346
|
<p>I want to re-render cart after remove button click.I think it's working cause , when i click remove then this item is removing from products (I got it from console.log) .But cart is not re-rendering .May be I could not use useEffect hook properly .</p>
<pre><code>import React,{useEffect} from 'react'
import { useSelector } from 'react-redux'
import Link from "next/link"
const cart = () => {
let products=useSelector((state)=>state)
const remove=(ID)=>{
products= products.filter(product=>{
return product.id!==ID
})
console.log(products);
}
useEffect(()=>{
},[products])
return (
<div className='flex flex-wrap'>
{
products && products.map((product)=>{
return(
<div className='bg-gray-700 border-white m-4 rounded-md min-w-[250px]' key={product.id}>
<div className='flex flex-col text-white p-4'>
<img src={product.image} alt="Image not loaded"/>
<h3><b>Product Name:</b> {product.name}</h3>
<h3><b>Price:</b> ${product.price}</h3>
<button onClick={()=>remove(product.id)} className='bg-gray-800 p-2 my-2 rounded-md hover:bg-black'>REMOVE</button>
</div>
</div>
)
})
}
<Link href="/"> <button className='p-2 bg-orange-400 outline-sm w-20'>HOME</button></Link>
</div>
)
}
export default cart
</code></pre>
|
[
{
"answer_id": 74626534,
"author": "NAZIR HUSSAIN",
"author_id": 20587701,
"author_profile": "https://Stackoverflow.com/users/20587701",
"pm_score": 2,
"selected": false,
"text": "import React,{useEffect} from 'react'\nimport { useSelector ,useDispatch} from 'react-redux'\nimport Link from \"next/link\"\nconst cart = () => {\nlet products=useSelector((state)=>state)\nconst dispatch=useDispatch();\n const remove=(ID)=>{\n products= products.filter(product=>{\n return product.id!==ID\n })\n console.log(products);\n dispatch(setProducts(products))\n }\n\n return (\n \n <div className='flex flex-wrap'>\n {\n products && products.map((product)=>{\n return(\n <div className='bg-gray-700 border-white m-4 rounded-md min-w-[250px]' key={product.id}>\n <div className='flex flex-col text-white p-4'>\n <img src={product.image} alt=\"Image not loaded\"/>\n <h3><b>Product Name:</b> {product.name}</h3>\n <h3><b>Price:</b> ${product.price}</h3>\n <button onClick={()=>remove(product.id)} className='bg-gray-800 p-2 my-2 rounded-md hover:bg-black'>REMOVE</button>\n </div>\n </div>\n )\n })\n }\n <Link href=\"/\"> <button className='p-2 bg-orange-400 outline-sm w-20'>HOME</button></Link>\n </div>\n )\n}\n\nexport default cart\n import React,{useState} from 'react'\nimport { useSelector } from 'react-redux'\nimport Link from \"next/link\"\nconst cart = () => {\n let products=useSelector((state)=>state)\nconst [data,setData] useState(products);\n\n const remove=(ID)=>{\n let filterData= products.filter(product=>{\n return product.id!==ID\n })\n console.log(filterData);\nsetData(filterData)\n }\n return (\n \n <div className='flex flex-wrap'>\n {\n data && data.map((product)=>{\n return(\n <div className='bg-gray-700 border-white m-4 rounded-md min-w-[250px]' key={product.id}>\n <div className='flex flex-col text-white p-4'>\n <img src={product.image} alt=\"Image not loaded\"/>\n <h3><b>Product Name:</b> {product.name}</h3>\n <h3><b>Price:</b> ${product.price}</h3>\n <button onClick={()=>remove(product.id)} className='bg-gray-800 p-2 my-2 rounded-md hover:bg-black'>REMOVE</button>\n </div>\n </div>\n )\n })\n }\n <Link href=\"/\"> <button className='p-2 bg-orange-400 outline-sm w-20'>HOME</button></Link>\n </div>\n )\n}\n\nexport default cart\n"
},
{
"answer_id": 74626604,
"author": "Aifos Si Prahs",
"author_id": 19135131,
"author_profile": "https://Stackoverflow.com/users/19135131",
"pm_score": 0,
"selected": false,
"text": "products = products.filter(product=>{\n return product.id!==ID\n })\n setProducts(products.filter(product=>{\n return product.id!==ID\n }))\n setProducts(products => products.filter(product=>{\n return product.id!==ID\n }))\n setProducts(products => products.splice(products.findIndex(p => p.id === ID), 1))\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14446795/"
] |
74,626,387
|
<p>I created a random code generator script via Google apps script. My goal is to generate 6000 <strong>uniques</strong> random codes (in spreadsheet) as fast as possible.
The following javascript code crashes with Google spreadsheet + apps script --> too long to execute and the same code under python generates 20,000 random codes in less than 1 second... I'm not a JS ninja, do you have any idea to optimize the JS code below ?</p>
<p>Code JS</p>
<pre><code>function main(nbre_car,nbre_pass,number,letter_maj,letter_min,spec_car){
var nbre_car = 6;
var nbre_pass = 6000;
var number = true;
var letter_maj = false;
var letter_min = false;
var spec_car = false;
var prefixe="FOULE";
return generate_password(nbre_car,nbre_pass,number,letter_maj,letter_min,spec_car,prefixe)
}
function combinaison_possible(char_number,lenght_possible_char){
combinaison_nbre=Math.pow(lenght_possible_char,char_number)
return combinaison_nbre
}
function generate_password(nbre_car,nbre_pass,number=true,letter_maj=false,letter_min=false,spec_car=false,prefixe="") {
if (Number.isInteger(nbre_car)&&Number.isInteger(nbre_pass)){
}
else{
return "Veuillez rentrer un nombre entier pour les champs en bleu"
}
var nbre_car = nbre_car || 10;
var nbre_pass = nbre_pass || 3;
var pass_number="123456789";
var pass_letter_maj="ABCDEFGHIJKLMNPQRSTUVWXYZ";
var pass_letter_min="abcdefghijklmnpqrstuvwxyz"
var pass_spec_car="'(-è_çà)=:;,!."
// Check entry type
// Create an empty map which will contain all password
var col = new Map([]);
var prefixe=prefixe;
var list_char='';
list_char= letter_maj == true ? list_char+pass_letter_maj : list_char
list_char= number == true ? list_char+pass_number : list_char
list_char= letter_min == true ? list_char+pass_letter_min : list_char
list_char= spec_car == true ? list_char+pass_spec_car : list_char
// Teste les combinaisons possible entre le nombre de caractère demandés pour le password et la liste disponible
if (combinaison_possible(nbre_car,list_char.length)>=nbre_pass) {
// Création des mots de passe unique
while(col.size===0||nbre_pass>col.size) {
Logger.log("col.size : "+col.size)
Logger.log("nbre_pass : "+nbre_pass)
search_new_pass=true;
while (search_new_pass==true){
pass=create_one_password(nbre_car,list_char,prefixe)
Logger.log('nom du password : '+pass)
if (verify_unique(col,pass)!=true)
col.set({}, pass);
Logger.log("valeur de col : "+col)
search_new_pass=false;
}
}
}
else{
col = [];
col.push("Vous avez demander trop de mots de passe, cela va créer des doublons,Veuillez diminuer le nombre de mots de passe à afficher");
}
final_values=[...col.values()];
//Logger.log('valeur final de col : '+final_values)
console.log(Array.from(col.values()));
return Array.from(col.values());
}
function create_one_password(nbre_car,list_char,prefixe) {
var nbre_car = nbre_car;
s = '', r = list_char;
for (var i=0; i < nbre_car; i++) {
s += r.charAt(Math.floor(Math.random()*r.length));
}
return prefixe+s;
}
</code></pre>
<p>Code Python</p>
<pre><code>import random
def combinaison_possible(char_number,lenght_possible_char):
combinaison_nbre=pow(lenght_possible_char,char_number)
return combinaison_nbre
def generate_password(nbre_car,nbre_pass,number=True,letter_maj=True,letter_min=True,spec_car=True,prefixe="FOULE") :
if(not isinstance(nbre_car,int) and isinstance(not nbre_pass,int)) :
print( "Veuillez rentrer un nombre entier pour les champs en bleu")
nbre_car = nbre_car
nbre_pass = nbre_pass
pass_number="123456789"
pass_letter_maj="ABCDEFGHIJKLMNPQRSTUVWXYZ"
pass_letter_min="abcdefghijklmnpqrstuvwxyz"
pass_spec_car="!@#$%^&*()_+"
prefixe=prefixe
list_char=''
col={}
longueur_col=len(col)
list_char= list_char+pass_letter_maj if letter_maj else list_char
list_char= list_char+pass_letter_min if letter_min else list_char
list_char= list_char+pass_number if number else list_char
list_char= list_char+pass_spec_car if spec_car else list_char
if (combinaison_possible(nbre_car,len(list_char))>=nbre_pass) :
while(len(col)==0 or nbre_pass>len(col)):
longueur_col=len(col)
search_new_pass=True
while (search_new_pass==True):
pass_word = prefixe+''.join(random.choice(list_char) for i in range(nbre_car))
if pass_word not in col:
col[longueur_col]=pass_word
search_new_pass=False
print (col)
else :
print("Le nombre de mot de passe à générer est trop important par rapport au nombre de caractères possible")
generate_password(6,20000)
</code></pre>
|
[
{
"answer_id": 74626821,
"author": "doubleunary",
"author_id": 13045193,
"author_profile": "https://Stackoverflow.com/users/13045193",
"pm_score": 2,
"selected": false,
"text": "verify_unique() col.set({}, pass) Array Map col.includes(pass) col.push(pass) col Array.from(col.values()) var prefixe = prefixe;"
},
{
"answer_id": 74628384,
"author": "kevinSpaceyIsKeyserSöze",
"author_id": 3433538,
"author_profile": "https://Stackoverflow.com/users/3433538",
"pm_score": 2,
"selected": true,
"text": "Crypto.getRandomValues() const CHARACTER_POOL =\n \"123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz'(-è_çà)=:;,!.\";\nconst PASSWORDS_TO_GENERATE = 20000;\nconst PASSWORD_LENGTH = 6;\nconst PREFIX = \"\";\n\nconst createPassword = () => {\n let password = \"\";\n for (let i = 0; i < PASSWORD_LENGTH; i++) {\n // this is not secure\n password += CHARACTER_POOL.charAt(\n Math.floor(Math.random() * CHARACTER_POOL.length)\n );\n }\n return `${PREFIX}${password}`;\n};\n\nconst generatePassword = () => {\n const passwords = [];\n while (passwords.length < PASSWORDS_TO_GENERATE) {\n const password = createPassword();\n if (!passwords.includes(password)) {\n passwords.push(password);\n }\n }\n return passwords;\n};\n\nconst start = new Date().getTime();\nconst passwords = generatePassword();\nconsole.log(`It took ${(new Date().getTime() - start) / 1000} to generate ${passwords.length} passwords`);\nconsole.log(passwords);"
},
{
"answer_id": 74649016,
"author": "Scott Sauyet",
"author_id": 1243641,
"author_profile": "https://Stackoverflow.com/users/1243641",
"pm_score": 0,
"selected": false,
"text": "const genPasswords = (chars) => (n, length = 6, pre = '') => Array .from (\n {length: n}, \n () => pre + Array.from({length}, () => chars[~~(Math.random() * chars.length)]) .join('')\n)\n\nconst pwdGen = genPasswords (\"123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz'(-è_çà)=:;,!.\")\n\nconsole.time('generate 20000')\nconst res = pwdGen (20000, 6, 'FOULE')\nconsole.timeEnd('generate 20000')\n\nconsole .log (res) .as-console-wrapper {max-height: 100% !important; top: 0}"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8592452/"
] |
74,626,398
|
<p>I have the following linq statement:</p>
<pre class="lang-cs prettyprint-override"><code>consumers = data.Select(x => new Consumer()
{
firstname = x.firstname,
lastname = x.lastname,
house = x.sublocationid,
floornr = x.floor,
appnr = x.roomnr
})
.Distinct()
.ToList();
</code></pre>
<p>Somehow this does not return distinct datasets. I assume it has something to do with the selection of the object? The distinct function is therefore not comparing the attributes directly but rather the objects? I am not understanding it fully unfortunately but in ms sql this statement works fine.</p>
<p>I also tried the following but it does not return a List object and I would need to use var or something else and I need a List of Consumer() objects.</p>
<pre class="lang-cs prettyprint-override"><code>consumers = data.Select(x => new Consumer()
{
firstname = x.firstname,
lastname = x.lastname,
house = x.sublocationid,
floornr = x.floor,
appnr = x.roomnr
})
.GroupBy(x => new { x.firstname, x.lastname, x.haus, x.etage, x.appnr })
.ToList();
</code></pre>
|
[
{
"answer_id": 74626821,
"author": "doubleunary",
"author_id": 13045193,
"author_profile": "https://Stackoverflow.com/users/13045193",
"pm_score": 2,
"selected": false,
"text": "verify_unique() col.set({}, pass) Array Map col.includes(pass) col.push(pass) col Array.from(col.values()) var prefixe = prefixe;"
},
{
"answer_id": 74628384,
"author": "kevinSpaceyIsKeyserSöze",
"author_id": 3433538,
"author_profile": "https://Stackoverflow.com/users/3433538",
"pm_score": 2,
"selected": true,
"text": "Crypto.getRandomValues() const CHARACTER_POOL =\n \"123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz'(-è_çà)=:;,!.\";\nconst PASSWORDS_TO_GENERATE = 20000;\nconst PASSWORD_LENGTH = 6;\nconst PREFIX = \"\";\n\nconst createPassword = () => {\n let password = \"\";\n for (let i = 0; i < PASSWORD_LENGTH; i++) {\n // this is not secure\n password += CHARACTER_POOL.charAt(\n Math.floor(Math.random() * CHARACTER_POOL.length)\n );\n }\n return `${PREFIX}${password}`;\n};\n\nconst generatePassword = () => {\n const passwords = [];\n while (passwords.length < PASSWORDS_TO_GENERATE) {\n const password = createPassword();\n if (!passwords.includes(password)) {\n passwords.push(password);\n }\n }\n return passwords;\n};\n\nconst start = new Date().getTime();\nconst passwords = generatePassword();\nconsole.log(`It took ${(new Date().getTime() - start) / 1000} to generate ${passwords.length} passwords`);\nconsole.log(passwords);"
},
{
"answer_id": 74649016,
"author": "Scott Sauyet",
"author_id": 1243641,
"author_profile": "https://Stackoverflow.com/users/1243641",
"pm_score": 0,
"selected": false,
"text": "const genPasswords = (chars) => (n, length = 6, pre = '') => Array .from (\n {length: n}, \n () => pre + Array.from({length}, () => chars[~~(Math.random() * chars.length)]) .join('')\n)\n\nconst pwdGen = genPasswords (\"123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz'(-è_çà)=:;,!.\")\n\nconsole.time('generate 20000')\nconst res = pwdGen (20000, 6, 'FOULE')\nconsole.timeEnd('generate 20000')\n\nconsole .log (res) .as-console-wrapper {max-height: 100% !important; top: 0}"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9161372/"
] |
74,626,424
|
<p>I am working on application to show mobile contact list with initials in a circle, but not getting initial character for some contact names.</p>
<p>In below code, first name is from mobile's contact list and second one I have typed from keyboard.
I am able to get correct length and also first character of the second name, but length for first name is double and also not able to get first character (it gives �).</p>
<pre><code>print("".substring(0,1)); //�
print("".length); //12
print("Nagesh".substring(0,1)); //N
print("Nagesh".length); //6
</code></pre>
<p>Thankyou in advance for answering....</p>
|
[
{
"answer_id": 74626821,
"author": "doubleunary",
"author_id": 13045193,
"author_profile": "https://Stackoverflow.com/users/13045193",
"pm_score": 2,
"selected": false,
"text": "verify_unique() col.set({}, pass) Array Map col.includes(pass) col.push(pass) col Array.from(col.values()) var prefixe = prefixe;"
},
{
"answer_id": 74628384,
"author": "kevinSpaceyIsKeyserSöze",
"author_id": 3433538,
"author_profile": "https://Stackoverflow.com/users/3433538",
"pm_score": 2,
"selected": true,
"text": "Crypto.getRandomValues() const CHARACTER_POOL =\n \"123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz'(-è_çà)=:;,!.\";\nconst PASSWORDS_TO_GENERATE = 20000;\nconst PASSWORD_LENGTH = 6;\nconst PREFIX = \"\";\n\nconst createPassword = () => {\n let password = \"\";\n for (let i = 0; i < PASSWORD_LENGTH; i++) {\n // this is not secure\n password += CHARACTER_POOL.charAt(\n Math.floor(Math.random() * CHARACTER_POOL.length)\n );\n }\n return `${PREFIX}${password}`;\n};\n\nconst generatePassword = () => {\n const passwords = [];\n while (passwords.length < PASSWORDS_TO_GENERATE) {\n const password = createPassword();\n if (!passwords.includes(password)) {\n passwords.push(password);\n }\n }\n return passwords;\n};\n\nconst start = new Date().getTime();\nconst passwords = generatePassword();\nconsole.log(`It took ${(new Date().getTime() - start) / 1000} to generate ${passwords.length} passwords`);\nconsole.log(passwords);"
},
{
"answer_id": 74649016,
"author": "Scott Sauyet",
"author_id": 1243641,
"author_profile": "https://Stackoverflow.com/users/1243641",
"pm_score": 0,
"selected": false,
"text": "const genPasswords = (chars) => (n, length = 6, pre = '') => Array .from (\n {length: n}, \n () => pre + Array.from({length}, () => chars[~~(Math.random() * chars.length)]) .join('')\n)\n\nconst pwdGen = genPasswords (\"123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz'(-è_çà)=:;,!.\")\n\nconsole.time('generate 20000')\nconst res = pwdGen (20000, 6, 'FOULE')\nconsole.timeEnd('generate 20000')\n\nconsole .log (res) .as-console-wrapper {max-height: 100% !important; top: 0}"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9592446/"
] |
74,626,444
|
<pre><code>import { NavLink } from "react-router-dom"
export const LinkMenu = () => {
const masterControl = ["excursion", "agencie","guide","driver","vehicle"]
return (
<div className="text-center text-light">
<h6>Master Control</h6>
{ masterControl.map((data) =>{
let res = <div><NavLink style={{textDecoration: 'none', color:"rgb(214, 62, 24)" }} to="/data">{data}</NavLink><br></br></div>
return res
})}
</div>
)}
</code></pre>
<p>I just need what is returned by the data constants to be able to pass it as the path</p>
|
[
{
"answer_id": 74626480,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 1,
"selected": false,
"text": "to={`/${data}`}\n"
},
{
"answer_id": 74626499,
"author": "kuuhak-u",
"author_id": 20458458,
"author_profile": "https://Stackoverflow.com/users/20458458",
"pm_score": 0,
"selected": false,
"text": "<NavLink style={{textDecoration: 'none', color:\"rgb(214, 62, 24)\" }} to={`/${data}`}>{data}</NavLink>\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20644226/"
] |
74,626,491
|
<pre><code>let responseData = [
{
type: 'element',
name: 'ns2:VehicleInfo',
elements: [
{
type: 'element',
name: 'ns2:price',
elements: [
{
type: 'text',
text: '123',
},
],
},
{
type: 'element',
name: 'ns2:model',
elements: [
{
type: 'text',
text: 'vento',
},
],
},
{
type: 'element',
name: 'ns2:brand',
elements: [
{
type: 'text',
text: 'Vw',
},
],
},
{
type: 'element',
name: 'ns2:date',
elements: [
{
type: 'text',
text: '29 Nov 2022',
},
],
},
{
type: 'element',
name: 'ns2:vin',
elements: [
{
type: 'text',
text: '1',
},
],
},
],
},
{
type: 'element',
name: 'ns2:VehicleInfo',
elements: [
{
type: 'element',
name: 'ns2:price',
elements: [
{
type: 'text',
text: '10012',
},
],
},
{
type: 'element',
name: 'ns2:model',
elements: [
{
type: 'text',
text: '4matic',
},
],
},
{
type: 'element',
name: 'ns2:brand',
elements: [
{
type: 'text',
text: 'BMW',
},
],
},
{
type: 'element',
name: 'ns2:date',
elements: [
{
type: 'text',
text: '29 Nov 2022',
},
],
},
{
type: 'element',
name: 'ns2:vin',
elements: [
{
type: 'text',
text: '2',
},
],
},
],
},
]
</code></pre>
<p>Using JavaScript
above data need to be formatted like</p>
<pre><code>let obj = \[
{
id: '1',
vin: '1',
brand: 'Vw',
model: 'vento',
date: '22/11/22',
price: '123',
},
{
id: '2',
vin: '2',
brand: 'BMW',
model: '4matic',
date: '22/11/22',
price: '10012',
},
{
id: '3',
vin: '3',
brand: 'TATA',
model: 'Nano',
date: '22/11/22',
price: '$10000',
},
\];`
</code></pre>
|
[
{
"answer_id": 74626631,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 4,
"selected": true,
"text": "map reduce let responseData = [\n {\n type: 'element',\n name: 'ns2:VehicleInfo',\n elements: [\n {\n type: 'element',\n name: 'ns2:price',\n elements: [\n {\n type: 'text',\n text: '123',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:model',\n elements: [\n {\n type: 'text',\n text: 'vento',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:brand',\n elements: [\n {\n type: 'text',\n text: 'Vw',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:date',\n elements: [\n {\n type: 'text',\n text: '29 Nov 2022',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:vin',\n elements: [\n {\n type: 'text',\n text: '1',\n },\n ],\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:VehicleInfo',\n elements: [\n {\n type: 'element',\n name: 'ns2:price',\n elements: [\n {\n type: 'text',\n text: '10012',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:model',\n elements: [\n {\n type: 'text',\n text: '4matic',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:brand',\n elements: [\n {\n type: 'text',\n text: 'BMW',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:date',\n elements: [\n {\n type: 'text',\n text: '29 Nov 2022',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:vin',\n elements: [\n {\n type: 'text',\n text: '2',\n },\n ],\n },\n ],\n },\n]\n\nconst result = responseData.map(item => {\n return item.elements.reduce((acc, item) => {\n return {\n ...acc,\n [item.name.replace('ns2:', '')] : item.elements[0].text\n }\n \n }, {})\n})\n\nconsole.log(result)"
},
{
"answer_id": 74626749,
"author": "Flo",
"author_id": 4472932,
"author_profile": "https://Stackoverflow.com/users/4472932",
"pm_score": 2,
"selected": false,
"text": "id map let responseData = [\n {\n type: 'element',\n name: 'ns2:VehicleInfo',\n elements: [\n {\n type: 'element',\n name: 'ns2:price',\n elements: [\n {\n type: 'text',\n text: '123',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:model',\n elements: [\n {\n type: 'text',\n text: 'vento',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:brand',\n elements: [\n {\n type: 'text',\n text: 'Vw',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:date',\n elements: [\n {\n type: 'text',\n text: '29 Nov 2022',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:vin',\n elements: [\n {\n type: 'text',\n text: '1',\n },\n ],\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:VehicleInfo',\n elements: [\n {\n type: 'element',\n name: 'ns2:price',\n elements: [\n {\n type: 'text',\n text: '10012',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:model',\n elements: [\n {\n type: 'text',\n text: '4matic',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:brand',\n elements: [\n {\n type: 'text',\n text: 'BMW',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:date',\n elements: [\n {\n type: 'text',\n text: '29 Nov 2022',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:vin',\n elements: [\n {\n type: 'text',\n text: '2',\n },\n ],\n },\n ],\n },\n]\n\nconst result = responseData.map((item, index) => {\n return item.elements.reduce((acc, item) => {\n return {\n ...acc,\n id: index+1,\n [item.name.replace('ns2:', '')] : item.elements[0].text\n }\n \n }, {})\n})\n\nconsole.log(result)"
},
{
"answer_id": 74626782,
"author": "Marios",
"author_id": 20229075,
"author_profile": "https://Stackoverflow.com/users/20229075",
"pm_score": 0,
"selected": false,
"text": "let obj = responseData.map((element,index)=>{\n const object={};\n object.id=index+1;\n object.vin=element.elements[4].elements[0].text;\n object.brand=element.elements[2].elements[0].text;\n object.model=element.elements[1].elements[0].text;\n object.date=element.elements[3].elements[0].text;\n object.price=element.elements[0].elements[0].text\n return object \n})\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9589631/"
] |
74,626,544
|
<p>Good afternoon,<br />
I need to create a 2D array from 1D , according to the following rules:\</p>
<ul>
<li>The 2d array must not contain<br />
<code>[["A1", "A1"], ["A2", "A2"], ["A3", "A3"], ["A4", "A4"]...]</code></li>
<li>The array should not repeat, it's same for me<br />
<code>[["A1", "A2"], ["A2", "A1"], ....]</code>\</li>
<li>For example
Input array<br />
<code>A ["A1", "A2", "A3", "A4"]</code><br />
Output array<br />
<code>B [['A1' 'A2'] ['A1' 'A3']['A1' 'A4']['A2' 'A1']['A2' 'A3']['A2' 'A4']['A3' 'A1'] ['A3' 'A2'] ['A3' 'A4']['A4' 'A1'] ['A4' 'A2']['A4' 'A3']]</code></li>
</ul>
<p>I need<br />
<code>[['A1' 'A2']['A1' 'A3']['A1' 'A4']['A2' 'A3']['A2' 'A4'] ['A3' 'A4']</code></p>
<pre><code> import numpy as np
x = ("A1", "A2", "A3", "A4")
arr = []
for i in range(0, len(x)):
for j in range(0, len(x)):
if x[i] != x[j]:
arr.append((x[i], x[j]))
mylist = np.unique(arr, axis=0)
print(mylist)
</code></pre>
<p>how to do it?</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 74626631,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 4,
"selected": true,
"text": "map reduce let responseData = [\n {\n type: 'element',\n name: 'ns2:VehicleInfo',\n elements: [\n {\n type: 'element',\n name: 'ns2:price',\n elements: [\n {\n type: 'text',\n text: '123',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:model',\n elements: [\n {\n type: 'text',\n text: 'vento',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:brand',\n elements: [\n {\n type: 'text',\n text: 'Vw',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:date',\n elements: [\n {\n type: 'text',\n text: '29 Nov 2022',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:vin',\n elements: [\n {\n type: 'text',\n text: '1',\n },\n ],\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:VehicleInfo',\n elements: [\n {\n type: 'element',\n name: 'ns2:price',\n elements: [\n {\n type: 'text',\n text: '10012',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:model',\n elements: [\n {\n type: 'text',\n text: '4matic',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:brand',\n elements: [\n {\n type: 'text',\n text: 'BMW',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:date',\n elements: [\n {\n type: 'text',\n text: '29 Nov 2022',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:vin',\n elements: [\n {\n type: 'text',\n text: '2',\n },\n ],\n },\n ],\n },\n]\n\nconst result = responseData.map(item => {\n return item.elements.reduce((acc, item) => {\n return {\n ...acc,\n [item.name.replace('ns2:', '')] : item.elements[0].text\n }\n \n }, {})\n})\n\nconsole.log(result)"
},
{
"answer_id": 74626749,
"author": "Flo",
"author_id": 4472932,
"author_profile": "https://Stackoverflow.com/users/4472932",
"pm_score": 2,
"selected": false,
"text": "id map let responseData = [\n {\n type: 'element',\n name: 'ns2:VehicleInfo',\n elements: [\n {\n type: 'element',\n name: 'ns2:price',\n elements: [\n {\n type: 'text',\n text: '123',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:model',\n elements: [\n {\n type: 'text',\n text: 'vento',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:brand',\n elements: [\n {\n type: 'text',\n text: 'Vw',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:date',\n elements: [\n {\n type: 'text',\n text: '29 Nov 2022',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:vin',\n elements: [\n {\n type: 'text',\n text: '1',\n },\n ],\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:VehicleInfo',\n elements: [\n {\n type: 'element',\n name: 'ns2:price',\n elements: [\n {\n type: 'text',\n text: '10012',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:model',\n elements: [\n {\n type: 'text',\n text: '4matic',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:brand',\n elements: [\n {\n type: 'text',\n text: 'BMW',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:date',\n elements: [\n {\n type: 'text',\n text: '29 Nov 2022',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:vin',\n elements: [\n {\n type: 'text',\n text: '2',\n },\n ],\n },\n ],\n },\n]\n\nconst result = responseData.map((item, index) => {\n return item.elements.reduce((acc, item) => {\n return {\n ...acc,\n id: index+1,\n [item.name.replace('ns2:', '')] : item.elements[0].text\n }\n \n }, {})\n})\n\nconsole.log(result)"
},
{
"answer_id": 74626782,
"author": "Marios",
"author_id": 20229075,
"author_profile": "https://Stackoverflow.com/users/20229075",
"pm_score": 0,
"selected": false,
"text": "let obj = responseData.map((element,index)=>{\n const object={};\n object.id=index+1;\n object.vin=element.elements[4].elements[0].text;\n object.brand=element.elements[2].elements[0].text;\n object.model=element.elements[1].elements[0].text;\n object.date=element.elements[3].elements[0].text;\n object.price=element.elements[0].elements[0].text\n return object \n})\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13634221/"
] |
74,626,609
|
<p>Somebody know if it is possible to how to create Dynamic membership rules for groups in Azure Active Directory from powershell instead of passing from “Rule builder in the Azure portal” ?</p>
<p>Thank you</p>
|
[
{
"answer_id": 74626631,
"author": "Sachila Ranawaka",
"author_id": 6428638,
"author_profile": "https://Stackoverflow.com/users/6428638",
"pm_score": 4,
"selected": true,
"text": "map reduce let responseData = [\n {\n type: 'element',\n name: 'ns2:VehicleInfo',\n elements: [\n {\n type: 'element',\n name: 'ns2:price',\n elements: [\n {\n type: 'text',\n text: '123',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:model',\n elements: [\n {\n type: 'text',\n text: 'vento',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:brand',\n elements: [\n {\n type: 'text',\n text: 'Vw',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:date',\n elements: [\n {\n type: 'text',\n text: '29 Nov 2022',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:vin',\n elements: [\n {\n type: 'text',\n text: '1',\n },\n ],\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:VehicleInfo',\n elements: [\n {\n type: 'element',\n name: 'ns2:price',\n elements: [\n {\n type: 'text',\n text: '10012',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:model',\n elements: [\n {\n type: 'text',\n text: '4matic',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:brand',\n elements: [\n {\n type: 'text',\n text: 'BMW',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:date',\n elements: [\n {\n type: 'text',\n text: '29 Nov 2022',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:vin',\n elements: [\n {\n type: 'text',\n text: '2',\n },\n ],\n },\n ],\n },\n]\n\nconst result = responseData.map(item => {\n return item.elements.reduce((acc, item) => {\n return {\n ...acc,\n [item.name.replace('ns2:', '')] : item.elements[0].text\n }\n \n }, {})\n})\n\nconsole.log(result)"
},
{
"answer_id": 74626749,
"author": "Flo",
"author_id": 4472932,
"author_profile": "https://Stackoverflow.com/users/4472932",
"pm_score": 2,
"selected": false,
"text": "id map let responseData = [\n {\n type: 'element',\n name: 'ns2:VehicleInfo',\n elements: [\n {\n type: 'element',\n name: 'ns2:price',\n elements: [\n {\n type: 'text',\n text: '123',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:model',\n elements: [\n {\n type: 'text',\n text: 'vento',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:brand',\n elements: [\n {\n type: 'text',\n text: 'Vw',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:date',\n elements: [\n {\n type: 'text',\n text: '29 Nov 2022',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:vin',\n elements: [\n {\n type: 'text',\n text: '1',\n },\n ],\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:VehicleInfo',\n elements: [\n {\n type: 'element',\n name: 'ns2:price',\n elements: [\n {\n type: 'text',\n text: '10012',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:model',\n elements: [\n {\n type: 'text',\n text: '4matic',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:brand',\n elements: [\n {\n type: 'text',\n text: 'BMW',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:date',\n elements: [\n {\n type: 'text',\n text: '29 Nov 2022',\n },\n ],\n },\n {\n type: 'element',\n name: 'ns2:vin',\n elements: [\n {\n type: 'text',\n text: '2',\n },\n ],\n },\n ],\n },\n]\n\nconst result = responseData.map((item, index) => {\n return item.elements.reduce((acc, item) => {\n return {\n ...acc,\n id: index+1,\n [item.name.replace('ns2:', '')] : item.elements[0].text\n }\n \n }, {})\n})\n\nconsole.log(result)"
},
{
"answer_id": 74626782,
"author": "Marios",
"author_id": 20229075,
"author_profile": "https://Stackoverflow.com/users/20229075",
"pm_score": 0,
"selected": false,
"text": "let obj = responseData.map((element,index)=>{\n const object={};\n object.id=index+1;\n object.vin=element.elements[4].elements[0].text;\n object.brand=element.elements[2].elements[0].text;\n object.model=element.elements[1].elements[0].text;\n object.date=element.elements[3].elements[0].text;\n object.price=element.elements[0].elements[0].text\n return object \n})\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6177280/"
] |
74,626,646
|
<p>How to Capture previous row value and perform subtraction</p>
<p><a href="https://i.stack.imgur.com/GbZ22.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GbZ22.png" alt="enter image description here" /></a></p>
<p>Refer Table 1 as main data, Table 2 as desired output, Let me explain you in detail, Closing_Bal is derived from (Opening_bal - EMI) for eg if (20 - 2) = 18, as value 18 i want in 2nd row under opening_bal column then ( opening_bal - EMI) and so till new LAN , If New LAN available then start the loop again ,</p>
<p>i have created lag function butnot able to run loop</p>
|
[
{
"answer_id": 74628070,
"author": "Dirk Horsten",
"author_id": 4385647,
"author_profile": "https://Stackoverflow.com/users/4385647",
"pm_score": 0,
"selected": false,
"text": "data B;\n set A;\n by lan;\n if not first.lan then do;\n opening_bal = lag(closing_bal);\n closing_bal = opening_bal - EMI;\n end;\nrun;\n lag"
},
{
"answer_id": 74632574,
"author": "PeterClemmensen",
"author_id": 4044936,
"author_profile": "https://Stackoverflow.com/users/4044936",
"pm_score": 2,
"selected": true,
"text": "data A;\ninput Month $ LAN Opening_Bal EMI Closing_Bal;\ninfile datalines dlm = '|' dsd;\ndatalines;\n1_Nov|1|20|2|18 \n2_Dec|1| |3| \n3_Jan|1| |5| \n4_Feb|1| |3| \n1_Nov|2|30|4|26 \n2_Dec|2| |3| \n3_Jan|2| |2| \n4_Feb|2| |5| \n5_Mar|2| |6| \n;\n\ndata B(drop = c);\n set A;\n by LAN;\n\n if first.LAN then c = Closing_Bal;\n\n if Opening_Bal = . then do;\n Opening_Bal = c;\n Closing_Bal = Opening_Bal - EMI;\n c = Closing_Bal;\n end;\n\n retain c;\nrun;\n Month LAN Opening_Bal EMI Closing_Bal\n1_Nov 1 20 2 18\n2_Dec 1 18 3 15\n3_Jan 1 15 5 10\n4_Feb 1 10 3 7\n1_Nov 2 30 4 26\n2_Dec 2 26 3 23\n3_Jan 2 23 2 21\n4_Feb 2 21 5 16\n5_Mar 2 16 6 10\n"
},
{
"answer_id": 74632964,
"author": "Tom",
"author_id": 4965549,
"author_profile": "https://Stackoverflow.com/users/4965549",
"pm_score": 1,
"selected": false,
"text": "data have;\n input Month $ LAN Opening_Bal EMI Closing_Bal;\ndatalines;\n1_Nov 1 20 2 18 \n2_Dec 1 . 3 . \n3_Jan 1 . 5 . \n4_Feb 1 . 3 . \n1_Nov 2 30 4 26 \n2_Dec 2 . 3 . \n3_Jan 2 . 2 . \n4_Feb 2 . 5 . \n5_Mar 2 . 6 . \n;\n\ndata want;\n set have (drop=closing_bal);\n retain Closing_Bal;\n Opening_Bal=coalesce(Opening_Bal,Closing_Bal);\n Closing_bal=Opening_bal - EMI ;\nrun;\n Opening_ Closing_\nObs Month LAN Bal EMI Bal\n\n 1 1_Nov 1 20 2 18\n 2 2_Dec 1 18 3 15\n 3 3_Jan 1 15 5 10\n 4 4_Feb 1 10 3 7\n 5 1_Nov 2 30 4 26\n 6 2_Dec 2 26 3 23\n 7 3_Jan 2 23 2 21\n 8 4_Feb 2 21 5 16\n 9 5_Mar 2 16 6 10\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14367504/"
] |
74,626,654
|
<p>I'm cleaning some data where there are multiple columns that need to be split into rows with both ',' and '/'. Data table below to explain what it the source code looks like.</p>
<pre><code>df <- data.table(
b = c("a", "d/e/f", "g,h"),
c = c("1", "2,3,4", "5/6")
)
</code></pre>
<p>I've tried using separate_rows, but it can only split one column on one of these separators at a time.</p>
<p>EDIT: The data table I'm looking for looks approximately like this:</p>
<pre><code>df_clean <- data.table(
b = c("a", "d", "d", "d",
"e", "e", "e", "f",
"f", "f", "g", "g",
"h", "h"),
c = c("1", "2", "3", "4",
"2", "3", "4",
"2", "3", "4",
"5", "6",
"5", "6")
)
</code></pre>
|
[
{
"answer_id": 74626814,
"author": "Aron Strandberg",
"author_id": 4885169,
"author_profile": "https://Stackoverflow.com/users/4885169",
"pm_score": 2,
"selected": false,
"text": "separate_rows library(tidyr)\n\ndf %>%\n separate_rows(b, sep = '/|,') %>%\n separate_rows(c, sep = '/|,')\n\n#> # A tibble: 14 × 2\n#> b c \n#> <chr> <chr>\n#> 1 a 1 \n#> 2 d 2 \n#> 3 d 3 \n#> 4 d 4 \n#> 5 e 2 \n#> 6 e 3 \n#> 7 e 4 \n#> 8 f 2 \n#> 9 f 3 \n#> 10 f 4 \n#> 11 g 5 \n#> 12 g 6 \n#> 13 h 5 \n#> 14 h 6\n"
},
{
"answer_id": 74626837,
"author": "IamTheB",
"author_id": 19161269,
"author_profile": "https://Stackoverflow.com/users/19161269",
"pm_score": 2,
"selected": false,
"text": "s <- strsplit(df$b, split = c(\",\",\"/\"))\ndata.frame(a = rep(df$a, sapply(s, length)), b = unlist(s))\n"
},
{
"answer_id": 74631294,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "cSplit library(splitstackshape)\ncSplit(df, \"b\", sep = \"/|,\", \"long\", fixed = FALSE) |> \n cSplit(\"c\", sep = \"/|,\", \"long\", fixed = FALSE)\n b c\n 1: a 1\n 2: d 2\n 3: d 3\n 4: d 4\n 5: e 2\n 6: e 3\n 7: e 4\n 8: f 2\n 9: f 3\n10: f 4\n11: g 5\n12: g 6\n13: h 5\n14: h 6\n"
},
{
"answer_id": 74631995,
"author": "sindri_baldur",
"author_id": 4552295,
"author_profile": "https://Stackoverflow.com/users/4552295",
"pm_score": 1,
"selected": false,
"text": "data.table # option 1\nfoo = \\(x) unlist(strsplit(x, \",|/\"))\ndf[, do.call(CJ, lapply(.SD, foo)), .I][, !\"I\"]\n sep = \",|/\"\nMap(\n expand.grid,\n strsplit(df$b, sep),\n strsplit(df$c, sep)\n) |> \n do.call(rbind, args = _)\n # b c\n# <char> <char>\n# 1: a 1\n# 2: d 2\n# 3: d 3\n# 4: d 4\n# 5: e 2\n# 6: e 3\n# 7: e 4\n# 8: f 2\n# 9: f 3\n# 10: f 4\n# 11: g 5\n# 12: g 6\n# 13: h 5\n# 14: h 6\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19536418/"
] |
74,626,656
|
<p>I am running into problems installing BeautifulSoup4. This is the code I am using in a Jupiter notebook to import beautifulsoup</p>
<pre><code>from selenium import webdriver
import beautifulsoup4
import pandas as pd
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Cell In [12], line 2
1 from selenium import webdriver
----> 2 import beautifulsoup4
3 import pandas as pd
ModuleNotFoundError: No module named 'beautifulsoup4'
</code></pre>
<p>When pip installing in terminal I get following output which states that beautiful soup should be installed:</p>
<pre><code>(CodingFolder) user ~ % pip install beautifulsoup4
Requirement already satisfied: beautifulsoup4 in ./opt/anaconda3/envs/CodingFolder/lib/python3.9/site-packages (4.11.1)
Requirement already satisfied: soupsieve>1.2 in ./opt/anaconda3/envs/CodingFolder/lib/python3.9/site-packages (from beautifulsoup4) (2.3.2.post1)
</code></pre>
<p>What am I missing ?</p>
|
[
{
"answer_id": 74626700,
"author": "baduker",
"author_id": 6106791,
"author_profile": "https://Stackoverflow.com/users/6106791",
"pm_score": 2,
"selected": true,
"text": "$ pip install beautifulsoup4\n from bs4 import BeautifulSoup\n import beautifulsoup4\n"
},
{
"answer_id": 74626804,
"author": "Naman Agarwal",
"author_id": 18459082,
"author_profile": "https://Stackoverflow.com/users/18459082",
"pm_score": -1,
"selected": false,
"text": "pip install beautifulsoup4\n from bs4 import BeautifulSoup\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17217956/"
] |
74,626,661
|
<p>When activity is started TextInputlayout with edittext always auto focasable. i try</p>
<pre><code>android:focusableInTouchMode="true"
</code></pre>
<p>but it doesn't work. Hear is my code.</p>
<pre><code><com.google.android.material.textfield.TextInputLayout
android:id="@+id/textInputMobile"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:errorEnabled="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvMessage">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/edtEmail"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawableStart="@drawable/ic_mobile"
android:drawablePadding="@dimen/_3sdp"
**android:focusableInTouchMode="true"**
android:fontFamily="@font/montserrat_regular"
android:hint="@string/str_mobile_number"
android:inputType="number"
android:maxLength="10"
android:paddingVertical="@dimen/_9sdp"
android:textColor="@color/colorBlack"
android:textSize="@dimen/_10ssp" />
</com.google.android.material.textfield.TextInputLayout>
</code></pre>
<p>I want to enable focus only when i touch the edit text.</p>
|
[
{
"answer_id": 74626700,
"author": "baduker",
"author_id": 6106791,
"author_profile": "https://Stackoverflow.com/users/6106791",
"pm_score": 2,
"selected": true,
"text": "$ pip install beautifulsoup4\n from bs4 import BeautifulSoup\n import beautifulsoup4\n"
},
{
"answer_id": 74626804,
"author": "Naman Agarwal",
"author_id": 18459082,
"author_profile": "https://Stackoverflow.com/users/18459082",
"pm_score": -1,
"selected": false,
"text": "pip install beautifulsoup4\n from bs4 import BeautifulSoup\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20526737/"
] |
74,626,662
|
<p>I have a matrix with zero's and one's. ~30% of the sample are 1s, I want to estimate a confidence-interval around this percentage (e.g., "if I sampled the whole population there would be likely 28-32% "1"s). For doing so you can bootstrap from the sample, (redraw the sample N times from itself with replacement and analyze the distribution of the percentage of 1s over all redrawn samples). However my data is nested (highly correlated) within rows and within columns. I tried out whether this nestedness makes a difference (since I have dichotmous variables I can use rflip() which simulates a biased coinflip), it does:</p>
<pre><code>library("mosaic")
#### data example ####
c1<-c(1,1,1,1,1,0,0,0,0,0) # high probability for "1"
c2<-c(1,0,0,0,0,0,0,0,0,0) # low probability for "1"
d<-cbind.data.frame(c1,c2)
#### a) resample over entire data ####
b<-vector()
for (i in 1:10000){
b[i] <- rflip(20, # Flip 20 times,
6/20)/ # Probability for "1": 6/20, i.e., probability for "0": 14/20
20 # divide by 20 to return relative frequency
}
mean(b)# returns 0.3007955 # mean over 10000 replications: close to 6/20
sd(b) # returns 0.1024339 # standard deviation important to compute confidence interval
#### b) resample per column ####
b1 <- vector()
b2 <- vector()
bt <- vector()
for (i in 1:10000){
b1[i] <- rflip(10,(5/10)) # Flip 10 times with probablility for c1
b2[i] <- rflip(10,(1/10)) # Flip 10 times with probablility for c2
bt[i] <- (b1[i]+b2[i])/20 # sum up all 20 flips and divide by 20 to return relative frequency
}
mean(bt)# returns 0.3001475 # mean similar to a)
sd(bt) # returns 0.09214384 # standard deviation smaller than a)
</code></pre>
<p>When I redraw 10 times from column c1 and 10 times from column c2 and replicate this process 10,000 times the distribution of the observed probabilities is more narrow than when I sample 20 times from the entire data. If the probability for "1" is identical in both columns approaches a) and b) lead to the same standard deviation.</p>
<p>I now want to consider not only the columns but also the rows, e.g. I want to draw 10 times from column 1 and 10 times from column 2 and I want to constrain that among these 20 draws there must be two draws per row. My first idea would be:</p>
<p>forloop{</p>
<ol>
<li>Randomize order of columns</li>
<li>draw 10 times from column 1 but constrain that there are maximum 2 redraws per row</li>
<li>draw 10 times from column 2 but constrain that the redraws from column 1 plus the redraws from column 2 are maximum 2 redraws per row (if we had 2 redraws from row 1 for column 1, no redraws from row 1 for column 2)</li>
</ol>
<p>}</p>
<p>Does anybody have an idea about how to do that or has anybody got a better idea? Must probably be a different function than rflip().
Would help me a lot!</p>
<p>Thanks,
ajj</p>
|
[
{
"answer_id": 74627048,
"author": "Vons",
"author_id": 2303235,
"author_profile": "https://Stackoverflow.com/users/2303235",
"pm_score": 0,
"selected": false,
"text": "sample(rep(1:10,2),size=10,replace=FALSE)\n"
},
{
"answer_id": 74627976,
"author": "jblood94",
"author_id": 9463489,
"author_profile": "https://Stackoverflow.com/users/9463489",
"pm_score": 2,
"selected": true,
"text": "r2dtable nrows <- 10L\nncols <- 6L\nnr <- rep(ncols, nrows)\nnc <- rep(nrows, ncols)\n\nm <- r2dtable(1, nr, nc)[[1]]\nm\n#> [,1] [,2] [,3] [,4] [,5] [,6]\n#> [1,] 2 0 1 1 1 1\n#> [2,] 2 1 1 0 1 1\n#> [3,] 0 1 1 2 2 0\n#> [4,] 0 3 1 1 0 1\n#> [5,] 1 2 1 0 1 1\n#> [6,] 0 0 1 2 0 3\n#> [7,] 3 0 1 1 0 1\n#> [8,] 2 0 0 1 3 0\n#> [9,] 0 0 1 2 1 2\n#> [10,] 0 3 2 0 1 0\nrowSums(m)\n#> [1] 6 6 6 6 6 6 6 6 6 6\ncolSums(m)\n#> [1] 10 10 10 10 10 10\n nrows <- 10L\nncols <- 2L\nnr <- rep(ncols, nrows)\nnc <- rep(nrows, ncols)\n\nm <- r2dtable(1, nr, nc)[[1]]\nm\n#> [,1] [,2]\n#> [1,] 2 0\n#> [2,] 0 2\n#> [3,] 1 1\n#> [4,] 2 0\n#> [5,] 0 2\n#> [6,] 2 0\n#> [7,] 1 1\n#> [8,] 1 1\n#> [9,] 0 2\n#> [10,] 1 1\n broadcast <- Rcpp::cppFunction(\n \"arma::cube broadcast(arma::cube& m, arma::mat& d) {return(m.each_slice() % d);}\",\n depends = \"RcppArmadillo\",\n plugins = \"cpp11\"\n)\n\nc1 <- c(1,1,1,1,1,0,0,0,0,0) # high probability for \"1\"\nc2 <- c(1,0,0,0,0,0,0,0,0,0) # low probability for \"1\"\nd <- cbind(c1, c2)\nnr <- nrow(d)\nnc <- ncol(d)\nnreps <- 1e4L\n\nbt <- colSums(\n broadcast(\n simplify2array(\n r2dtable(\n nreps,\n rep(nc, nr),\n rep(nr, nc)\n )\n ),\n d\n ),\n dims = 2\n)/nr/nc\np <- mean(d)\nmean(d) # true mean\n#> [1] 0.3\nmean(bt) # estimated mean\n#> [1] 0.300685\nsqrt(p*(1 - p)/nr/nc) # expected SD from uniform samples of size nr*nc\n#> [1] 0.1024695\nsqrt((p*(1 - p) - var(colMeans(d))*(1 - 1/nc))/nr/nc) # expected SD from column-wise resampling\n#> [1] 0.09219544\nsd(bt) # estimated SD from constrained row and column resampling\n#> [1] 0.05604547\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19496867/"
] |
74,626,663
|
<p>I have a repo that has another remote <em><remote_2></em> besides origin. When I execute a command <code>git checkout development</code>, it checks out to <em><remote_2>/development</em> branch. Now, I want to checkout to <em>origin/development</em>. When I execute a command <code>git checkout origin/development</code> it says:</p>
<p>You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.</p>
<p>And when I do <code>git status</code> it says: HEAD detached at origin/development.</p>
<p>I'm not that good into git, but how can I checkout to <em>origin/development</em>, because I want to push commits on origin remote, and only sometimes to <remote_2>.</p>
<p>When I do <code>git branch -a</code> I have this:</p>
<pre><code>* development
main
remotes/remote_2/development
remotes/remote_2/main
remotes/origin/HEAD -> origin/main
remotes/origin/development
remotes/origin/main
</code></pre>
|
[
{
"answer_id": 74626733,
"author": "Romain Valeri",
"author_id": 1057485,
"author_profile": "https://Stackoverflow.com/users/1057485",
"pm_score": 3,
"selected": true,
"text": "development remote_2/development # get on your branch\ngit checkout development\n\n# point to the right commit\ngit reset --hard origin/development\n\n# set up remote\ngit push -u origin HEAD\n remote_2 git push remote_2 HEAD"
},
{
"answer_id": 74628237,
"author": "Vishal",
"author_id": 7182784,
"author_profile": "https://Stackoverflow.com/users/7182784",
"pm_score": 0,
"selected": false,
"text": "git checkout main git checkout -b origin_developement origin/developement\n origin_developement origin/developement"
},
{
"answer_id": 74628583,
"author": "Jay",
"author_id": 4068476,
"author_profile": "https://Stackoverflow.com/users/4068476",
"pm_score": 1,
"selected": false,
"text": "git checkout git checkout -b development origin/development\n -B -b development git checkout origin remote_2 .git/config [checkout]\n defaultRemote = origin\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14143586/"
] |
74,626,682
|
<p>I am following this tutorial:
<a href="https://openliberty.io/guides/microprofile-config-intro.html" rel="nofollow noreferrer">https://openliberty.io/guides/microprofile-config-intro.html</a></p>
<p>I have the following servlet :</p>
<pre><code>import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns="/car-types")
public class InventoryServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
System.out.println("Inside the /cat-types servlet preparing to respond with carInventory.html");
RequestDispatcher view = request.getRequestDispatcher("carInventory.html");
view.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
</code></pre>
<p>My webapp folder contains inside the file carInventory.html, however when I access in the browser the link I get the following message: <code>RESTEASY003210: Could not find resource for full path: http://localhost:9080/OpenLibertyExperiments/carInventory.html</code></p>
<p>The system.out message from the doGet message is seen in the server logs, so the servlet is reached corectly, but the html file is not found...this is what I understand from the error.</p>
<p>This is what features i defined to use:</p>
<pre><code> <featureManager>
<feature>servlet-5.0</feature>
<feature>restfulWS-3.0</feature>
<feature>jsonp-2.0</feature>
<feature>jsonb-2.0</feature>
<feature>cdi-3.0</feature>
<feature>mpConfig-3.0</feature>
<feature>mpRestClient-3.0</feature>
<feature>mpOpenAPI-3.0</feature>
</featureManager>
</code></pre>
<p><a href="https://i.stack.imgur.com/YeqnP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YeqnP.png" alt="enter image description here" /></a></p>
<p>Any ideas on what could it be ?</p>
|
[
{
"answer_id": 74626733,
"author": "Romain Valeri",
"author_id": 1057485,
"author_profile": "https://Stackoverflow.com/users/1057485",
"pm_score": 3,
"selected": true,
"text": "development remote_2/development # get on your branch\ngit checkout development\n\n# point to the right commit\ngit reset --hard origin/development\n\n# set up remote\ngit push -u origin HEAD\n remote_2 git push remote_2 HEAD"
},
{
"answer_id": 74628237,
"author": "Vishal",
"author_id": 7182784,
"author_profile": "https://Stackoverflow.com/users/7182784",
"pm_score": 0,
"selected": false,
"text": "git checkout main git checkout -b origin_developement origin/developement\n origin_developement origin/developement"
},
{
"answer_id": 74628583,
"author": "Jay",
"author_id": 4068476,
"author_profile": "https://Stackoverflow.com/users/4068476",
"pm_score": 1,
"selected": false,
"text": "git checkout git checkout -b development origin/development\n -B -b development git checkout origin remote_2 .git/config [checkout]\n defaultRemote = origin\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1206610/"
] |
74,626,693
|
<p>I just want to know that how to install Tailwind CSS properly
all I want the steps 1 by 1 because I have tried to do so but it doesn't work properly</p>
<p>I have tried to copy the steps from the main website of twilwind.com but I don't get the right installation I don't know why somehow</p>
|
[
{
"answer_id": 74626733,
"author": "Romain Valeri",
"author_id": 1057485,
"author_profile": "https://Stackoverflow.com/users/1057485",
"pm_score": 3,
"selected": true,
"text": "development remote_2/development # get on your branch\ngit checkout development\n\n# point to the right commit\ngit reset --hard origin/development\n\n# set up remote\ngit push -u origin HEAD\n remote_2 git push remote_2 HEAD"
},
{
"answer_id": 74628237,
"author": "Vishal",
"author_id": 7182784,
"author_profile": "https://Stackoverflow.com/users/7182784",
"pm_score": 0,
"selected": false,
"text": "git checkout main git checkout -b origin_developement origin/developement\n origin_developement origin/developement"
},
{
"answer_id": 74628583,
"author": "Jay",
"author_id": 4068476,
"author_profile": "https://Stackoverflow.com/users/4068476",
"pm_score": 1,
"selected": false,
"text": "git checkout git checkout -b development origin/development\n -B -b development git checkout origin remote_2 .git/config [checkout]\n defaultRemote = origin\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5942719/"
] |
74,626,726
|
<p><a href="https://i.stack.imgur.com/tThIq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tThIq.png" alt="enter image description here" /></a>I'm trying to send the whatsapp cloud template from postman.
I created a template in whatsapp cloud with header media image,
body content,footer and two buttons.</p>
<p>the response of the templates when i use get api is as below</p>
<pre><code> {
"name": "trns_btn_img_header_XXX",
"components": [
{
"type": "HEADER",
"format": "IMAGE",
"example": {
"header_handle": [
"https://img.url.com"
]
}
},
{
"type": "BODY",
"text": "Body message"
},
{
"type": "FOOTER",
"text": "ftr optioal"
},
{
"type": "BUTTONS",
"buttons": [
{
"type": "QUICK_REPLY",
"text": "qrbtnone"
},
{
"type": "QUICK_REPLY",
"text": "qrbtntwo"
}
]
}
],
"language": "en_US",
"status": "APPROVED",
"category": "TRANSACTIONAL",
"id": "17XX209448XXXXXX"
}
</code></pre>
<p>I tried the template json object in postman is as below</p>
<pre><code>{
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": "{{message_to}}",
"type": "template",
"template": {
"name": "trns_btn_img_header_XXX",
"language": {
"code": "en_US"
},
"components": [
{
"type": "header",
"parameters": [
{
"type": "image",
"image": {
"link": "https://img.jpg.com"
}
}
]
},
{
"type": "body",
"parameters": [
{
"type": "text",
"text": "Body message from pm"
},
]
},
{
"type": "footer",
"parameters": [
{
"type": "text",
"text": "footer message from pm"
},
]
},
{
"type": "button",
"sub_type": "quick_reply",
"index": "0",
"parameters": [
{
"type": "text",
"text": "btnone"
}
]
},
{
"type": "button",
"sub_type": "quick_reply",
"index": "1",
"parameters": [
{
"type": "text",
"text": "btntwo"
}
]
}
]
}
}
</code></pre>
<p>the response error is "error": {
"message": "(#132000) Number of parameters does not match the expected number of params"</p>
|
[
{
"answer_id": 74626733,
"author": "Romain Valeri",
"author_id": 1057485,
"author_profile": "https://Stackoverflow.com/users/1057485",
"pm_score": 3,
"selected": true,
"text": "development remote_2/development # get on your branch\ngit checkout development\n\n# point to the right commit\ngit reset --hard origin/development\n\n# set up remote\ngit push -u origin HEAD\n remote_2 git push remote_2 HEAD"
},
{
"answer_id": 74628237,
"author": "Vishal",
"author_id": 7182784,
"author_profile": "https://Stackoverflow.com/users/7182784",
"pm_score": 0,
"selected": false,
"text": "git checkout main git checkout -b origin_developement origin/developement\n origin_developement origin/developement"
},
{
"answer_id": 74628583,
"author": "Jay",
"author_id": 4068476,
"author_profile": "https://Stackoverflow.com/users/4068476",
"pm_score": 1,
"selected": false,
"text": "git checkout git checkout -b development origin/development\n -B -b development git checkout origin remote_2 .git/config [checkout]\n defaultRemote = origin\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5657929/"
] |
74,626,761
|
<p>I want to run a DAG on 2nd and 5th working day of every month.</p>
<p>eg1: Suppose, 1st Day of the month falls on Friday. In that case the 2nd working day of the month falls on 4th of that Month(i.e. on Monday) and 5th working Day falls on 7th of that month.</p>
<p>eg2: Suppose 1st Day of Month falls on Wednesday. In that case, the 2nd working Day will fall on 2nd Day of that Month, but the 5th Working Day will fall on 7th of that month (i.e. on Tuesday)</p>
<p>eg3: suppose 1st Day of Month falls on Sunday. In that case, the 2nd working day will fall on 3rd of that month and the 5th working day will fall on 6th of that month (i.e. on Friday)</p>
<p>So, how to schedule the DAG in Airflow for such scenarios.</p>
<p>#aiflow #DAG #schedule</p>
<p>I am looking for scheduling logic or code</p>
|
[
{
"answer_id": 74626733,
"author": "Romain Valeri",
"author_id": 1057485,
"author_profile": "https://Stackoverflow.com/users/1057485",
"pm_score": 3,
"selected": true,
"text": "development remote_2/development # get on your branch\ngit checkout development\n\n# point to the right commit\ngit reset --hard origin/development\n\n# set up remote\ngit push -u origin HEAD\n remote_2 git push remote_2 HEAD"
},
{
"answer_id": 74628237,
"author": "Vishal",
"author_id": 7182784,
"author_profile": "https://Stackoverflow.com/users/7182784",
"pm_score": 0,
"selected": false,
"text": "git checkout main git checkout -b origin_developement origin/developement\n origin_developement origin/developement"
},
{
"answer_id": 74628583,
"author": "Jay",
"author_id": 4068476,
"author_profile": "https://Stackoverflow.com/users/4068476",
"pm_score": 1,
"selected": false,
"text": "git checkout git checkout -b development origin/development\n -B -b development git checkout origin remote_2 .git/config [checkout]\n defaultRemote = origin\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15147133/"
] |
74,626,767
|
<p>I try to write a code to read a JSON File and allows user to input all the parametes for the objects in the JSON File one by one.<br />
I try to write something like an "awaitable Button", but I failed to write a "GetAwaiter" extension for the button, although I found informations about how to do it.</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-inherit-from-existing-windows-forms-controls?view=netframeworkdesktop-4.8" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-inherit-from-existing-windows-forms-controls?view=netframeworkdesktop-4.8</a></p>
<p><a href="https://stackoverflow.com/questions/73959407/how-can-i-combine-await-whenany-with-getawaiter-extension-method">how can I combine await.WhenAny() with GetAwaiter extension method</a></p>
<p><a href="http://blog.roboblob.com/2014/10/23/awaiting-for-that-button-click/" rel="nofollow noreferrer">http://blog.roboblob.com/2014/10/23/awaiting-for-that-button-click/</a></p>
<p>So here is my code after clicking a button "loadJSON":</p>
<pre><code>for (int i = 0; i<templist_net.Count; i++)
{
GeneratorFunctions.GetNetworkParameterList(templist_net[i].Type, templist_net[i], treeViewPath.SelectedPath, SolutionFolder);
cBoxPouItem.Text = templist_net[i].Type;
ListViewParam2.ItemsSource = GeneratorFunctions.TempList; // Parameter list binding
temp = GeneratorFunctions.TempList;
ListViewParam2.Visibility = Visibility.Visible; // Set list 2 visible
ListViewParam.Visibility = Visibility.Collapsed; // Set list 1 invisible
//something stop loop, and wait user to type parameters in Listview, and click Button, Then the loop move on.
}
</code></pre>
<p>And Here is code trying to write a Button with extension. I add a new class for custom control, and write the extension.</p>
<pre><code>public partial class CustomControl2 : System.Windows.Forms.Button
{
static CustomControl2()
{
}
public static TaskAwaiter GetAwaiter(this Button self)
{
ArgumentNullException.ThrowIfNull(self);
TaskCompletionSource tcs = new();
self.Click += OnClick;
return tcs.Task.GetAwaiter();
void OnClick(object sender, EventArgs args)
{
self.Click -= OnClick;
tcs.SetResult();
}
}
}
</code></pre>
<p>But I can't write a extension, which inherit System.Windows.Forms.Button. What should I do?</p>
<p>UPDATE:
here is what i tried.</p>
<pre><code> private async Task Btn_loadJsonAsync(object sender, RoutedEventArgs e) {
// Initialize an open file dialog, whose filter has a extend name ".json"
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "(*.json)|*.json";
TextBoxInformation.Text += "Opening project ...\n";
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
networks = GeneratorFunctions.ReadjsonNetwork(openFileDialog.FileName);
for (int i = 0; i < networks.Count; i++)
{
if (temp != null)
{
if (networks[i].Type == "Network")
{
templist_net.Add(networks[i]);
i = 1;
}
if (networks[i].Type == "Subsystem")
{
templist_sub.Add(networks[i]);
i = 1;
}
if (networks[i].Type == "Component: Data Point Based Control")
{
templist_com.Add(networks[i]);
i = 1;
}
}
}
using (SemaphoreSlim semaphore = new SemaphoreSlim(0, 1))
{
void OnClick(object sender, RoutedEventArgs e) => semaphore.Release();
btn.Click += OnClick;
for (int i = 0; i < templist_net.Count; i++)
{
//...
//wait here until [btn] is clicked...
await semaphore.WaitAsync();
}
btn.Click -= OnClick;
}}}
</code></pre>
|
[
{
"answer_id": 74626733,
"author": "Romain Valeri",
"author_id": 1057485,
"author_profile": "https://Stackoverflow.com/users/1057485",
"pm_score": 3,
"selected": true,
"text": "development remote_2/development # get on your branch\ngit checkout development\n\n# point to the right commit\ngit reset --hard origin/development\n\n# set up remote\ngit push -u origin HEAD\n remote_2 git push remote_2 HEAD"
},
{
"answer_id": 74628237,
"author": "Vishal",
"author_id": 7182784,
"author_profile": "https://Stackoverflow.com/users/7182784",
"pm_score": 0,
"selected": false,
"text": "git checkout main git checkout -b origin_developement origin/developement\n origin_developement origin/developement"
},
{
"answer_id": 74628583,
"author": "Jay",
"author_id": 4068476,
"author_profile": "https://Stackoverflow.com/users/4068476",
"pm_score": 1,
"selected": false,
"text": "git checkout git checkout -b development origin/development\n -B -b development git checkout origin remote_2 .git/config [checkout]\n defaultRemote = origin\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16274577/"
] |
74,626,787
|
<p>I would like to get/create a string with a specific length (10) and with a specific values (first 2 characters specific, remaining 8 characters should repeat).</p>
<h3>Example 1</h3>
<p>I am getting value from front-end as <code>AB</code> and I need to have a string with length of 10. The final string value should be <code>AB00000000</code> and I need to store it in the DB. So, whatever value I receive from the front-end, I need to save it with string sized 10 with rest of chars as zero (<code>0</code>).</p>
<h3>A few more examples</h3>
<ul>
<li>From UI: <code>ABC</code>, final output: <code>ABC0000000</code></li>
<li>From UI: <code>ABCD</code>, final output: <code>ABCD000000</code></li>
</ul>
<p>I came across some methods like <code>StringUtils.rightpad("AB",10,"0")</code> from Apache commons-lang, which gives me what I want exactly, but I would need to add this JAR only for this.</p>
<p>Is there any better way to achieve it?</p>
|
[
{
"answer_id": 74626733,
"author": "Romain Valeri",
"author_id": 1057485,
"author_profile": "https://Stackoverflow.com/users/1057485",
"pm_score": 3,
"selected": true,
"text": "development remote_2/development # get on your branch\ngit checkout development\n\n# point to the right commit\ngit reset --hard origin/development\n\n# set up remote\ngit push -u origin HEAD\n remote_2 git push remote_2 HEAD"
},
{
"answer_id": 74628237,
"author": "Vishal",
"author_id": 7182784,
"author_profile": "https://Stackoverflow.com/users/7182784",
"pm_score": 0,
"selected": false,
"text": "git checkout main git checkout -b origin_developement origin/developement\n origin_developement origin/developement"
},
{
"answer_id": 74628583,
"author": "Jay",
"author_id": 4068476,
"author_profile": "https://Stackoverflow.com/users/4068476",
"pm_score": 1,
"selected": false,
"text": "git checkout git checkout -b development origin/development\n -B -b development git checkout origin remote_2 .git/config [checkout]\n defaultRemote = origin\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13876589/"
] |
74,626,796
|
<p>This is my Frontend code</p>
<pre><code> const fetchData = () => {
const options = {
method: 'GET',
url: 'http://localhost:1337/user/chart',
headers: {'x-access-token': sessionStorage.getItem('token')},
body: [chartData.datasets]
}
axios.request(options).then((response) => {
console.log(response)
}).catch((error) => {
console.error(error)})
}
</code></pre>
<p>This is backend</p>
<pre><code>app.get('/user/chart', async (req, res) => {
const token = req.headers['x-access-token']
if (!token){
return res.status(404).json({ success: false, msg: "Token not found" });
}
try {
const decoded = jwt.verify(token, process.env.access_secret)
const email = decoded.email
await User.updateOne(
{ email: email },
{ $set: {} },
)
console.log(req.body)
return res.status(200).json({message: 'ok', label:[]})
} catch (error) {
console.log(error)
res.json({ status: 'error', error: 'invalid token' })
}
})
</code></pre>
<p>When I console.log(req.body) it is an empty {}.
Why is it empty?
I am using a GET request to retrieve the chart data</p>
|
[
{
"answer_id": 74627030,
"author": "Neo",
"author_id": 10165237,
"author_profile": "https://Stackoverflow.com/users/10165237",
"pm_score": 2,
"selected": false,
"text": "const url = '/user/chart';\n\nconst config = {\n headers: {'x-access-token': sessionStorage.getItem('token')},\n params:{someKey:chartData.datasets}\n};\n\naxios.get(url, config)\n"
},
{
"answer_id": 74628511,
"author": "Emre Yılmaz",
"author_id": 20633709,
"author_profile": "https://Stackoverflow.com/users/20633709",
"pm_score": 0,
"selected": false,
"text": "const fetchData = () => {\nconst options = {\n method: 'POST',\n url: 'http://localhost:1337/user/chart',\n headers: {'x-access-token': sessionStorage.getItem('token')},\n body: {name : \"xx\",mail:\"xx@\"}\n }\n axios.request(options).then((response) => {\n console.log(response)\n }).catch((error) => {\n console.error(error)})\n }\n app.post('/user/chart', async (req, res) => {\nconst {name , mail} = req.body\nconst token = req.headers['x-access-token']\nif (!token){\n return res.status(404).json({ success: false, msg: \"Token not found\" });\n }\n\ntry {\n const decoded = jwt.verify(token, process.env.access_secret)\n const email = decoded.email\n await User.updateOne(\n { email: email },\n { $set: {} },\n\n )\n console.log(req.body)\n return res.status(200).json({message: 'ok', label:[]})\n} catch (error) {\n console.log(error)\n res.json({ status: 'error', error: 'invalid token' })\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20449926/"
] |
74,626,812
|
<p>I have to iterate from 0 to any Integer (call it x) that can be positive or negative (0 and x both included) (whether I iterate from x to 0 or from 0 to x does not matter)
I know I can use an if-else statement to first check if x is positive or negative and then use <code>range(x+1)</code> if x>0 or <code>range(x, 1)</code> if x<0 (both will work when x=0) like:</p>
<pre><code>if x >= 0:
for i in range(x+1):
pass
else:
for i in range(x, 1):
pass
</code></pre>
<p>but I want a better way especially since I will actually be iterating over 2 Integers and this code is messy (and here also whether I iterate from y to 0 or from 0 to y does not matter)</p>
<pre><code>if (x >= 0) and (y >= 0):
for i in range(x+1):
for j in range(y+1):
pass
elif (x >= 0) and (y < 0):
for i in range(x+1):
for j in range(y, 1):
pass
elif (x < 0) and (y >= 0):
for i in range(x, 1):
for j in range(y+1):
pass
else:
for i in range(x, 1):
for j in range(y, 1):
pass
</code></pre>
|
[
{
"answer_id": 74626929,
"author": "The Myth",
"author_id": 15042008,
"author_profile": "https://Stackoverflow.com/users/15042008",
"pm_score": 0,
"selected": false,
"text": "x = -9\ny = 1\ndef getPosNeg(num):\n if num >= 0:\n return f\"0, {num+1}\"\n return f\"{num}, 1\"\nx_eval = eval(getPosNeg(x)) # use eval\ny_eval = eval(getPosNeg(y)) # use eval\nfor i in range(*x_eval):\n for j in range(*y_eval):\n print(i, j) \n x = -9\ny = 1\n\ndef getPosNeg(num):\n if num >= 0:\n return (0, num+1)\n return (num, 1)\nx_eval = getPosNeg(x)\ny_eval = getPosNeg(y)\nfor i in range(*x_eval):\n for j in range(*y_eval):\n print(i, j) \n abs() x = -9\ny = 1\n\nfor i in range(abs(x+1)):\n for j in range(abs(y+1)):\n print(i, j)\n"
},
{
"answer_id": 74626941,
"author": "ILS",
"author_id": 10017662,
"author_profile": "https://Stackoverflow.com/users/10017662",
"pm_score": 1,
"selected": false,
"text": "get_range_args = lambda x: (0, x+1) if x > 0 else (x, 1)\nfor i in range(*get_range_args(x)):\n for j in range(*get_range_args(y)):\n pass\n"
},
{
"answer_id": 74626988,
"author": "Anton Borkivskyi",
"author_id": 8004349,
"author_profile": "https://Stackoverflow.com/users/8004349",
"pm_score": 1,
"selected": false,
"text": "for i in range(min(x, 0), max(x, 0) + 1):\n for j in range(min(y, 0), max(y, 0) + 1):\n pass\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16714199/"
] |
74,626,834
|
<p>does anyone have an idea how to save a CMD output to a .txt with C? I would like to do a ping and tracert and then ask if the result should be saved. Should it be saved, the result should be saved in a .txt.</p>
<p>My code is like this:</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main ()
{
char Testprint1[100],Testprint2[100];
sprintf(Testprint2, "ping 127.0.0.1");
system(Testprint2);
sprintf(Testprint2, "tracert 127.0.0.1");
system(Testprint2);
printf("\nDo you want to save the output? (y)Yes / (n)No: ");
if (Answer=='j')
{
FILE *Test;
Test = fopen("Test_Log.txt", "w");
fprintf(Test, "Ping:\n%s\n\nTracert:\n%s\n",Testprint1,Testprint2);
if(Pinglog == NULL)
{
printf("Log could not be saved.\n");
system("\n\npause\n");
}
else
{
printf("Log has been saved.");
fclose(Pinglog);
system("cls");
}
}
else if(Answer=='n')
{
system("cls");
system("\n\npause\n");
}
}
</code></pre>
<p>The txt includes:</p>
<p>Ping:
ping 127.0.0.1</p>
<p>Tracert:
tracert 127.0.0.1</p>
<p>It is plausible for me that only this comes out as a result, but I have no idea how I can change that and how I can save the CMD output e.g. in a variable and then save it in the .txt.</p>
|
[
{
"answer_id": 74627028,
"author": "tenfour",
"author_id": 402169,
"author_profile": "https://Stackoverflow.com/users/402169",
"pm_score": 1,
"selected": false,
"text": "ping.exe ping.exe IcmpSendEcho ping.exe ping.exe IcmpSendEcho ping.exe stdout > ping >output.txt system() CreateProcess"
},
{
"answer_id": 74628498,
"author": "jvx8ss",
"author_id": 11107859,
"author_profile": "https://Stackoverflow.com/users/11107859",
"pm_score": 0,
"selected": false,
"text": "ping #include <stdio.h>\n\n#define BUFSIZE 1000\n#define CMDBUFSIZE 100\n\nint main()\n{\n char buf[BUFSIZE] = {0}; // Will hold cmd output\n char cmdbuf[CMDBUFSIZE]; // Used to format the cmd\n char *ip = \"google.com\";\n\n snprintf(cmdbuf, CMDBUFSIZE, \"ping %s /n 1\", ip);\n\n FILE *p = _popen(cmdbuf, \"r\");\n if (p == NULL) {\n puts(\"popen failed\");\n return 1;\n }\n\n fread(buf, BUFSIZE - 1, 1, p);\n printf(\"%s\", buf);\n\n _pclose(p); // Make sure to _pclose so that the cmd doesn't turn into a zombie process\n}\n"
},
{
"answer_id": 74631315,
"author": "Elia Karrer",
"author_id": 17653989,
"author_profile": "https://Stackoverflow.com/users/17653989",
"pm_score": 0,
"selected": false,
"text": "ping 127.0.0.1 > Test_Log.txt\n ping 127.0.0.1 Test_Log.txt"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20598206/"
] |
74,626,842
|
<p>I have the following tibble and a nested list of data frames:</p>
<pre><code>>source
# A tibble: 6 × 2
lon lat
<dbl> <dbl>
1 6.02 55.1
2 6.02 55.0
3 6.02 54.9
>dest
[[1]][[1]]
lon lat
1 54.98908 6.900084
2 54.92777 6.772623
3 55.09501 6.911837
[[1]][[2]]
lon lat
1 54.98908 6.900084
2 54.92777 6.772623
3 55.09501 6.911837
[[1]][[3]]
lon lat
1 54.98908 6.900084
2 54.92777 6.772623
3 55.09501 6.911837
[[2]][[1]]
lon lat
1 54.98908 6.900084
2 54.92777 6.772623
3 55.09501 6.911837
[[2]][[2]]
lon lat
1 54.98908 6.900084
2 54.92777 6.772623
3 55.09501 6.911837
[[2]][[3]]
lon lat
1 54.98908 6.900084
2 54.92777 6.772623
3 55.09501 6.911837
</code></pre>
<p>I would like to apply a function on a row from a tible source and to each "block" from dest.</p>
<p>Example: <p>
<code>row 1</code> from source should by applied to <strong>each row</strong> from <code>dest[[1]][[1]]</code> and <code>dest[[2]][[1]]</code> <p>
<code>row 2</code> from source should by applied to <strong>each row</strong> from <code>dest[[1]][[2]]</code> and <code>dest[[2]][[2]]</code> <p>
<code>row 3</code> from source should by applied to <strong>each row</strong> from <code>dest[[1]][[3]]</code> and <code>dest[[2]][[3]]</code> <p></p>
<p>and so on.</p>
<p>How could I make this happen?
I got tangled up with apply,lappl and maply and would appreciate any help.</p>
<pre><code>source<-structure(list(lon = c(6.02125801226333, 6.02125801226333, 6.02125801226333,
6.02125801226333, 6.02125801226333, 6.02125801226333), lat = c(55.0579432585625,
54.9681151832365, 54.8782857724705, 54.7884550247254, 54.6986229384757,
54.6087895122085)), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))
dest<-list(list(structure(list(lon = c(55.0446726604773, 55.0911992769466,
55.1399831259253), lat = c(6.11070373013145, 5.93718385855719,
6.05909963519238)), class = "data.frame", row.names = c(NA, -3L
)), structure(list(lon = c(54.963042116042, 54.9238652445021,
54.9948148730435), lat = c(6.11154210955708, 6.10009257140253,
5.93487232950475)), class = "data.frame", row.names = c(NA, -3L
)), structure(list(lon = c(54.9181540526, 54.9628448755405, 54.8174082489187
), lat = c(5.94011737583315, 5.98947008604159, 6.08806491235748
)), class = "data.frame", row.names = c(NA, -3L)), structure(list(
lon = c(54.7263291045393, 54.8728552727446, 54.8675223815364
), lat = c(5.95561986508533, 6.0534792303467, 5.97754320721106
)), class = "data.frame", row.names = c(NA, -3L)), structure(list(
lon = c(54.7185472365059, 54.7069293987346, 54.78280968399
), lat = c(5.93305860952388, 5.93121414118021, 5.9884946645099
)), class = "data.frame", row.names = c(NA, -3L)), structure(list(
lon = c(54.560413160877, 54.5853088068835, 54.5185005363673
), lat = c(6.0976246910947, 5.93394019791707, 6.02387338808233
)), class = "data.frame", row.names = c(NA, -3L))), list(
structure(list(lon = c(55.050226235055, 55.0240838617402,
54.9636263846607), lat = c(5.90235917535441, 5.90965086672992,
5.97880750058409)), class = "data.frame", row.names = c(NA,
-3L)), structure(list(lon = c(55.0746706563331, 55.0478637437921,
54.8541974469044), lat = c(5.98859383669152, 5.92618888252071,
6.04742105597978)), class = "data.frame", row.names = c(NA,
-3L)), structure(list(lon = c(54.7575000883344, 54.7676512681177,
54.9427732774055), lat = c(6.06061526193956, 6.09764527834345,
5.90903632630959)), class = "data.frame", row.names = c(NA,
-3L)), structure(list(lon = c(54.7776555082601, 54.8462348683655,
54.7620026570004), lat = c(6.1346781687426, 6.12031707754559,
5.91627897917598)), class = "data.frame", row.names = c(NA,
-3L)), structure(list(lon = c(54.6176186034159, 54.7833923796146,
54.6922873458308), lat = c(6.10088997672983, 6.09177636538747,
6.14915348430183)), class = "data.frame", row.names = c(NA,
-3L)), structure(list(lon = c(54.5680535136696, 54.5386600427152,
54.5879440622283), lat = c(6.13919150641202, 5.91144136237118,
5.89113937054887)), class = "data.frame", row.names = c(NA,
-3L))))
</code></pre>
|
[
{
"answer_id": 74627187,
"author": "harre",
"author_id": 4786466,
"author_profile": "https://Stackoverflow.com/users/4786466",
"pm_score": 1,
"selected": false,
"text": "for(each_row in 1:nrow(source)) {\n for(each_list in 1:length(dest)) {\n dest[[each_list]][[each_row]][[\"lon\"]] <- dest[[each_list]][[each_row]][[\"lon\"]]+source[[each_row, \"lon\"]]\n dest[[each_list]][[each_row]][[\"lat\"]] <- dest[[each_list]][[each_row]][[\"lat\"]]+source[[each_row, \"lat\"]]\n }\n}\n [[1]]\n[[1]][[1]]\n lon lat\n1 61.06593 61.16865\n2 61.11246 60.99513\n3 61.16124 61.11704\n\n[[1]][[2]]\n lon lat\n1 60.98430 61.07966\n2 60.94512 61.06821\n3 61.01607 60.90299\n\n[[1]][[3]]\n lon lat\n1 60.93941 60.81840\n2 60.98410 60.86776\n3 60.83867 60.96635\n\n[[1]][[4]]\n lon lat\n1 60.74759 60.74407\n2 60.89411 60.84193\n3 60.88878 60.76600\n\n[[1]][[5]]\n lon lat\n1 60.73981 60.63168\n2 60.72819 60.62984\n3 60.80407 60.68712\n\n[[1]][[6]]\n lon lat\n1 60.58167 60.70641\n2 60.60657 60.54273\n3 60.53976 60.63266\n\n\n[[2]]\n[[2]][[1]]\n lon lat\n1 61.07148 60.96030\n2 61.04534 60.96759\n3 60.98488 61.03675\n\n[[2]][[2]]\n lon lat\n1 61.09593 60.95671\n2 61.06912 60.89430\n3 60.87546 61.01554\n\n[[2]][[3]]\n lon lat\n1 60.77876 60.93890\n2 60.78891 60.97593\n3 60.96403 60.78732\n\n[[2]][[4]]\n lon lat\n1 60.79891 60.92313\n2 60.86749 60.90877\n3 60.78326 60.70473\n\n[[2]][[5]]\n lon lat\n1 60.63888 60.79951\n2 60.80465 60.79040\n3 60.71355 60.84778\n\n[[2]][[6]]\n lon lat\n1 60.58931 60.74798\n2 60.55992 60.52023\n3 60.60920 60.49993\n"
},
{
"answer_id": 74627408,
"author": "harre",
"author_id": 4786466,
"author_profile": "https://Stackoverflow.com/users/4786466",
"pm_score": 3,
"selected": true,
"text": "split mapply lapply dplyr::bind_cols lapply(dest,\n \\(x) mapply(dplyr::bind_cols, split(source, seq(nrow(source))), x, SIMPLIFY = FALSE))\n [[1]]\n[[1]]$`1`\n# A tibble: 3 × 4\n lon...1 lat...2 lon...3 lat...4\n <dbl> <dbl> <dbl> <dbl>\n1 6.02 55.1 55.0 6.11\n2 6.02 55.1 55.1 5.94\n3 6.02 55.1 55.1 6.06\n\n[[1]]$`2`\n# A tibble: 3 × 4\n lon...1 lat...2 lon...3 lat...4\n <dbl> <dbl> <dbl> <dbl>\n1 6.02 55.0 55.0 6.11\n2 6.02 55.0 54.9 6.10\n3 6.02 55.0 55.0 5.93\n\n[[1]]$`3`\n# A tibble: 3 × 4\n lon...1 lat...2 lon...3 lat...4\n <dbl> <dbl> <dbl> <dbl>\n1 6.02 54.9 54.9 5.94\n2 6.02 54.9 55.0 5.99\n3 6.02 54.9 54.8 6.09\n\n[[1]]$`4`\n# A tibble: 3 × 4\n lon...1 lat...2 lon...3 lat...4\n <dbl> <dbl> <dbl> <dbl>\n1 6.02 54.8 54.7 5.96\n2 6.02 54.8 54.9 6.05\n3 6.02 54.8 54.9 5.98\n\n[[1]]$`5`\n# A tibble: 3 × 4\n lon...1 lat...2 lon...3 lat...4\n <dbl> <dbl> <dbl> <dbl>\n1 6.02 54.7 54.7 5.93\n2 6.02 54.7 54.7 5.93\n3 6.02 54.7 54.8 5.99\n\n[[1]]$`6`\n# A tibble: 3 × 4\n lon...1 lat...2 lon...3 lat...4\n <dbl> <dbl> <dbl> <dbl>\n1 6.02 54.6 54.6 6.10\n2 6.02 54.6 54.6 5.93\n3 6.02 54.6 54.5 6.02\n\n\n[[2]]\n[[2]]$`1`\n# A tibble: 3 × 4\n lon...1 lat...2 lon...3 lat...4\n <dbl> <dbl> <dbl> <dbl>\n1 6.02 55.1 55.1 5.90\n2 6.02 55.1 55.0 5.91\n3 6.02 55.1 55.0 5.98\n\n[[2]]$`2`\n# A tibble: 3 × 4\n lon...1 lat...2 lon...3 lat...4\n <dbl> <dbl> <dbl> <dbl>\n1 6.02 55.0 55.1 5.99\n2 6.02 55.0 55.0 5.93\n3 6.02 55.0 54.9 6.05\n\n[[2]]$`3`\n# A tibble: 3 × 4\n lon...1 lat...2 lon...3 lat...4\n <dbl> <dbl> <dbl> <dbl>\n1 6.02 54.9 54.8 6.06\n2 6.02 54.9 54.8 6.10\n3 6.02 54.9 54.9 5.91\n\n[[2]]$`4`\n# A tibble: 3 × 4\n lon...1 lat...2 lon...3 lat...4\n <dbl> <dbl> <dbl> <dbl>\n1 6.02 54.8 54.8 6.13\n2 6.02 54.8 54.8 6.12\n3 6.02 54.8 54.8 5.92\n\n[[2]]$`5`\n# A tibble: 3 × 4\n lon...1 lat...2 lon...3 lat...4\n <dbl> <dbl> <dbl> <dbl>\n1 6.02 54.7 54.6 6.10\n2 6.02 54.7 54.8 6.09\n3 6.02 54.7 54.7 6.15\n\n[[2]]$`6`\n# A tibble: 3 × 4\n lon...1 lat...2 lon...3 lat...4\n <dbl> <dbl> <dbl> <dbl>\n1 6.02 54.6 54.6 6.14\n2 6.02 54.6 54.5 5.91\n3 6.02 54.6 54.6 5.89\n"
},
{
"answer_id": 74627599,
"author": "DashdotdotDashdotdot",
"author_id": 20548300,
"author_profile": "https://Stackoverflow.com/users/20548300",
"pm_score": 1,
"selected": false,
"text": "> dest2[[1]][[1]]\n lon lat lon_src lat_src\n1 55.04467 6.110704 6.021258 55.05794\n2 55.09120 5.937184 6.021258 55.05794\n3 55.13998 6.059100 6.021258 55.05794\n dest2 <- dest\n\naddStart <- function(startRow, destElements, group) {\n start <- source[startRow, ]\n \n for (i in destElements) {\n rows007 <- nrow(dest[[i]][[group]])\n toadd = data.frame( matrix(rep(start, each = rows007), ncol = 2) )\n names(toadd) = c(\"lon_src\",\"lat_src\")\n dest2[[i]][[group]] <- cbind(dest[[i]][[group]],toadd)\n \n }\n return(dest2)\n}\n\ndest2 <- addStart(1, 1:2, 1)\ndest2[[1]][[1]]\ndest2[[2]][[1]]\n\ndest2 <- addStart(2, 1:2, 2)\ndest2[[1]][[2]]\ndest2[[2]][[2]]\n\ndest2 <- addStart(3, 1:2, 3)\ndest2[[1]][[3]]\ndest2[[2]][[3]]\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/771699/"
] |
74,626,847
|
<p>How to update state from selectedValue? or How to pass selected value as argument to the helper method</p>
<pre><code>class SelectParker extends Component {
state = {
selectedValue: "",
values: [],
};
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/users")
.then(function (res) {
return res.json();
})
.then((json) => {
this.setState({
values: json,
});
});
}
handleOnChange = (event) => {
console.log(event);
};
render() {
return (
<div className="card">
<div className="card-header">Select Parker</div>
<div className="card-body">
<div>
<select className="form-select" aria-label="Default select example">
{this.state.values.map((obj) => {
return (
<option key={obj.id} value={obj.id}>
{obj.name}
</option>
);
})}
</select>
</div>
</div>
</div>
);
}
}
export default SelectParker;
</code></pre>
<p>How to pass selected value as argument to the helper method to update the state</p>
|
[
{
"answer_id": 74626930,
"author": "Neo",
"author_id": 10165237,
"author_profile": "https://Stackoverflow.com/users/10165237",
"pm_score": 0,
"selected": false,
"text": " handleOnChange = (event) => {\n this.setState({selectedValue:event.target.value});\n };\n\n<select className=\"form-select\" aria-label=\"Default select example\"\n onChange={handleOnChange}\n >\n {this.state.values.map((obj) => {\n return (\n <option key={obj.id} value={obj.id}>\n {obj.name}\n </option>\n );\n })}\n </select>\n"
},
{
"answer_id": 74627440,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 2,
"selected": true,
"text": "import React from 'react';\n\nclass SelectParker extends React.Component {\n state = {\n selectedValue: \"\",\n values: [],\n };\n\n componentDidMount() {\n fetch(\"https://jsonplaceholder.typicode.com/users\")\n .then(function (res) {\n return res.json();\n })\n .then((json) => {\n this.setState({\n values: json,\n });\n });\n }\n\n handleOnChange = (event) => {\n console.log(event.target.value)\n this.setState({\n selectedValue: event.target.value\n })\n };\n render() {\n return (\n <div className=\"card\">\n <div className=\"card-header\">Select Parker</div>\n <div className=\"card-body\">\n <div>\n <select value={this.state.selectedValue} className=\"form-select\" aria-label=\"Default select example\" onChange={this.handleOnChange}>\n {this.state.values.map((obj: any) => {\n return (\n <option key={obj.id} value={obj.id}>\n {obj.name}\n </option>\n );\n })}\n </select>\n </div>\n </div>\n </div>\n );\n }\n}\n\nexport default SelectParker;\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18862993/"
] |
74,626,871
|
<p>Im using a M1 mac and Im trying to install mkcert using brew,</p>
<p>The command that I use is:</p>
<p><code>brew install mkcert</code></p>
<p>This is the error that I get:</p>
<pre><code>brew install mkcert
fatal: Could not resolve HEAD to a revision
Warning: No available formula with the name "mkcert".
==> Searching for similarly named formulae...
Error: No similarly named formulae found.
==> Searching for a previously deleted formula (in the last month)...
Error: No previously deleted formula found.
==> Searching taps on GitHub...
Error: No formulae found in taps.
</code></pre>
<p>What am I doing wrong?</p>
|
[
{
"answer_id": 74633712,
"author": "chenrui",
"author_id": 791609,
"author_profile": "https://Stackoverflow.com/users/791609",
"pm_score": -1,
"selected": false,
"text": "$ brew search mkdcert\n==> Formulae\nmkcert ✔\n\n$ brew install mkcert\n==> Downloading https://ghcr.io/v2/homebrew/core/mkcert/manifests/1.4.4\n######################################################################## 100.0%\n==> Downloading https://ghcr.io/v2/homebrew/core/mkcert/blobs/sha256:af89337b73c8d4bb20c0cdfeeaccc17b620d8badf39edfb06a8fb191ec328c36\n==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sha256:af89337b73c8d4bb20c0cdfeeaccc17b620d8badf39edfb06a8fb191ec328c36?se=2022-11-30T20%3A3\n######################################################################## 100.0%\n==> Pouring mkcert--1.4.4.arm64_ventura.bottle.tar.gz\n /opt/homebrew/Cellar/mkcert/1.4.4: 6 files, 3.8MB\n==> Running `brew cleanup mkcert`...\nDisable this behaviour by setting HOMEBREW_NO_INSTALL_CLEANUP.\nHide these hints with HOMEBREW_NO_ENV_HINTS (see `man brew`).\n\n$ mkcert --version\nv1.4.4\n"
},
{
"answer_id": 74654174,
"author": "Ivan Solobear",
"author_id": 6297861,
"author_profile": "https://Stackoverflow.com/users/6297861",
"pm_score": 0,
"selected": false,
"text": "fatal: Could not resolve HEAD to a revision\n \nrm -rf $(brew --repo homebrew/core)\nbrew tap homebrew/core\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6297861/"
] |
74,626,897
|
<p>I'm trying to write a sort function in Perl. I need "name_iwant_last" to be the last in a sorted hash.</p>
<pre><code>%libs = (
"00000000000","00000000000",
"aaaaaaaaaaa","aaaaaaaaaaa",
"AAAAAAAAAA","AAAAAAAAAA",
"name_iwant_last","name_iwant_last",
"zzzzzzzzzzzzz","zzzzzzzzzzzzz",
"ZZZZZZZZZZZ","ZZZZZZZZZZZ",
"9999999999","9999999999"
);
sub lib_sort {
#print "cosa ordino ";
#print $libs{$a};
#print $libs{$b};
#print "\n";
return 1 if (index($libs{$a} , "name_iwant_last") != -1);
return -1 if $libs{$a} < $libs{$b};
return 0 if $libs{$a} == $libs{$b};
return 1 if $libs{$a} > $libs{$b};
}
foreach my $lib (sort lib_sort values %libs) {
print $lib;
print "\n";
}
</code></pre>
<p>But, when I run this code, the print is in random order.</p>
<p>Expected:</p>
<pre><code>aaaaa
AAAAA...
name_iwant_last
</code></pre>
<p>Resulted:
random.</p>
|
[
{
"answer_id": 74627130,
"author": "Dave Cross",
"author_id": 7231,
"author_profile": "https://Stackoverflow.com/users/7231",
"pm_score": 3,
"selected": true,
"text": "use warnings < == > lt eq gt use warnings use strict cmp <=> sub lib_sort {\n\n return 1 if (index($libs{$a} , \"name_iwant_last\") != -1);\n return $libs{$a} cmp $libs{$b};\n}\n"
},
{
"answer_id": 74627367,
"author": "raffaelesergi",
"author_id": 20644610,
"author_profile": "https://Stackoverflow.com/users/20644610",
"pm_score": 0,
"selected": false,
"text": "%libs = (\n\"00000000000\",\"00000000000\",\n\"aaaaaaaaaaa\",\"aaaaaaaaaaa\",\n\"AAAAAAAAAA\",\"AAAAAAAAAA\",\n\"name_iwant_last\",\"name_iwant_last\",\n\"zzzzzzzzzzzzz\",\"zzzzzzzzzzzzz\",\n\"ZZZZZZZZZZZ\",\"ZZZZZZZZZZZ\",\n\"9999999999\",\"9999999999\"\n);\n\nsub lib_sort {\n #print \"cosa ordino \";\n #print $libs{$a};\n #print $libs{$b};\n #print \"\\n\";\n if (index($libs{$a} , \"name_iwant_last\") != -1) { \n return 1;\n } elsif (index($libs{$b} , \"name_iwant_last\") != -1) { \n return -1;\n } elsif ($libs{$a} lt $libs{$b}) { \n return -1;\n } elsif ($libs{$a} eq $libs{$b}) { \n return 0;\n } elsif ($libs{$a} gt $libs{$b}) { \n return 1;\n }\n}\n\nforeach my $lib (sort lib_sort values %libs) {\n print $lib;\n print \"\\n\";\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20644610/"
] |
74,626,911
|
<p>I am looking to calculate the percentage increase or decrease between the first and last non-na value for the following dataset:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Year</th>
<th>Company</th>
<th>Data</th>
</tr>
</thead>
<tbody>
<tr>
<td>2019</td>
<td>X</td>
<td>341976.00</td>
</tr>
<tr>
<td>2020</td>
<td>X</td>
<td>1.000</td>
</tr>
<tr>
<td>2021</td>
<td>X</td>
<td>282872.00</td>
</tr>
<tr>
<td>2019</td>
<td>Y</td>
<td>NaN</td>
</tr>
<tr>
<td>2020</td>
<td>Y</td>
<td>NaN</td>
</tr>
<tr>
<td>2021</td>
<td>Y</td>
<td>NaN</td>
</tr>
<tr>
<td>2019</td>
<td>Z</td>
<td>4394.00</td>
</tr>
<tr>
<td>2020</td>
<td>Z</td>
<td>173.70</td>
</tr>
<tr>
<td>2021</td>
<td>Z</td>
<td>518478.00</td>
</tr>
</tbody>
</table>
</div>
<p>As I want the relative change I would expect the formula to do something like:</p>
<pre><code>(last non-na value)/(first non-na value)-1
</code></pre>
<p>This should return something like:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Year</th>
<th>Company</th>
<th>Data</th>
<th>Data</th>
</tr>
</thead>
<tbody>
<tr>
<td>2019</td>
<td>X</td>
<td>341976.00</td>
<td>NaN</td>
</tr>
<tr>
<td>2020</td>
<td>X</td>
<td>1.000</td>
<td>NaN</td>
</tr>
<tr>
<td>2021</td>
<td>X</td>
<td>282872.00</td>
<td>-0.17</td>
</tr>
<tr>
<td>2019</td>
<td>Y</td>
<td>NaN</td>
<td>NaN</td>
</tr>
<tr>
<td>2020</td>
<td>Y</td>
<td>NaN</td>
<td>NaN</td>
</tr>
<tr>
<td>2021</td>
<td>Y</td>
<td>NaN</td>
<td>NaN</td>
</tr>
<tr>
<td>2019</td>
<td>Z</td>
<td>4394.00</td>
<td>NaN</td>
</tr>
<tr>
<td>2020</td>
<td>Z</td>
<td>173.70</td>
<td>NaN</td>
</tr>
<tr>
<td>2021</td>
<td>Z</td>
<td>518478.00</td>
<td>11.700</td>
</tr>
</tbody>
</table>
</div>
<p>I have tried to combine groupby based on the company field with the first_valid_index but havent had any luck finding a solution. What is the most efficient way of calculating the relative change as above?</p>
|
[
{
"answer_id": 74626995,
"author": "Paweł Pietraszko",
"author_id": 19391219,
"author_profile": "https://Stackoverflow.com/users/19391219",
"pm_score": 0,
"selected": false,
"text": "np.nan .dropna dropna"
},
{
"answer_id": 74627006,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "GroupBy.first GroupBy.last 1 s = df.groupby('Company')['Data'].agg(['last','first']).eval('last / first').sub(1)\n Company idx = df.dropna(subset=['Data']).drop_duplicates(['Company'], keep='last').index\n Series.map df.loc[idx, 'Date'] = df.loc[idx, 'Company'].map(s)\nprint (df)\n\n Year Company Data Date\n0 2019 X 341976.0 NaN\n1 2020 X 1.0 NaN\n2 2021 X 282872.0 -0.172831\n3 2019 Y NaN NaN\n4 2020 Y NaN NaN\n5 2021 Y NaN NaN\n6 2019 Z 4394.0 NaN\n7 2020 Z 173.7 NaN\n8 2021 Z 518478.0 116.996814\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12966571/"
] |
74,626,931
|
<p>I have a list <code>a = {2,3,4,5}</code>, and I want to create another list and make that list append all the combinations from 0 to <code>a.size()-1</code>, so my output would yield something like <code>{{2},{2,3},{2,3,4},{2,3,4,5}}</code>,</p>
<p>Here is my code so far:</p>
<pre><code>public static List<List<Integer>> kFactorization(List<Integer> A) {
List<Integer> b = new ArrayList<>();
List<List<Integer>> c = new ArrayList<>();
for (int x = A.size(); x <= 0; x++){
for(int y = 0; y <= x; y++){
b.add(A.get(y));
c.addAll(Collections.singleton(b));
}
}
return c;
}
</code></pre>
<p>What changes to my code do I need to make in order for this to work?? and is there a faster approach to do this?</p>
|
[
{
"answer_id": 74626995,
"author": "Paweł Pietraszko",
"author_id": 19391219,
"author_profile": "https://Stackoverflow.com/users/19391219",
"pm_score": 0,
"selected": false,
"text": "np.nan .dropna dropna"
},
{
"answer_id": 74627006,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "GroupBy.first GroupBy.last 1 s = df.groupby('Company')['Data'].agg(['last','first']).eval('last / first').sub(1)\n Company idx = df.dropna(subset=['Data']).drop_duplicates(['Company'], keep='last').index\n Series.map df.loc[idx, 'Date'] = df.loc[idx, 'Company'].map(s)\nprint (df)\n\n Year Company Data Date\n0 2019 X 341976.0 NaN\n1 2020 X 1.0 NaN\n2 2021 X 282872.0 -0.172831\n3 2019 Y NaN NaN\n4 2020 Y NaN NaN\n5 2021 Y NaN NaN\n6 2019 Z 4394.0 NaN\n7 2020 Z 173.7 NaN\n8 2021 Z 518478.0 116.996814\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18984687/"
] |
74,626,932
|
<p>We would like to add a line to drawing we drew earlier using the paint function of customPaint.
The following drawing will be displayed:</p>
<p><a href="https://i.stack.imgur.com/dvmWw.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>And we would like to change the drawing after a few seconds to the following drawing:</p>
<p><a href="https://i.stack.imgur.com/7rfat.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>Meaning that a short line will be added to the original drawing.
The user will choose which drawing he saw before the drawing changed.
We tried to solve this problem with flutter timer and flutter future.dleay but nothing happened after the time we set and the debuger console showed: "Unhandled Exception: Object has been disposed".
We would be happy to know if there are other options that can help us reach our goal: different timing functions, another drawing option that works with a timer or future.delay
We tried to solve our problem with this function:</p>
<pre><code>void paint(Canvas canvas, Size size){
const p1 = Offset(50, 50);
const p2 = Offset(50, 300);
const p3 = Offset(50, 50);
const p4 = Offset(250, 50);
const p5 = Offset(250, 50);
const p6 = Offset(250, 150);
const p7 = Offset(250, 150);
const p8 = Offset(250, 300);
final paint = Paint()
..color = Colors.black
..strokeWidth = 4
..strokeCap = StrokeCap.round;
canvas.drawLine(p1, p2, paint);
canvas.drawLine(p3, p4, paint);
canvas.drawLine(p5, p6, paint);
Timer(
Duration(seconds: 1),
() {
canvas.drawLine(p7, p8, paint);
},
);'
</code></pre>
<p>this section located on the next line of the fucntion below</p>
|
[
{
"answer_id": 74626995,
"author": "Paweł Pietraszko",
"author_id": 19391219,
"author_profile": "https://Stackoverflow.com/users/19391219",
"pm_score": 0,
"selected": false,
"text": "np.nan .dropna dropna"
},
{
"answer_id": 74627006,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "GroupBy.first GroupBy.last 1 s = df.groupby('Company')['Data'].agg(['last','first']).eval('last / first').sub(1)\n Company idx = df.dropna(subset=['Data']).drop_duplicates(['Company'], keep='last').index\n Series.map df.loc[idx, 'Date'] = df.loc[idx, 'Company'].map(s)\nprint (df)\n\n Year Company Data Date\n0 2019 X 341976.0 NaN\n1 2020 X 1.0 NaN\n2 2021 X 282872.0 -0.172831\n3 2019 Y NaN NaN\n4 2020 Y NaN NaN\n5 2021 Y NaN NaN\n6 2019 Z 4394.0 NaN\n7 2020 Z 173.7 NaN\n8 2021 Z 518478.0 116.996814\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20643821/"
] |
74,626,944
|
<p>I have a JSON Array with:</p>
<pre><code>{
"status": 200,
"user": "niebauer",
"channels": [
{
"name": "maxmustermann",
"followers": 17193,
"views": 650255,
"partnered": false
},
{
"name": "harrypotter",
"followers": 21487,
"views": 5110,
"partnered": false
},
{
"name": "welten",
"followers": 1017,
"views": 9318,
"partnered": false
},
{
"name": "meeresbuecher",
"followers": 5141,
"views": 61411,
"partnered": false
},
{
"name": "weltrekord",
"followers": 171777,
"views": 17832138,
"partnered": true
},
{
"name": "tvtotaler",
"followers": 2117,
"views": 21300,
"partnered": false
},
{
"name": "kramkiste",
"followers": 6819,
"views": 30414,
"partnered": false
}
],
"cursor": ""
}
</code></pre>
<p>And now i want to have in my output only the name from the channels. It should be:
maxmustermann
harrypotter
welten
...</p>
<p>How can I do this in Node.js? I found many questions with it, but no actual answer. Most of them are from 2012 and older. Thanks.</p>
<p>In this there are 7 channels. How can i get the counter aswell for it? So i get a output of "7"?</p>
|
[
{
"answer_id": 74626995,
"author": "Paweł Pietraszko",
"author_id": 19391219,
"author_profile": "https://Stackoverflow.com/users/19391219",
"pm_score": 0,
"selected": false,
"text": "np.nan .dropna dropna"
},
{
"answer_id": 74627006,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 2,
"selected": true,
"text": "GroupBy.first GroupBy.last 1 s = df.groupby('Company')['Data'].agg(['last','first']).eval('last / first').sub(1)\n Company idx = df.dropna(subset=['Data']).drop_duplicates(['Company'], keep='last').index\n Series.map df.loc[idx, 'Date'] = df.loc[idx, 'Company'].map(s)\nprint (df)\n\n Year Company Data Date\n0 2019 X 341976.0 NaN\n1 2020 X 1.0 NaN\n2 2021 X 282872.0 -0.172831\n3 2019 Y NaN NaN\n4 2020 Y NaN NaN\n5 2021 Y NaN NaN\n6 2019 Z 4394.0 NaN\n7 2020 Z 173.7 NaN\n8 2021 Z 518478.0 116.996814\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20644685/"
] |
74,626,946
|
<p>I have a file that looks like this, I want to get data from this file so that I can create a dictionary that takes the neighboruhood names as keys, with its values being ID, Population, and Low rate.</p>
<pre><code>ID Neighbourhood Name Population Low rate
1 East Billin-Pickering 43567 1000
2 North Eglinton-Silverstone-Ajax 33098 9087
3 Wistle-dong Lock 25009 6754
4 Squarion-Staion 10000 8790
5 Doki doki lolo 6789 2315
</code></pre>
<p>The output should look something like this (IF THE DICTIONARY I AM GIVEN IS EMPTY)</p>
<pre><code> {'East Billin-Pickering':
{'id': 1, 'population': 43567, 'low_rate': 1000,
'North Eglinton-Silverstone-Ajax':
{'id': 2, 'population': 33098, 'low_rate': 9087},
'Wistle-dong Lock':
{'id': 3, 'population': 25009, 'low_rate': 6754},
'Squarion-Staion':
{'id': 4, 'population': 10000, 'low_rate': 8790},
'Doki doki lolo':
{'id': 5, 'population': 6789, 'low_rate': 2315}}
</code></pre>
<p>The file is already open, and I am also given a dictionary that may or may not have given values in it. How would I update that dictionary using data from the file?</p>
<p>Can somebody give me hints? I'm so confused.</p>
<p>I have no idea on how to start this. I know I have loop through the file, and will have to use strip() and split() methods at one point. I'm not sure how to actually get the values themselves, and modify them into a dictionary.</p>
<pre><code>def get_data(data: dict, file: TextIO) -> None:
"""
"""
opened = file.read().strip()
for line in file:
words = line.split(SEP)
income_data = tuple(opened[POP], opened[LI_COL])
data[LI_NBH_NAME_COL] = tuple(opened[ID_COL], income_data)
# Constants I'm using are:
SEP = ','
POP = 2
LI_COL = 3
ID_COL = 0
</code></pre>
<p>I'm trying to write an answer that does not use any imports, even the CSV import, mostly for understanding. I want to write a program that doesn't use imports so that I can better understand what's happening before I start importing csv.</p>
<p>How would this work?</p>
|
[
{
"answer_id": 74627039,
"author": "Georgios Loudaros",
"author_id": 8843034,
"author_profile": "https://Stackoverflow.com/users/8843034",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\n\nfilename = 'myCSV.csv'\n\ndef read_csv(filename):\n return pd.read_csv(filename).to_dict('records')\n"
},
{
"answer_id": 74627164,
"author": "Matija Pul",
"author_id": 20642560,
"author_profile": "https://Stackoverflow.com/users/20642560",
"pm_score": 1,
"selected": false,
"text": "csv DictReader import csv\n\nwith open('input.csv', newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n print(row)\n {'ID': '1', 'Neighbourhood Name': 'East Billin-Pickering', 'Population': '43567', 'Low rate': '1000'}\n{'ID': '2', 'Neighbourhood Name': 'North Eglinton-Silverstone-Ajax', 'Population': '33098', 'Low rate': '9087'}\n{'ID': '3', 'Neighbourhood Name': 'Wistle-dong Lock', 'Population': '25009', 'Low rate': '6754'}\n{'ID': '4', 'Neighbourhood Name': 'Squarion-Staion', 'Population': '10000', 'Low rate': '8790'}\n{'ID': '5', 'Neighbourhood Name': 'Doki doki lolo', 'Population': '6789', 'Low rate': '2315'}\n import csv\n\nresult_dict = {}\n\nwith open('input.csv', newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n result_dict[row[\"Neighbourhood Name\"]] = {\n \"ID\": row.get(\"id\"),\n \"population\": row.get(\"population\"),\n \"low_rate\": row.get(\"low_rate\")\n }\n"
},
{
"answer_id": 74627197,
"author": "Jan Tkacik",
"author_id": 2478677,
"author_profile": "https://Stackoverflow.com/users/2478677",
"pm_score": 2,
"selected": false,
"text": "import pandas as pd\n\ndata = pd.read_csv(\"test.csv\", delimiter=\"\\t\") # Set delimiter and file name to your specific file \ndata = data.set_index(\"Neighbourhood Name\")\nfinal_dict = data.to_dict(orient=\"index\")\n {\n \"East Billin-Pickering\":{\n \"ID\":1,\n \"Population\":43567,\n \"Low rate \":1000\n },\n \"North Eglinton-Silverstone-Ajax\":{\n \"ID\":2,\n \"Population\":33098,\n \"Low rate \":9087\n },\n \"Wistle-dong Lock\":{\n \"ID\":3,\n \"Population\":25009,\n \"Low rate \":6754\n },\n \"Squarion-Staion\":{\n \"ID\":4,\n \"Population\":10000,\n \"Low rate \":8790\n },\n \"Doki doki lolo\":{\n \"ID\":5,\n \"Population\":6789,\n \"Low rate \":2315\n }\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74626946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,627,014
|
<p>How do you compute this probability density function, with a triangular distribution of parameters (a,b,c)?</p>
<pre><code>f(x)= 0 , x<a
2(x-a)/((b-a)(c-a)) , a <= x <= c
2(b-x)/((b-a)(b-c)) , c < x <=b
0 , x> b
</code></pre>
|
[
{
"answer_id": 74627039,
"author": "Georgios Loudaros",
"author_id": 8843034,
"author_profile": "https://Stackoverflow.com/users/8843034",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\n\nfilename = 'myCSV.csv'\n\ndef read_csv(filename):\n return pd.read_csv(filename).to_dict('records')\n"
},
{
"answer_id": 74627164,
"author": "Matija Pul",
"author_id": 20642560,
"author_profile": "https://Stackoverflow.com/users/20642560",
"pm_score": 1,
"selected": false,
"text": "csv DictReader import csv\n\nwith open('input.csv', newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n print(row)\n {'ID': '1', 'Neighbourhood Name': 'East Billin-Pickering', 'Population': '43567', 'Low rate': '1000'}\n{'ID': '2', 'Neighbourhood Name': 'North Eglinton-Silverstone-Ajax', 'Population': '33098', 'Low rate': '9087'}\n{'ID': '3', 'Neighbourhood Name': 'Wistle-dong Lock', 'Population': '25009', 'Low rate': '6754'}\n{'ID': '4', 'Neighbourhood Name': 'Squarion-Staion', 'Population': '10000', 'Low rate': '8790'}\n{'ID': '5', 'Neighbourhood Name': 'Doki doki lolo', 'Population': '6789', 'Low rate': '2315'}\n import csv\n\nresult_dict = {}\n\nwith open('input.csv', newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n result_dict[row[\"Neighbourhood Name\"]] = {\n \"ID\": row.get(\"id\"),\n \"population\": row.get(\"population\"),\n \"low_rate\": row.get(\"low_rate\")\n }\n"
},
{
"answer_id": 74627197,
"author": "Jan Tkacik",
"author_id": 2478677,
"author_profile": "https://Stackoverflow.com/users/2478677",
"pm_score": 2,
"selected": false,
"text": "import pandas as pd\n\ndata = pd.read_csv(\"test.csv\", delimiter=\"\\t\") # Set delimiter and file name to your specific file \ndata = data.set_index(\"Neighbourhood Name\")\nfinal_dict = data.to_dict(orient=\"index\")\n {\n \"East Billin-Pickering\":{\n \"ID\":1,\n \"Population\":43567,\n \"Low rate \":1000\n },\n \"North Eglinton-Silverstone-Ajax\":{\n \"ID\":2,\n \"Population\":33098,\n \"Low rate \":9087\n },\n \"Wistle-dong Lock\":{\n \"ID\":3,\n \"Population\":25009,\n \"Low rate \":6754\n },\n \"Squarion-Staion\":{\n \"ID\":4,\n \"Population\":10000,\n \"Low rate \":8790\n },\n \"Doki doki lolo\":{\n \"ID\":5,\n \"Population\":6789,\n \"Low rate \":2315\n }\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20357700/"
] |
74,627,158
|
<p>I am trying to create a effect when you hover over my abbrivated name it expands to its full size however,I've run into a problem that detracts from the visual appeal of the website I'm trying to achieve and makes it appear tacky.What I want is for the element to expand in a isolated manner and does not affect anything else on the website.</p>
<p>Here is the link:<a href="https://jsfiddle.net/dkpsgo73/" rel="nofollow noreferrer">https://jsfiddle.net/dkpsgo73/</a></p>
<pre><code> <nav>
<header>
<h1 class="Name">
[
<span id="zk-trigger"><span class="Fname"> S</span><span id="hide1" class="hide"><span class="Fname">eid</span></span>
J<span id="hide2" class="hide">ama</span>
</span>
]
</h1>
</header>
<!-- Navigational Bar -->
<div class="nav-menu">
<ul>
<li><a href="#Home">Home</a></li>
<li><a href="#About">About</a></li>
<li><a href="#Projects">Projects</a></li>
<li><a href="#Skills">Skills</a></li>
<li><a href="#Contact">Contact</a></li>
</ul>
</div>
<!-- Navigational Bar -->
</nav>
</code></pre>
<p>I read a lot of different advise on the subject, including position absolute and z-index, but I was unable to find a solution because I am still very new to learning how to code.</p>
|
[
{
"answer_id": 74627227,
"author": "Cervus camelopardalis",
"author_id": 10347145,
"author_profile": "https://Stackoverflow.com/users/10347145",
"pm_score": 2,
"selected": true,
"text": "header {\n min-width: 200px;\n}\n html,\nbody {\n margin: 0;\n font-family: \"Rubik\", sans-serif;\n background-color: #333333ff;\n}\n\n/* Font Config */\nh1 {\n font-weight: normal;\n font-size: 25px;\n text-transform: uppercase;\n letter-spacing: 1px;\n margin: 0 0 0 0;\n color: #f6f2f0;\n}\n\n/* Navigation Bar */\nnav {\n /*Keeps the nav fixed*/\n position: fixed;\n /*Size of the nav bar*/\n height: 70px;\n width: 100%;\n /*Spaces out the nav elements*/\n display: flex;\n justify-content: space-around;\n align-items: center;\n padding: 0 10px;\n /*Blur property*/\n backdrop-filter: blur(5px);\n background-color: #262626ff;\n opacity: 0.9;\n border-bottom: 5px solid #6527a7ff;\n}\n\n/* Navigation Bar */\n.Name {\n display: inline;\n font-style: italic;\n}\n\n#hide1,\n#hide2 {\n display: inline-block;\n max-width: 0;\n opacity: 0;\n transition: max-width 0.2s, opacity 0.2s;\n}\n\n#zk-trigger:hover #hide1,\n#zk-trigger:hover #hide2 {\n max-width: 100px;\n opacity: 1;\n transition: max-width 0.5s, opacity 0.2s;\n}\n\n.Fname {\n color: #ffc000;\n}\n\nli {\n display: inline;\n padding: 8px;\n font-size: 20px;\n}\n\n/* My Nav List Position */\n.nav-menu {\n display: flex;\n justify-content: flex-end;\n}\n\n/* My Nav List Position */\n\n/* Navigation Link Interaction */\n.nav-menu li a {\n color: #f6f2f0;\n}\n\n.nav-menu li a:link {\n text-decoration: none;\n}\n\n.nav-menu li a:hover {\n color: #ffc000;\n text-decoration: none;\n}\n\n/* Navigation Link Interaction */\n\n/* Added */\nheader {\n min-width: 200px;\n} <!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\" />\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Portfolio</title>\n <link href=\"Styles.css\" rel=\"stylesheet\" />\n <link href=\"https://fonts.googleapis.com/css2?family=Rubik:wght@300;400&display=swap\" rel=\"stylesheet\" />\n</head>\n\n<body>\n <nav>\n <header>\n <h1 class=\"Name\">\n [\n <span id=\"zk-trigger\"><span class=\"Fname\"> S</span><span id=\"hide1\" class=\"hide\"><span class=\"Fname\">eid</span></span>\n J<span id=\"hide2\" class=\"hide\">ama</span>\n </span>\n ]\n </h1>\n </header>\n <!-- Navigational Bar -->\n <div class=\"nav-menu\">\n <ul>\n <li><a href=\"#Home\">Home</a></li>\n <li><a href=\"#About\">About</a></li>\n <li><a href=\"#Projects\">Projects</a></li>\n <li><a href=\"#Skills\">Skills</a></li>\n <li><a href=\"#Contact\">Contact</a></li>\n </ul>\n </div>\n <!-- Navigational Bar -->\n </nav>\n</body>\n\n</html>"
},
{
"answer_id": 74627441,
"author": "Moob",
"author_id": 1921385,
"author_profile": "https://Stackoverflow.com/users/1921385",
"pm_score": 0,
"selected": false,
"text": "box-sizing:border-box space-between html,\nbody {\n margin: 0;\n font-family: \"Rubik\", sans-serif;\n background-color: #333333ff;\n}\n/* consistent box-sizing where width is inclusive of padding */\n* {box-sizing:border-box}\n\n/* Font Config */\n\nh1 {\n font-weight: normal;\n font-size: 25px;\n text-transform: uppercase;\n letter-spacing: 1px;\n margin: 0 0 0 0;\n color: #f6f2f0;\n white-space:nowrap;\n}\n\n\n/* Font Config */\n\n\n/* Navigation Bar */\n\nnav {\n /*Keeps the nav fixed*/\n position: fixed;\n /*Size of the nav bar*/\n height: 70px;\n width: 100%;\n /*Spaces out the nav elements*/\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 0 10px;\n /*Blur property*/\n backdrop-filter: blur(5px);\n background-color: #262626ff;\n opacity: 0.9;\n border-bottom: 5px solid #6527a7ff;\n}\n\n\n/* Navigation Bar */\n\n.Name {\n display: inline;\n font-style: italic;\n}\n\n#hide1,\n#hide2 {\n display: inline-block;\n max-width: 0;\n opacity: 0;\n transition: max-width 0.2s, opacity 0.2s;\n}\n\n#zk-trigger:hover #hide1,\n#zk-trigger:hover #hide2 {\n max-width: 100px;\n opacity: 1;\n transition: max-width 0.5s, opacity 0.2s;\n}\n\n.Fname {\n color: #ffc000;\n}\n\nli {\n display: inline;\n padding: 8px;\n font-size: 20px;\n}\n\n\n/* My Nav List Position */\n\n.nav-menu {\n display: flex;\n justify-content: flex-end;\n}\n\n\n/* My Nav List Position */\n\n\n/* Navigation Link Interaction */\n\n.nav-menu li a {\n color: #f6f2f0;\n}\n\n.nav-menu li a:link {\n text-decoration: none;\n}\n\n.nav-menu li a:hover {\n color: #ffc000;\n text-decoration: none;\n}\n\n\n/* Navigation Link Interaction */ <!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\" />\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Portfolio</title>\n <link href=\"Styles.css\" rel=\"stylesheet\" />\n <link href=\"https://fonts.googleapis.com/css2?family=Rubik:wght@300;400&display=swap\" rel=\"stylesheet\" />\n</head>\n\n<body>\n <nav>\n <header>\n <h1 class=\"Name\">\n [\n <span id=\"zk-trigger\"><span class=\"Fname\"> S</span><span id=\"hide1\" class=\"hide\"><span class=\"Fname\">eid</span></span>\n J<span id=\"hide2\" class=\"hide\">ama</span>\n </span>\n ]\n </h1>\n </header>\n <!-- Navigational Bar -->\n <div class=\"nav-menu\">\n <ul>\n <li><a href=\"#Home\">Home</a></li>\n <li><a href=\"#About\">About</a></li>\n <li><a href=\"#Projects\">Projects</a></li>\n <li><a href=\"#Skills\">Skills</a></li>\n <li><a href=\"#Contact\">Contact</a></li>\n </ul>\n </div>\n <!-- Navigational Bar -->\n </nav>\n</body>\n\n</html>"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20626347/"
] |
74,627,184
|
<p>I use the latest angular and material (15) but I want to use also flex layout.</p>
|
[
{
"answer_id": 74665690,
"author": "JSON Derulo",
"author_id": 5470544,
"author_profile": "https://Stackoverflow.com/users/5470544",
"pm_score": 1,
"selected": false,
"text": "@angular/flex-layout"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17384995/"
] |
74,627,205
|
<p>I am currently working on an app where I have the necessity to get the current date and time in the Europe/Rome timezone. I have created the following method to do so:</p>
<pre><code>static func getItalianDate() -> Date {
let timezone = TimeZone(identifier: "Europe/Rome")!
let seconds = TimeInterval(timezone.secondsFromGMT(for: Date()))
let date = Date(timeInterval: seconds, since: Date())
return date
}
</code></pre>
<p>This however won't return the correct value in case the user manipulates the date and timezone from the settings General -> Date and Time and I can't figure out how to get the correct answer. The format I need is something like: "yyyy-MM-dd HH:mm:ss".</p>
<p>Any suggestion?</p>
<p><strong>EDIT</strong></p>
<p>I found this <a href="https://stackoverflow.com/questions/70786159/how-to-handle-incorrect-system-time-offset-from-the-system-timezone-on-device">question</a> - still unanswered - with the same problem I am facing here. Is using a server the only option available?</p>
|
[
{
"answer_id": 74665690,
"author": "JSON Derulo",
"author_id": 5470544,
"author_profile": "https://Stackoverflow.com/users/5470544",
"pm_score": 1,
"selected": false,
"text": "@angular/flex-layout"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8938882/"
] |
74,627,237
|
<pre><code>ACCOUNT = c(M205109, M205109, M201212, M205668, M207954, M208966, M203465, M207622, M201869, M201869)
age = c(20, 20, 18, 29, 21, 19, 19, 23, 22, 22)
</code></pre>
<p>The code I am using</p>
<pre><code>library(tidyverse)
library(data.table)
library(dtplyr)
library(lubridate)
age_summary_all <- data %>%
distinct(ACCOUNT) %>%
summarise(min = min(age, na.rm=TRUE),
q1 = quantile(age, 0.25, na.rm=TRUE),
median = median(age,na.rm=TRUE),
mean = mean(age,na.rm=TRUE),
q3 = quantile(age, 0.75, na.rm=TRUE),
max = max(age, na.rm=TRUE))
</code></pre>
<p>I get this error:</p>
<blockquote>
<p>Error in <code>summarise()</code>: ! Problem while computing <code>min = min(age, na.rm = TRUE)</code>. Caused by error in <code>mask$eval_all_summarise()</code>: !
object 'age' not found</p>
</blockquote>
<p>The really odd thing is that exactly the same code runs fine if the distinct is replaced by a group_by clause referring to a different column, but I need to run the analysis on unique individuals - the nature of the data is such that individual accounts are likely to have more than one entry in the data table. So, for the example above I would expect n = 8 for the summarise clause.</p>
<p>All the packages are definitely up to date.</p>
|
[
{
"answer_id": 74627313,
"author": "Vinícius Félix",
"author_id": 9696037,
"author_profile": "https://Stackoverflow.com/users/9696037",
"pm_score": 0,
"selected": false,
"text": "account <- c(\"M205109\", \"M205109\", \"M201212\", \"M205668\", \"M207954\", \"M208966\", \"M203465\", \"M207622\", \"M201869\", \"M201869\")\nage <- c(20, 20, 18, 29, 21, 19, 19, 23, 22, 22)\n\nlibrary(dplyr) \n\ndata <- data.frame(account , age)\n\nage_summary_all <- \n data %>%\n group_by(account) %>%\n summarise(min = min(age, na.rm=TRUE),\n q1 = quantile(age, 0.25, na.rm=TRUE),\n median = median(age,na.rm=TRUE),\n mean = mean(age,na.rm=TRUE),\n q3 = quantile(age, 0.75, na.rm=TRUE),\n max = max(age, na.rm=TRUE))\n\nage_summary_all\n\n# A tibble: 8 x 7\n account min q1 median mean q3 max\n <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>\n1 M201212 18 18 18 18 18 18\n2 M201869 22 22 22 22 22 22\n3 M203465 19 19 19 19 19 19\n4 M205109 20 20 20 20 20 20\n5 M205668 29 29 29 29 29 29\n6 M207622 23 23 23 23 23 23\n7 M207954 21 21 21 21 21 21\n8 M208966 19 19 19 19 19 19\n"
},
{
"answer_id": 74627326,
"author": "Andre Wildberg",
"author_id": 9462095,
"author_profile": "https://Stackoverflow.com/users/9462095",
"pm_score": 3,
"selected": true,
"text": "distinct .keep_all=T .keep_all=T library(dplyr)\n\ndata %>%\n distinct(ACCOUNT)\n# A tibble: 8 × 1\n ACCOUNT\n <chr>\n1 M205109\n2 M201212\n3 M205668\n4 M207954\n5 M208966\n6 M203465\n7 M207622\n8 M201869\n .keep_all=T data %>% \n distinct(ACCOUNT, .keep_all=T)\n# A tibble: 8 × 2\n ACCOUNT age\n <chr> <dbl>\n1 M205109 20\n2 M201212 18\n3 M205668 29\n4 M207954 21\n5 M208966 19\n6 M203465 19\n7 M207622 23\n8 M201869 22\n data %>%\n distinct(ACCOUNT, .keep_all=T) %>%\n summarise(min = min(age, na.rm=TRUE),\n q1 = quantile(age, 0.25, na.rm=TRUE),\n median = median(age,na.rm=TRUE),\n mean = mean(age,na.rm=TRUE),\n q3 = quantile(age, 0.75, na.rm=TRUE),\n max = max(age, na.rm=TRUE))\n# A tibble: 1 × 6\n min q1 median mean q3 max\n <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>\n1 18 19 20.5 21.4 22.2 29\n data <- structure(list(ACCOUNT = c(\"M205109\", \"M205109\", \"M201212\", \"M205668\",\n\"M207954\", \"M208966\", \"M203465\", \"M207622\", \"M201869\", \"M201869\"\n), age = c(20, 20, 18, 29, 21, 19, 19, 23, 22, 22)), class = c(\"tbl_df\",\n\"tbl\", \"data.frame\"), row.names = c(NA, -10L))\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17498917/"
] |
74,627,259
|
<p>I am doing a Vaadin App that has three Views, and whenever the users enters an unknown URL he sees this page:</p>
<p>Could not navigate to 'stackoverflow'
Reason: Couldn't find route for 'stackoverflow'</p>
<p>Available routes:
app
login
logout</p>
<p>This detailed message is only shown when running in development mode.
I want to define a route instead of showing this page, how to do it? Like whenever this messgage is shown it should just swallow it and redirect to an existing route.</p>
|
[
{
"answer_id": 74627532,
"author": "Leif Åstrand",
"author_id": 2376954,
"author_profile": "https://Stackoverflow.com/users/2376954",
"pm_score": 2,
"selected": false,
"text": "VerticalLayout HasErrorParameter<NotFoundException> @Route"
},
{
"answer_id": 74640101,
"author": "Stimpson Cat",
"author_id": 2605902,
"author_profile": "https://Stackoverflow.com/users/2605902",
"pm_score": 0,
"selected": false,
"text": "@Tag(Tag.DIV)\n@DefaultErrorHandler\npublic class MYNoRouteHandler extends RouteNotFoundError {\n\nprivate static final long serialVersionUID = 7169334501543395112L;\nprivate static final Logger log = LoggerFactory.getLogger(MyNoRouteHandler.class);\n\n@Override\npublic int setErrorParameter(BeforeEnterEvent event, ErrorParameter<NotFoundException> parameter) {\n log.debug(\"Not existing view requested with name: /\" + event.getLocation().getPath());\n log.debug(\"Redirect user to /start\");\n event.forwardTo(StartView.class);\n return HttpServletResponse.SC_NOT_FOUND;\n }\n}\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605902/"
] |
74,627,276
|
<p>I tried loading the SVG path into imageView, but I couldn't</p>
<p>for example, I have SVG path as String</p>
<pre><code>"<svg width="35" height="35" viewBox="0 0 35 35" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M6.48918 13.6276C6.70383 13.0193 7.37699 12.6841 7.98482 12.8979C8.59265 13.1117 8.89133 13.7854 8.67782 14.3938C8.33132 15.3794 8.16683 16.4263 8.16683 17.4949C8.16683 18.572 8.36283 19.64 8.71399 20.6325C8.92864 21.2403 8.59148 21.8766 7.98482 22.0919C7.37699 22.3072 6.70501 22.0065 6.48918 21.3988C6.0505 20.1567 5.8335 18.8386 5.8335 17.4949C5.8335 16.1619 6.05634 14.861 6.48918 13.6276ZM26.3225 14.4302C26.1125 13.8209 26.4438 13.1817 27.0528 12.9709C27.6606 12.76 28.3 13.0547 28.5111 13.6641C28.9311 14.8823 29.1668 16.1806 29.1668 17.4949C29.1668 18.8454 28.9545 20.1511 28.5111 21.3988C28.2941 22.0061 27.6233 22.3448 27.0155 22.1285C26.4088 21.912 26.0705 21.24 26.2863 20.6325C26.641 19.6356 26.8335 18.5775 26.8335 17.4949C26.8335 16.4413 26.6597 15.4037 26.3225 14.4302ZM17.5002 24.4999C18.1445 24.4999 18.6668 23.9772 18.6668 23.3324C18.6668 22.6876 18.1445 22.1649 17.5002 22.1649C16.8558 22.1649 16.3335 22.6876 16.3335 23.3324C16.3335 23.9772 16.8558 24.4999 17.5002 24.4999Z" fill="#88B8E9"/> <path fill-rule="evenodd" clip-rule="evenodd" d="M10.5 11.0833C10.5 8.82817 12.3282 7 14.5833 7H20.4167C22.6718 7 24.5 8.82817 24.5 11.0833V23.9167C24.5 26.1718 22.6718 28 20.4167 28H14.5833C12.3282 28 10.5 26.1718 10.5 23.9167V11.0833ZM17.5 24.5C18.1443 24.5 18.6667 23.9777 18.6667 23.3333C18.6667 22.689 18.1443 22.1667 17.5 22.1667C16.8557 22.1667 16.3333 22.689 16.3333 23.3333C16.3333 23.9777 16.8557 24.5 17.5 24.5Z" fill="#88B8E9"/> </svg>"
</code></pre>
<p>how can load this path into imageView</p>
|
[
{
"answer_id": 74627753,
"author": "Javlon",
"author_id": 12153321,
"author_profile": "https://Stackoverflow.com/users/12153321",
"pm_score": 0,
"selected": false,
"text": "SvgDetector.java SvgDrawableTranscoder.java SvgModule.java SvgSoftwareLayerSetter.java GenericRequestBuilder<Uri,InputStream,SVG,PictureDrawable>\n requestBuilder = Glide.with(context)\n .using(Glide.buildStreamModelLoader(Uri.class, context), InputStream.class)\n .from(Uri.class)\n .as(SVG.class)\n .transcode(new SvgDrawableTranscoder(), PictureDrawable.class)\n .sourceEncoder(new StreamEncoder())\n .cacheDecoder(new FileToStreamDecoder<SVG>(new SvgDecoder()))\n .decoder(new SvgDecoder())\n .placeholder(R.drawable.svg_image_view_placeholder)\n .error(R.drawable.error_image)\n .listener(new SvgSoftwareLayerSetter<Uri>());\n\nUri uri = Uri.parse(svgImageUrl);\nrequestBuilder\n .diskCacheStrategy(DiskCacheStrategy.SOURCE)\n .load(uri)\n .into(imageView);\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12143623/"
] |
74,627,282
|
<p>I have a Json file like below and already parsed and Model passed to next page. What I am trying to generate a list based on <code>YoutubeId</code> on the next page.</p>
<pre><code>final videoID;
final CourseLessonDetailsData courseLessons;
final CourseLessonsModel courseLessonsModel;
</code></pre>
<p>Json response:</p>
<pre><code>{
"CourseLessonDetailsData": [
{
"request_status": "Successful",
"ID": "24973",
"LessonContentDetails": [
{
"TopicInfo": [
{
"ID": "2764",
"CourseCode": "DTS",
}
],
"PreAssessment": [],
"Video": [
{
"YoutubeId": "yt_id1",
}
],
}
],
}
{
"request_status": "Successful",
"ID": "24974",
"LessonContentDetails": [
{
"TopicInfo": [
{
"ID": "2765",
"CourseCode": "DTS",
}
],
"PreAssessment": [],
"Video": [
{
"YoutubeId": "yt_id2",
}
],
}
],
}
{
"request_status": "Successful",
"ID": "24975",
"LessonContentDetails": [
{
"TopicInfo": [
{
"ID": "2766",
"CourseCode": "DTS",
}
],
"PreAssessment": [],
"Video": [
{
"YoutubeId": "yt_id3",
}
],
}
],
}
]
},
</code></pre>
<p>Using the following code, I'm able to parse the first item but not able to get the rest.</p>
<pre><code>for(var data in widget.courseLessonsModel.courseLessonDetailsData as Iterable){
youTubeIds.add(widget.courseLessons.lessonContentDetails!.first.video!.first.youtubeId);
}
print(youTubeIds);
</code></pre>
<p>Here's how to my <code>list</code> is printed.</p>
<p><code>[yt_id1, yt_id1, yt_id1]</code></p>
<p>while my expected output is</p>
<p><code>[yt_id1, yt_id2, yt_id3]</code></p>
<p>I'm aware that I'm using <code>first</code> so only the first option will be retrieved. How should I retrieve all and what to replace with <code>first</code>?</p>
|
[
{
"answer_id": 74627751,
"author": "Arbiter Chil",
"author_id": 10782024,
"author_profile": "https://Stackoverflow.com/users/10782024",
"pm_score": 1,
"selected": false,
"text": "import 'dart:convert';\n\nModel modelFromJson(String str) => Model.fromJson(json.decode(str));\n\nString modelToJson(Model data) => json.encode(data.toJson());\n\nclass Model {\n Model({\n this.requestStatus,\n this.id,\n this.lessonContentDetails,\n });\n\n String? requestStatus;\n String? id;\n List<LessonContentDetail>? lessonContentDetails;\n\n factory Model.fromJson(Map<String, dynamic> json) => Model(\n requestStatus: json[\"request_status\"] == null ? null : json[\"request_status\"]!,\n id: json[\"ID\"] == null ? null : json[\"ID\"]!,\n lessonContentDetails: json[\"LessonContentDetails\"] == null ? null : List<LessonContentDetail>.from(json[\"LessonContentDetails\"].map((x) => LessonContentDetail.fromJson(x))),\n );\n\n Map<String, dynamic> toJson() => {\n \"request_status\": requestStatus == null ? null : requestStatus!,\n \"ID\": id == null ? null : id!,\n \"LessonContentDetails\": lessonContentDetails == null ? null : List<dynamic>.from(lessonContentDetails!.map((x) => x.toJson())),\n };\n}\n\nclass LessonContentDetail {\n LessonContentDetail({\n this.topicInfo,\n this.preAssessment,\n this.video,\n });\n\n List<TopicInfo>? topicInfo;\n List<dynamic>? preAssessment;\n List<Video>? video;\n\n factory LessonContentDetail.fromJson(Map<String, dynamic> json) => LessonContentDetail(\n topicInfo: json[\"TopicInfo\"] == null ? null : List<TopicInfo>.from(json[\"TopicInfo\"].map((x) => TopicInfo.fromJson(x))),\n preAssessment: json[\"PreAssessment\"] == null ? null : List<dynamic>.from(json[\"PreAssessment\"].map((x) => x)),\n video: json[\"Video\"] == null ? null : List<Video>.from(json[\"Video\"].map((x) => Video.fromJson(x))),\n );\n\n Map<String, dynamic> toJson() => {\n \"TopicInfo\": topicInfo == null ? null : List<dynamic>.from(topicInfo!.map((x) => x.toJson())),\n \"PreAssessment\": preAssessment == null ? null : List<dynamic>.from(preAssessment!.map((x) => x)),\n \"Video\": video == null ? null : List<dynamic>.from(video!.map((x) => x.toJson())),\n };\n}\n\nclass TopicInfo {\n TopicInfo({\n this.id,\n this.courseCode,\n });\n\n String? id;\n String? courseCode;\n\n factory TopicInfo.fromJson(Map<String, dynamic> json) => TopicInfo(\n id: json[\"ID\"] == null ? null : json[\"ID\"]!,\n courseCode: json[\"CourseCode\"] == null ? null : json[\"CourseCode\"]!,\n );\n\n Map<String, dynamic> toJson() => {\n \"ID\": id == null ? null : id!,\n \"CourseCode\": courseCode == null ? null : courseCode!,\n };\n}\n\nclass Video {\n Video({\n this.youtubeId,\n });\n\n String? youtubeId;\n\n factory Video.fromJson(Map<String, dynamic> json) => Video(\n youtubeId: json[\"YoutubeId\"] == null ? null : json[\"YoutubeId\"]!,\n );\n\n Map<String, dynamic> toJson() => {\n \"YoutubeId\": youtubeId == null ? null : youtubeId!,\n };\n}\n final dataList = {\n \"CourseLessonDetailsData\": [\n {\n \"request_status\": \"Successful\",\n \"ID\": \"24973\",\n \"LessonContentDetails\": [\n {\n \"TopicInfo\": [\n {\"ID\": \"2764\", \"CourseCode\": \"DTS\"}\n ],\n \"PreAssessment\": [],\n \"Video\": [\n {\"YoutubeId\": \"yt_id1\"}\n ]\n }\n ]\n },\n {\n \"request_status\": \"Successful\",\n \"ID\": \"24973\",\n \"LessonContentDetails\": [\n {\n \"TopicInfo\": [\n {\"ID\": \"2764\", \"CourseCode\": \"DTS\"}\n ],\n \"PreAssessment\": [],\n \"Video\": [\n {\"YoutubeId\": \"yt_id2\"}\n ]\n }\n ]\n },\n {\n \"request_status\": \"Successful\",\n \"ID\": \"24973\",\n \"LessonContentDetails\": [\n {\n \"TopicInfo\": [\n {\"ID\": \"2764\", \"CourseCode\": \"DTS\"}\n ],\n \"PreAssessment\": [],\n \"Video\": [\n {\"YoutubeId\": \"yt_id3\"}\n ]\n }\n ]\n }\n ]\n };\n/// This the the model which gonna hold the data\nfinal List<Model> models = [];\n/// Now lets create a another list to put the id\nfinal List<String> ids = [];\n\n runthisinOninit(){\n \n try {\n models.addAll(dataList[\"CourseLessonDetailsData\"]!\n .map((e) => Model.fromJson(e))\n .toList());\n } finally {\n for (var x in models) {\n final xy = x.lessonContentDetails!;\n\n if (xy.isNotEmpty) {\n for (var y in xy) {\n final xyz = y.video!;\n for (var z in xyz) {\n ids.add(z.youtubeId!);\n }\n }\n }\n }\n\n log(ids.toList().toString(),name:\"My ID LIST\");\n }\n\n}\n\n////as per result will be \n////[yt_id1, yt_id2, yt_id3]\n https://gist.github.com/Erchil66/47777fd92e9c3f194a3cd81b5d49111a\n"
},
{
"answer_id": 74637665,
"author": "Tahir",
"author_id": 6340327,
"author_profile": "https://Stackoverflow.com/users/6340327",
"pm_score": 0,
"selected": false,
"text": "List ytIdList = [];\nListView.builder(\n itemCount: snapshot.data!.courseLessonDetailsData!.length,\n itemBuilder: (context, index){\n ytIdList.add(snapshot.data!.courseLessonDetailsData![index].lessonContentDetails!.first.video!.first.youtubeId);\n // print(ytIdList);\n return Card();\n})\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340327/"
] |
74,627,328
|
<p>I know, we don't want to use <code>global variables</code> because then we will need to use <code>synchronization</code> which will affect the performance.</p>
<p>I also know that <code>ThreadLocal</code> is like a <code>global variable</code>, but every <code>thread</code> will have its version of it, and every <code>thread</code> can modify its version freely without affecting the other <code>threads</code>.</p>
<p>My Question is why don't we make every <code>thread</code> create its own version of that variable <code>internally</code>?</p>
<p>What is the benefit of using <code>ThreadLocal</code> that I can't achieve with any other mechanism?</p>
<p>Please provide a solid example if possible.</p>
<p><strong>Note</strong>:- for any one that would suggest I should take a look at <a href="https://stackoverflow.com/questions/817856/when-and-how-should-i-use-a-threadlocal-variable">This question</a>, the answers in that question don't answer my question because they don't say why I can't replace <code>using ThreadLocal</code> by creating the variable internally inside the <code>thread</code>.</p>
|
[
{
"answer_id": 74627751,
"author": "Arbiter Chil",
"author_id": 10782024,
"author_profile": "https://Stackoverflow.com/users/10782024",
"pm_score": 1,
"selected": false,
"text": "import 'dart:convert';\n\nModel modelFromJson(String str) => Model.fromJson(json.decode(str));\n\nString modelToJson(Model data) => json.encode(data.toJson());\n\nclass Model {\n Model({\n this.requestStatus,\n this.id,\n this.lessonContentDetails,\n });\n\n String? requestStatus;\n String? id;\n List<LessonContentDetail>? lessonContentDetails;\n\n factory Model.fromJson(Map<String, dynamic> json) => Model(\n requestStatus: json[\"request_status\"] == null ? null : json[\"request_status\"]!,\n id: json[\"ID\"] == null ? null : json[\"ID\"]!,\n lessonContentDetails: json[\"LessonContentDetails\"] == null ? null : List<LessonContentDetail>.from(json[\"LessonContentDetails\"].map((x) => LessonContentDetail.fromJson(x))),\n );\n\n Map<String, dynamic> toJson() => {\n \"request_status\": requestStatus == null ? null : requestStatus!,\n \"ID\": id == null ? null : id!,\n \"LessonContentDetails\": lessonContentDetails == null ? null : List<dynamic>.from(lessonContentDetails!.map((x) => x.toJson())),\n };\n}\n\nclass LessonContentDetail {\n LessonContentDetail({\n this.topicInfo,\n this.preAssessment,\n this.video,\n });\n\n List<TopicInfo>? topicInfo;\n List<dynamic>? preAssessment;\n List<Video>? video;\n\n factory LessonContentDetail.fromJson(Map<String, dynamic> json) => LessonContentDetail(\n topicInfo: json[\"TopicInfo\"] == null ? null : List<TopicInfo>.from(json[\"TopicInfo\"].map((x) => TopicInfo.fromJson(x))),\n preAssessment: json[\"PreAssessment\"] == null ? null : List<dynamic>.from(json[\"PreAssessment\"].map((x) => x)),\n video: json[\"Video\"] == null ? null : List<Video>.from(json[\"Video\"].map((x) => Video.fromJson(x))),\n );\n\n Map<String, dynamic> toJson() => {\n \"TopicInfo\": topicInfo == null ? null : List<dynamic>.from(topicInfo!.map((x) => x.toJson())),\n \"PreAssessment\": preAssessment == null ? null : List<dynamic>.from(preAssessment!.map((x) => x)),\n \"Video\": video == null ? null : List<dynamic>.from(video!.map((x) => x.toJson())),\n };\n}\n\nclass TopicInfo {\n TopicInfo({\n this.id,\n this.courseCode,\n });\n\n String? id;\n String? courseCode;\n\n factory TopicInfo.fromJson(Map<String, dynamic> json) => TopicInfo(\n id: json[\"ID\"] == null ? null : json[\"ID\"]!,\n courseCode: json[\"CourseCode\"] == null ? null : json[\"CourseCode\"]!,\n );\n\n Map<String, dynamic> toJson() => {\n \"ID\": id == null ? null : id!,\n \"CourseCode\": courseCode == null ? null : courseCode!,\n };\n}\n\nclass Video {\n Video({\n this.youtubeId,\n });\n\n String? youtubeId;\n\n factory Video.fromJson(Map<String, dynamic> json) => Video(\n youtubeId: json[\"YoutubeId\"] == null ? null : json[\"YoutubeId\"]!,\n );\n\n Map<String, dynamic> toJson() => {\n \"YoutubeId\": youtubeId == null ? null : youtubeId!,\n };\n}\n final dataList = {\n \"CourseLessonDetailsData\": [\n {\n \"request_status\": \"Successful\",\n \"ID\": \"24973\",\n \"LessonContentDetails\": [\n {\n \"TopicInfo\": [\n {\"ID\": \"2764\", \"CourseCode\": \"DTS\"}\n ],\n \"PreAssessment\": [],\n \"Video\": [\n {\"YoutubeId\": \"yt_id1\"}\n ]\n }\n ]\n },\n {\n \"request_status\": \"Successful\",\n \"ID\": \"24973\",\n \"LessonContentDetails\": [\n {\n \"TopicInfo\": [\n {\"ID\": \"2764\", \"CourseCode\": \"DTS\"}\n ],\n \"PreAssessment\": [],\n \"Video\": [\n {\"YoutubeId\": \"yt_id2\"}\n ]\n }\n ]\n },\n {\n \"request_status\": \"Successful\",\n \"ID\": \"24973\",\n \"LessonContentDetails\": [\n {\n \"TopicInfo\": [\n {\"ID\": \"2764\", \"CourseCode\": \"DTS\"}\n ],\n \"PreAssessment\": [],\n \"Video\": [\n {\"YoutubeId\": \"yt_id3\"}\n ]\n }\n ]\n }\n ]\n };\n/// This the the model which gonna hold the data\nfinal List<Model> models = [];\n/// Now lets create a another list to put the id\nfinal List<String> ids = [];\n\n runthisinOninit(){\n \n try {\n models.addAll(dataList[\"CourseLessonDetailsData\"]!\n .map((e) => Model.fromJson(e))\n .toList());\n } finally {\n for (var x in models) {\n final xy = x.lessonContentDetails!;\n\n if (xy.isNotEmpty) {\n for (var y in xy) {\n final xyz = y.video!;\n for (var z in xyz) {\n ids.add(z.youtubeId!);\n }\n }\n }\n }\n\n log(ids.toList().toString(),name:\"My ID LIST\");\n }\n\n}\n\n////as per result will be \n////[yt_id1, yt_id2, yt_id3]\n https://gist.github.com/Erchil66/47777fd92e9c3f194a3cd81b5d49111a\n"
},
{
"answer_id": 74637665,
"author": "Tahir",
"author_id": 6340327,
"author_profile": "https://Stackoverflow.com/users/6340327",
"pm_score": 0,
"selected": false,
"text": "List ytIdList = [];\nListView.builder(\n itemCount: snapshot.data!.courseLessonDetailsData!.length,\n itemBuilder: (context, index){\n ytIdList.add(snapshot.data!.courseLessonDetailsData![index].lessonContentDetails!.first.video!.first.youtubeId);\n // print(ytIdList);\n return Card();\n})\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20531364/"
] |
74,627,333
|
<p>I have this link:</p>
<pre><code><a href="#">Laboris chuck pastrami ribeye nisi</a>
</code></pre>
<p>I'm adding an arrow using a pseudo element:</p>
<pre><code>a::after {
content: ">";
margin-left: 7px;
display: inline-block;
}
</code></pre>
<p>But how can I prevent the pseuto element to break into a new line alone? I want to keep the arrow attached to the last word at all times. See Fiddle.
If I remove <code>display: inline-block;</code> from the <code>::after</code>, it seems to work and the arrow breaks with the last word, but then the pseudo element is also underlined like the parent. I don't want that.</p>
<p>How can I get around this? Any ideas?</p>
<p><a href="https://jsfiddle.net/qga5us4L/" rel="nofollow noreferrer">JsFiddle here</a>.</p>
<p><a href="https://i.stack.imgur.com/gnXL9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gnXL9.jpg" alt="What I have" /></a></p>
<p><a href="https://i.stack.imgur.com/GHnxG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GHnxG.jpg" alt="What I want" /></a></p>
|
[
{
"answer_id": 74627751,
"author": "Arbiter Chil",
"author_id": 10782024,
"author_profile": "https://Stackoverflow.com/users/10782024",
"pm_score": 1,
"selected": false,
"text": "import 'dart:convert';\n\nModel modelFromJson(String str) => Model.fromJson(json.decode(str));\n\nString modelToJson(Model data) => json.encode(data.toJson());\n\nclass Model {\n Model({\n this.requestStatus,\n this.id,\n this.lessonContentDetails,\n });\n\n String? requestStatus;\n String? id;\n List<LessonContentDetail>? lessonContentDetails;\n\n factory Model.fromJson(Map<String, dynamic> json) => Model(\n requestStatus: json[\"request_status\"] == null ? null : json[\"request_status\"]!,\n id: json[\"ID\"] == null ? null : json[\"ID\"]!,\n lessonContentDetails: json[\"LessonContentDetails\"] == null ? null : List<LessonContentDetail>.from(json[\"LessonContentDetails\"].map((x) => LessonContentDetail.fromJson(x))),\n );\n\n Map<String, dynamic> toJson() => {\n \"request_status\": requestStatus == null ? null : requestStatus!,\n \"ID\": id == null ? null : id!,\n \"LessonContentDetails\": lessonContentDetails == null ? null : List<dynamic>.from(lessonContentDetails!.map((x) => x.toJson())),\n };\n}\n\nclass LessonContentDetail {\n LessonContentDetail({\n this.topicInfo,\n this.preAssessment,\n this.video,\n });\n\n List<TopicInfo>? topicInfo;\n List<dynamic>? preAssessment;\n List<Video>? video;\n\n factory LessonContentDetail.fromJson(Map<String, dynamic> json) => LessonContentDetail(\n topicInfo: json[\"TopicInfo\"] == null ? null : List<TopicInfo>.from(json[\"TopicInfo\"].map((x) => TopicInfo.fromJson(x))),\n preAssessment: json[\"PreAssessment\"] == null ? null : List<dynamic>.from(json[\"PreAssessment\"].map((x) => x)),\n video: json[\"Video\"] == null ? null : List<Video>.from(json[\"Video\"].map((x) => Video.fromJson(x))),\n );\n\n Map<String, dynamic> toJson() => {\n \"TopicInfo\": topicInfo == null ? null : List<dynamic>.from(topicInfo!.map((x) => x.toJson())),\n \"PreAssessment\": preAssessment == null ? null : List<dynamic>.from(preAssessment!.map((x) => x)),\n \"Video\": video == null ? null : List<dynamic>.from(video!.map((x) => x.toJson())),\n };\n}\n\nclass TopicInfo {\n TopicInfo({\n this.id,\n this.courseCode,\n });\n\n String? id;\n String? courseCode;\n\n factory TopicInfo.fromJson(Map<String, dynamic> json) => TopicInfo(\n id: json[\"ID\"] == null ? null : json[\"ID\"]!,\n courseCode: json[\"CourseCode\"] == null ? null : json[\"CourseCode\"]!,\n );\n\n Map<String, dynamic> toJson() => {\n \"ID\": id == null ? null : id!,\n \"CourseCode\": courseCode == null ? null : courseCode!,\n };\n}\n\nclass Video {\n Video({\n this.youtubeId,\n });\n\n String? youtubeId;\n\n factory Video.fromJson(Map<String, dynamic> json) => Video(\n youtubeId: json[\"YoutubeId\"] == null ? null : json[\"YoutubeId\"]!,\n );\n\n Map<String, dynamic> toJson() => {\n \"YoutubeId\": youtubeId == null ? null : youtubeId!,\n };\n}\n final dataList = {\n \"CourseLessonDetailsData\": [\n {\n \"request_status\": \"Successful\",\n \"ID\": \"24973\",\n \"LessonContentDetails\": [\n {\n \"TopicInfo\": [\n {\"ID\": \"2764\", \"CourseCode\": \"DTS\"}\n ],\n \"PreAssessment\": [],\n \"Video\": [\n {\"YoutubeId\": \"yt_id1\"}\n ]\n }\n ]\n },\n {\n \"request_status\": \"Successful\",\n \"ID\": \"24973\",\n \"LessonContentDetails\": [\n {\n \"TopicInfo\": [\n {\"ID\": \"2764\", \"CourseCode\": \"DTS\"}\n ],\n \"PreAssessment\": [],\n \"Video\": [\n {\"YoutubeId\": \"yt_id2\"}\n ]\n }\n ]\n },\n {\n \"request_status\": \"Successful\",\n \"ID\": \"24973\",\n \"LessonContentDetails\": [\n {\n \"TopicInfo\": [\n {\"ID\": \"2764\", \"CourseCode\": \"DTS\"}\n ],\n \"PreAssessment\": [],\n \"Video\": [\n {\"YoutubeId\": \"yt_id3\"}\n ]\n }\n ]\n }\n ]\n };\n/// This the the model which gonna hold the data\nfinal List<Model> models = [];\n/// Now lets create a another list to put the id\nfinal List<String> ids = [];\n\n runthisinOninit(){\n \n try {\n models.addAll(dataList[\"CourseLessonDetailsData\"]!\n .map((e) => Model.fromJson(e))\n .toList());\n } finally {\n for (var x in models) {\n final xy = x.lessonContentDetails!;\n\n if (xy.isNotEmpty) {\n for (var y in xy) {\n final xyz = y.video!;\n for (var z in xyz) {\n ids.add(z.youtubeId!);\n }\n }\n }\n }\n\n log(ids.toList().toString(),name:\"My ID LIST\");\n }\n\n}\n\n////as per result will be \n////[yt_id1, yt_id2, yt_id3]\n https://gist.github.com/Erchil66/47777fd92e9c3f194a3cd81b5d49111a\n"
},
{
"answer_id": 74637665,
"author": "Tahir",
"author_id": 6340327,
"author_profile": "https://Stackoverflow.com/users/6340327",
"pm_score": 0,
"selected": false,
"text": "List ytIdList = [];\nListView.builder(\n itemCount: snapshot.data!.courseLessonDetailsData!.length,\n itemBuilder: (context, index){\n ytIdList.add(snapshot.data!.courseLessonDetailsData![index].lessonContentDetails!.first.video!.first.youtubeId);\n // print(ytIdList);\n return Card();\n})\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1583995/"
] |
74,627,343
|
<p>Given class A</p>
<pre><code>public class A<T> where T : B{
...
}
</code></pre>
<p>Is A coupled to B? Or is is more useful to think of this as a type restriction?</p>
<p>I was making a class diagram and was wondering how to represent this type of relationship when planning out a system's architecture.</p>
|
[
{
"answer_id": 74627751,
"author": "Arbiter Chil",
"author_id": 10782024,
"author_profile": "https://Stackoverflow.com/users/10782024",
"pm_score": 1,
"selected": false,
"text": "import 'dart:convert';\n\nModel modelFromJson(String str) => Model.fromJson(json.decode(str));\n\nString modelToJson(Model data) => json.encode(data.toJson());\n\nclass Model {\n Model({\n this.requestStatus,\n this.id,\n this.lessonContentDetails,\n });\n\n String? requestStatus;\n String? id;\n List<LessonContentDetail>? lessonContentDetails;\n\n factory Model.fromJson(Map<String, dynamic> json) => Model(\n requestStatus: json[\"request_status\"] == null ? null : json[\"request_status\"]!,\n id: json[\"ID\"] == null ? null : json[\"ID\"]!,\n lessonContentDetails: json[\"LessonContentDetails\"] == null ? null : List<LessonContentDetail>.from(json[\"LessonContentDetails\"].map((x) => LessonContentDetail.fromJson(x))),\n );\n\n Map<String, dynamic> toJson() => {\n \"request_status\": requestStatus == null ? null : requestStatus!,\n \"ID\": id == null ? null : id!,\n \"LessonContentDetails\": lessonContentDetails == null ? null : List<dynamic>.from(lessonContentDetails!.map((x) => x.toJson())),\n };\n}\n\nclass LessonContentDetail {\n LessonContentDetail({\n this.topicInfo,\n this.preAssessment,\n this.video,\n });\n\n List<TopicInfo>? topicInfo;\n List<dynamic>? preAssessment;\n List<Video>? video;\n\n factory LessonContentDetail.fromJson(Map<String, dynamic> json) => LessonContentDetail(\n topicInfo: json[\"TopicInfo\"] == null ? null : List<TopicInfo>.from(json[\"TopicInfo\"].map((x) => TopicInfo.fromJson(x))),\n preAssessment: json[\"PreAssessment\"] == null ? null : List<dynamic>.from(json[\"PreAssessment\"].map((x) => x)),\n video: json[\"Video\"] == null ? null : List<Video>.from(json[\"Video\"].map((x) => Video.fromJson(x))),\n );\n\n Map<String, dynamic> toJson() => {\n \"TopicInfo\": topicInfo == null ? null : List<dynamic>.from(topicInfo!.map((x) => x.toJson())),\n \"PreAssessment\": preAssessment == null ? null : List<dynamic>.from(preAssessment!.map((x) => x)),\n \"Video\": video == null ? null : List<dynamic>.from(video!.map((x) => x.toJson())),\n };\n}\n\nclass TopicInfo {\n TopicInfo({\n this.id,\n this.courseCode,\n });\n\n String? id;\n String? courseCode;\n\n factory TopicInfo.fromJson(Map<String, dynamic> json) => TopicInfo(\n id: json[\"ID\"] == null ? null : json[\"ID\"]!,\n courseCode: json[\"CourseCode\"] == null ? null : json[\"CourseCode\"]!,\n );\n\n Map<String, dynamic> toJson() => {\n \"ID\": id == null ? null : id!,\n \"CourseCode\": courseCode == null ? null : courseCode!,\n };\n}\n\nclass Video {\n Video({\n this.youtubeId,\n });\n\n String? youtubeId;\n\n factory Video.fromJson(Map<String, dynamic> json) => Video(\n youtubeId: json[\"YoutubeId\"] == null ? null : json[\"YoutubeId\"]!,\n );\n\n Map<String, dynamic> toJson() => {\n \"YoutubeId\": youtubeId == null ? null : youtubeId!,\n };\n}\n final dataList = {\n \"CourseLessonDetailsData\": [\n {\n \"request_status\": \"Successful\",\n \"ID\": \"24973\",\n \"LessonContentDetails\": [\n {\n \"TopicInfo\": [\n {\"ID\": \"2764\", \"CourseCode\": \"DTS\"}\n ],\n \"PreAssessment\": [],\n \"Video\": [\n {\"YoutubeId\": \"yt_id1\"}\n ]\n }\n ]\n },\n {\n \"request_status\": \"Successful\",\n \"ID\": \"24973\",\n \"LessonContentDetails\": [\n {\n \"TopicInfo\": [\n {\"ID\": \"2764\", \"CourseCode\": \"DTS\"}\n ],\n \"PreAssessment\": [],\n \"Video\": [\n {\"YoutubeId\": \"yt_id2\"}\n ]\n }\n ]\n },\n {\n \"request_status\": \"Successful\",\n \"ID\": \"24973\",\n \"LessonContentDetails\": [\n {\n \"TopicInfo\": [\n {\"ID\": \"2764\", \"CourseCode\": \"DTS\"}\n ],\n \"PreAssessment\": [],\n \"Video\": [\n {\"YoutubeId\": \"yt_id3\"}\n ]\n }\n ]\n }\n ]\n };\n/// This the the model which gonna hold the data\nfinal List<Model> models = [];\n/// Now lets create a another list to put the id\nfinal List<String> ids = [];\n\n runthisinOninit(){\n \n try {\n models.addAll(dataList[\"CourseLessonDetailsData\"]!\n .map((e) => Model.fromJson(e))\n .toList());\n } finally {\n for (var x in models) {\n final xy = x.lessonContentDetails!;\n\n if (xy.isNotEmpty) {\n for (var y in xy) {\n final xyz = y.video!;\n for (var z in xyz) {\n ids.add(z.youtubeId!);\n }\n }\n }\n }\n\n log(ids.toList().toString(),name:\"My ID LIST\");\n }\n\n}\n\n////as per result will be \n////[yt_id1, yt_id2, yt_id3]\n https://gist.github.com/Erchil66/47777fd92e9c3f194a3cd81b5d49111a\n"
},
{
"answer_id": 74637665,
"author": "Tahir",
"author_id": 6340327,
"author_profile": "https://Stackoverflow.com/users/6340327",
"pm_score": 0,
"selected": false,
"text": "List ytIdList = [];\nListView.builder(\n itemCount: snapshot.data!.courseLessonDetailsData!.length,\n itemBuilder: (context, index){\n ytIdList.add(snapshot.data!.courseLessonDetailsData![index].lessonContentDetails!.first.video!.first.youtubeId);\n // print(ytIdList);\n return Card();\n})\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9003022/"
] |
74,627,354
|
<p>I'm having trouble with my project to school. I want to create map in 2D array and push it inside vector. I just can't find the way how to do it. It should be this idea, but I don't know how to write it down. Anyone knows how to do it? Or can you find other solution? All should be OOP. Thanks!</p>
<pre><code>Map::Map()
{
// std::vector<std::vector<char>> m_map_library; - this is in .h
char mapa[4][5] = {
"####",
"####",
"####",
"####"
};
m_map_library.push_back(mapa);
}
</code></pre>
|
[
{
"answer_id": 74627751,
"author": "Arbiter Chil",
"author_id": 10782024,
"author_profile": "https://Stackoverflow.com/users/10782024",
"pm_score": 1,
"selected": false,
"text": "import 'dart:convert';\n\nModel modelFromJson(String str) => Model.fromJson(json.decode(str));\n\nString modelToJson(Model data) => json.encode(data.toJson());\n\nclass Model {\n Model({\n this.requestStatus,\n this.id,\n this.lessonContentDetails,\n });\n\n String? requestStatus;\n String? id;\n List<LessonContentDetail>? lessonContentDetails;\n\n factory Model.fromJson(Map<String, dynamic> json) => Model(\n requestStatus: json[\"request_status\"] == null ? null : json[\"request_status\"]!,\n id: json[\"ID\"] == null ? null : json[\"ID\"]!,\n lessonContentDetails: json[\"LessonContentDetails\"] == null ? null : List<LessonContentDetail>.from(json[\"LessonContentDetails\"].map((x) => LessonContentDetail.fromJson(x))),\n );\n\n Map<String, dynamic> toJson() => {\n \"request_status\": requestStatus == null ? null : requestStatus!,\n \"ID\": id == null ? null : id!,\n \"LessonContentDetails\": lessonContentDetails == null ? null : List<dynamic>.from(lessonContentDetails!.map((x) => x.toJson())),\n };\n}\n\nclass LessonContentDetail {\n LessonContentDetail({\n this.topicInfo,\n this.preAssessment,\n this.video,\n });\n\n List<TopicInfo>? topicInfo;\n List<dynamic>? preAssessment;\n List<Video>? video;\n\n factory LessonContentDetail.fromJson(Map<String, dynamic> json) => LessonContentDetail(\n topicInfo: json[\"TopicInfo\"] == null ? null : List<TopicInfo>.from(json[\"TopicInfo\"].map((x) => TopicInfo.fromJson(x))),\n preAssessment: json[\"PreAssessment\"] == null ? null : List<dynamic>.from(json[\"PreAssessment\"].map((x) => x)),\n video: json[\"Video\"] == null ? null : List<Video>.from(json[\"Video\"].map((x) => Video.fromJson(x))),\n );\n\n Map<String, dynamic> toJson() => {\n \"TopicInfo\": topicInfo == null ? null : List<dynamic>.from(topicInfo!.map((x) => x.toJson())),\n \"PreAssessment\": preAssessment == null ? null : List<dynamic>.from(preAssessment!.map((x) => x)),\n \"Video\": video == null ? null : List<dynamic>.from(video!.map((x) => x.toJson())),\n };\n}\n\nclass TopicInfo {\n TopicInfo({\n this.id,\n this.courseCode,\n });\n\n String? id;\n String? courseCode;\n\n factory TopicInfo.fromJson(Map<String, dynamic> json) => TopicInfo(\n id: json[\"ID\"] == null ? null : json[\"ID\"]!,\n courseCode: json[\"CourseCode\"] == null ? null : json[\"CourseCode\"]!,\n );\n\n Map<String, dynamic> toJson() => {\n \"ID\": id == null ? null : id!,\n \"CourseCode\": courseCode == null ? null : courseCode!,\n };\n}\n\nclass Video {\n Video({\n this.youtubeId,\n });\n\n String? youtubeId;\n\n factory Video.fromJson(Map<String, dynamic> json) => Video(\n youtubeId: json[\"YoutubeId\"] == null ? null : json[\"YoutubeId\"]!,\n );\n\n Map<String, dynamic> toJson() => {\n \"YoutubeId\": youtubeId == null ? null : youtubeId!,\n };\n}\n final dataList = {\n \"CourseLessonDetailsData\": [\n {\n \"request_status\": \"Successful\",\n \"ID\": \"24973\",\n \"LessonContentDetails\": [\n {\n \"TopicInfo\": [\n {\"ID\": \"2764\", \"CourseCode\": \"DTS\"}\n ],\n \"PreAssessment\": [],\n \"Video\": [\n {\"YoutubeId\": \"yt_id1\"}\n ]\n }\n ]\n },\n {\n \"request_status\": \"Successful\",\n \"ID\": \"24973\",\n \"LessonContentDetails\": [\n {\n \"TopicInfo\": [\n {\"ID\": \"2764\", \"CourseCode\": \"DTS\"}\n ],\n \"PreAssessment\": [],\n \"Video\": [\n {\"YoutubeId\": \"yt_id2\"}\n ]\n }\n ]\n },\n {\n \"request_status\": \"Successful\",\n \"ID\": \"24973\",\n \"LessonContentDetails\": [\n {\n \"TopicInfo\": [\n {\"ID\": \"2764\", \"CourseCode\": \"DTS\"}\n ],\n \"PreAssessment\": [],\n \"Video\": [\n {\"YoutubeId\": \"yt_id3\"}\n ]\n }\n ]\n }\n ]\n };\n/// This the the model which gonna hold the data\nfinal List<Model> models = [];\n/// Now lets create a another list to put the id\nfinal List<String> ids = [];\n\n runthisinOninit(){\n \n try {\n models.addAll(dataList[\"CourseLessonDetailsData\"]!\n .map((e) => Model.fromJson(e))\n .toList());\n } finally {\n for (var x in models) {\n final xy = x.lessonContentDetails!;\n\n if (xy.isNotEmpty) {\n for (var y in xy) {\n final xyz = y.video!;\n for (var z in xyz) {\n ids.add(z.youtubeId!);\n }\n }\n }\n }\n\n log(ids.toList().toString(),name:\"My ID LIST\");\n }\n\n}\n\n////as per result will be \n////[yt_id1, yt_id2, yt_id3]\n https://gist.github.com/Erchil66/47777fd92e9c3f194a3cd81b5d49111a\n"
},
{
"answer_id": 74637665,
"author": "Tahir",
"author_id": 6340327,
"author_profile": "https://Stackoverflow.com/users/6340327",
"pm_score": 0,
"selected": false,
"text": "List ytIdList = [];\nListView.builder(\n itemCount: snapshot.data!.courseLessonDetailsData!.length,\n itemBuilder: (context, index){\n ytIdList.add(snapshot.data!.courseLessonDetailsData![index].lessonContentDetails!.first.video!.first.youtubeId);\n // print(ytIdList);\n return Card();\n})\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14817982/"
] |
74,627,372
|
<p>I'm new in sql and i try to change my where conditions based on a column value in my select from Orcale table, like bellow:</p>
<pre><code>Select
a
,b
,c
,date_time
from t
where
condition_1
or condition_2
</code></pre>
<p>so the condition_2 is i want to check if the date_time column is like '<strong>date 00:00:00</strong>' so
i will do</p>
<pre><code>to_date(to_char(date_time,'yyyy-mm-dd'), 'yyyy-mm-dd') **>=**
to_date(to_char(to_date('2022-01-01 11:11:59','yyyy-mm-dd hh24:mi:ss'),'yyyy-mm-dd'),'yyyy-mm-dd')
</code></pre>
<p>if not then i will do this condition</p>
<pre><code>date_time **>** to_date('2022-01-01 11:11:59','yyyy-mm-dd hh24:mi:ss')
</code></pre>
<p>i tried to do it with case when inside my where but can not find the good logical way.</p>
<p>Can anyone help me please!
Thanks</p>
|
[
{
"answer_id": 74627751,
"author": "Arbiter Chil",
"author_id": 10782024,
"author_profile": "https://Stackoverflow.com/users/10782024",
"pm_score": 1,
"selected": false,
"text": "import 'dart:convert';\n\nModel modelFromJson(String str) => Model.fromJson(json.decode(str));\n\nString modelToJson(Model data) => json.encode(data.toJson());\n\nclass Model {\n Model({\n this.requestStatus,\n this.id,\n this.lessonContentDetails,\n });\n\n String? requestStatus;\n String? id;\n List<LessonContentDetail>? lessonContentDetails;\n\n factory Model.fromJson(Map<String, dynamic> json) => Model(\n requestStatus: json[\"request_status\"] == null ? null : json[\"request_status\"]!,\n id: json[\"ID\"] == null ? null : json[\"ID\"]!,\n lessonContentDetails: json[\"LessonContentDetails\"] == null ? null : List<LessonContentDetail>.from(json[\"LessonContentDetails\"].map((x) => LessonContentDetail.fromJson(x))),\n );\n\n Map<String, dynamic> toJson() => {\n \"request_status\": requestStatus == null ? null : requestStatus!,\n \"ID\": id == null ? null : id!,\n \"LessonContentDetails\": lessonContentDetails == null ? null : List<dynamic>.from(lessonContentDetails!.map((x) => x.toJson())),\n };\n}\n\nclass LessonContentDetail {\n LessonContentDetail({\n this.topicInfo,\n this.preAssessment,\n this.video,\n });\n\n List<TopicInfo>? topicInfo;\n List<dynamic>? preAssessment;\n List<Video>? video;\n\n factory LessonContentDetail.fromJson(Map<String, dynamic> json) => LessonContentDetail(\n topicInfo: json[\"TopicInfo\"] == null ? null : List<TopicInfo>.from(json[\"TopicInfo\"].map((x) => TopicInfo.fromJson(x))),\n preAssessment: json[\"PreAssessment\"] == null ? null : List<dynamic>.from(json[\"PreAssessment\"].map((x) => x)),\n video: json[\"Video\"] == null ? null : List<Video>.from(json[\"Video\"].map((x) => Video.fromJson(x))),\n );\n\n Map<String, dynamic> toJson() => {\n \"TopicInfo\": topicInfo == null ? null : List<dynamic>.from(topicInfo!.map((x) => x.toJson())),\n \"PreAssessment\": preAssessment == null ? null : List<dynamic>.from(preAssessment!.map((x) => x)),\n \"Video\": video == null ? null : List<dynamic>.from(video!.map((x) => x.toJson())),\n };\n}\n\nclass TopicInfo {\n TopicInfo({\n this.id,\n this.courseCode,\n });\n\n String? id;\n String? courseCode;\n\n factory TopicInfo.fromJson(Map<String, dynamic> json) => TopicInfo(\n id: json[\"ID\"] == null ? null : json[\"ID\"]!,\n courseCode: json[\"CourseCode\"] == null ? null : json[\"CourseCode\"]!,\n );\n\n Map<String, dynamic> toJson() => {\n \"ID\": id == null ? null : id!,\n \"CourseCode\": courseCode == null ? null : courseCode!,\n };\n}\n\nclass Video {\n Video({\n this.youtubeId,\n });\n\n String? youtubeId;\n\n factory Video.fromJson(Map<String, dynamic> json) => Video(\n youtubeId: json[\"YoutubeId\"] == null ? null : json[\"YoutubeId\"]!,\n );\n\n Map<String, dynamic> toJson() => {\n \"YoutubeId\": youtubeId == null ? null : youtubeId!,\n };\n}\n final dataList = {\n \"CourseLessonDetailsData\": [\n {\n \"request_status\": \"Successful\",\n \"ID\": \"24973\",\n \"LessonContentDetails\": [\n {\n \"TopicInfo\": [\n {\"ID\": \"2764\", \"CourseCode\": \"DTS\"}\n ],\n \"PreAssessment\": [],\n \"Video\": [\n {\"YoutubeId\": \"yt_id1\"}\n ]\n }\n ]\n },\n {\n \"request_status\": \"Successful\",\n \"ID\": \"24973\",\n \"LessonContentDetails\": [\n {\n \"TopicInfo\": [\n {\"ID\": \"2764\", \"CourseCode\": \"DTS\"}\n ],\n \"PreAssessment\": [],\n \"Video\": [\n {\"YoutubeId\": \"yt_id2\"}\n ]\n }\n ]\n },\n {\n \"request_status\": \"Successful\",\n \"ID\": \"24973\",\n \"LessonContentDetails\": [\n {\n \"TopicInfo\": [\n {\"ID\": \"2764\", \"CourseCode\": \"DTS\"}\n ],\n \"PreAssessment\": [],\n \"Video\": [\n {\"YoutubeId\": \"yt_id3\"}\n ]\n }\n ]\n }\n ]\n };\n/// This the the model which gonna hold the data\nfinal List<Model> models = [];\n/// Now lets create a another list to put the id\nfinal List<String> ids = [];\n\n runthisinOninit(){\n \n try {\n models.addAll(dataList[\"CourseLessonDetailsData\"]!\n .map((e) => Model.fromJson(e))\n .toList());\n } finally {\n for (var x in models) {\n final xy = x.lessonContentDetails!;\n\n if (xy.isNotEmpty) {\n for (var y in xy) {\n final xyz = y.video!;\n for (var z in xyz) {\n ids.add(z.youtubeId!);\n }\n }\n }\n }\n\n log(ids.toList().toString(),name:\"My ID LIST\");\n }\n\n}\n\n////as per result will be \n////[yt_id1, yt_id2, yt_id3]\n https://gist.github.com/Erchil66/47777fd92e9c3f194a3cd81b5d49111a\n"
},
{
"answer_id": 74637665,
"author": "Tahir",
"author_id": 6340327,
"author_profile": "https://Stackoverflow.com/users/6340327",
"pm_score": 0,
"selected": false,
"text": "List ytIdList = [];\nListView.builder(\n itemCount: snapshot.data!.courseLessonDetailsData!.length,\n itemBuilder: (context, index){\n ytIdList.add(snapshot.data!.courseLessonDetailsData![index].lessonContentDetails!.first.video!.first.youtubeId);\n // print(ytIdList);\n return Card();\n})\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9879904/"
] |
74,627,374
|
<p>I need to set max-width of a table-row. My CSS code:</p>
<pre><code>table tr {
max-width: 1580px;
margin-left: auto;
margin-right: auto;
padding-left: 50px;
padding-right: 50px;
}
</code></pre>
<p>Unfortunately it doesn't work, padding is seen in the browser, but it doesn't push it. Margin and max-width are not even seen in the browser - inspect/computed.</p>
|
[
{
"answer_id": 74627669,
"author": "Mohammed Alduraidi",
"author_id": 10063030,
"author_profile": "https://Stackoverflow.com/users/10063030",
"pm_score": -1,
"selected": false,
"text": "tr {\n max-width: 1580px;\n width:100%\n}\n\n\n\n \n"
},
{
"answer_id": 74629300,
"author": "Aviral Gupta",
"author_id": 20019318,
"author_profile": "https://Stackoverflow.com/users/20019318",
"pm_score": 0,
"selected": false,
"text": "tr{\n background: cyan;\n} <table>\n <tr>\n <th>Company</th>\n <th>Contact</th>\n <th>Country</th>\n </tr>\n <tr>\n <td>Alfreds Futterkiste</td>\n <td>Maria Anders</td>\n <td>Germany</td>\n </tr>\n <tr>\n <td>Centro comercial Moctezuma</td>\n <td>Francisco Chang</td>\n <td>Mexico</td>\n </tr>\n </table>"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19318284/"
] |
74,627,425
|
<p>The analysis of my C# project outputs a file in an (to me) unknown file format. I would like to convert the output of the analysis to fullhtml with <code>plog-converter</code>, but this tool does not understand the generated analysis output. The output looks like <a href="https://pastebin.com/qUbg3E2D" rel="nofollow noreferrer">this (pastebin link)</a>.</p>
<p>I have setup both the pvs core and dotnet package. Running <code>./pvs-studio-dotnet -t ~/Desktop/pvs-test/pvs-test.csproj -o analysis -r</code> seems to work, the exit code is 0. After converting the analysis output to fullhtml with <code>plog-converter</code>, the page looks like this:</p>
<p><a href="https://i.stack.imgur.com/rrrJ6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rrrJ6.png" alt="enter image description here" /></a></p>
<p>which does not seem correct.</p>
|
[
{
"answer_id": 74628421,
"author": "Kulikov Konstantin",
"author_id": 20099290,
"author_profile": "https://Stackoverflow.com/users/20099290",
"pm_score": 2,
"selected": true,
"text": "pvs-studio-dotnet -t ~/Desktop/pvs-test/pvs-test.csproj -o analysis.json -r\n plog-converter -t fullhtml -o ./fullhtml_folder analysis.json\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17788348/"
] |
74,627,442
|
<p>We don't talk enough about React state Management.
Managing the state is one of the most difficult parts of any react application. probably why there are many state management libraries available and more coming around every day. introduction of redux has helped in the management of props drilling but the question now is which state management is better.. of recent I have had tech friends from other companies suggesting I try .. X-STATE rather than redux other say context.. redux works for me but sometimes can be a bit complicated .. want to hear from you guys</p>
<p>i have tried redux toolkit as well and seem like a good choice but will like to know what developers using xstate and context api think .. best from someeone who has used both redux and any of this two</p>
|
[
{
"answer_id": 74627470,
"author": "Adam",
"author_id": 954940,
"author_profile": "https://Stackoverflow.com/users/954940",
"pm_score": 1,
"selected": false,
"text": "useState useState useState"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6019596/"
] |
74,627,493
|
<p>The same 2 errors appear in 2 different files when I run my flutter program, does anyone know how to fix this? this is my code</p>
<p>code for list restaurant.dart</p>
<pre><code>import 'package:flutter/material.dart';
import 'package:resto_app/data/model/restaurant_list.dart';
import 'package:resto_app/ui/detail_page.dart';
class CardRestaurant extends StatelessWidget {
final Restaurant restaurant;
const CardRestaurant({Key? key, required this.restaurant}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: InkWell(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) {
return RestaurantDetailPage(idrestaurant: restaurant.id);
}));
},
child: Stack(
children: <Widget>[
Container(
margin:
const EdgeInsets.only(left: 40, top: 5, right: 20, bottom: 5),
height: 170.0,
width: double.infinity,
decoration: BoxDecoration(
color: Colors.lime.shade100,
borderRadius: BorderRadius.circular(20.0),
),
child: Padding(
padding: const EdgeInsets.only(
left: 200, top: 20, right: 20, bottom: 20),
child: Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(
width: 120.0,
child: Expanded(child: Text(restaurant.name)),
),
_sizebox(10),
Row(
children: [
_icon(Icons.star_rate, 20, Colors.yellow),
Text(
' ${restaurant.rating}',
),
],
)
],
),
),
),
),
Positioned(
left: 20.0,
top: 15.0,
bottom: 15.0,
child: ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: Hero(
tag: restaurant.pictureId,
child: Image.network(
"https://restaurant-api.dicoding.dev/images/small/" +
restaurant.pictureId,
width: 200,
fit: BoxFit.cover,
),
),
),
),
],
),
),
);
}
}
Widget _sizebox(double height) {
return SizedBox(
height: height,
);
}
Widget _icon(IconData icon, double size, Color color) {
return Icon(
icon,
size: size,
color: color,
);
}
</code></pre>
<p>and my detailrestaurant.dart code</p>
<p>`</p>
<pre><code>`import 'package:flutter/material.dart';
import 'package:resto_app/data/model/restaurants_detail.dart';
import 'package:resto_app/common/constant.dart';
class RestaurantDetail extends StatelessWidget {
static const routeName = '/restaurant_detail';
final Restaurant restaurant;
const RestaurantDetail({Key? key, required this.restaurant})
: super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Hero(
tag: restaurant.pictureId,
child: Image.network(
"https://restaurant-api.dicoding.dev/images/medium/" +
restaurant.pictureId,
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(restaurant.name),
_sizebox(10),
Row(
children: [
_icon(Icons.location_city, 20, Colors.grey),
const SizedBox(
width: 10,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(restaurant.city),
Text(restaurant.address),
],
)
],
),
],
),
Row(
children: [
_icon(Icons.star_rate, 20, Colors.yellow),
Text(
' ${restaurant.rating}',
),
],
)
],
),
),
_barrierContent(),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding:
const EdgeInsets.only(top: 10, right: 20, left: 20),
child: Text('Description'),
),
Container(
padding: const EdgeInsets.only(
top: 10, right: 20, left: 20, bottom: 20),
width: double.infinity,
child: Text(restaurant.description)),
],
),
_barrierContent(),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10, horizontal: 20),
child: Column(
children: [
Text('Category'),
ListBody(
children: restaurant.categories.map((food) {
return Text(
'- ${food.name}',
);
}).toList(),
),
],
),
),
_barrierContent(),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10, horizontal: 20),
child: Column(
children: [
Text('Menu Food'),
ListBody(
children: restaurant.menus.foods.map((categori) {
return Text(
'- ${categori.name}',
);
}).toList(),
),
],
),
),
_barrierContent(),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10, horizontal: 20),
child: Column(
children: [
Text('Menu Drink'),
ListBody(
children: restaurant.menus.drinks.map((drink) {
return Text('- ${drink.name}');
}).toList(),
),
],
),
),
_barrierContent(),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10, horizontal: 10),
child: Column(
children: [
Text('Comment'),
ListBody(
children: restaurant.customerReviews.map((review) {
return Padding(
padding: const EdgeInsets.all(16.0),
child: Expanded(
child: Row(children: [
Container(
width: 40,
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.blue),
child: Center(
child: Text(
review.name.characters.elementAt(0),
style: const TextStyle(
color: Colors.white, fontSize: 20),
)),
),
const SizedBox(
width: 15,
),
Expanded(
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
review.name,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold),
),
Text(
' ${review.date}',
style: TextStyle(
fontSize: 14,
color: Colors.grey.shade500),
)
],
),
SizedBox(
width: 270,
child: Text(
review.review,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
)
],
),
)
]),
),
);
}).toList(),
),
],
),
),
_barrierContent()
],
),
],
),
),
),
);
}
}
Widget _barrierContent() {
return Container(
height: 10,
color: Colors.grey.shade200,
);
}
Widget _sizebox(double height) {
return SizedBox(
height: height,
);
}
Widget _icon(IconData icon, double size, Color color) {
return Icon(
icon,
size: size,
color: color,
);
}
</code></pre>
<p>`</p>
<p>``</p>
<p>error
The same 2 errors appear in 2 different files when I run my flutter program, does anyone know how to fix this?</p>
<p><a href="https://i.stack.imgur.com/9RTBj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9RTBj.png" alt="Error" /></a></p>
|
[
{
"answer_id": 74627470,
"author": "Adam",
"author_id": 954940,
"author_profile": "https://Stackoverflow.com/users/954940",
"pm_score": 1,
"selected": false,
"text": "useState useState useState"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20004053/"
] |
74,627,501
|
<p>Why the variables a, c, d have not changed, but b has changed?</p>
<pre><code>a = 0
b = []
c = []
d = 'a'
def func_a(a):
a += 1
def func_b(b):
b += [1]
def func_c(c):
c = [2]
def func_d(d):
d += 'd'
func_a(a)
func_b(b)
func_c(c)
func_d(d)
print('a = ', a)
print('b = ', b)
print('c = ', c)
print('d = ', d)
</code></pre>
<p>I think it has to do with the fact that all variables are global, but I don't understand why b changes then..</p>
|
[
{
"answer_id": 74627470,
"author": "Adam",
"author_id": 954940,
"author_profile": "https://Stackoverflow.com/users/954940",
"pm_score": 1,
"selected": false,
"text": "useState useState useState"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20644688/"
] |
74,627,514
|
<p><a href="https://i.stack.imgur.com/Baufs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Baufs.png" alt="enter image description here" /></a></p>
<p>I don't know how to change the grey color of overdue dates. For me there is not enough contrast between past date, future date and today's date.</p>
|
[
{
"answer_id": 74662920,
"author": "jraufeisen",
"author_id": 2641242,
"author_profile": "https://Stackoverflow.com/users/2641242",
"pm_score": 2,
"selected": false,
"text": "CupertinoDatePicker TextStyle _themeTextStyle(BuildContext context, { bool isValid = true }) {\n final TextStyle style = CupertinoTheme.of(context).textTheme.dateTimePickerTextStyle;\n return isValid\n ? style.copyWith(color: CupertinoDynamicColor.maybeResolve(style.color, context))\n : style.copyWith(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context));\n}\n CupertinoTheme textTheme.dateTimePickerTextStyle "
},
{
"answer_id": 74663312,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 0,
"selected": false,
"text": "CupertinoDatePicker CupertinoDatePicker // ...\n child: CupertinoDatePicker(\n onDateTimeChanged: (date) {},\n ),\n // ...\n const Widget _startSelectionOverlay = CupertinoPickerDefaultSelectionOverlay(capEndEdge: false);\nconst Widget _centerSelectionOverlay = CupertinoPickerDefaultSelectionOverlay(capStartEdge: false, capEndEdge: false);\nconst Widget _endSelectionOverlay = CupertinoPickerDefaultSelectionOverlay(capStartEdge: false);\n CupertinoPickerDefaultSelectionOverlay /// default margin and use rounded corners on the left and right side of the\n /// rectangular overlay.\n /// Default to true and must not be null.\n const CupertinoPickerDefaultSelectionOverlay({\n super.key,\n this.background = CupertinoColors.tertiarySystemFill,\n this.capStartEdge = true,\n this.capEndEdge = true,\n }) : assert(background != null),\n assert(capStartEdge != null),\n assert(capEndEdge != null);\n Color this.background = const Color.fromARGB(49, 0, 253, 30),\n Colors.red Colors.green const"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9611719/"
] |
74,627,520
|
<p>I am trying to use fill down function available in power query to replace black cells with previous values.
Below is the sample of data I am working on;</p>
<p><a href="https://i.stack.imgur.com/ueVft.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ueVft.png" alt="enter image description here" /></a></p>
<p>The goal is to repeat values in column Status for respective IDs. Using Fill down would be easy except for the coloured instances as there is no value against those IDs and I would want them blank as there is no value for them.</p>
<p>The desired output is as follows;</p>
<p><a href="https://i.stack.imgur.com/3N62l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3N62l.png" alt="enter image description here" /></a></p>
<p>Is there is DAX formula which I can use to justify the need?</p>
<p>Truly appreciate your help.</p>
|
[
{
"answer_id": 74662920,
"author": "jraufeisen",
"author_id": 2641242,
"author_profile": "https://Stackoverflow.com/users/2641242",
"pm_score": 2,
"selected": false,
"text": "CupertinoDatePicker TextStyle _themeTextStyle(BuildContext context, { bool isValid = true }) {\n final TextStyle style = CupertinoTheme.of(context).textTheme.dateTimePickerTextStyle;\n return isValid\n ? style.copyWith(color: CupertinoDynamicColor.maybeResolve(style.color, context))\n : style.copyWith(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context));\n}\n CupertinoTheme textTheme.dateTimePickerTextStyle "
},
{
"answer_id": 74663312,
"author": "Gwhyyy",
"author_id": 18670641,
"author_profile": "https://Stackoverflow.com/users/18670641",
"pm_score": 0,
"selected": false,
"text": "CupertinoDatePicker CupertinoDatePicker // ...\n child: CupertinoDatePicker(\n onDateTimeChanged: (date) {},\n ),\n // ...\n const Widget _startSelectionOverlay = CupertinoPickerDefaultSelectionOverlay(capEndEdge: false);\nconst Widget _centerSelectionOverlay = CupertinoPickerDefaultSelectionOverlay(capStartEdge: false, capEndEdge: false);\nconst Widget _endSelectionOverlay = CupertinoPickerDefaultSelectionOverlay(capStartEdge: false);\n CupertinoPickerDefaultSelectionOverlay /// default margin and use rounded corners on the left and right side of the\n /// rectangular overlay.\n /// Default to true and must not be null.\n const CupertinoPickerDefaultSelectionOverlay({\n super.key,\n this.background = CupertinoColors.tertiarySystemFill,\n this.capStartEdge = true,\n this.capEndEdge = true,\n }) : assert(background != null),\n assert(capStartEdge != null),\n assert(capEndEdge != null);\n Color this.background = const Color.fromARGB(49, 0, 253, 30),\n Colors.red Colors.green const"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10631960/"
] |
74,627,538
|
<p>username is saving but information such as first_name, email and etc are not.</p>
<pre><code>`from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from rest_framework import serializers
class RegisterSerializer(serializers.ModelSerializer):
email = serializers.CharField(required=True)
first_name = serializers.CharField(max_length=50, required=True)
last_name = serializers.CharField(max_length=50, required=True)
password = serializers.CharField(
write_only=True, required=True, validators=[validate_password])
password2 = serializers.CharField(write_only=True, required=True)
is_admin = serializers.BooleanField(default=False)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email',
'password', 'password2', 'is_admin')
def validate(self, attrs):
if attrs['password'] != attrs['password2']:
raise serializers.ValidationError(
{"password": "Password fields didn't match."})
return attrs
def create(self, validated_data):
user = User.objects.create(
username=validated_data['username']
)
user.set_password(validated_data['password'])
user.save()
return user`
</code></pre>
<p>i have searched online for hours, but have not managed to make much progress. if someone could elaborate on my issue and explain what I have done wrong that would be greatly appreciated</p>
|
[
{
"answer_id": 74627650,
"author": "Sezer BOZKIR",
"author_id": 5942941,
"author_profile": "https://Stackoverflow.com/users/5942941",
"pm_score": 0,
"selected": false,
"text": "def create(self, validated_data):\n user = User.objects.create(\n username=validated_data['username'],\n first_name=validated_data['first_name'], # <-- add here to all necessary parameters like this\n )\n\n user.set_password(validated_data['password'])\n user.save()\n"
},
{
"answer_id": 74627674,
"author": "ShiBil PK",
"author_id": 12478660,
"author_profile": "https://Stackoverflow.com/users/12478660",
"pm_score": 2,
"selected": true,
"text": "user = User.objects.create(\n username=validated_data['username'], \n first_name =validated_data['first_name'],\n last_name =validated_data['last_name'], \n # Add other fields here\n)\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14372027/"
] |
74,627,570
|
<p>Please help me to find the solution for below error. i have tried using imap and pop3 setting, below are the configuration settings i have used</p>
<p>pop3:</p>
<p>Server name: outlook.office365.com</p>
<p>Port: 995</p>
<p>imap:</p>
<p>Server name: outlook.office365.com</p>
<p>Port: 993</p>
<p>Error im getting:</p>
<p>Exception in component tPOP_1 (test)</p>
<p>javax.mail.MessagingException: Connection timed out: connect;</p>
<p>nested exception is:</p>
<p>java.net.ConnectException: Connection timed out: connect</p>
<p>at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:479)</p>
<p>at javax.mail.Service.connect(Service.java:275)</p>
<p>at javax.mail.Service.connect(Service.java:156)</p>
<p>at javax.mail.Service.connect(Service.java:105)</p>
<p>at accor.test_0_1.test.tPOP_1Process(test.java:769)</p>
<p>at accor.test_0_1.test.runJobInTOS(test.java:4959)</p>
<p>at accor.test_0_1.test.main(test.java:4727)</p>
<p>Caused by: java.net.ConnectException: Connection timed out: connect</p>
<p>at java.net.DualStackPlainSocketImpl.connect0(Native Method)</p>
<p>at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)</p>
<p>at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)</p>
<p>at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)</p>
<p>at java.net.AbstractPlainSocketImpl.connect(Unknown Source)</p>
<p>at java.net.PlainSocketImpl.connect(Unknown Source)</p>
<p>at java.net.SocksSocketImpl.connect(Unknown Source)</p>
<p>[FATAL]: accor.test_0_1.test - tPOP_1 Connection timed out: connect</p>
<p>Attached is the tpop component settings i have used.</p>
<p><a href="https://i.stack.imgur.com/ObQsb.png" rel="nofollow noreferrer">tpop component settings</a></p>
<p>configuration settings i have used</p>
<p>pop3:</p>
<p>Server name: outlook.office365.com</p>
<p>Port: 995</p>
<p>imap:</p>
<p>Server name: outlook.office365.com</p>
<p>Port: 993</p>
|
[
{
"answer_id": 74638984,
"author": "Amine Ben Khelifa",
"author_id": 9674760,
"author_profile": "https://Stackoverflow.com/users/9674760",
"pm_score": 1,
"selected": false,
"text": "-Dmail.imap.auth.plain.disable=true"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12104796/"
] |
74,627,581
|
<p>I have a data frame called 'data' that contains multiple columns:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">Grade</th>
<th style="text-align: center;">EMPID</th>
<th style="text-align: center;">PayBand</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">A</td>
<td style="text-align: center;">12345</td>
<td style="text-align: center;">15001-20000</td>
</tr>
<tr>
<td style="text-align: center;">c</td>
<td style="text-align: center;">64859</td>
<td style="text-align: center;">30001-35000</td>
</tr>
<tr>
<td style="text-align: center;">A</td>
<td style="text-align: center;">61245</td>
<td style="text-align: center;">20001-25000</td>
</tr>
<tr>
<td style="text-align: center;">D</td>
<td style="text-align: center;">75134</td>
<td style="text-align: center;">45001-50000</td>
</tr>
<tr>
<td style="text-align: center;">D</td>
<td style="text-align: center;">78451</td>
<td style="text-align: center;">40001-45000</td>
</tr>
<tr>
<td style="text-align: center;">C</td>
<td style="text-align: center;">31645</td>
<td style="text-align: center;">30001-35000</td>
</tr>
<tr>
<td style="text-align: center;">A</td>
<td style="text-align: center;">62513</td>
<td style="text-align: center;">20001-25000</td>
</tr>
<tr>
<td style="text-align: center;">D</td>
<td style="text-align: center;">91843</td>
<td style="text-align: center;">25001-30000</td>
</tr>
<tr>
<td style="text-align: center;">D</td>
<td style="text-align: center;">91648</td>
<td style="text-align: center;">35001-40000</td>
</tr>
</tbody>
</table>
</div>
<p>I need R code to create a data frame that counts the number of each Grade within each PayBand that looks like this. E.g:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">PayBand</th>
<th style="text-align: center;">A</th>
<th style="text-align: center;">C</th>
<th style="text-align: center;">D</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">15001-20000</td>
<td style="text-align: center;">1</td>
<td style="text-align: center;">0</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td style="text-align: center;">20001-25000</td>
<td style="text-align: center;">2</td>
<td style="text-align: center;">0</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td style="text-align: center;">25001-30000</td>
<td style="text-align: center;">0</td>
<td style="text-align: center;">0</td>
<td style="text-align: center;">1</td>
</tr>
<tr>
<td style="text-align: center;">30001-35000</td>
<td style="text-align: center;">0</td>
<td style="text-align: center;">2</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td style="text-align: center;">35001-40000</td>
<td style="text-align: center;">0</td>
<td style="text-align: center;">0</td>
<td style="text-align: center;">1</td>
</tr>
<tr>
<td style="text-align: center;">40001-45000</td>
<td style="text-align: center;">0</td>
<td style="text-align: center;">0</td>
<td style="text-align: center;">1</td>
</tr>
<tr>
<td style="text-align: center;">45001-50000</td>
<td style="text-align: center;">0</td>
<td style="text-align: center;">0</td>
<td style="text-align: center;">1</td>
</tr>
</tbody>
</table>
</div>
<p>I am unsure how to create the new dataframe and the new columns that are based off the first dataframe. Any help is much appreciated.</p>
|
[
{
"answer_id": 74638984,
"author": "Amine Ben Khelifa",
"author_id": 9674760,
"author_profile": "https://Stackoverflow.com/users/9674760",
"pm_score": 1,
"selected": false,
"text": "-Dmail.imap.auth.plain.disable=true"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17490257/"
] |
74,627,629
|
<p>I'm not sure what's wrong here, as far as I can tell I am doing this correctly as it has worked everywhere else in my app. The only difference is that I'm trying to do this from a FlatList component. What is wrong with this? I've also tried putting {navigation} in renderMyItem instead of FLToyCard brackets, didn't work either. Error I'm getting is:
<code>TypeError: undefined is not an object (evaluating 'navigation.navigate')</code>.</p>
<pre><code>import { StyleSheet, Text, View, FlatList } from 'react-native'
import React from 'react'
import Toy from './Database'
import ToyCard from './ToyCard'
const FLToyCard = ({navigation}) => {
const headerComp = () => {
return(
<View style={{alignSelf: 'center'}}>
<Text style={{fontSize: 25, padding: 10}}>All Toys For Sale</Text>
</View>
)
}
const renderMyItem = ({item}) => {
return(
<View style={{flex: 1}}>
<ToyCard
name={item.name}
image={item.image}
price={item.price}
desc={item.desc}
seller={item.seller}
onPress={()=>navigation.navigate('SlugProduct')}
/>
</View>
)
}
return(
<View>
<FlatList
data={Toy}
renderItem={renderMyItem}
keyExtractor={(item)=>item.id}
numColumns={2}
ListHeaderComponent={headerComp}
/>
</View>
)
}
export default FLToyCard
</code></pre>
<p>This is my App.js:</p>
<pre><code>import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native'
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import SlugProduct from './Screens/SlugProduct';
export default function App() {
const Stack = createNativeStackNavigator()
return (
<NavigationContainer>
<Stack.Navigator initialRouteName='Login' >
// list of other pages
<Stack.Screen name="SlugProduct" component={SlugProduct} />
<Stack.Screen name='ViewToys' component={ViewToys}
</Stack.Navigator>
</NavigationContainer>
);
}
</code></pre>
<p>EDIT: heres the ViewToys page that FLToyCard is being input into. I've tried adding the onPress into both Views and FLToyCard but got the same error each time.</p>
<pre><code>import { StyleSheet, Text, View, ScrollView} from 'react-native'
import React from 'react'
import FLToyCard from '../Components/FlatListCards'
const ViewToys = ({navigation}) => {
return (
<View style={{backgroundColor: '#ffce20', height: '100%'}}>
<View>
<FLToyCard />
</View>
</View>
)
}
export default ViewToys
</code></pre>
|
[
{
"answer_id": 74627799,
"author": "Alpha",
"author_id": 13701584,
"author_profile": "https://Stackoverflow.com/users/13701584",
"pm_score": 2,
"selected": true,
"text": "navigation props import { StyleSheet, Text, View, ScrollView} from 'react-native'\nimport React from 'react'\n\nimport FLToyCard from '../Components/FlatListCards'\n\nconst ViewToys = ({navigation}) => {\n return (\n <View style={{backgroundColor: '#ffce20', height: '100%'}}>\n <View>\n <FLToyCard navigation={navigation}/>\n </View>\n </View>\n )\n}\n\nexport default ViewToys\n"
},
{
"answer_id": 74627822,
"author": "NAZIR HUSSAIN",
"author_id": 20587701,
"author_profile": "https://Stackoverflow.com/users/20587701",
"pm_score": 1,
"selected": false,
"text": " <FLToyCard /> <FLToyCard navigation={navigation} />"
},
{
"answer_id": 74629159,
"author": "rafiulah",
"author_id": 17426448,
"author_profile": "https://Stackoverflow.com/users/17426448",
"pm_score": -1,
"selected": false,
"text": " import { NavigationContainer,useFocusEffect } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack';"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19299100/"
] |
74,627,657
|
<p>My goal is to create a faded blue circle on black background.</p>
<p>However, there is a white square surrounding the circle, and it doesn't look good.</p>
<p>What can I do to get rid of this white background?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
background-color: black;
}
.circle {
border-radius: 50%;
width: 200px;
height: 200px;
background-color: blue;
}
.circle:after {
content: "";
display: block;
width: 100%;
height: 100%;
background-image: radial-gradient(ellipse at center center, rgba(0, 0, 0, 0) 0%, rgba(255, 255, 255, 1) 70%, rgba(255, 255, 255, 1) 100%);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="circle"> </div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74627799,
"author": "Alpha",
"author_id": 13701584,
"author_profile": "https://Stackoverflow.com/users/13701584",
"pm_score": 2,
"selected": true,
"text": "navigation props import { StyleSheet, Text, View, ScrollView} from 'react-native'\nimport React from 'react'\n\nimport FLToyCard from '../Components/FlatListCards'\n\nconst ViewToys = ({navigation}) => {\n return (\n <View style={{backgroundColor: '#ffce20', height: '100%'}}>\n <View>\n <FLToyCard navigation={navigation}/>\n </View>\n </View>\n )\n}\n\nexport default ViewToys\n"
},
{
"answer_id": 74627822,
"author": "NAZIR HUSSAIN",
"author_id": 20587701,
"author_profile": "https://Stackoverflow.com/users/20587701",
"pm_score": 1,
"selected": false,
"text": " <FLToyCard /> <FLToyCard navigation={navigation} />"
},
{
"answer_id": 74629159,
"author": "rafiulah",
"author_id": 17426448,
"author_profile": "https://Stackoverflow.com/users/17426448",
"pm_score": -1,
"selected": false,
"text": " import { NavigationContainer,useFocusEffect } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack';"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20621572/"
] |
74,627,729
|
<p><strong>What is the Goal?:</strong>
I want to know the new Coordinates of a point after rotating the 3D-Object (Cuboid), around the anchorpoint (x,y & z) on the opposite side.</p>
<p><strong>What i did:</strong>
I tried to calculate the position with the following function. I had to convert <code>doubles</code> to <code>floats</code> , because of the Autodesk Inventor API. Note: <code>Vector</code> is the difference from the <code>origin</code> /anchorpoint to the designated point.</p>
<pre><code>Vector3 coordinateTransformation(Vector3 vector, float r_x, float r_y, float r_z, Vector3 origin)
{
vector.X = vector.X; //Just for demonstration
vector.Y = vector.Y * Convert.ToSingle(Math.Cos(DegreesToRadians(r_x))) - vector.Z * Convert.ToSingle(Math.Sin(DegreesToRadians(r_x)));
vector.Z = vector.Y * Convert.ToSingle(Math.Sin(DegreesToRadians(r_x))) + vector.Z * Convert.ToSingle(Math.Cos(DegreesToRadians(r_x)));
vector.X = vector.X * Convert.ToSingle(Math.Cos(DegreesToRadians(r_y))) + vector.Z * Convert.ToSingle(Math.Sin(DegreesToRadians(r_y)));
vector.Y = vector.Y; //Just for demonstration
vector.Z = vector.Z * Convert.ToSingle(Math.Cos(DegreesToRadians(r_y))) - vector.X * Convert.ToSingle(Math.Sin(DegreesToRadians(r_y)));
vector.X = vector.X * Convert.ToSingle(Math.Cos(DegreesToRadians(r_z))) - vector.Y * Convert.ToSingle(Math.Sin(DegreesToRadians(r_z)));
vector.Y = vector.X * Convert.ToSingle(Math.Sin(DegreesToRadians(r_z))) + vector.Y * Convert.ToSingle(Math.Cos(DegreesToRadians(r_z)));
vector.Z = vector.Z; //Just for demonstration
vector.X = Math.Abs(vector.X) + origin.X;
vector.Y = Math.Abs(vector.Y) + origin.Y;
vector.Z = Math.Abs(vector.Z) + origin.Z;
return vector;
}
</code></pre>
<p>Somehow the object does not get placed on the correct place.</p>
<p><strong>Next step:</strong> On the internet i found a website which does the correct transformation.<a href="https://keisan.casio.com/exec/system/15362817755710" rel="nofollow noreferrer">Casio Website</a>
If i manually set <code>vector</code> to the calculated point on the website, everything else works fine. <strong>So i somehow have to get the exact same calculation into my code.</strong></p>
<p>If you need further information, feel free to comment!</p>
<p><strong>Edit:</strong>
<strong>1 :</strong> I want to place 2 Objects (e.g. Cuboids) within 1 Assembly Group in Inventor. Every Object as an anchorpoint (origin) and on the opposite side a connection point, which is described as the delta between the anchorpoint and the connection point itself. At first one Object is placed on the origin coordinates, followed by a rotation around the anchorpoint (degrees). After that the connection point coordinates of Object 1 have changed. In the next step i want to place Object 2 with its origin on the connection point of Object 1, while Object 2 has the same rotation as Object 1.
<strong>2 :</strong> Inventor uses a right-handed coordinate system</p>
|
[
{
"answer_id": 74627799,
"author": "Alpha",
"author_id": 13701584,
"author_profile": "https://Stackoverflow.com/users/13701584",
"pm_score": 2,
"selected": true,
"text": "navigation props import { StyleSheet, Text, View, ScrollView} from 'react-native'\nimport React from 'react'\n\nimport FLToyCard from '../Components/FlatListCards'\n\nconst ViewToys = ({navigation}) => {\n return (\n <View style={{backgroundColor: '#ffce20', height: '100%'}}>\n <View>\n <FLToyCard navigation={navigation}/>\n </View>\n </View>\n )\n}\n\nexport default ViewToys\n"
},
{
"answer_id": 74627822,
"author": "NAZIR HUSSAIN",
"author_id": 20587701,
"author_profile": "https://Stackoverflow.com/users/20587701",
"pm_score": 1,
"selected": false,
"text": " <FLToyCard /> <FLToyCard navigation={navigation} />"
},
{
"answer_id": 74629159,
"author": "rafiulah",
"author_id": 17426448,
"author_profile": "https://Stackoverflow.com/users/17426448",
"pm_score": -1,
"selected": false,
"text": " import { NavigationContainer,useFocusEffect } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack';"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19288804/"
] |
74,627,754
|
<p>I have a column in my dataframe from a survey that has two different units in it. I need to remove these and convert the info into a consistent unit ie a column of all cm without the unit being present.</p>
<p>Here is some sample data</p>
<pre><code>df <- data.frame(v1 = c('100 cm', '6 foot 10', '200 cm', '5 foot 11')
</code></pre>
<p>I attempted to use this readr::parse_number(df$v1) but that would turn '6 foot 10' into 6. I'm not sure it's that helpful anyway because I still need to convert the heights recorded as feet and inches into cm</p>
|
[
{
"answer_id": 74627799,
"author": "Alpha",
"author_id": 13701584,
"author_profile": "https://Stackoverflow.com/users/13701584",
"pm_score": 2,
"selected": true,
"text": "navigation props import { StyleSheet, Text, View, ScrollView} from 'react-native'\nimport React from 'react'\n\nimport FLToyCard from '../Components/FlatListCards'\n\nconst ViewToys = ({navigation}) => {\n return (\n <View style={{backgroundColor: '#ffce20', height: '100%'}}>\n <View>\n <FLToyCard navigation={navigation}/>\n </View>\n </View>\n )\n}\n\nexport default ViewToys\n"
},
{
"answer_id": 74627822,
"author": "NAZIR HUSSAIN",
"author_id": 20587701,
"author_profile": "https://Stackoverflow.com/users/20587701",
"pm_score": 1,
"selected": false,
"text": " <FLToyCard /> <FLToyCard navigation={navigation} />"
},
{
"answer_id": 74629159,
"author": "rafiulah",
"author_id": 17426448,
"author_profile": "https://Stackoverflow.com/users/17426448",
"pm_score": -1,
"selected": false,
"text": " import { NavigationContainer,useFocusEffect } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack';"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20623966/"
] |
74,627,757
|
<p>How can I limit the hover effect time in html, I tried to make a code like below, so that the hover effect disappears after a while</p>
<pre><code><div class="hover">Hover me!</div>
<style>
.hover {
cursor: pointer;
-webkit-tap-highlight-color: transparent;
background: green;
}
.hover:active {
background: red;
// maximum hover time of 3 seconds
}
</style>
</code></pre>
<p>Please help me with main code as above</p>
|
[
{
"answer_id": 74627799,
"author": "Alpha",
"author_id": 13701584,
"author_profile": "https://Stackoverflow.com/users/13701584",
"pm_score": 2,
"selected": true,
"text": "navigation props import { StyleSheet, Text, View, ScrollView} from 'react-native'\nimport React from 'react'\n\nimport FLToyCard from '../Components/FlatListCards'\n\nconst ViewToys = ({navigation}) => {\n return (\n <View style={{backgroundColor: '#ffce20', height: '100%'}}>\n <View>\n <FLToyCard navigation={navigation}/>\n </View>\n </View>\n )\n}\n\nexport default ViewToys\n"
},
{
"answer_id": 74627822,
"author": "NAZIR HUSSAIN",
"author_id": 20587701,
"author_profile": "https://Stackoverflow.com/users/20587701",
"pm_score": 1,
"selected": false,
"text": " <FLToyCard /> <FLToyCard navigation={navigation} />"
},
{
"answer_id": 74629159,
"author": "rafiulah",
"author_id": 17426448,
"author_profile": "https://Stackoverflow.com/users/17426448",
"pm_score": -1,
"selected": false,
"text": " import { NavigationContainer,useFocusEffect } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack';"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19799462/"
] |
74,627,817
|
<p>I have created a list view with images in flutter. it works but the images is wrong size. It looks like this:</p>
<p><a href="https://i.stack.imgur.com/AXINc.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AXINc.jpg" alt="enter image description here" /></a></p>
<p>But what I want is this:</p>
<p><a href="https://i.stack.imgur.com/eDwnu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eDwnu.png" alt="enter image description here" /></a></p>
<p>This is the code I am using:</p>
<pre><code>SizedBox(
height: 300,
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemBuilder: (BuildContext ctx, int index) {
return SizedBox(
width: MediaQuery.of(context).size.width * 0.5,
child: Card(
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.file(
File(_imageFileListM[index].path),
fit: BoxFit.fitWidth,
),
),
margin: const EdgeInsets.all(10),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
));
},
itemCount: _imageFileListM.length,
))
</code></pre>
<p>What am I doing wrong?</p>
|
[
{
"answer_id": 74628105,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "SizedBox(\n height: 300,\n child: ListView.builder(\n shrinkWrap: true,\n scrollDirection: Axis.horizontal,\n itemBuilder: (BuildContext ctx, int index) {\n return SizedBox(\n width: MediaQuery.of(context).size.width * 0.5,\n child: Card(\n elevation: 0,\n color: Colors.transparent,\n surfaceTintColor: Colors.transparent,\n child: Align(\n alignment: Alignment.center,\n child: Container(\n clipBehavior: Clip.antiAlias,\n decoration: BoxDecoration(\n color: Colors.transparent,\n borderRadius: BorderRadius.circular(10),\n ),\n child: Image.file(\n File(_imageFileListM[index].path),\n fit: BoxFit.contain,\n ),\n ),\n ),\n margin: const EdgeInsets.all(10),\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(20.0),\n ),\n ));\n },\n itemCount: _imageFileListM.length,\n )),\n"
},
{
"answer_id": 74628153,
"author": "Ante Bule",
"author_id": 17104517,
"author_profile": "https://Stackoverflow.com/users/17104517",
"pm_score": 0,
"selected": false,
"text": "FittedBox SizedBox(\n height: 300,\n child: ListView.builder(\n shrinkWrap: true,\n scrollDirection: Axis.horizontal,\n itemBuilder: (BuildContext ctx, int index) {\n return SizedBox(\n width: MediaQuery.of(context).size.width * 0.5,\n child: FittedBox(\n child: Card(\n child: ClipRRect(\n borderRadius: BorderRadius.circular(20),\n child: Image.file(\n File(_imageFileListM[index].path),\n fit: BoxFit.fitWidth,\n ),\n ),\n margin: const EdgeInsets.all(10),\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(20.0),\n ),\n ),\n ));\n },\n itemCount: _imageFileListM.length,\n )))\n"
},
{
"answer_id": 74628971,
"author": "Phil",
"author_id": 7270457,
"author_profile": "https://Stackoverflow.com/users/7270457",
"pm_score": 0,
"selected": false,
"text": "class ImageWidget extends StatelessWidget {\n final String url;\n const ImageWidget({super.key, required this.url});\n\n @override\n Widget build(BuildContext context) {\n return ClipRRect(\n borderRadius: BorderRadius.circular(16),\n child: Stack(\n children: [\n SizedBox.expand(\n child: Image.network(\n url,\n fit: BoxFit.contain,\n ),\n ),\n const Positioned(\n left: 0,\n right: 0,\n bottom: 0,\n child: ImageChildWidget(),\n ),\n ],\n ),\n );\n }\n}\n class ImageChildWidget extends StatelessWidget {\n const ImageChildWidget({super.key});\n\n @override\n Widget build(BuildContext context) {\n return const ColoredBox(\n color: Color.fromARGB(155, 0, 0, 0),\n child: Padding(\n padding: EdgeInsets.all(8),\n child: Text(\n 'Some Long Text',\n style: TextStyle(\n color: Colors.white,\n fontSize: 16,\n ),\n ),\n ),\n );\n }\n}\n class GridExample extends StatefulWidget {\n const GridExample({super.key});\n\n @override\n State<GridExample> createState() => GridExampleState();\n}\n\nclass GridExampleState extends State<GridExample> {\n // Generate a random list of images\n List<String> urls = List.generate(\n 10,\n (_) {\n int random = Random().nextInt(500) + 250; // 250-500\n return 'https://picsum.photos/$random/$random';\n },\n );\n\n @override\n Widget build(BuildContext context) {\n return GridView.builder(\n key: widget.key,\n itemCount: urls.length,\n padding: const EdgeInsets.all(16),\n gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(\n crossAxisCount: 2,\n mainAxisSpacing: 16,\n crossAxisSpacing: 16,\n ),\n itemBuilder: (context, index) {\n return ImageWidget(\n key: ValueKey(urls[index]),\n url: urls[index],\n );\n },\n );\n }\n}\n import 'dart:math';\n\nimport 'package:flutter/material.dart';\n\nvoid main() {\n runApp(const MyApp());\n}\n\nclass MyApp extends StatelessWidget {\n const MyApp({super.key});\n\n @override\n Widget build(BuildContext context) {\n return const MaterialApp(\n debugShowCheckedModeBanner: false,\n home: Scaffold(\n body: Center(\n child: GridExample(\n key: ValueKey('grid'),\n ),\n ),\n ),\n );\n }\n}\n\nclass GridExample extends StatefulWidget {\n const GridExample({super.key});\n\n @override\n State<GridExample> createState() => GridExampleState();\n}\n\nclass GridExampleState extends State<GridExample> {\n // Generate a random list of images\n List<String> urls = List.generate(\n 10,\n (_) {\n int random = Random().nextInt(500) + 250; // 250-500\n return 'https://picsum.photos/$random/$random';\n },\n );\n\n @override\n Widget build(BuildContext context) {\n return GridView.builder(\n key: widget.key,\n itemCount: urls.length,\n padding: const EdgeInsets.all(16),\n gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(\n crossAxisCount: 2,\n mainAxisSpacing: 16,\n crossAxisSpacing: 16,\n ),\n itemBuilder: (context, index) {\n return ImageWidget(\n key: ValueKey(urls[index]),\n url: urls[index],\n );\n },\n );\n }\n}\n\nclass ImageWidget extends StatelessWidget {\n final String url;\n const ImageWidget({super.key, required this.url});\n\n @override\n Widget build(BuildContext context) {\n return ClipRRect(\n borderRadius: BorderRadius.circular(16),\n child: Stack(\n children: [\n SizedBox.expand(\n child: Image.network(\n url,\n fit: BoxFit.contain,\n ),\n ),\n const Positioned(\n left: 0,\n right: 0,\n bottom: 0,\n child: ImageChildWidget(),\n ),\n ],\n ),\n );\n }\n}\n\nclass ImageChildWidget extends StatelessWidget {\n const ImageChildWidget({super.key});\n\n @override\n Widget build(BuildContext context) {\n return const ColoredBox(\n color: Color.fromARGB(155, 0, 0, 0),\n child: Padding(\n padding: EdgeInsets.all(8),\n child: Text(\n 'Some Long Text',\n style: TextStyle(\n color: Colors.white,\n fontSize: 16,\n ),\n ),\n ),\n );\n }\n}\n\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4517263/"
] |
74,627,827
|
<p>I'm reading an advanced React book called <em>React Cookbook</em>. For some reason, the author uses a <code>key</code> with prefix, like this:</p>
<pre><code><div>
{state.items.map((s, i) => (
<div key={`square-${i}`}>
{s}
</div>
))}
</div>
</code></pre>
<p>I keep seeing <code>key</code> constructed that way and it always surprises me, especially from an advanced author. As far as I know, there is no difference between this and just <code>key={i}</code>.</p>
<p>When I started with React, I had some less advanced React devs telling me that this is useful when you nest lists, like this:</p>
<pre><code><div>
{state.items.map((s, i) => (
<div key={`square-${i}`}>
{s.map(f, j) => (
<div key={`foo-${j}`}>
{f}
</div>
)}
</div>
))}
</div>
</code></pre>
<p>But, this is also useless, since key uniqueness is scoped, right? So the keys at different levels or different lists don't need to be unique.</p>
<p>Perhaps there would be <em>some</em> sense in doing that if my list consisted of two or more kinds of things, like this:</p>
<pre><code><div key={`${item.type}-${i}`}>
</code></pre>
<p>But other that this, why would someone use index-based key in shape of anything else that just the index?</p>
|
[
{
"answer_id": 74628119,
"author": "Shubham Waje",
"author_id": 13483939,
"author_profile": "https://Stackoverflow.com/users/13483939",
"pm_score": 1,
"selected": false,
"text": "foo-${i} i index foo-0 foo-1"
},
{
"answer_id": 74628387,
"author": "enapupe",
"author_id": 1666071,
"author_profile": "https://Stackoverflow.com/users/1666071",
"pm_score": 2,
"selected": true,
"text": "react-dom <parent key=\"unique\">\n <sibling key=\"must\" />\n <sibling key=\"be\" />\n <sibling key=\"unique\">\n <child key=\"unique\" />\n </sibling>\n </parent>\n <div>\n {['a', 'b', 'c', 'd', 'e'].map((letter, idx) => (\n <span key={idx}>{letter}</span>\n ))}\n {['a', 'b', 'c', 'd', 'e'].map((letter, idx) => (\n <span key={idx}>{letter}</span>\n ))}\n </div>\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4403732/"
] |
74,627,848
|
<p>On the <code>master</code> branch, I have new version of the folder with files in it, e.g.:</p>
<pre><code>config
- db
- rdbms
- postgres.conf
- redis.conf
- nosql
- mongo.conf
- web
- apache.conf
- security.conf
</code></pre>
<p>I need to take older version of these files and add them to the master but the top folder <code>config</code> should be renamed to <code>config-old</code>, so that both <code>config</code> and <code>config-old</code> are present:</p>
<pre><code>config
- db
- rdbms
- postgres.conf
- redis.conf
- nosql
- mongo.conf
- web
- apache.conf
- security.conf
config-old
- db
- rdbms
- postgres.conf
- redis.conf
- nosql
- mongo.conf
- web
- apache.conf
- nginx.conf
</code></pre>
<p>I know how to use <code>git show</code> or <code>git cat-file</code> to restore individual files and using shell redirection I can save them under another name, but how do I do this with an entire folder and all subfolder/subfiles in it?</p>
<p>Obviously, I can just switch to the required branch/revision, copy the folder somewhere outside of the git root, switch back to master and then copy back under different name, but I wonder if this can be done with git itself?</p>
|
[
{
"answer_id": 74628119,
"author": "Shubham Waje",
"author_id": 13483939,
"author_profile": "https://Stackoverflow.com/users/13483939",
"pm_score": 1,
"selected": false,
"text": "foo-${i} i index foo-0 foo-1"
},
{
"answer_id": 74628387,
"author": "enapupe",
"author_id": 1666071,
"author_profile": "https://Stackoverflow.com/users/1666071",
"pm_score": 2,
"selected": true,
"text": "react-dom <parent key=\"unique\">\n <sibling key=\"must\" />\n <sibling key=\"be\" />\n <sibling key=\"unique\">\n <child key=\"unique\" />\n </sibling>\n </parent>\n <div>\n {['a', 'b', 'c', 'd', 'e'].map((letter, idx) => (\n <span key={idx}>{letter}</span>\n ))}\n {['a', 'b', 'c', 'd', 'e'].map((letter, idx) => (\n <span key={idx}>{letter}</span>\n ))}\n </div>\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1802425/"
] |
74,627,859
|
<p>I keep getting an 'unused arguments' error when I call the SMD function</p>
<p>I'm using smd() as part of a larger data analysis, comparing groups created through k-means clustering. And it was all working fine... until it wasn't. I'd been editing other parts of the main script - adding a derived variable.</p>
<p>I've puzzled for some time, checking syntax and the code that creates the function arguments. All to no avail. Finally I wrote a short script to see if I had this problem with some very basic data. And I still do. The new script is</p>
<pre><code>library(smd)
Mean_x <- 75
Mean_y <- 25
n_x <- 25
n_y <- 25
sd_x <- 40
sd_y <- 20
temp_smd <- smd(Mean.1=Mean_x, Mean.2=Mean_y, s.1=sd_x, s.2=sd_y, n.1=n_x, n.2=n_y)
</code></pre>
<p>... and I get the error message</p>
<pre><code>Error in smd(Mean.1 = Mean_x, Mean.2 = Mean_y, s.1 = sd_x, s.2 = sd_y, :
unused arguments (Mean.1 = Mean_x, Mean.2 = Mean_y, s.1 = sd_x, s.2 = sd_y, n.1 = n_x, n.2 = n_y)
</code></pre>
<p>I even tried smd::smd, in case there was a package conflict that I wasn't aware of.</p>
<p>All help appreciated</p>
|
[
{
"answer_id": 74628119,
"author": "Shubham Waje",
"author_id": 13483939,
"author_profile": "https://Stackoverflow.com/users/13483939",
"pm_score": 1,
"selected": false,
"text": "foo-${i} i index foo-0 foo-1"
},
{
"answer_id": 74628387,
"author": "enapupe",
"author_id": 1666071,
"author_profile": "https://Stackoverflow.com/users/1666071",
"pm_score": 2,
"selected": true,
"text": "react-dom <parent key=\"unique\">\n <sibling key=\"must\" />\n <sibling key=\"be\" />\n <sibling key=\"unique\">\n <child key=\"unique\" />\n </sibling>\n </parent>\n <div>\n {['a', 'b', 'c', 'd', 'e'].map((letter, idx) => (\n <span key={idx}>{letter}</span>\n ))}\n {['a', 'b', 'c', 'd', 'e'].map((letter, idx) => (\n <span key={idx}>{letter}</span>\n ))}\n </div>\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20645097/"
] |
74,627,881
|
<p>I have a data frame with 9 observations of two different dates. Like:</p>
<pre><code>df <- data.frame(date1 = c("2018-11-01", "2018-10-28", "2019-01-22", "2019-03-22", "2018-10-03", "2018-09- 10","2020-07-01", "2018-03-02", "2018-11-09"),
date2 = c("2018-12-31","2018-12-31","2018-12-31","2019-12-31","2018-12-31","2018-12-31","2020-12-31","2018-12-31","2018-12-31"))
</code></pre>
<p>For every pair of dates I want to extract the sequence between them by month and write it in a new data frame. For just one pair of observations I use: <code>seq(month(date1), month(date2)) </code>
This works nice but not so for date1 and date 2 being a vector > 1. I tried commands like rowwise or tried to loop through the original data frame but nothing worked out.</p>
<p>I tried:</p>
<pre><code>df %>%
rowwise() %>%
as.data.frame(df[i,])
</code></pre>
<p>or something like:</p>
<pre><code>for(i in 1:nrow(df)){
as.data.frame(df[i,])
i = i + 1
}
</code></pre>
<p>What I need is a single data frame for every sequence of months for every pair of dates like df1, df2, df3 ... and so on.
Every help or idea would be highly appreciated.
Thank you.</p>
|
[
{
"answer_id": 74628163,
"author": "harre",
"author_id": 4786466,
"author_profile": "https://Stackoverflow.com/users/4786466",
"pm_score": 2,
"selected": true,
"text": "lubridate dplyr group_split library(dplyr)\nlibrary(lubridate)\n\ndf |>\n mutate(across(everything(), ymd)) |>\n group_by(date1, date2) |>\n mutate(new = list(seq(month(date1), month(date2)))) |>\n unnest_longer(new) |>\n group_split(.keep = FALSE)\n [[1]]\n# A tibble: 10 × 1\n new\n <int>\n 1 3\n 2 4\n 3 5\n 4 6\n 5 7\n 6 8\n 7 9\n 8 10\n 9 11\n10 12\n\n[[2]]\n# A tibble: 4 × 1\n new\n <int>\n1 9\n2 10\n3 11\n4 12\n\n[[3]]\n# A tibble: 3 × 1\n new\n <int>\n1 10\n2 11\n3 12\n\n[[4]]\n# A tibble: 3 × 1\n new\n <int>\n1 10\n2 11\n3 12\n\n[[5]]\n# A tibble: 2 × 1\n new\n <int>\n1 11\n2 12\n\n[[6]]\n# A tibble: 2 × 1\n new\n <int>\n1 11\n2 12\n\n[[7]]\n# A tibble: 12 × 1\n new\n <int>\n 1 1\n 2 2\n 3 3\n 4 4\n 5 5\n 6 6\n 7 7\n 8 8\n 9 9\n10 10\n11 11\n12 12\n\n[[8]]\n# A tibble: 10 × 1\n new\n <int>\n 1 3\n 2 4\n 3 5\n 4 6\n 5 7\n 6 8\n 7 9\n 8 10\n 9 11\n10 12\n\n[[9]]\n# A tibble: 6 × 1\n new\n <int>\n1 7\n2 8\n3 9\n4 10\n5 11\n6 12\n list2env df |>\n mutate(across(everything(), ymd)) |>\n group_by(date1, date2) |>\n mutate(new = list(seq(month(date1), month(date2)))) |>\n unnest_longer(new) |>\n group_split(.keep = FALSE) -> listdf\n\nnames(listdf) <- paste0(\"monthdf\", seq(length(listdf)))\nlist2env(listdf, .GlobalEnv)\n"
},
{
"answer_id": 74628166,
"author": "Ricardo Semião e Castro",
"author_id": 13048728,
"author_profile": "https://Stackoverflow.com/users/13048728",
"pm_score": 0,
"selected": false,
"text": "purrr::pmap rowwise df %>%\n mutate(across(.fns = as.Date)) %>%\n pmap(~ as.Date(..1:..2))\n pmap_dfr pmap_dfc [[1]]\n[1] \"2018-11-01\" \"2018-11-02\" \"2018-11-03\" \"2018-11-04\" \"2018-11-05\" ...\n\n[[2]]\n[1] \"2018-10-28\" \"2018-10-29\" \"2018-10-30\" \"2018-10-31\" \"2018-11-01\" ...\n\n[[3]]\n[1] \"2019-01-22\" \"2019-01-21\" \"2019-01-20\" \"2019-01-19\" \"2019-01-18\" ...\n\n[[4]]\n[1] \"2019-03-22\" \"2019-03-23\" \"2019-03-24\" \"2019-03-25\" \"2019-03-26\" ...\n\n[[5]]\n[1] \"2018-10-03\" \"2018-10-04\" \"2018-10-05\" \"2018-10-06\" \"2018-10-07\" ...\n\n[[6]]\n[1] \"2018-09-10\" \"2018-09-11\" \"2018-09-12\" \"2018-09-13\" \"2018-09-14\" ...\n\n[[7]]\n[1] \"2020-07-01\" \"2020-07-02\" \"2020-07-03\" \"2020-07-04\" \"2020-07-05\" ...\n\n[[8]]\n[1] \"2018-03-02\" \"2018-03-03\" \"2018-03-04\" \"2018-03-05\" \"2018-03-06\" ...\n\n[[9]]\n[1] \"2018-11-09\" \"2018-11-10\" \"2018-11-11\" \"2018-11-12\" \"2018-11-13\" ...\n"
}
] |
2022/11/30
|
[
"https://Stackoverflow.com/questions/74627881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19892554/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.