qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,165,714 | <p>I am reloading a specfic page . But after reloading it is jumping to the top of the page which i dont want . Is there any other way where i can jump to a specific section so that it scrolls by itself to that section after reloading.</p>
| [
{
"answer_id": 74165693,
"author": "Mohammed Ahmed",
"author_id": 4292093,
"author_profile": "https://Stackoverflow.com/users/4292093",
"pm_score": 1,
"selected": false,
"text": ".box {\n position: absolute;\n top:10px;\n left:50%;\n background:white;\n padding:10px;\n borde... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18622011/"
] |
74,165,743 | <p>There is a PHP script on the server which runs about 20 - 30 seconds depending on the size of the file it's working on.</p>
<p>To stop the running instance when a new one ist started I change a session variable. Within the work loop in the script I am checking if this session variable has changed to stop the execution.
And this does not work out. Why is this ?</p>
<p>Basically I am starting the session first:</p>
<pre class="lang-php prettyprint-override"><code>session_start();
</code></pre>
<p>Then I generate a random number, assing this to an instance variable, kill the belonging session variable and assign the generated number to that session variable:</p>
<pre class="lang-php prettyprint-override"><code>$this->number = rand();
unset( $_SESSION[ 'number' ] );
$_SESSION[ 'number' ] = $this->number;
</code></pre>
<p>Within the loop I let this <code>$_SESSION[ 'number' ]</code> being checked for a change which should appear when a new script instance is started:</p>
<pre class="lang-php prettyprint-override"><code>for( $i = 0 to 1.000.000 ){
$s = $_SESSION[ 'number' ];
if( $this->number !== $s ){
die();
}
</code></pre>
<p>So let's say:</p>
<p>script1 starts the session, stores 1 in <code>$_SESSION[ 'number' ]</code> and checks changes to <code>$_SESSION[ 'number' ]</code> to die while looping.</p>
<p>script2 starts and stores 2 in <code>$_SESSION[ 'number' ]</code></p>
<p>At that moment script1 should get aware of this change and stop working</p>
<p>what is does NOT.</p>
<p>Please be so kind and tell me why this does not work out, as I let the script echo the actual <code>$_SESSION[ 'number' ]</code> on start and see that the see the number generated from the script started before, being changed the by the last started instance.</p>
| [
{
"answer_id": 74167597,
"author": "Shlomi Hassid",
"author_id": 1486486,
"author_profile": "https://Stackoverflow.com/users/1486486",
"pm_score": 2,
"selected": false,
"text": "$_SESSION"
}
] | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2546717/"
] |
74,165,768 | <p>I have a data frame with two columns below:</p>
<pre><code>HomeTeam AwayTeam
Zimbabwe Kenya
Netherlands Zimbabwe
Kenya Amsterdam
</code></pre>
<p>I want to create a column Team from both these column but it shouldn't repeat the name of the team. How do I go about it?</p>
| [
{
"answer_id": 74167597,
"author": "Shlomi Hassid",
"author_id": 1486486,
"author_profile": "https://Stackoverflow.com/users/1486486",
"pm_score": 2,
"selected": false,
"text": "$_SESSION"
}
] | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20309947/"
] |
74,165,774 | <p>I need to customize the shipping confirmation email. I want to use a tag to determine which of two text sections are included in the email. The problem is there is usually an array of tags. I can get section "A" like this...</p>
<p>{% for tag in tags %}
{% if tag == 'a' %}
A
{% endif %}
{% endfor %}</p>
<p>There is only a single 'a' tag in the array so I only get the "A" text once.</p>
<p>But I can't figure out how to get the "B" text to appear just one time.</p>
<p>If I do this, it appears for every tag that does not == 'a'...</p>
<p>{% for tag in tags %}
{% unless tag contains 'a' %}
B
{% endunless %}
{% endfor %}</p>
<p>Is there a way to get one instance of "B"?</p>
| [
{
"answer_id": 74166314,
"author": "Fabio Filippi",
"author_id": 343794,
"author_profile": "https://Stackoverflow.com/users/343794",
"pm_score": 0,
"selected": false,
"text": "{% assign a_not_found = true %}\n{% for tag in tags %}\n {% if tag == 'a' %}\n ...\n {% assign a_not_foun... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2197029/"
] |
74,165,783 | <p>I am writing a Python program to perform a set of steps as outlined below:</p>
<pre><code># Author: Evan Gertis
# Date : 10/22
# program : quantile decile calculator
import csv
import logging
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors
from matplotlib.ticker import PercentFormatter
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
# Step 1: read csv
testScoresCSV = open('test_scores.csv')
testScoresDF = pd.read_csv(testScoresCSV)
# testScoresDF = pd.DataFrame(testScoresData)
# testScoresData = map(int,testScoresData)
# testScoresList = list(testScoresData)
print(testScoresDF.head())
# Step 3: use numpy to determine Q1, Q2, Q3
quantiles = np.quantile(testScoresDF, q=[0.25, 0.5, 0.75])
logging.debug(f"{quantiles}")
# Step 4: repeat step 3 with deciles
deciles = np.quantile(testScoresDF, q=[0.1,1,0.1])
logging.debug(f"{deciles}")
# Step 5: repeat step 3 with percentiles
percentiles = np.percentile(testScoresDF, q=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1])
logging.debug(f"{percentiles}")
# Step 6: plot the results
N_points = len(testScoresDF)
logging.debug(f"N_points:{N_points}")
n_bins = 20
# Create a random number generator with a fixed seed for reproducibility
rng = np.random.default_rng(19680801)
# Generate two normal distributions
dist1 = rng.standard_normal(N_points)
dist2 = 0.4 * rng.standard_normal(N_points) + 5
fig, axs = plt.subplots(1, 2, sharey=True, tight_layout=True)
# We can set the number of bins with the *bins* keyword argument.
axs[0].hist(dist1, bins=n_bins)
axs[1].hist(dist2, bins=n_bins)
# plt.show()
</code></pre>
<p>Expected:</p>
<p>This program should return the expected output for the quantiles Q1-Q3, deciles D1-D10, and percentiles and a plot of the distribution.</p>
<p>Actual:</p>
<pre><code> Test_Scores
0 88
1 45
2 53
3 86
4 33
2022-10-22 14:30:48,381 - DEBUG - [37.75 57. 76. ]
2022-10-22 14:30:48,381 - DEBUG - [30.9 99. 30.9]
2022-10-22 14:30:48,381 - DEBUG - [25.177 25.354 25.531 25.708 25.885 26.062 26.239 26.416 26.593 26.77 ]
2022-10-22 14:30:48,382 - DEBUG - N_points:60
</code></pre>
| [
{
"answer_id": 74166314,
"author": "Fabio Filippi",
"author_id": 343794,
"author_profile": "https://Stackoverflow.com/users/343794",
"pm_score": 0,
"selected": false,
"text": "{% assign a_not_found = true %}\n{% for tag in tags %}\n {% if tag == 'a' %}\n ...\n {% assign a_not_foun... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3937811/"
] |
74,165,789 | <p>I need your support while working with dates.
While importing an .xls file, the column of dates was correctly converted into numbers by R. Unfortunately some dates are still there in the format: dd/mm/yyyy or d/mm/yyyy or dd/mm/yy. Probably this results from different settings of different os. I don't know. Is there a way to manage this?</p>
<p>Thank you in advance</p>
<blockquote>
<pre><code> my_data <- read_excel("my_file.xls")
</code></pre>
</blockquote>
<blockquote>
<pre><code>born_date
18520
30859
16/04/1972
26612
30291
24435
11/02/1964
26/09/1971
18427
23688
</code></pre>
</blockquote>
<blockquote>
<p>Original_dates<br />
14/9/1950<br />
26/6/1984<br />
16/04/1972<br />
9/11/1972<br />
6/12/1982<br />
24/11/1966<br />
11/02/1964<br />
26/09/1971<br />
13/6/1950</p>
</blockquote>
| [
{
"answer_id": 74166314,
"author": "Fabio Filippi",
"author_id": 343794,
"author_profile": "https://Stackoverflow.com/users/343794",
"pm_score": 0,
"selected": false,
"text": "{% assign a_not_found = true %}\n{% for tag in tags %}\n {% if tag == 'a' %}\n ...\n {% assign a_not_foun... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19938845/"
] |
74,165,798 | <p>I can iterate over a list or string in fixed-size slices like this:</p>
<pre><code>for n in range(0, len(somelongstring), 10):
print(somelongstring[n:n+10])
</code></pre>
<p>But how do I iterate over 10-line slices from an open file, or over some other iterable, without reading the whole thing into a list? Every so often I need to do this, and there <em>must</em> be a straightforward formula using <a href="https://docs.python.org/3/library/itertools.html" rel="nofollow noreferrer">itertools</a>, but there is <em>nothing</em> similar in the itertools documentation, and I can't google it or figure it out and I end up solving the problem some other way. What am I missing?</p>
<pre><code>with open("filename.txt") as source:
for tenlinegroup in ten_at_a_time_magic(source, 10):
print(...)
</code></pre>
| [
{
"answer_id": 74165887,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": -1,
"selected": false,
"text": "itertools.islice"
},
{
"answer_id": 74166653,
"author": "treuss",
"author_i... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/699305/"
] |
74,165,806 | <p>I have a monolith app where its models are joined to each others(OnetOne, ManyToMany..).</p>
<p>I was able to create the different Microservices, but I got stuck on how to transition these relationships into Microservices.</p>
<p>Here is my first Class:</p>
<pre><code>@Entity
@Table
public class A {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
@ManyToOne
@JoinColumn(name = "ID",referencedColumnName="ID")
private B b;
//getters and setters
}
@Entity
@Table
public class B{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
//getters and setters
}
</code></pre>
<p>I also Created a microservice for A (controller,repository, service...) and a separate microservice for B.</p>
<p>I am trying to call the Class Model B from the microservice B. But I am not sure how to do it?</p>
<p>I also wonder if it is write to link two classes by joint in microservices or not ?</p>
<p>Thanks</p>
| [
{
"answer_id": 74165887,
"author": "assume_irrational_is_rational",
"author_id": 11622508,
"author_profile": "https://Stackoverflow.com/users/11622508",
"pm_score": -1,
"selected": false,
"text": "itertools.islice"
},
{
"answer_id": 74166653,
"author": "treuss",
"author_i... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11754694/"
] |
74,165,811 | <p>I'm working on a project where I need to take an existing .txt file containing student names and number grades, assign letter grades to each student, and output name, grade, letter grade separated by commas. Then send the new output to a new file.</p>
<p>Example of text:</p>
<pre><code>name_one, 85
name_two, 76.5
</code></pre>
<p>Desired Output:</p>
<pre><code>name_one, 85, B
name_two, 76.5, C
</code></pre>
<p>Here's the code I have so far:</p>
<pre><code>import numbers
import string
gradesDict = {}
with open("C:\\Users\\awolf\\.vscode\\extensions\\StudentExamRecords.txt", "r") as f:
for line in f:
(key, value) = line.strip().split(",")
gradesDict[float(value)] = value
def letter_grade(value):
if value > 95:
return "A"
elif value > 91:
return "A-"
elif value > 87:
return "B+"
elif value > 83:
return "B"
elif value > 80:
return "B-"
elif value > 78:
return "C+"
elif value > 75:
return "C"
elif value > 70:
return "D"
else:
return "F"
print(key + "," + value)
</code></pre>
<p>I've created a dictionary to contain the data, opened the file path, stripped line notations and split string values into key/value, converted values to float, and created conditions to assign letter grades. What I am getting hung up on is adding the letter grade to the end of each line. I feel like I need to create a new variable "letterGrade" within the "def letter_grade" function and append the information to each line, but nothing I have tried is working.</p>
| [
{
"answer_id": 74165991,
"author": "René",
"author_id": 7475838,
"author_profile": "https://Stackoverflow.com/users/7475838",
"pm_score": 0,
"selected": false,
"text": "pandas"
},
{
"answer_id": 74166016,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profi... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20309945/"
] |
74,165,821 | <p>In rust, you can have a trait, implement it into a struct, and upcast your struct to a trait object :</p>
<pre><code>trait T {}
struct S {}
impl T for S {}
fn main() {
let s: S = S {};
let s_as_t: &dyn T = &s;
}
</code></pre>
<p>This is an incredibly useful feature, because if I have multiple objects which all implement the trait <code>T</code>, I can now put them all in a single array of type <code>Vec<Box<dyn T>></code>, and define global behaviors really easily by calling a function on each element.</p>
<p><strong>BUT</strong></p>
<p>How do I do the same thing when my original trait also has an associated type ?</p>
<p>This works really well, no pb :</p>
<pre><code>trait T_Subtype {}
trait T {
type subtype: T_Subtype;
}
struct S {}
impl T_Subtype for S {}
impl T for S {
type subtype = S;
}
fn main() {
let s: S = S {};
let s_as_t: &dyn T<subtype = S> = &s;
}
</code></pre>
<p>But I can't find any way to upcast the associated type, the following code cannot compile :</p>
<pre><code>trait T_Subtype {}
trait T {
type subtype: T_Subtype;
}
struct S {}
impl T_Subtype for S {}
impl T for S {
type subtype = S;
}
fn main() {
let s: S = S {};
let s_as_t: &dyn T<subtype = dyn T_Subtype> = &s; // only line that changes
}
</code></pre>
<p>Without this feature, I cannot put <em>(this is an illustration)</em> multiple structs <code>S1</code> <code>S2</code> and <code>S3</code>, that all implement <code>T</code> but might have a different subtype, in a single array, and I have to define global behaviors for each subtype, making it really hard to maintain <em>(especially if there are multiple subtypes)</em>, even though the function I want to call on all of them <strong>is defined</strong> !</p>
| [
{
"answer_id": 74165994,
"author": "virchau13",
"author_id": 9684433,
"author_profile": "https://Stackoverflow.com/users/9684433",
"pm_score": 2,
"selected": false,
"text": "trait SubtypeTrait {}\n\ntrait T {\n type Subtype: SubtypeTrait;\n fn foo(arg: &<Self as T>::Subtype);\n}\n\... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13223443/"
] |
74,165,852 | <p>I'm trying to convert a HDR image float array I load to a 10-bit DWORD with WIC.</p>
<p>The type of the loading file is GUID_WICPixelFormat128bppPRGBAFloat and I got an array of 4 floats per color.</p>
<p>When I try to convert these to 10 bit as follows:</p>
<pre><code>struct RGBX
{
unsigned int b : 10;
unsigned int g : 10;
unsigned int r : 10;
int a : 2;
} rgbx;
</code></pre>
<p>(which is the format requested by the NVIDIA encoding library for 10-bit rgb),</p>
<p>then I assume I have to divide each of the floats by 1024.0f in order to get them inside the 10 bits of a DWORD.</p>
<p>However, I notice that some of the floats are > 1, which means that their range is not [0,1] as it happens when the image is 8 bit.</p>
<p>What would their range be? How to store a floating point color into a 10-bits integer?</p>
<p>I'm trying to use the NVidia's HDR encoder which requires an ARGB10 like the above structure.</p>
<p>How is the 10 bit information of a color stored as a floating point number?</p>
<p>Btw I tried to convert with WIC but conversion from GUID_WICPixelFormat128bppPRGBAFloat to GUID_WICPixelFormat32bppR10G10B10A2 fails.</p>
<pre><code>HRESULT ConvertFloatTo10(const float* f, int wi, int he, std::vector<DWORD>& out)
{
CComPtr<IWICBitmap> b;
wbfact->CreateBitmapFromMemory(wi, he, GUID_WICPixelFormat128bppPRGBAFloat, wi * 16, wi * he * 16, (BYTE*)f, &b);
CComPtr<IWICFormatConverter> wf;
wbfact->CreateFormatConverter(&wf);
wf->Initialize(b, GUID_WICPixelFormat32bppR10G10B10A2, WICBitmapDitherTypeNone, 0, 0, WICBitmapPaletteTypeCustom);
// This last call fails with 0x88982f50 : The component cannot be found.
}
</code></pre>
<p>Edit: I found a paper (<a href="https://hal.archives-ouvertes.fr/hal-01704278/document" rel="nofollow noreferrer">https://hal.archives-ouvertes.fr/hal-01704278/document</a>), is this relevant to this question?</p>
| [
{
"answer_id": 74228349,
"author": "Chuck Walbourn",
"author_id": 3780494,
"author_profile": "https://Stackoverflow.com/users/3780494",
"pm_score": 3,
"selected": true,
"text": "std::unique_ptr<ScratchImage> timage(new (std::nothrow) ScratchImage);\nif (!timage)\n{\n wprintf(L\"\\nERR... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451321/"
] |
74,165,864 | <p>I have problem in my testcase on <a href="https://www.codewars.com/kata/57eb8fcdf670e99d9b000272/train/python" rel="nofollow noreferrer">CodeWars</a>. I fail here:</p>
<pre><code>print(high('what time are we climbing up the volcano'))
</code></pre>
<p>Instead of 'volcano', I got the what in my new_dictionary variable the w at place 23 and v is on place 22 , and i got what as a result because the word have greater letter than the another. Did i understand bad question?</p>
<p>Here's my code:</p>
<pre><code> from string import ascii_lowercase
def high(x):
x = x.split()
print(x)
high_scoring_word = {}
new_dictionary = {letter: str(index) for index, letter in enumerate(ascii_lowercase, start=1)}
for word in x:
get_index = 0
for character in word:
if character in new_dictionary:
character_index = new_dictionary[character]
if get_index == 0:
get_index += int(character_index)
elif get_index < int(character_index):
get_index = 0
get_index += int(character_index)
high_scoring_word[word] = get_index
max_value = max(high_scoring_word, key = high_scoring_word.get)
return max_value
</code></pre>
| [
{
"answer_id": 74165947,
"author": "doxdeveloper",
"author_id": 16561009,
"author_profile": "https://Stackoverflow.com/users/16561009",
"pm_score": 1,
"selected": false,
"text": "def high(x):\n result = {} #dictionary for storing each word with its score\n x = x.split(\" \")\n f... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19753231/"
] |
74,165,890 | <p>I have written some powershell code, since I wanted to achive two things.
The first one was to organize my gists and the second one to learn ps1 script syntax.
Until now I guess I've managed some impressive things on one hand, on the other I got stuck...</p>
<p>I read lots of interesting and sophisticated articles on git and earlier on I also used <code>.gitignore</code> files quite successfully.</p>
<p>Now this particular script does EVERYTIME Ignore the <code>.gitignore</code> seamingly not dependend on what im doing.</p>
<p>May somebody of you help me busting this mystery why this script always ignores my gitignore - it sucks that everytime on the first hand it uploads itself everywhere (which is the reason why it writes itself to the <code>.gitignore</code> in line: <code>40 ++</code>) and even more it gets wierd if everytime the <code>node_modules</code> where uploaded too</p>
<p>(testing this script on a freshly generated <code>npx create-react-app testapp</code> in the apps root folder)</p>
<p>By the way, to make things easier I also cleaned the cache with <code>git rm -r --cached .</code> in line 88 before the <code>git add .</code> this also does not work</p>
<p>Filename : <code>git-create-repo.ps1</code></p>
<p>Sourcecode:</p>
<pre><code>$workdir = Convert-Path $pwd
$gituser = "l00tz1ffer"
$gitserver = "lootziffers-welt.de"
$defaultRemoteName = "origin"
$targetBranchName = "master"
$gitHubExists = 0
$workDirName = $workdir.Substring(($workdir.LastIndexOf("\") + 1), ($workdir.Length - 1 ) - $workdir.LastIndexOf("\"))
$git_dir_string = $workDirName + ".git"
echo $workDirName
git remote -v | Out-File -FilePath remotes.temp -Encoding utf8 -Append
$File = 'remotes.temp'
foreach ($line in Get-Content $File) {
$remoteListingLine = $line
$remoteHostName = $remoteListingLine.Substring(($remoteListingLine.IndexOf("@") + 1), ($remoteListingLine.LastIndexOf(":") - 1 ) - $remoteListingLine.IndexOf("@"))
echo $remoteHostName
if ($remoteHostName -contains "github.com") {
echo "GitHub Repo found"
$remoteListingLine = $remoteListingLine -replace $defaultRemoteName, "github"
echo "Renaming properly ..."
echo $remoteListingLine
git remote rename $defaultRemoteName "github"
$gitHubExists = 1
}
}
Remove-Item 'remotes.temp'
if (-not (Test-Path -Path .gitignore)) {
New-Item -Path '.gitignore' -ItemType File
}
If ( $workDirName -ne "git-create-repo" -and $workDirName -ne "git-create-repo.git") {
$File = '.gitignore'
foreach ($line in Get-Content $File) {
if (-not (Test-Path -Path new.gitignore)) {
New-Item -Path 'new.gitignore' -ItemType File
}
echo ".gitignore enthält folgenden Wert: $line"
if ($line -contains "git-create-repo.ps1") {
echo "Duplicate entry found, Removing it"
}
elseif ($line.Length -eq 0) {
echo "Empty Line Found in .gitignore -> Removing it"
}
elseif ($line -contains $null) {
echo "Empty Line Found in .gitignore -> Removing it"
}
else {
line | Out-File -FilePath new.gitignore -Encoding utf8 -Append
}
}
Remove-Item '.gitignore'
Rename-Item 'new.gitignore' '.gitignore'
"git-create-repo.ps1" >> | Out-File -FilePath .gitignore -Encoding utf8 -Append
}
Start-Sleep -Seconds 3
git remote rm $defaultRemoteName
git branch -mv main $targetBranchName
ssh git@$gitserver "cd $gituser && mkdir $git_dir_string && cd $git_dir_string && git init --bare"
#if (Test-Path -Path '.git' -PathType Container) {
git init
echo "Lokales Repo wurde Initialisiert"
git rm -r --cached .
git add .\.gitignore
$timestamp = (get-date).ToString('G')
git commit -m "Autogenerated Commit from ${[System.Environment]::UserName} -> Zeit: $timestamp"
echo "Autogenerated Commit -> Zeit: $timestamp"
git rm -r --cached .
git add .
echo "Dateien wurden zum Lokalen Repository hinzugefuegt"
#}
$timestamp = (get-date).ToString('G')
git commit -m "Autogenerated Commit from ${[System.Environment]::UserName} -> Zeit: $timestamp"
echo "Autogenerated Commit -> Zeit: $timestamp"
$git_repo_string = "git@lootziffers-welt.de:" + $gituser + "/" + $workDirName + ".git"
echo "Der Verwendete Remote Git Repo string lautet: $git_repo_string"
git remote add $defaultRemoteName $git_repo_string
git push $defaultRemoteName $targetBranchName
if ($gitHubExists -eq 1) {
git push github $targetBranchName
}
scp git@${gitserver}:${gituser}/repos.txt repos.txt
if (-not (Test-Path -Path .gitignore)) {
New-Item -Path 'repos.txt' -ItemType File
}
$File = "repos.txt"
foreach ($line in Get-Content $File) {
echo "repos.txt enthält folgenden Wert: $line"
if ($line -contains $git_repo_string) {
echo "Duplicate entry found, Removing it"
}
elseif ($line.Length -eq 0) {
echo "Empty Line Found in .gitignore -> Removing it"
}
elseif ($line -contains $null) {
echo "Empty Line Found in .gitignore -> Removing it"
}
else {
line | Out-File -FilePath new.repos.txt -Encoding utf8 -Append
}
}
Remove-Item 'repos.txt'
Rename-Item 'new.repos.txt' 'repos.txt'
${git_repo_string}.ToString() | Out-File -FilePath repos.txt -Encoding utf8 -Append
scp repos.txt git@${gitserver}:${gituser}/repos.txt
Remove-Item 'repos.txt'
Start-Sleep -Seconds 5
</code></pre>
<p>Here i will give you a basic idea of how my <code>.gitignore</code> file looks like</p>
<pre><code># See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules/*
node_modules/
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
git-create-repo.ps1
</code></pre>
<p>Thank you my dear friends out there for your quick support and taking time to overview this huge bulk of code.</p>
<p>Sincierly</p>
| [
{
"answer_id": 74169825,
"author": "jessehouwing",
"author_id": 736079,
"author_profile": "https://Stackoverflow.com/users/736079",
"pm_score": 2,
"selected": true,
"text": ".gitignore"
},
{
"answer_id": 74227661,
"author": "L00tz1ffer",
"author_id": 12636602,
"author... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12636602/"
] |
74,165,901 | <p>I wanted to add/subtract the <code>UTC</code> offset (usually in hours) to/from the datetime object in polars but I don't seem to see a way to do this. the UTC offset can be dynamic given there's Day Light Saving period comes into play in a calendar year. (e.g., EST/EDT maps to 5/4 hours of <code>UTC</code> offset respectively).</p>
<pre><code>from datetime import datetime
import pytz
import polars as pl
from datetime import date
# Make a datetime-only dataframe that covers DST period of year, in UTC time first.
df = pl.DataFrame(
pl.date_range(low=date(2022,1,3),
high=date(2022,9,30),
interval="5m",
time_unit="ns",
time_zone="UTC")
.alias("timestamp")
)
# Convert timezone to "America/New_York", which covers both EST and EDT.
us_df = df.with_column(
pl.col("timestamp")
.dt
.cast_time_zone(tz="America/New_York")
.alias("datetime")
)
# Check us_df output
us_df
# output, here `polars` is showing US time without the UTC offset
# Before 0.14.22 `polars` is showing time with UTC offset
# i.e., `23:45:00 UTC` should be `19:45:00 EDT`
# Now `polars` is showing `15:45:00 EDT`, without 4 hours of offset
┌─────────────────────────┬────────────────────────────────┐
│ timestamp ┆ datetime │
│ --- ┆ --- │
│ datetime[ns, UTC] ┆ datetime[ns, America/New_York] │
╞═════════════════════════╪════════════════════════════════╡
│ 2022-01-03 00:00:00 UTC ┆ 2022-01-02 14:00:00 EST │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2022-01-03 00:05:00 UTC ┆ 2022-01-02 14:05:00 EST │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2022-01-03 00:10:00 UTC ┆ 2022-01-02 14:10:00 EST │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2022-01-03 00:15:00 UTC ┆ 2022-01-02 14:15:00 EST │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ ... ┆ ... │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2022-09-29 23:45:00 UTC ┆ 2022-09-29 15:45:00 EDT │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2022-09-29 23:50:00 UTC ┆ 2022-09-29 15:50:00 EDT │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2022-09-29 23:55:00 UTC ┆ 2022-09-29 15:55:00 EDT │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2022-09-30 00:00:00 UTC ┆ 2022-09-29 16:00:00 EDT │
└─────────────────────────┴────────────────────────────────┘
</code></pre>
<p>Converting <code>to_pandas</code>, we should observe that the underlying <code>datetime</code> object does not include that 4 hours of offset in the actual time as well (remember EST is also in this dataframe, and it has a 5-hour offset).</p>
<pre><code> # Convert to pandas
us_pd = us_df.to_pandas()
us_pd
# output
timestamp datetime
0 2022-01-03 00:00:00+00:00 2022-01-02 14:00:00-05:00
1 2022-01-03 00:05:00+00:00 2022-01-02 14:05:00-05:00
2 2022-01-03 00:10:00+00:00 2022-01-02 14:10:00-05:00
3 2022-01-03 00:15:00+00:00 2022-01-02 14:15:00-05:00
4 2022-01-03 00:20:00+00:00 2022-01-02 14:20:00-05:00
... ... ...
77756 2022-09-29 23:40:00+00:00 2022-09-29 15:40:00-04:00
77757 2022-09-29 23:45:00+00:00 2022-09-29 15:45:00-04:00
77758 2022-09-29 23:50:00+00:00 2022-09-29 15:50:00-04:00
77759 2022-09-29 23:55:00+00:00 2022-09-29 15:55:00-04:00
77760 2022-09-30 00:00:00+00:00 2022-09-29 16:00:00-04:00
</code></pre>
<p>What I wanted was to include the <code>UTC</code> offset into the actual time, such that I can do filtering on the time (in a natural way). For instance, if I am seeing 2300UTC is 1900EDT, I can use filter using 1900 directly (please note I can't just add/substract the <code>UTC</code> offset on the fly during filtering, as the number of hours is a dynamic variable given DST).</p>
<p>The underlying python <code>datetime</code> does have <code>utcoffset</code> function, which can be applied on each datetime object, but I'd need to convert <code>polars</code> to <code>pandas</code> first (I don't see how to do this within <code>polars</code>).</p>
<p>I've also observed this peculiar difference:</p>
<pre><code> us_pd.datetime[us_pd.shape[0]-1].to_pydatetime()
# We can see it is identical to what's already in `polars` and `pandas` dataframe.
datetime.datetime(2022, 9, 29, 16, 0, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>)
# Now we create a single datetime object with arbitrary UTC time and convert it to New York time
datetime(2022, 9, 30, 22, 45, 0,0, pytz.utc).astimezone(pytz.timezone("America/New_York"))
# The representation here is actually the correct New York time (as in, the offset has been included)
datetime.datetime(2022, 9, 30, 18, 45, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>)
</code></pre>
| [
{
"answer_id": 74170231,
"author": "FObersteiner",
"author_id": 10197418,
"author_profile": "https://Stackoverflow.com/users/10197418",
"pm_score": 1,
"selected": false,
"text": "with_time_zone"
},
{
"answer_id": 74225924,
"author": "braaannigan",
"author_id": 5387991,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4436572/"
] |
74,165,911 | <p>I have a few strings:</p>
<pre><code>some-text-123123#####abcdefg/
some-STRING-413123#####qwer123t/
some-STRING-413123#####456zxcv/
</code></pre>
<p>I would like to receive:</p>
<pre><code>abcdefg
qwer123t
456zxcv
</code></pre>
<p>I have tried regexp:</p>
<pre><code>/[^#####]*[^\/]/
</code></pre>
<p>But this not working...</p>
| [
{
"answer_id": 74165958,
"author": "acdcjunior",
"author_id": 1850609,
"author_profile": "https://Stackoverflow.com/users/1850609",
"pm_score": 4,
"selected": true,
"text": "#"
},
{
"answer_id": 74166241,
"author": "damonholden",
"author_id": 17670742,
"author_profile... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310092/"
] |
74,165,919 | <p>A series of file names should be in format:</p>
<pre><code>ABCDEF - XY1234 - FileName.ext
</code></pre>
<p>(The middle section is fixed length (2 alpha + 4 numeric), the first and last sections can be longer or shorter than the example. The extension will always be three alphanumeric characters.)</p>
<p>However, some files do not have the hyphens surrounded by spaces:</p>
<pre><code>EFGHI- WX2345 -FileName.ext
JKLMN-VW3456 - FileName.ext
OPQRS - UV4567- FileName.ext
</code></pre>
<p>Is there a way to replace all these combinations "X -X", "X-X", and "X- X" with "X - X" using sed?</p>
<p>(I have tried the pattern of a non-whitespace character followed by a hyphen - <code>'\S\-'</code> as my pattern, but replacing this with a space followed by the hyphen <code>'\ \-'</code> then means I lose the character represented by the <code>'\S'</code>. Had this worked my intention would have been to pass each filename through the three variations to ensure compliance.)</p>
| [
{
"answer_id": 74165978,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 2,
"selected": true,
"text": "sed -E 's/[[:blank:]]*-[[:blank:]]*/ - /g' file\n\nEFGHI - WX2345 - FileName.ext\nJKLMN - VW3456 - FileName.ext\nOPQRS... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5847482/"
] |
74,165,928 | <p>There is an array of movies, with tuples in it:</p>
<pre><code>films = [(film_name,film_rating),...]
</code></pre>
<p>How do I find a film name which has the same name, but the number 2 added to it (like a part 2)?</p>
| [
{
"answer_id": 74165978,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 2,
"selected": true,
"text": "sed -E 's/[[:blank:]]*-[[:blank:]]*/ - /g' file\n\nEFGHI - WX2345 - FileName.ext\nJKLMN - VW3456 - FileName.ext\nOPQRS... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16409755/"
] |
74,165,939 | <p>So I've been working on this little project of mine which involves building simple TCP reverse shell from "scratch" using sockets. Is there a way for the code below to be less redundant?</p>
<pre><code>elif command == "camera":
try:
open_camera()
except:
pass
elif command == "fullscreen":
full_screen()
elif command == "exit_prog":
exit_prog()
elif command == "minimise":
minimise()
elif command == "enter":
enter()
elif command == "right":
right()
elif command =="left":
left()
elif command == "break":
break
else:
s.send("Invalid command !\n".encode())
</code></pre>
| [
{
"answer_id": 74165978,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 2,
"selected": true,
"text": "sed -E 's/[[:blank:]]*-[[:blank:]]*/ - /g' file\n\nEFGHI - WX2345 - FileName.ext\nJKLMN - VW3456 - FileName.ext\nOPQRS... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20186529/"
] |
74,165,951 | <p>So for this code I want to input any string and I want it to return true if there's a sequence of 3 same consecutive characters in n.</p>
<p>This code works however, it only counts the first three consecutive numbers in n, but I want it to count any sequence in n.</p>
<pre class="lang-py prettyprint-override"><code>def consec(n):
for i in range(len(n)):
if n[i] == n[i+1] == n[i+2]:
return True
else:
return False
</code></pre>
<p>eg: if consec("AAABC")</p>
<p>it prints true</p>
<p>but if consec("ABCCC")</p>
<p>it prints false even though there are 3 consecutive characters, they just happen to be later in the string.</p>
<p>What should I change about this code ?</p>
<p>Thanks,</p>
| [
{
"answer_id": 74166027,
"author": "RJ Adriaansen",
"author_id": 11380795,
"author_profile": "https://Stackoverflow.com/users/11380795",
"pm_score": 0,
"selected": false,
"text": "import re\n\ndef check_string(text):\n if re.findall(r'(\\w)\\1\\1+', text):\n return True\n el... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20214604/"
] |
74,165,962 | <p>Why is this code giving me a "length cannot be less than zero" error message?</p>
<pre><code>class Fraction
{
private double Numerator = 0;
private double Denominator= 1;
public static Fraction Parse(string str)
{
Fraction newFrac = new Fraction();
int indexSlash = str.IndexOf("/");
newFrac.Numerator = int.Parse(str.Substring(0, indexSlash));
newFrac.Denominator = int.Parse(str.Substring(indexSlash + 1));
return newFrac;
}
}
</code></pre>
| [
{
"answer_id": 74165999,
"author": "PMF",
"author_id": 2905768,
"author_profile": "https://Stackoverflow.com/users/2905768",
"pm_score": 2,
"selected": false,
"text": "string.IndexOf()"
},
{
"answer_id": 74166176,
"author": "Dmitry Bychenko",
"author_id": 2319407,
"au... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310101/"
] |
74,165,972 | <p>Can someone please give a sample Java code (Not XML config) for adding retry on Spring Integration SFTP Outbound Gateway for a file upload ? I know it should be RequestHandlerRetryAdvice, but how do I add it to annotation of Spring Integration SFTP Outbound Gateway ?</p>
| [
{
"answer_id": 74166444,
"author": "Soumen Ghosh",
"author_id": 7256972,
"author_profile": "https://Stackoverflow.com/users/7256972",
"pm_score": 0,
"selected": false,
"text": "\n@Configuration\n@EnableRetry\npublic class EncryptionLoadCacheRetryTemplate {\n\n @Value(\"${<env variable>:... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20055777/"
] |
74,165,976 | <p>Here is my Controller</p>
<pre class="lang-js prettyprint-override"><code> const getCountofCenters = async (req, res) => {
const result = Center.countDocuments();
await result.then(() => res.status(200).send(result))
.catch((err) => {
res.status(200).send(err)
});
}
</code></pre>
<p>This is the Api call</p>
<pre class="lang-js prettyprint-override"><code> router.get("/count", CenterController.getCountofCenters);
</code></pre>
<p>This is the output which I get from the Postman test, empty array</p>
<pre class="lang-json prettyprint-override"><code> {}
</code></pre>
<p><a href="https://i.stack.imgur.com/cqsVB.png" rel="nofollow noreferrer">enter image description here</a></p>
| [
{
"answer_id": 74166138,
"author": "NeNaD",
"author_id": 14389830,
"author_profile": "https://Stackoverflow.com/users/14389830",
"pm_score": 2,
"selected": true,
"text": "const getCountofCenters = async (req, res) => {\n try {\n const result = await Center.countDocuments();\n retu... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19673961/"
] |
74,166,023 | <p>When I run static code analysis it says:</p>
<p><code>Bitwise operator "~" has a signed operand "(uint8)0U"</code>.</p>
<p>How come this operand is signed while I am explicitly casting it to <code>uint8</code> which is equivalent to <code>unsigned char</code> and also postfixing it with literal <code>U</code> which stands for unsigned integer?</p>
| [
{
"answer_id": 74166232,
"author": "chqrlie",
"author_id": 4593267,
"author_profile": "https://Stackoverflow.com/users/4593267",
"pm_score": 3,
"selected": false,
"text": "0U"
},
{
"answer_id": 74190244,
"author": "Lundin",
"author_id": 584518,
"author_profile": "http... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18347023/"
] |
74,166,044 | <p>I've just revisited some old discord bot code and quite obviously it does not work.
The code below is a lot larger, but even when I shrink it down to importing modules, setting a client prefix, on_ready(), and finally a client.command(), the bot just wont listen or respond.</p>
<pre><code>import discord
from discord.ext import commands, tasks
client = commands.Bot(command_prefix = '!!')
@client.command(name="ping")
async def ping(ctx):
print('listening')
await ctx.send('Pong! '+str(round(client.latency * 1000))+'ms')
client.run(my token)
</code></pre>
<p>Now, here I am listening for '!! ping', or '!!ping' (ive tried typing both)
If the bot is listening to this command, it should atleast print out <code>listening</code> into my terminal. If that is so, it should send a message to my discord channel.</p>
<p>However, neither of these are happening.</p>
<p>Note: An on ready function as shown below prints <code>Bot is ready</code>. Additonally, in discord I can see the bot is online.</p>
<pre><code>#Connect Bot
@client.event
async def on_ready():
change_status.start()
print('Bot is ready')
</code></pre>
| [
{
"answer_id": 74168114,
"author": "ovlmid",
"author_id": 20304539,
"author_profile": "https://Stackoverflow.com/users/20304539",
"pm_score": -1,
"selected": false,
"text": "client = commands.Bot(command_prefix = '!!')\n"
},
{
"answer_id": 74170164,
"author": "Migi",
"aut... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14222251/"
] |
74,166,058 | <p>It is constantly showing the error that ZeroDivisionError.</p>
<pre><code>start= 11
end = 75
print("Prime numbers between ",start," and ",end," are : ")
for i in range (start, end+1):
if i > 1:
c = 2*i
for j in range(c):
if i//j == 0:
break
else:
print(i)
</code></pre>
| [
{
"answer_id": 74168114,
"author": "ovlmid",
"author_id": 20304539,
"author_profile": "https://Stackoverflow.com/users/20304539",
"pm_score": -1,
"selected": false,
"text": "client = commands.Bot(command_prefix = '!!')\n"
},
{
"answer_id": 74170164,
"author": "Migi",
"aut... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20309978/"
] |
74,166,087 | <p>I have this</p>
<pre><code>id phone1 phone2
1 300 301
1 303 300
1 300 303
2 400 401
</code></pre>
<p>Want this</p>
<pre><code>id phone1 phone2 phone3
1 300 303 301
2 400 401
</code></pre>
<p>I have tried group by id and column phone1, apply count function, iterate over it adding to a list verifying if is already there the id and phone and sum the third column, and do the same thing with phone2 in the same list</p>
<p>After it reorganize the dataframe iterating the list but this is so slow with the millions of data that i have to proccess</p>
<pre><code>dataframe1 = dataframe.groupby(['id', 'phone1']).count().reset_index()
dataframe2 = dataframe.groupby(['id', 'phone2']).count().reset_index()
</code></pre>
<p>result to add in a list</p>
<pre><code>id phone1 phone2
1 300 2
1 303 1
2 401 1
id phone1 phone2
1 300 1
1 301 1
1 303 1
2 400 1
</code></pre>
| [
{
"answer_id": 74168114,
"author": "ovlmid",
"author_id": 20304539,
"author_profile": "https://Stackoverflow.com/users/20304539",
"pm_score": -1,
"selected": false,
"text": "client = commands.Bot(command_prefix = '!!')\n"
},
{
"answer_id": 74170164,
"author": "Migi",
"aut... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19787051/"
] |
74,166,126 | <p>I'm trying to resolve some FCC tuts. The function should be very simple, a sum function for args as an array, using the rest operator. However I don't get why my answer doesn't work, here is the code with some parameters:</p>
<pre><code>function sum(...args) {
if (args == []) {
return 0
} else {
let sum = 0;
for (let i of args) {
sum = sum + args[i];
i++;
}
return sum;
};
};
// Using 0, 1, 2 as inputs, 3 is expected to return... and it does!
sum(0, 1, 2);
// However, if the args do not start with 0, it returns NaN
sum(1, 2);
</code></pre>
| [
{
"answer_id": 74168114,
"author": "ovlmid",
"author_id": 20304539,
"author_profile": "https://Stackoverflow.com/users/20304539",
"pm_score": -1,
"selected": false,
"text": "client = commands.Bot(command_prefix = '!!')\n"
},
{
"answer_id": 74170164,
"author": "Migi",
"aut... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20309501/"
] |
74,166,231 | <p>I was wondering if python has a simple method for caching a sequence of values, where the sequence can be updated each time the script is run. For example, let's say I have a list of tuples where each tuple is a <code>datetime</code> and a <code>float</code>. The <code>datetime</code> represents the time a speed was recorded by an anemometer and the <code>float</code> is the speed recorded. When I run my script, new values should be added to my list and remember the next time I run the script. When I first started programming, the way I solved this was using a <code>pickle</code>, as follows:</p>
<pre><code>import os
import pickle
import datetime
db_path = "speeds.p"
# get all our previous speeds
speeds = []
if os.path.exists(db_path):
with open(db_path, "rb") as f:
speeds = pickle.load(f)
def data_from_endpoint():
data = (
(datetime.datetime(2022, 10, 22, 21, 15), 13),
(datetime.datetime(2022, 10, 22, 21, 30), 24),
(datetime.datetime(2022, 10, 22, 21, 45), 37)
)
for i in data:
yield i
try:
# add new speeds
for t, v in data_from_endpoint():
if len(speeds) == 0 or t > speeds[-1][0]:
print(f"Adding {t}, {v}")
speeds.append((t, v))
finally:
# save all speeds
with open(db_path, "wb") as f:
pickle.dump(speeds, f)
print(f"Number of values: {len(speeds)}")
</code></pre>
<p>The way I would solve this now is to use a sqlite database. Both solutions involve a lot of code for something so simple and I'm wondering if python has a simpler way of doing this.</p>
| [
{
"answer_id": 74166506,
"author": "Dronakuul",
"author_id": 19953747,
"author_profile": "https://Stackoverflow.com/users/19953747",
"pm_score": 1,
"selected": false,
"text": "import pickle\nimport datetime\n\ndb_path = \"speeds.p\"\n\ndef data_from_endpoint():\n data = (\n (da... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/607846/"
] |
74,166,243 | <p>I have a .csv file that is about 5mb (~45,000 rows). What I need to do is run through each row of the file and check if the ID in each line is already in a table in my database. If it is, I can delete that row from the file.</p>
<p>I did a good amount of research on the most memory efficient way to do this, so I've been using a method of writing lines that don't need to get deleted to a temporary file and then renaming that file as the original. Code below:</p>
<pre><code>$file= fopen($filename, 'r');
$temp = fopen($tempFilename, 'w');
while(($row = fgetcsv($file)) != FALSE){
// id is the 7th value in the row
$id = $row[6];
// check table to see if id exists
$sql = "SELECT id FROM table WHERE id = $id";
$result = mysqli_query($conn, $sql);
// if id is in the database, skip to next row
if(mysqli_num_rows($result) > 0){
continue;
}
// else write line to temp file
fputcsv($temp, $row);
}
fclose($file);
fclose($temp);
// overwrite original file
rename($tempFilename, $filename);
</code></pre>
<p>Problem is, I'm running into a timeout while executing this bit of code. Anything I can do to make the code more efficient?</p>
| [
{
"answer_id": 74166302,
"author": "Piemol",
"author_id": 3090890,
"author_profile": "https://Stackoverflow.com/users/3090890",
"pm_score": 2,
"selected": false,
"text": "LOAD DATA INFILE"
},
{
"answer_id": 74166309,
"author": "Honk der Hase",
"author_id": 2443226,
"a... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13872573/"
] |
74,166,293 | <p>The standard way to make an API call in functional React is with <code>useEffect</code>:</p>
<pre><code>function Pizzeria() {
const [pizzas, setPizzas] = useState([])
useEffect(
() => fetchPizzas().then(setPizzas),
[]
)
return (
<div>
{pizzas.map((p, i) => <Pizza pizza={p} key={i} />)}
</div>
)
}
</code></pre>
<p>But, as <a href="https://articles.wesionary.team/why-useeffect-is-a-bad-place-to-make-api-calls-98a606735c1c" rel="nofollow noreferrer">this article</a> points out, <code>useEffect</code> will not fire until <em>after</em> the component has rendered (the first time). Obviously in this trivial case it makes no difference, but in general, it would be better to kick off my async network call as soon as possible.</p>
<p>In a class component, I could theoretically use <code>componentWillMount</code> for this. In functional React, it seems like a <a href="https://stackoverflow.com/questions/62091146/componentwillmount-for-react-functional-component">useRef-based solution</a> could work. (Allegedly, <a href="https://tanstack.com/query/v4/docs/reference/useQuery" rel="nofollow noreferrer">tanstack's useQuery hook</a>, and probably other libraries, also do this.)</p>
<p>But <code>componentWillMount</code> is deprecated. Is there a reason why I should not do this? If not, what is the best way in functional React to achieve the effect of starting an async call early as possible (which subsequently sets state on the mounted component)? What are the pitfalls?</p>
| [
{
"answer_id": 74166360,
"author": "Ben West",
"author_id": 1193622,
"author_profile": "https://Stackoverflow.com/users/1193622",
"pm_score": 2,
"selected": false,
"text": "componentWillMount"
},
{
"answer_id": 74166363,
"author": "acdcjunior",
"author_id": 1850609,
"... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4185992/"
] |
74,166,329 | <p>What constraints are copied with table when we create table by using create table as select statement..?</p>
| [
{
"answer_id": 74166360,
"author": "Ben West",
"author_id": 1193622,
"author_profile": "https://Stackoverflow.com/users/1193622",
"pm_score": 2,
"selected": false,
"text": "componentWillMount"
},
{
"answer_id": 74166363,
"author": "acdcjunior",
"author_id": 1850609,
"... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310314/"
] |
74,166,331 | <p>I'm trying to setup some functions to continuously fetch and send data back and forth. However, after sending, there needs to be a brief rest period (which is why I have asyncio.sleep(10)). So, I want to be continuously fetching data in my loop during this waiting time. My problem is once task #1 starts sleeping and task #2 begins executing, it never reverts back to task #1 when it wakes up. It gets stuck in this fetching data loop endlessly.</p>
<p>I tried fixing this problem with a global boolean variable to indicate when the sender was on cooldown but that felt like a cheap solution. I wanted to find out if there was a way to achieve my goals using asyncio built-in functions.</p>
<p>Trying to repeat this process: fetch some data continuously -> send some data -> go on cooldown and continue fetching data during this period</p>
<pre><code>import asyncio
data = []
async def fetcher():
while True:
# Some code continuously fetching data
print("STUCK IN FETCHER")
async def sender():
# Some code which sends data
await asyncio.sleep(10)
async def main():
while True:
t1 = asyncio.create_task(sender())
t2 = asyncio.create_task(fetcher())
await t1
asyncio.run(main())
</code></pre>
| [
{
"answer_id": 74166392,
"author": "Simon Hawe",
"author_id": 14078758,
"author_profile": "https://Stackoverflow.com/users/14078758",
"pm_score": 2,
"selected": false,
"text": "await asyncio.sleep(0)"
},
{
"answer_id": 74176276,
"author": "koyeung",
"author_id": 135699,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20278411/"
] |
74,166,366 | <p>We are building an installer that enables Internet Information Services (IIS) and installs .NET 6 hosting bundle in a windows 10 machine. We are using <strong>Advanced installer</strong> to build our installer.</p>
<p>We are facing a problem if the host machine already has a higher version of .NET hosting bundle installed e.g. version 6.0.9. And if our installer tries installing a lower version of .NET hosting bundle e.g. 6.0.4, it gets canceled because a higher version is already installed on that machine. From <a href="https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/hosting-bundle?view=aspnetcore-6.0" rel="nofollow noreferrer">this documentation</a>, we found that we need to install/repair .NET hosting bundle after the installation of Internet Information Services (IIS) otherwise Internet Information Services won't work. Because the installation of 6.0.4 is getting canceled, IIS is not working.
<a href="https://i.stack.imgur.com/eArqW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eArqW.png" alt="enter image description here" /></a></p>
<p><strong>Our approach</strong>: what we want to do is if version 6.0.4 gets canceled because of a higher version of the .NET hosting bundle. We want to repair the existing 6.0.9 version installed on the host machine.</p>
<p><strong>How can we repair a higher version of .NET hosting bundle installed on the host machine without knowing the location of the .NET hosting bundle .exe file?</strong></p>
<p><strong>Please also suggest if there is a better alternative approach to resolve the issue.</strong></p>
| [
{
"answer_id": 74166392,
"author": "Simon Hawe",
"author_id": 14078758,
"author_profile": "https://Stackoverflow.com/users/14078758",
"pm_score": 2,
"selected": false,
"text": "await asyncio.sleep(0)"
},
{
"answer_id": 74176276,
"author": "koyeung",
"author_id": 135699,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15349504/"
] |
74,166,390 | <p>i want to search a date like the following:</p>
<pre><code>09-11
03-22
</code></pre>
<p>and it will search in the available documents and bring the matched documnet.
an available document example :</p>
<pre><code>2022-09-11T15:31:25.083+00:00
</code></pre>
<p>how can i do this?</p>
<p>i tried following query but that didn't work:</p>
<pre><code>db.users.find({ createdAt: new RegExp('09-11') }) // Null
</code></pre>
| [
{
"answer_id": 74166392,
"author": "Simon Hawe",
"author_id": 14078758,
"author_profile": "https://Stackoverflow.com/users/14078758",
"pm_score": 2,
"selected": false,
"text": "await asyncio.sleep(0)"
},
{
"answer_id": 74176276,
"author": "koyeung",
"author_id": 135699,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20250969/"
] |
74,166,415 | <p>I'm doing some exercise in "List" and "Match-With" but I'm a little stuck.</p>
<p>The exercise tell me Program the <code>upper l x</code> function that counts all the elements larger than x in the list</p>
<p>Example :</p>
<pre><code>upper [10;20;30;40;50] 35;
</code></pre>
<p>the results is <code>2</code>.</p>
<p>I did this :</p>
<pre><code>let rec upper x l1 =
match l1 with
|[] -> 0
|[a] -> if (a>x) then 1 else 0
|(a::r) when a>x -> +1
|(a::r) when a<x -> upper x r
</code></pre>
<p>but nothings work.</p>
| [
{
"answer_id": 74166392,
"author": "Simon Hawe",
"author_id": 14078758,
"author_profile": "https://Stackoverflow.com/users/14078758",
"pm_score": 2,
"selected": false,
"text": "await asyncio.sleep(0)"
},
{
"answer_id": 74176276,
"author": "koyeung",
"author_id": 135699,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14795970/"
] |
74,166,425 | <p>I've built a simple website with authorization and registration system. <br />
So I have user accounts and I wonder where to store profile pictures for every user. <br />
I tried to store them in MYSQL in BLOB, but I don't think it is the best way to do this.</p>
| [
{
"answer_id": 74166392,
"author": "Simon Hawe",
"author_id": 14078758,
"author_profile": "https://Stackoverflow.com/users/14078758",
"pm_score": 2,
"selected": false,
"text": "await asyncio.sleep(0)"
},
{
"answer_id": 74176276,
"author": "koyeung",
"author_id": 135699,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11360200/"
] |
74,166,440 | <p>I have a method as follows (simplified for clarity and brevity):</p>
<pre><code>public static List<Person> getPersons(String a, int b, DataSetX dataSetX, DataSetY dataSetY) {
List<Person> persons = new ArrayList<>();
if(dataSetX != null) {
while (dataSetX.hasNext()) {
// create an instance of person with very specific attributes set
persons.add(processX(dataSetX.next()));
}
}
if(dataSetY != null) {
while (dataSetY.hasNext()) {
// create an instance of person with very specific attributes set
persons.add(processY(dataSetY.next()));
}
}
return persons;
}
</code></pre>
<p>The method in reality is a bit more complicate than this (doing a bit more processing using also the <code>a</code> and <code>b</code> variables) but overall this is the method structure.</p>
<p>I was thinking to split this method into 2, one method for dealing with <code>DataSetX</code> and the other with <code>DataSetY</code>.<br />
I was thinking to structure it as follows:</p>
<pre><code>public static List<Person> getPersons(String a, DataSetX dataSetX, List<Person> persons) {
if(dataSetX != null) {
while (dataSetX.hasNext()) {
// create an instance of person with very specific attributes set
persons.add(processX(dataSetX.next()));
}
}
return persons;
}
</code></pre>
<p>I would then call the methods as follows:</p>
<pre><code>List<Person> persons = getPersons(a, dataSetX, new ArrayList<Person>());
getPersons(a, dataSetX, persons);
// now I can use persons list with the result of both present
</code></pre>
<p>With this approach I reuse the same list and don't need to concat 2 different lists from 2 different methods if I just created the list inside the methods and returned.<br />
On the other side it looks kind of weird and possibly error prone.</p>
<p>Is there a way to be able to split the function and avoid creating multiple lists and merging them (as I need 1 list in the end).<br />
Is there some design pattern suited for this?</p>
| [
{
"answer_id": 74166392,
"author": "Simon Hawe",
"author_id": 14078758,
"author_profile": "https://Stackoverflow.com/users/14078758",
"pm_score": 2,
"selected": false,
"text": "await asyncio.sleep(0)"
},
{
"answer_id": 74176276,
"author": "koyeung",
"author_id": 135699,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9055634/"
] |
74,166,459 | <p>My entire feature stack is divided into @sanity(10 scenarios) and @smoke(2 scenarios) and whole stack is considered as @regression (no tag required, and total scenarios: 37). My question is how can I pass tag value via command line. Please note this is a cucumber-testng project
Below is how my runner file looks:
<a href="https://i.stack.imgur.com/mxnwh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mxnwh.png" alt="enter image description here" /></a></p>
<p>Please note, I have tried below command line commands but it still runs @smoke and @sanity both cases (meaning 12 scenarios)</p>
<p>./gradlew -i test -Denv=release -D"cucumber.options=--tags @sanity" ---> It runs 12 scenarios</p>
<p>./gradlew -i test -Denv=release -Dcucumber.filter.tags="@smoke"---> It runs 12 scenarios</p>
| [
{
"answer_id": 74168885,
"author": "hhs",
"author_id": 5262092,
"author_profile": "https://Stackoverflow.com/users/5262092",
"pm_score": 1,
"selected": false,
"text": "tags=@sanity or @smoke"
}
] | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4952126/"
] |
74,166,471 | <p>I'm trying to get count of values from NSCountedSet using loop and have no idea how to get these.</p>
<pre><code>for item in set {
}
</code></pre>
<p>I'll be grateful for any help!</p>
| [
{
"answer_id": 74168885,
"author": "hhs",
"author_id": 5262092,
"author_profile": "https://Stackoverflow.com/users/5262092",
"pm_score": 1,
"selected": false,
"text": "tags=@sanity or @smoke"
}
] | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310371/"
] |
74,166,474 | <p>How can I get in javascript the color scales defined in the variable <code>scales</code> in
<a href="https://github.com/plotly/plotly.js/blob/master/src/components/colorscale/scales.js" rel="nofollow noreferrer">https://github.com/plotly/plotly.js/blob/master/src/components/colorscale/scales.js</a>?</p>
<p>I inspected the <code>Plotly</code> object in debugger console, but I can't find the attributes.</p>
| [
{
"answer_id": 74166595,
"author": "Aifos Si Prahs",
"author_id": 19135131,
"author_profile": "https://Stackoverflow.com/users/19135131",
"pm_score": 0,
"selected": false,
"text": "Plotly.d3.scale.category10();\n"
}
] | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11769765/"
] |
74,166,494 | <p>I have a function which takes a list of a base class as argument, and I have a variable which is a list of a derived class. Using this variable as the argument gives mypy error: <em>Argument 1 to "do_stuff" has incompatible type "List[DerivedClass]"; expected "List[BaseClass]"</em>.</p>
<pre class="lang-py prettyprint-override"><code>class BaseClass(TypedDict):
base_field: str
class DerivedClass(BaseClass):
derived_field: str
def do_stuff(data: List[BaseClass]) -> None:
pass
foo: List[DerivedClass] = [{'base_field': 'foo', 'derived_field': 'bar'}]
do_stuff(foo)
</code></pre>
<p>If the argument and variable are instead BaseClass and DerivedClass respectively, i.e. not lists, it understands that the variable can be casted implicitly to the base class. But for lists it doesn't work. How can I solve this, preferably other than <em>#type: ignore</em>.</p>
| [
{
"answer_id": 74166516,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 3,
"selected": true,
"text": "do_stuff"
},
{
"answer_id": 74166533,
"author": "Simon Hawe",
"author_id": 14078758,
"author_prof... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19405704/"
] |
74,166,534 | <p>I'm trying to destructure a JSON file that looks like this:</p>
<pre><code>[
{
"Bags": [
{
"id": 1,
"name": "Michael Kors Bag",
"price": 235,
"imgURL": "/imgs/03045643da82a42a4a5c86842f4b17f1.jpg"
},
{
"id": 2,
"name": "Ted Baker Bag",
"price": 495,
"imgURL": "/imgs/4c176b2fa86bdcddf74822c2501bbcac.jpg"
},
{
"id": 3,
"name": "Coach Bag",
"price": 238,
"imgURL": "/imgs/coach-jes-crossbody-signature-canvas-brown-black-59181.jpg"
},
{
"id": 4,
"name": "Kate Spade Bag",
"price": 35,
"imgURL": "/imgs/10.jpg"
}
]
},
{
"Shoes": [
{
"id": 1,
"name": "Michael Kors Bag",
"price": 235,
"imgURL": "/imgs/03045643da82a42a4a5c86842f4b17f1.jpg"
},
{
"id": 2,
"name": "Ted Baker Bag",
"price": 495,
"imgURL": "/imgs/4c176b2fa86bdcddf74822c2501bbcac.jpg"
},
{
"id": 3,
"name": "Coach Bag",
"price": 238,
"imgURL": "/imgs/coach-jes-crossbody-signature-canvas-brown-black-59181.jpg"
},
{
"id": 4,
"name": "Kate Spade Bag",
"price": 35,
"imgURL": "/imgs/10.jpg"
}
]
}
]
</code></pre>
<p>So that I get the name of the objects ("Bags" and "Shoes").</p>
<p>I'm trying to print out the results on a page based on which is which and I'm feeding in the names as strings to a Store component like so:</p>
<pre><code><Route path="/store" element={<Store merch="Bags" />} />
</code></pre>
<p>This is my Store.tsx file, it doesn't work at all but it's my attempt:</p>
<pre><code>import storeItems from "../data/items.json";
import { Row, Col, Container } from "react-bootstrap";
import { StoreItem } from "../components/StoreItem";
import { useState } from "react";
type StoreProps = {
merch: string;
};
export function Store({ merch }: StoreProps) {
const [data, setData] = useState([]);
for (let i = 0; i < storeItems.length; i++) {
let a = Object.values(storeItems[i]);
console.log(a);
}
console.log(storeItems);
return (
<>
<Container className="mw-80 d-flex align-items-center justify-content-center p-0 flex-column mb-5">
<h1 className="m-5">Bags</h1>
<Row md={2} xs={1} lg={3} className="g-3">
{storeItems.map((item) => (
<Col>
<StoreItem key={item.id} {...item} />
</Col>
))}
</Row>
</Container>
</>
);
}
</code></pre>
| [
{
"answer_id": 74166559,
"author": "Zachiah",
"author_id": 10892722,
"author_profile": "https://Stackoverflow.com/users/10892722",
"pm_score": 3,
"selected": true,
"text": "[\"Bags\", \"Shoes\"]"
},
{
"answer_id": 74166579,
"author": "Amirhossein Sefati",
"author_id": 118... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310478/"
] |
74,166,560 | <p>I have two tables that have the same columns; AgencyA & AgencyB. Columns; Subject, Event_Combined and License_Fee. How can I combine the columns for each table? IE Subject column will have all the data from AgencyA and AgencyB.
Ive tried this</p>
<pre><code>SELECT Subject, Event_Combined, License_Fee
FROM AgencyA
UNION ALL
SELECT Subject, Event_Combined, License_Fee
FROM AgencyB
</code></pre>
<p>Which combines everything but how do I run the query below?</p>
<pre><code>SELECT
Subject,
SUM(License_Fee) as Gross,
COUNT(DISTINCT(Event_Combined)) as Total_Sales,
SUM(License_Fee)/COUNT(DISTINCT(Event_Combined)) as Result
FROM AgencyA
GROUP BY Subject
ORDER BY Gross DESC
</code></pre>
<p>Thanks!</p>
| [
{
"answer_id": 74166559,
"author": "Zachiah",
"author_id": 10892722,
"author_profile": "https://Stackoverflow.com/users/10892722",
"pm_score": 3,
"selected": true,
"text": "[\"Bags\", \"Shoes\"]"
},
{
"answer_id": 74166579,
"author": "Amirhossein Sefati",
"author_id": 118... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310467/"
] |
74,166,564 | <p>From its documentation, it states that Mono returns empty when it "completes without emitting any items". What does it mean to complete without emitting any items? Does it mean that it never sent any request or?</p>
| [
{
"answer_id": 74173203,
"author": "Martin Tarjányi",
"author_id": 6051176,
"author_profile": "https://Stackoverflow.com/users/6051176",
"pm_score": 1,
"selected": false,
"text": "Mono"
},
{
"answer_id": 74178888,
"author": "Simon Baslé",
"author_id": 1113486,
"author... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12421494/"
] |
74,166,580 | <p>Is there a way to enforce the structure of an object setting?</p>
<p>For example <code>package.json</code>:</p>
<pre><code>{
"contributes": {
"configuration": {
"properties": {
"myextension.mysetting": {
"type": "object",
"default": {
"anyKey": {
"property1": "",
"property2": ""
}
}
}
}
}
}
}
</code></pre>
<p>The setting <code>myextension.mysetting</code> is an object type, where key <code>anyKey</code> could be any string at user's choosing and <code>property1</code> and <code>property2</code> are the only acceptable properties in that object. If user attempt enter other property name (i.e. <code>property3</code>) it should show it as not an acceptable property.</p>
<p>Is this possible?</p>
| [
{
"answer_id": 74166785,
"author": "rioV8",
"author_id": 9938317,
"author_profile": "https://Stackoverflow.com/users/9938317",
"pm_score": 2,
"selected": true,
"text": "\"additionalProperties\": false\n"
},
{
"answer_id": 74166921,
"author": "vanowm",
"author_id": 2930038... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2930038/"
] |
74,166,582 | <p>Let's say that we have a long list of items and we would only like to print 10 at a time before asking the user whether to display more items. What would be the most efficient way to iterate through the list and print 10 items at a time? Would slicing be the answer here?</p>
| [
{
"answer_id": 74166636,
"author": "Amirhossein Sefati",
"author_id": 11856099,
"author_profile": "https://Stackoverflow.com/users/11856099",
"pm_score": 0,
"selected": false,
"text": "def printNextTenItems(list, times):\n print(list[10*times: 10*times + 10])\n\ntimes = 0\nkeepGoing =... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,166,587 | <p>I'm trying to create a list which have a values which are either zero or one (if the values in the table's column is Null or not). But my list only contains ones.</p>
<pre><code>list = []
for i in range(len(df['DefaultDate'])):
if df['DefaultDate'][i] == 'nan':
list.append(0)
else:
list.append(1)
print(list)
print(df['DefaultDate'])
</code></pre>
| [
{
"answer_id": 74166636,
"author": "Amirhossein Sefati",
"author_id": 11856099,
"author_profile": "https://Stackoverflow.com/users/11856099",
"pm_score": 0,
"selected": false,
"text": "def printNextTenItems(list, times):\n print(list[10*times: 10*times + 10])\n\ntimes = 0\nkeepGoing =... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310521/"
] |
74,166,596 | <p>what's wrong with this code?
It's supposed to get a digit from me, then show all the numbers between 100 & 1000000 containing that digit...</p>
<pre><code>#include <stdio.h>
int main () {
int n,m;
puts("Enter your digit:\n");
scanf("%d\n", n);
int j=100;
while (j<=1000000) {
m=10;
if (j%m==n) {printf("%d\n",j);}
while (j/m>=1) {
if ((j/m)%10==n) {printf("%d\n",j);}
m=m*10;}
j+=1;}
return 0;
}
</code></pre>
| [
{
"answer_id": 74166636,
"author": "Amirhossein Sefati",
"author_id": 11856099,
"author_profile": "https://Stackoverflow.com/users/11856099",
"pm_score": 0,
"selected": false,
"text": "def printNextTenItems(list, times):\n print(list[10*times: 10*times + 10])\n\ntimes = 0\nkeepGoing =... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310430/"
] |
74,166,619 | <p>So my problem, to which I have been searching a solution for hours now, is, that I have a list of list with lists of various lengths and different items:</p>
<pre><code>list_1=[[160,137,99,81,78,60],[132,131,131,127,124,123],'none',[99,95,80,78]]
</code></pre>
<p>Now I want to change the fifth number of every list and add +1. My problem is, that I keep getting 'out of range' or other problems, because list 3 doesn't contain numbers and list 3+4 don't contain a fifth element.</p>
<p>I have so far found no answer to this. My first guess was adding zeros to the lists, but I'm not supposed to do that. It would also falsify the results, since then it would add +1 to any zero I have created.</p>
| [
{
"answer_id": 74166676,
"author": "Amirhossein Sefati",
"author_id": 11856099,
"author_profile": "https://Stackoverflow.com/users/11856099",
"pm_score": 0,
"selected": false,
"text": "list_1=[[160,137,99,81,78,60],[132,131,131,127,124,123],'none',[99,95,80,78]]\n\ndef addOneToFifthEleme... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310544/"
] |
74,166,648 | <p>I've encountered a very strange problem, implementing axios interceptors for handling the expired token and refreshing it.</p>
<h3>Setting</h3>
<p>I'm implementing the JWT authentication with access and refresh tokens.</p>
<p>When the request is being sent to the API route that requires JWT authentication, request interceptor is here to make sure the headers contain an Authorization with Bearer token. The response interceptor checks if the new access token is needed, sends a request to refresh it, and finally updates the axios instance with the new config.</p>
<p>I wrote the code following the Dave Gray's <a href="https://www.youtube.com/watch?v=nI8PYZNFtac&list=PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd&index=4" rel="nofollow noreferrer">video</a>, but with TypeScript.</p>
<h3>Problem</h3>
<p>When testing this code, I set the refresh token lifetime to be very long, while setting the access token lifetime to be 5 seconds. After it expires, when the request to the protected route is happening, everything goes according to the plan—the logs from the backend contain two successfully completed requests: (1) to the protected route with 401 response and then (2) the refresh request.</p>
<p>At this point, I see the DOMException in the browser console (Chrome and Safari), which states that <code>setRequestHeader</code> fails to execute because a source code function is not a valid header value. Which, of course, it is not! The piece of code is <a href="https://github.com/axios/axios/blob/9bd53214f6339c3064d4faee91c223b35846f2dd/lib/core/AxiosHeaders.js#L119" rel="nofollow noreferrer">this</a>.</p>
<h3>Code</h3>
<pre><code>const axiosPrivate = axios.create({
baseURL: BASE_URL,
headers: { "Content-Type": "application/json" },
withCredentials: true,
});
interface IRequestConfig extends AxiosRequestConfig {
sent?: boolean;
}
const useAxiosPrivate = () => {
const { auth } = useAuth()!;
const refresh = useRefreshToken();
React.useEffect(() => {
const requestInterceptor = axiosPrivate.interceptors.request.use(
(config: AxiosRequestConfig) => {
config.headers = config.headers ?? {};
if (!config.headers["Authorization"]) {
config.headers["Authorization"] = `Bearer ${auth?.token}`;
}
return config;
},
async (error: AxiosError): Promise<AxiosError> => {
return Promise.reject(error);
}
);
const responseInterceptor = axiosPrivate.interceptors.response.use(
(response: AxiosResponse) => response,
async (error: AxiosError): Promise<AxiosError> => {
const prevRequestConfig = error.config as IRequestConfig;
if (error?.response?.status === 401 && !prevRequestConfig?.sent) {
const newAccessToken = await refresh();
prevRequestConfig.sent = true;
prevRequestConfig.headers = prevRequestConfig.headers!;
prevRequestConfig.headers[
"Authorization"
] = `Bearer ${newAccessToken}`;
return axiosPrivate(prevRequestConfig);
}
return Promise.reject(error);
}
);
return () => {
axiosPrivate.interceptors.request.eject(requestInterceptor);
axiosPrivate.interceptors.response.eject(responseInterceptor);
};
}, [auth, refresh]);
return axiosPrivate;
};
</code></pre>
<h3>Error</h3>
<pre><code>DOMException: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'function (header, parser) {
header = normalizeHeader(header);
if (!header) return undefined;
const key = findKey(this, header);
if (key) {
const value = this[key];
if (!parser) {
return value;
}
if (parser === true) {
return parseTokens(value);
}
if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isFunction(parser)) {
return parser.call(this, value, key);
}
if (_utils_js__WEBPACK_IMPORTED_MODULE_0__["default"].isRegExp(parser)) {
return parser.exec(value);
}
throw new TypeError('parser must be boolean|regexp|function');
}
}' is not a valid HTTP header field value.
</code></pre>
<h3>Research</h3>
<p>So far, I've only found one <a href="https://github.com/axios/axios/issues/5055" rel="nofollow noreferrer">similar issue</a> in the internet, which has links to some others. <a href="https://github.com/axios/axios/pull/5090" rel="nofollow noreferrer">One of them</a> gives me a hint, that it may be the problem with how <code>axios</code> reads the configuration given to an axios instance.</p>
<p>I'm not sure if the problem is indeed somewhere in axios. I'll be extremely grateful for any useful thoughts on this problem!</p>
| [
{
"answer_id": 74308583,
"author": "Daniel Dan",
"author_id": 16537404,
"author_profile": "https://Stackoverflow.com/users/16537404",
"pm_score": 3,
"selected": true,
"text": "axiosPrivate"
},
{
"answer_id": 74308935,
"author": "Lev Pleshkov",
"author_id": 2852665,
"a... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2852665/"
] |
74,166,650 | <p>How can I push down the triangle and include the content on top of the white circles? I'm trying to find a solution for creating a hero section that contains a background image with the three overlay shapes included as part of the image. On top of the overlays will be an h1, p and btn. I included a screenshot below on what the design is supposed to look like.</p>
<p>There are these three overlays:</p>
<ol>
<li>Straight angled shape with 0% transparency at bottom.</li>
<li>Outer circle with transparency.</li>
<li>Inner circle with transparency.</li>
</ol>
<p>Here's what I have so far. I included a snippet below and also have a working version on <a href="https://codepen.io/Codewalker/pen/zYjgVpa?editors=1100" rel="nofollow noreferrer">Codepen</a>. The circles are in the right place at bottom left.</p>
<p><a href="https://i.stack.imgur.com/em3E2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/em3E2.jpg" alt="enter image description here" /></a></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>*{
padding: 0;
margin: 0;
box-sizing: border-box;
}
svg {
width: 628;
height: 628:
}
.element {
position: relative;
width: 100%;
min-height: 628px;
background: url(https://images-prod.healthline.com/hlcmsresource/images/AN_images/health-benefits-of-apples-1296x728-feature.jpg) no-repeat center top;
background-size: cover;
}
.element:before{
content: '';
position: absolute; bottom: 0; left: 0;
width: 100%;0
-webkit-clip-path: polygon(0 0, 0% 100%, 100% 100%);
clip-path: polygon(0 0, 0% 100%, 100% 100%);
}
.circle-outer {
cx: 200;
cy: 720;
fill: #fff;
fill-opacity: 0.6;
r: 420;
w: 628;
h: 628;
}
.circle-inner {
cx: 200;
cy: 720;
fill: #fff;
fill-opacity: 0.6;
r: 400;
}
.hero-triangle {
content: '';
position: relative;
width: 100%;
height: 100px;
background: #fff;
-webkit-clip-path: polygon(0 8%, 0% 100%, 100% 100%);
clip-path: polygon(0 80%, 0% 100%, 100% 100%);
z-index: 99;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="element">
<div class="hero-content">
<h1>This belongs in circle</h1>
<p>This belongs in circle too.</p>
<button class="btn btn-primary">Learn more</button>
</div>
<svg viewbox width="1000" height="580" viewBox="0 0 100 100">
<circle class="circle-outer" />
<circle class="circle-inner" />
<polygon points="0,0 0,200 1000,200" style="fill:#fff;" />
</svg>
</div>
</div>
<div class="container">
<h4>Body content must be positioned right underneath hero image for all widths.</h4></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74169236,
"author": "chrwahl",
"author_id": 322084,
"author_profile": "https://Stackoverflow.com/users/322084",
"pm_score": 1,
"selected": false,
"text": "* {\n padding: 0;\n margin: 0;\n}\n\n.element {\n position: relative;\n width: 100%;\n min-height: 628px;\n back... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/953542/"
] |
74,166,656 | <p>I have setup a containerized Wordpress project as a Azure App Service based on the <a href="https://hub.docker.com/_/wordpress" rel="nofollow noreferrer">official Wordpress Docker image</a> where I have made no modifications to the image itself other than adding a SSH server based on the instructions given by <a href="https://learn.microsoft.com/en-us/azure/app-service/configure-custom-container?pivots=container-linux#enable-ssh" rel="nofollow noreferrer">Azure</a>. This is what the Dockerfile looks like:</p>
<pre><code>FROM wordpress:6.0.3-php7.4
########################################## Add SSH support for Azure ##########################################
# Install OpenSSH and set the password for root to "Docker!".
RUN apt update \
&& apt install -y openssh-server \
&& rm -rf /var/lib/apt/lists/*
RUN echo "root:Docker!" | chpasswd
# Copy the sshd_config file to the /etc/ssh/ directory
COPY docker/ssh/sshd_config /etc/ssh/
# Copy and configure the ssh_setup file
RUN mkdir -p /tmp
COPY docker/ssh/ssh_setup.sh /tmp
RUN chmod +x /tmp/ssh_setup.sh \
&& (sleep 1;/tmp/ssh_setup.sh 2>&1 > /dev/null)
# Open port 2222 for SSH access
EXPOSE 80 2222
###############################################################################################################
COPY docker/script.sh script.sh
RUN chmod +x script.sh
CMD []
ENTRYPOINT ["./script.sh"]
</code></pre>
<p>And <code>docker/script.sh</code></p>
<pre><code>#!/bin/bash
exec service ssh start &
exec /usr/local/bin/docker-entrypoint.sh apache2-foreground
</code></pre>
<p>On the App Service I have added the <code>WEBSITES_ENABLE_APP_SERVICE_STORAGE=true</code> application setting to enable <a href="https://learn.microsoft.com/en-us/azure/app-service/configure-custom-container?pivots=container-linux#use-persistent-shared-storage" rel="nofollow noreferrer">persistent storage</a> as well as set the <code>WORDPRESS_DB_HOST</code>, <code>WORDPRESS_DB_NAME</code>, <code>WORDPRESS_DB_PASSWORD</code> and <code>WORDPRESS_DB_USER</code> settings to connect to my database running on a another host.</p>
<p>When accessing the app service page in the browser and going through the Wordpress setup I can easily upload new files which are placed in the file system at <code>/var/www/html/wp-content/uploads/<year>/<month>/<filename></code> which I can then access in my browser at <code>https://my-app-service.azurewebsites.net/wp-content/uploads/<year>/<month>/<filename></code>.</p>
<p>With Azure only persisting data written in <code>/home</code> I instead tried to move the <code>/var/www/html/wp-content/uploads</code> directory to <code>/home/uploads</code> and then create a symbolic link to this from the expected path like so (the symbolic link creation could then also be added to the Dockerfile to automate this during deployment):</p>
<pre><code>$ cd /var/www/html/wp-content
$ mv uploads /home/uploads
$ ln -s /home/uploads uploads
</code></pre>
<p>Now however, when I access <code>https://my-app-service.azurewebsites.net/wp-content/uploads/<year>/<month>/<filename></code> I just get an empty 400 response.</p>
<p>In order to see if this was some sort of limitation of Azure I decided to try something similar with the most simple Python page instead. Dockerfile:</p>
<pre><code>FROM python:3.10.0
RUN mkdir -p /var/www/html
WORKDIR /var/www/html
########################################## Add SSH support for Azure ##########################################
# Install OpenSSH and set the password for root to "Docker!".
RUN apt update \
&& apt install -y openssh-server \
&& rm -rf /var/lib/apt/lists/*
RUN echo "root:Docker!" | chpasswd
# Copy the sshd_config file to the /etc/ssh/ directory
COPY docker/ssh/sshd_config /etc/ssh/
# Copy and configure the ssh_setup file
RUN mkdir -p /tmp
COPY docker/ssh/ssh_setup.sh /tmp
RUN chmod +x /tmp/ssh_setup.sh \
&& (sleep 1;/tmp/ssh_setup.sh 2>&1 > /dev/null)
# Open port 2222 for SSH access
EXPOSE 80 2222
###############################################################################################################
COPY docker/script.sh script.sh
RUN chmod +x script.sh
CMD []
ENTRYPOINT ["./script.sh"]
</code></pre>
<p>And docker/script.sh</p>
<pre><code>#!/bin/bash
exec service ssh start &
exec python -m http.server 80
</code></pre>
<p>Doing the same thing here works, so it doesn't seem to be a limitation with Azure. What I don't understand, however, is that the Wordpress docker image with the symbolic link works as expected running on my local machine.</p>
<p>What am I doing wrong? Why does the Python project work but not the Wordpress one?</p>
| [
{
"answer_id": 74203789,
"author": "Slava Kuravsky",
"author_id": 3730077,
"author_profile": "https://Stackoverflow.com/users/3730077",
"pm_score": 2,
"selected": false,
"text": "<VirtualHost *:80>\n DocumentRoot /var/www\n <Directory />\n Options FollowSymLinks\n All... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1523238/"
] |
74,166,704 | <p>By default, it seems like a <code>sphere</code> object in P5 is located at <code>(0,0)</code>. I want to create an object that is visually represented by a <code>sphere</code> with the ability to define the <code>x</code> and <code>y</code> coordinates of the <code>sphere</code> object.</p>
<p>Because I want to deal with multiple of these objects and draw connections between them, I don't want to use the <code>translate</code> function for a <code>sphere</code> to position it every time. Is there a way to position the sphere to the coordinates I want without the <code>translate</code> function?</p>
| [
{
"answer_id": 74166724,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 0,
"selected": false,
"text": "function createSphere(x, y, z, r) {\n translate(x, y, z)\n sphere(r)\n}\n"
},
{
"answer_id": 74166972,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17473106/"
] |
74,166,720 | <p>Here is a list of 6 tuples:</p>
<pre><code>listoftuples = [
( { 'd1':[ {'start': 1.2, 'end': 2.7}, {'start': 3.0, 'end': 4.0} ] }, [] ),
( { 'd2':[ {'start': 1.4, 'end': 2.3}, {'start': 3.2, 'end': 4.3} ] }, [] ),
( { 'd3':[ {'start': 1.7, 'end': 2.0}, {'start': 3.5, 'end': 4.0} ] }, [] ),
( { 'd4':[ {'start': 1.5, 'end': 2.4}, {'start': 3.7, 'end': 4.2} ] }, [] ),
( { 'd5':[ {'start': 1.3, 'end': 2.0}, {'start': 3.0, 'end': 4.0} ] }, [] ),
( { 'd6':[ {'start': 1.1, 'end': 2.6}, {'start': 3.6, 'end': 4.0} ] }, [] ),
</code></pre>
<p>]</p>
<p>Each tuple contains a dictionary and an empty list. And each dictionary contains a list of 2 dictionaries.</p>
<p>I can´t find the way to loop over all dictionaries and get all the values for the key "start".
This would be the result I am looking for:</p>
<pre><code>result_list = [1.2,3.0,1.4,3.2,1.5,3.5,1.3,3.7,1.3,3.0,1.1,3.6]
</code></pre>
<p>Any help would be greatly appreciated. Thanks in advance.</p>
| [
{
"answer_id": 74166771,
"author": "Rahul K P",
"author_id": 4407666,
"author_profile": "https://Stackoverflow.com/users/4407666",
"pm_score": 3,
"selected": true,
"text": "In [1]: [i['start'] for item in listoftuples for i in list(item[0].values())[0]]\nOut[1]: [1.2, 3.0, 1.4, 3.2, 1.7,... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9794687/"
] |
74,166,725 | <p>I have trouble finding the time complexity of my program and the exact formula to compute the number of calls (represented by the length of the list). Here is my python program that I wrote:</p>
<pre><code>from math import *
def calc(n):
i = n
li = []
while i>0:
j = 0
li.append(1)
while j<n:
li.append(1)
k = j
while k<n:
li.append(1)
k+=1
j+=1
i = floor(i/2)
return len(li)
for i in range(1, 16):
print(calc(i))
</code></pre>
| [
{
"answer_id": 74166771,
"author": "Rahul K P",
"author_id": 4407666,
"author_profile": "https://Stackoverflow.com/users/4407666",
"pm_score": 3,
"selected": true,
"text": "In [1]: [i['start'] for item in listoftuples for i in list(item[0].values())[0]]\nOut[1]: [1.2, 3.0, 1.4, 3.2, 1.7,... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310614/"
] |
74,166,730 | <p>The last <code>else</code> <code>if</code> block is not getting executed when the condition is satisfied please help. Thank you.</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>let rotatingArr = (n, arr, k) => {
if (n == arr.length && k !== 0 && k <= arr.length) {
let arr2 = []
arr
let delItems = Math.abs(arr.length - k)
console.log(delItems)
let modArr = arr.slice().splice(delItems)
modArr
arr.splice(-k)
console.log(arr)
let result = [...modArr, ...arr];
return result
} else if (k == 0) {
return arr;
} else if (11 > k > arr.length) {
k = k - 5
arr
let delItems = Math.abs(arr.length - k)
console.log(delItems)
let modArr = arr.slice().splice(delItems)
modArr
arr.splice(-k)
console.log(arr)
let result = [...modArr, ...arr];
return result
}
}
console.log(rotatingArr(5, [1, 2, 3, 4, 5], 10))</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74166771,
"author": "Rahul K P",
"author_id": 4407666,
"author_profile": "https://Stackoverflow.com/users/4407666",
"pm_score": 3,
"selected": true,
"text": "In [1]: [i['start'] for item in listoftuples for i in list(item[0].values())[0]]\nOut[1]: [1.2, 3.0, 1.4, 3.2, 1.7,... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17355214/"
] |
74,166,768 | <p>In this code:</p>
<pre class="lang-js prettyprint-override"><code>function max(...numbers){
let result = -Infinity; // <= here's the question
for (let number of numbers) {
if (number > result) result = number
}
return result;
}
</code></pre>
<p>I don't understand the meaning of the minus in front of infinity. The code returns the highest number given in the arguments. I returns <code>Infinity</code> without the minus.</p>
| [
{
"answer_id": 74166771,
"author": "Rahul K P",
"author_id": 4407666,
"author_profile": "https://Stackoverflow.com/users/4407666",
"pm_score": 3,
"selected": true,
"text": "In [1]: [i['start'] for item in listoftuples for i in list(item[0].values())[0]]\nOut[1]: [1.2, 3.0, 1.4, 3.2, 1.7,... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4803880/"
] |
74,166,770 | <p>I am facing difficulty in understanding the following concepts. I had <a href="https://stackoverflow.com/questions/74163620/difference-between-createobject-and-new-when-opening-a-new-excel-application?noredirect=1#comment130944741_74163620">posted a question</a> some time back - read through the answers but some things are still not clear. I state my confusion below:</p>
<p><strong>My first question refers to the following code piece</strong></p>
<pre><code>Option Strict On
Imports Microsoft.Office.Interop
Dim oxl As Excel.Application
oxl = CreateObject("Excel.Application")
</code></pre>
<p>In the above code piece, the statement <code>oxl = CreateObject("Excel.Application")</code> throws an error stating, <code>Option Strict On disallows implicit conversions from Object to Application</code>. My question is I read from many sources that it is always better to keep Option Strict ON but in this case when we need to create a new excel application, the Option Strict ON is preventing us from doing so. <strong>So what is the best practice that should be followed for such a conflict?</strong></p>
<p>Next I tried replacing the statement <code>oxl = CreateObject("Excel.Application")</code> with <code>oxl = New Excel.Application</code>. It was observed that even with Option Strict ON, we can create a new excel application object with the NEW keyword. It was also checked with GetType that in both cases that is, using CreateObject and NEW, the type of object being created was: <code>System._ComObject</code>.So my question is if the type of object being created remains remains the same, <strong>why is that Option Strict disallows <code>CreateObject</code> but allows the creation of the excel application object using <code>NEW</code>?</strong></p>
<p>To study it further, I extended the above code to the following:</p>
<pre><code>Option Strict On
Imports System
Imports Microsoft.Office.Interop
Module Program
Dim oxl As Excel.Application
Dim owb As Excel.Workbook
Dim osheet As Excel.Worksheet
Sub Main()
oxl = New Excel.Application
'oxl = CreateObject("Excel.Application")
Console.WriteLine(oxl.GetType)
oxl.Visible = True
owb = oxl.Workbooks.Add()
osheet = owb.Worksheets("Sheet1") ‘Error: Option Strict ON disallows implicit conversions from ‘Object’ to ‘Worksheet’
osheet.Range("A1").Value = 53
Console.WriteLine("Hello World!")
Console.ReadLine()
End Sub
End Module
</code></pre>
<p>When we run the code we see that the error <code>Option Strict ON disallows implicit conversions from ‘Object’ to ‘Worksheet’</code> comes at the line: <code>osheet = owb.Worksheets("Sheet1")</code></p>
<p><strong>Question:</strong>
Why is the error coming? I mean if, <code>owb = oxl.Workbooks.Add()</code>can work (that it returns a workbook which is referred to by <code>owb</code>) then why is <code>osheet = owb.Worksheets("Sheet1")</code> not working because the right hand side returns the “Sheet1” of the workbook which <code>osheet</code> should be able to point to (given that it is of the type <code>Excel.Worksheet</code>)?</p>
| [
{
"answer_id": 74166771,
"author": "Rahul K P",
"author_id": 4407666,
"author_profile": "https://Stackoverflow.com/users/4407666",
"pm_score": 3,
"selected": true,
"text": "In [1]: [i['start'] for item in listoftuples for i in list(item[0].values())[0]]\nOut[1]: [1.2, 3.0, 1.4, 3.2, 1.7,... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12508654/"
] |
74,166,793 | <p>I am wanting to include dynamic variables inside of an if statement.</p>
<pre><code>{% elif request.path == "/order/**{{city}}**" %}
</code></pre>
<p>I have a database I can refer to, to get the city names I need out depending on the url but am having a hard time sending that info in through this if statement.
(Everything works dynamically up until this point)</p>
<p>Solutions?</p>
| [
{
"answer_id": 74166771,
"author": "Rahul K P",
"author_id": 4407666,
"author_profile": "https://Stackoverflow.com/users/4407666",
"pm_score": 3,
"selected": true,
"text": "In [1]: [i['start'] for item in listoftuples for i in list(item[0].values())[0]]\nOut[1]: [1.2, 3.0, 1.4, 3.2, 1.7,... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9465752/"
] |
74,166,804 | <p>I am creating a code editor using contenteditable and would like to add some syntax highlighting as a background color for all span element. I am using a negative margin to compensate for the border of the element (not shown in the following example, as it is irrelevant to the question). Here is the problem: Using a negative margin on an inline element clips the text at the end, like this:</p>
<p><a href="https://i.stack.imgur.com/jvwLl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jvwLl.png" alt="enter image description here" /></a></p>
<p>I have tried <strong>cannot</strong> use the following, as it messes with my editor in some browsers:</p>
<ul>
<li>Pseudo elements</li>
<li>position: absolute</li>
</ul>
<p>Here is a code example of the text being clipped:</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>span{
margin-left: -20px;
}
/* For visualization only */
* span:first-child{
background-color: red;
}
* span:last-child{
background-color: yellow;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<span>Hello world</span><span>Hello world</span>
</div></code></pre>
</div>
</div>
</p>
<p>If anyone knows how to achieve this without using the aforementioned techniques it would be greatly appreciated.</p>
<p>Edit: The following is an illustration of the desired outcome. This might look like an undesirable effect, but it does make sense in the context of my project.</p>
<p><a href="https://i.stack.imgur.com/cdeUx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cdeUx.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74167036,
"author": "Crystal",
"author_id": 16513001,
"author_profile": "https://Stackoverflow.com/users/16513001",
"pm_score": 0,
"selected": false,
"text": "span.wrapper { \nbackground: rgb(249,246,0);\nbackground: linear-gradient(90deg, rgba(246,2,2,1) 44%, rgba(249,24... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3289949/"
] |
74,166,813 | <p>What I want to do is filter two different values from an object so I can merge them</p>
<p>I need to find a way to merge only the keys with the same value in "artist" <em>and</em> with the same value in "Title"</p>
<p>I got the merge code from another question, so I don't know so much of what's happening there for me to make any change.</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>var data = '[{"title":"Better","artist":"Ben Platt","plays":"5"},{"title":"Better","artist":"OneRepublic","plays":"12"},{"title":"Honest Man","artist":"Ben Platt","plays":"23"},{"title":"Better","artist":"Ben Plat","plays":"9"}]';
obj = JSON.parse(data);
// turns the "plays" value into an integer
for (i = 0; i < obj.length; i++) {
obj[i].plays = parseInt(obj[i].plays, 10);
}
// merge all the songs with the same name and sum the "plays" value
grouped = obj.reduce(function(hash) {
return function(r, a) {
(hash[a.name] = hash[a.title] || r[r.push({
title: a.title,
plays: 0
}) - 1]).plays += a.plays;
return r;
};
}(Object.create(null)), []);
console.log(grouped);</code></pre>
</div>
</div>
</p>
<p>The output I'm looking for would be something like this:</p>
<pre><code>'[{"title":"Better","artist":"Ben Platt","plays":"14"},{"title":"Better","artist":"OneRepublic","plays":"12"},{"title":"Honest Man","artist":"Ben Platt","plays":"23"}'
</code></pre>
| [
{
"answer_id": 74167036,
"author": "Crystal",
"author_id": 16513001,
"author_profile": "https://Stackoverflow.com/users/16513001",
"pm_score": 0,
"selected": false,
"text": "span.wrapper { \nbackground: rgb(249,246,0);\nbackground: linear-gradient(90deg, rgba(246,2,2,1) 44%, rgba(249,24... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310423/"
] |
74,166,830 | <p>I sorted a list of passengers but some of them are not in their appropriate groups.</p>
<p>I'm using this criteria:</p>
<p>1st Group: Type H<br />
2nd Group: Type E AND Row 1-4<br />
3rd Group: Type G AND Row 1-4<br />
4th Group: Type E OR (Type G AND Row 10 or 11)<br />
5th Group: Type G AND Row 23-26<br />
6th Group: Type G AND Row 17-22<br />
7th Group: Type G AND Row 11-16<br />
8th Group: Type G AND Row 5-10</p>
<p>The 1st group has should appear at the beginning of the list and 8th Group should appear at end of the list. The Priority numbers range from 103 to 1.</p>
<p>Here is the original unsorted list of passengers (Name, type, rowNumber):</p>
<pre><code>Whitley G 8
Knowles G 1
Rocha G 24
Boyle G 24
Wooten G 2
Forbes G 16
Vinson E 1
Valencia E 7
Lindsay E 16
Rasmussen E 5
Sargent G 11
Sosa G 23
Head G 3
Holcomb G 5
Carney G 4
Kirkland G 14
Levine E 9
Cash G 10
Kaufman G 6
Ratliff G 9
Macias G 4
Sharpe G 17
Sweet G 17
Delaney G 9
Emerson G 5
Castaneda E 9
Rutledge G 26
Stuart G 19
Rosales G 23
Baird G 2
Clemons G 8
Mcgowan G 18
Compton E 10
Albert G 15
Acevedo G 14
Mayer E 9
Fitzpatrick G 16
Chaney G 8
Jarvis G 3
Berger G 26
Britt E 11
Odonnell E 8
Levy E 9
Mullen G 6
Pollard G 22
Lott G 10
Cantrell G 15
Holder E 5
Vaughan E 11
Mccarty E 24
Wilder G 11
Mayo G 1
Pickett G 8
Sykes G 26
Bender G 13
Aguirre G 16
Bernard G 10
Hopper H 7
Melendez G 13
Macdonald H 18
Carver G 15
Gould E 26
Suarez G 6
Zamora G 15
Hinton G 13
Cabrera G 26
Dickson G 22
Salas G 24
Bentley G 13
Fuentes G 23
Terrell H 3
Holman E 7
Mcintyre G 16
Hebert G 13
Hendricks G 3
Jacobson G 14
Kline G 14
Faulkner G 5
Chan G 14
Mays G 1
Crosby G 25
Buck G 22
Maddox G 20
Buckley E 17
Kane G 10
Rivas E 26
Dudley G 22
Best G 12
Finley G 24
William G 18
Frost G 2
Ashley G 14
Mcconnell G 7
Blevins G 11
Middleton G 17
Bean G 18
Sheppard G 11
Estes E 7
Pugh G 8
Rivers E 6
Barr G 4
Landry E 10
Foley G 2
</code></pre>
<p>Here is my some of my code:</p>
<pre><code>public void loadOldPQ(ArrayList<Passenger> list) throws IOException {
int priorityNumber = list.size();
while (!list.isEmpty()) {
//H forLoop capture all required passengers
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getType().equalsIgnoreCase("H")) {
list.get(i).setKey(priorityNumber);
oldPQ.add((list.get(i)));
list.remove(i);
priorityNumber--;
}
}
//Type E AND Row 1-4 forLoop works
for (int j = 0; j < list.size(); j++) {
if (list.get(j).getRow() >= 1 && list.get(j).getRow() <= 4
&& list.get(j).getType().equalsIgnoreCase("E")) {
list.get(j).setKey(priorityNumber);
oldPQ.add(list.get(j));
list.remove(j);
priorityNumber--;
}
}
//Type G(implied) and Row 1-4 forLoop works
for (int k = 0; k < list.size(); k++) {
if (list.get(k).getRow() >= 1 && list.get(k).getRow() <= 4) {
list.get(k).setKey(priorityNumber);
oldPQ.add(list.get(k));
list.remove(k);
priorityNumber--;
}
}
//Type E or Row 10, 11 forLoop
for (int l = 0; l < list.size(); l++) {
if (list.get(l).getType().equalsIgnoreCase("E") || list.get(l).getRow() == 10
|| list.get(l).getRow() == 11) {
list.get(l).setKey(priorityNumber);
oldPQ.add(list.get(l));
list.remove(l);
priorityNumber--;
}
}
//Row 23-26 forLoop
for (int m = 0; m < list.size(); m++) {
if (list.get(m).getRow() >= 23 && list.get(m).getRow() <= 26) {
list.get(m).setKey(priorityNumber);
oldPQ.add(list.get(m));
list.remove(m);
priorityNumber--;
}
}
//Row 17-22 forLoop
for (int n = 0; n < list.size(); n++) {
if (list.get(n).getRow() >= 17 && list.get(n).getRow() <= 22) {
list.get(n).setKey(priorityNumber);
oldPQ.add(list.get(n));
list.remove(n);
priorityNumber--;
}
}
//Row 11-16 forLoop (row 11 should've already been removed)
for (int o = 0; o < list.size(); o++) {
if (list.get(o).getRow() >= 11 && list.get(o).getRow() <= 16) {
list.get(o).setKey(priorityNumber);
oldPQ.add(list.get(o));
list.remove(o);
priorityNumber--;
}
}
//Row 5-10 forLoop (Row 10 passengers should've already be removed)
for (int p = 0; p < list.size(); p++) {
if (list.get(p).getRow() >= 5 && list.get(p).getRow() <= 10) {
list.get(p).setKey(priorityNumber);
oldPQ.add(list.get(p));
list.remove(p);
priorityNumber--;
}
}
}
oldProcedure(oldPQ);
}
</code></pre>
<p>For instance, Kane, McConnell, Estes should be group with 4th group. Clemons, Chauncy, Pickett should appear towards the end of the list in 8th Group because they have row numbers 5-10.</p>
<p>Here are my results:</p>
<pre><code>Name Type Row Key
Hopper H 7 103
Macdonald H 18 102
Terrell H 3 101
Vinson E 1 100
Knowles G 1 99
Wooten G 2 98
Head G 3 97
Carney G 4 96
Macias G 4 95
Baird G 2 94
Jarvis G 3 93
Mayo G 1 92
Hendricks G 3 91
Mays G 1 90
Frost G 2 89
Barr G 4 88
Foley G 2 87
Valencia E 7 86
Rasmussen E 5 85
Levine E 9 84
Castaneda E 9 83
Compton E 10 82
Mayer E 9 81
Britt E 11 80
Levy E 9 79
Lott G 10 78
Holder E 5 77
Mccarty E 24 76
Bernard G 10 75
Gould E 26 74
Holman E 7 73
Buckley E 17 72
Rivas E 26 71
Blevins G 11 70
Sheppard G 11 69
Rivers E 6 68
Rocha G 24 67
Sosa G 23 66
Rutledge G 26 65
Rosales G 23 64
Berger G 26 63
Sykes G 26 62
Cabrera G 26 61
Salas G 24 60
Fuentes G 23 59
Crosby G 25 58
Finley G 24 57
Sharpe G 17 56
Stuart G 19 55
Mcgowan G 18 54
Pollard G 22 53
Dickson G 22 52
Buck G 22 51
Dudley G 22 50
William G 18 49
Middleton G 17 48
Forbes G 16 47
Sargent G 11 46
Kirkland G 14 45
Albert G 15 44
Fitzpatrick G 16 43
Cantrell G 15 42
Wilder G 11 41
Bender G 13 40
Melendez G 13 39
Zamora G 15 38
Bentley G 13 37
Hebert G 13 36
Kline G 14 35
Chan G 14 34
Best G 12 33
Whitley G 8 32
Holcomb G 5 31
Kaufman G 6 30
Delaney G 9 29
Clemons G 8 28
Chaney G 8 27
Mullen G 6 26
Pickett G 8 25
Suarez G 6 24
Faulkner G 5 23
Kane G 10 22
Mcconnell G 7 21
Estes E 7 20
Landry E 10 19
Lindsay E 16 18
Odonnell E 8 17
Boyle G 24 16
Sweet G 17 15
Maddox G 20 14
Bean G 18 13
Acevedo G 14 12
Aguirre G 16 11
Hinton G 13 10
Jacobson G 14 9
Cash G 10 8
Emerson G 5 7
Pugh G 8 6
Vaughan E 11 5
Carver G 15 4
Ashley G 14 3
Ratliff G 9 2
Mcintyre G 16 1
</code></pre>
| [
{
"answer_id": 74167036,
"author": "Crystal",
"author_id": 16513001,
"author_profile": "https://Stackoverflow.com/users/16513001",
"pm_score": 0,
"selected": false,
"text": "span.wrapper { \nbackground: rgb(249,246,0);\nbackground: linear-gradient(90deg, rgba(246,2,2,1) 44%, rgba(249,24... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17919480/"
] |
74,166,844 | <p>I'm working on one project for some time now on flutter. Part of the source code has been designed so that it can be used again as is in other projects.</p>
<p>I'm working with <strong>Visual Studio Code</strong>.</p>
<p>Now I'm creating a second project. I'd like to organize folders this way:</p>
<pre><code>Parent folder
Project1 folder
Project2 folder
my_library
</code></pre>
<p>Is it possible to add the library folder to the projects, as it is not inside their respective folders?</p>
| [
{
"answer_id": 74168039,
"author": "Richard Heap",
"author_id": 9597706,
"author_profile": "https://Stackoverflow.com/users/9597706",
"pm_score": 1,
"selected": false,
"text": "pubspec.yaml"
},
{
"answer_id": 74171284,
"author": "Jacques",
"author_id": 11350338,
"auth... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11350338/"
] |
74,166,863 | <p>I have this pipeline :</p>
<pre><code> let pipeline = [
{
$match: {
date: { $gte: new Date("2022-10-19"), $lte: new Date("2022-10-26") },
},
},
{
$group: {
_id: "$date",
tasks: { $push: "$$ROOT" },
},
},
{
$sort: { _id: -1 },
},
];
const aggregationData = await ScheduleTaskModel.aggregate(pipeline);
</code></pre>
<p>where i group all "tasks" between a date range by date and i get that result :</p>
<pre><code>[
{
"date": "2022-10-21T00:00:00.000Z",
"tasks": [...tasks with this date]
},
{
"date": "2022-10-20T00:00:00.000Z",
"tasks": [...tasks with this date]
}
]
</code></pre>
<p>as you see i have "tasks" only for 2 dates in that range,what if i want all dates to appear even the ones with no tasks so it would be like this with empty arrays ?</p>
<pre><code>[
{
"date": "2022-10-26T00:00:00.000Z",
"tasks": []
},
{
"date": "2022-10-25T00:00:00.000Z",
"tasks": []
},
{
"date": "2022-10-24T00:00:00.000Z",
"tasks": []
},
{
"date": "2022-10-23T00:00:00.000Z",
"tasks": []
},
{
"date": "2022-10-22T00:00:00.000Z",
"tasks": []
},
{
"date": "2022-10-21T00:00:00.000Z",
"tasks": [...tasks with this date]
},
{
"date": "2022-10-20T00:00:00.000Z",
"tasks": [...tasks with this date]
},
{
"date": "2022-10-19T00:00:00.000Z",
"tasks": []
},
]
</code></pre>
<p>i tried to use $densify but unfortunately it requires upgrading my mongoDb atlas cluster which is not possible..</p>
| [
{
"answer_id": 74168039,
"author": "Richard Heap",
"author_id": 9597706,
"author_profile": "https://Stackoverflow.com/users/9597706",
"pm_score": 1,
"selected": false,
"text": "pubspec.yaml"
},
{
"answer_id": 74171284,
"author": "Jacques",
"author_id": 11350338,
"auth... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14718856/"
] |
74,166,867 | <p>I was wondering if I could get your suggestions on how to remove the code duplication/repetition here.</p>
<p>Any preferred and correct way of doing so?</p>
<p>Summary: This function returns a car's name and accepts the car code as a parameter</p>
<pre><code>public string GetMatchingCar(string carCode)
{
//CarResults is the list of cars that consists the details of the car as a collection.
var carResults = new List<Car>
{
new Car{Name="AB car", Code="AB", Colors = new List<string>{"blue","green","black"}, Features=new List<string>{"compact","fast","light"} },
new Car{Name="AC car", Code="AC", Colors = new List<string>{"gray","white","yellow"}, Features=new List<string>{"extended","fast","heavy"} },
new Car{Name="DE car", Code="DE", Colors = new List<string>{"red","green","purple"}, Features=new List<string>{"sports","light"} },
//and so on
};
//Specifications is a list of specification to choose from that includes color and feature.
var specifications = new List<Specification>
{
new Specification{Color="blue", Feature="heavy"},
new Specification{Color="red", Feature="light"},
new Specification{Color="maroon", Feature="compact"},
new Specification{Color="black", Feature="manual"},
new Specification{Color="neon", Feature="heavy"},
//and so on
}
//Now, we need to return the car based on the priority of criteria. Say P1, P2 and P3. P1's priority being highest.
//P1: Code + Color + Feature
//P2: Code + Feature
//P3: Feature
//just for example, priorities can be from P1 - P7
//Now we have to combine the specification with carCode to check the priorities and return the matching car.
//TODO: Here, is where I think I am doing wrong by having each for loop for each priority (as priorities can be upto Seven). All the foreach loop won't be executed if a priority is matched and returns a car.
//TODO: Wondering how could I improve this?
//priority P1: Code + Color + Feature
foreach(var specification in specifications){
var matchingCarP1 = carResults.FirstOrDefault(x=> x.Code.Equals(carCode) && x.Colors.Contains(specification.Color) && x.Features.Contains(specification.Feature));
if(matchingCarP1 != null) return matchingCarP1.Name;
}
//priority P2: Code + Feature
foreach(var specification in specifications){
var matchingCarP2 = carResults.FirstOrDefault(x=> x.Code.Equals(carCode) && x.Features.Contains(specification.Feature));
if(matchingCarP2 != null) return matchingCarP2.Name;
}
//priority P3: Feature
foreach(var specification in specifications){
var matchingCarP3 = carResults.FirstOrDefault(x.Features.Contains(specification.Feature));
if(matchingCarP3 != null) return matchingCarP3.Name;
}
//Other priorities
return string.Empty;
}
</code></pre>
<p>Any suggestions or feedback on this would be really helpful and highly appreciated!
Thank you!</p>
| [
{
"answer_id": 74168039,
"author": "Richard Heap",
"author_id": 9597706,
"author_profile": "https://Stackoverflow.com/users/9597706",
"pm_score": 1,
"selected": false,
"text": "pubspec.yaml"
},
{
"answer_id": 74171284,
"author": "Jacques",
"author_id": 11350338,
"auth... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11444453/"
] |
74,166,875 | <p>I created a 3D contour map in Mathematica a while back, and I am trying to do it in Python this time. First let me show you what I obtained:</p>
<p>Mathematica:</p>
<p><a href="https://i.stack.imgur.com/iNuVa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iNuVa.png" alt="enter image description here" /></a></p>
<p>Python:</p>
<p><a href="https://i.stack.imgur.com/cmz42.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cmz42.png" alt="enter image description here" /></a></p>
<p>Now, I would like the foreground (the visible part of the hills) to hide the background (the invisible part). In the Python version, it seems as if you are watching these mountains as if you were beneath them. I am not sure how to fix it, to make it more like the Mathematica version (I don't care about the colors, I actually like the colors in the Python version better). Here is the code:</p>
<pre><code>import numpy as np
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
plt.rcParams["lines.linewidth"]=0.5
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
X, Y = np.mgrid[-3:3:30j, -3:3:30j]
Z= np.exp(-(abs(X)**2 + abs(Y)**2)) + 0.8*np.exp(-4*((abs(X-1.5))**4.2 + (abs(Y-1.4))**4.2))
ax.plot_surface(X, Y, Z, cmap="coolwarm", rstride=1, cstride=1, alpha=0.2)
# ax.contourf(X, Y, Z, levels=60, colors="k", linestyles="solid", alpha=0.9, antialiased=True)
ax.contour(X, Y, Z, levels=60, linestyles="solid", alpha=0.9, antialiased=True)
plt.show()
plt.savefig('contour3D.png', dpi=300)
</code></pre>
| [
{
"answer_id": 74167072,
"author": "matoqq",
"author_id": 3597814,
"author_profile": "https://Stackoverflow.com/users/3597814",
"pm_score": 0,
"selected": false,
"text": "ax.plot_surface(X, Y, Z, cmap=\"coolwarm\", rstride=1, cstride=1, alpha=1)\n"
},
{
"answer_id": 74167252,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2672662/"
] |
74,166,916 | <p>Using Django 4.1.2, filtering does not work for database fields.</p>
<p>Given the following model:</p>
<pre><code>class Activities(models.Model):
es_date = models.DateField(blank=True, null=True)
ef_date = models.DateField(blank=True, null=True)
ls_date = models.DateField(blank=True, null=True)
lf_date = models.DateField(blank=True, null=True)
</code></pre>
<p>Migration done and DB content can be retrieved, for instance it gives back all of them properly:</p>
<pre><code>>>>from mymodel.models import Activities
>>>Activities.objects.all()
<QuerySet [<Activities: Task 33>, <Activities: Task 30>...]>
</code></pre>
<p>or requesting a particular item also works properly:</p>
<pre><code>>>>Activities.objects.get(id=1)
<Activities: Task 1>
</code></pre>
<p>although applying filter for a given field it drops "<strong>NameError</strong>" error</p>
<pre><code>>>>Activities.objects.all().filter(es_date>timezone.now())
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'es_date' is not defined
</code></pre>
<p>What might be the error?</p>
| [
{
"answer_id": 74167072,
"author": "matoqq",
"author_id": 3597814,
"author_profile": "https://Stackoverflow.com/users/3597814",
"pm_score": 0,
"selected": false,
"text": "ax.plot_surface(X, Y, Z, cmap=\"coolwarm\", rstride=1, cstride=1, alpha=1)\n"
},
{
"answer_id": 74167252,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3407564/"
] |
74,166,924 | <p>I have encountered this error.</p>
<blockquote>
<p><code>ModuleNotFoundError: No module named 'rest_framework'</code></p>
</blockquote>
<p>I have a virtual environment setted up and the rest framework is installed correctly.</p>
<p>When I run <code>pip3.10 show djangoframework</code>, I get</p>
<pre><code>Name: djangorestframework
Version: 3.14.0
Summary: Web APIs for Django, made easy.
Home-page: https://www.django-rest-framework.org/
Author: Tom Christie
Author-email: tom@tomchristie.com
License: BSD
Location: c:\users\chan\desktop\testpy\lib\site-packages
Requires: django, pytz
Required-by:
</code></pre>
<p>My interpreter is Python 3.10.8 which is the same version and it is for the virtual environment. my VSCode shows my interpreter as <code>Python 3.10.8 ("TESTPY":venv) .\Scripts\python.exe</code>.</p>
<p>I also have included the rest_framework in the INSTALLED_APPS in the settings.py</p>
<pre><code>INSTALLED_APPS = [
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
</code></pre>
<p>Below is the full error I get.</p>
<pre><code>(TESTPY) PS C:\Users\Chan\Desktop\TESTPY> python3 manage.py runserver
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1016, in _bootstrap_inner
self.run()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\threading.py", line 953, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Chan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "C:\Users\Chan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run
autoreload.raise_last_exception()
File "C:\Users\Chan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception
raise _exception[1]
File "C:\Users\Chan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\__init__.py", line 398, in execute
autoreload.check_errors(django.setup)()
File "C:\Users\Chan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "C:\Users\Chan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\Chan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\apps\registry.py", line 91, in populate
app_config = AppConfig.create(entry)
File "C:\Users\Chan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\apps\config.py", line 193, in create
import_module(entry)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'rest_framework'
</code></pre>
<p>I have googled to fix this issue so many times now that all the links are purple.. Anyone have any idea why this is happening? Thanks</p>
<p>Edit:</p>
<p>When I run <code>pip list</code>, this is what I get.</p>
<pre><code>(TESTPY) PS C:\Users\Chan\Desktop\TESTPY> pip list
Package Version
------------------- -------
asgiref 3.5.2
Django 4.1.2
djangorestframework 3.14.0
pip 22.3
pytz 2022.5
setuptools 63.2.0
sqlparse 0.4.3
tzdata 2022.5
</code></pre>
| [
{
"answer_id": 74167072,
"author": "matoqq",
"author_id": 3597814,
"author_profile": "https://Stackoverflow.com/users/3597814",
"pm_score": 0,
"selected": false,
"text": "ax.plot_surface(X, Y, Z, cmap=\"coolwarm\", rstride=1, cstride=1, alpha=1)\n"
},
{
"answer_id": 74167252,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12983780/"
] |
74,166,927 | <p>can someone please help? I have been struggling with this for hrs. Here is the code. I have to be able to type whatever name into the boxes click the display button to show what I typed, concatenate with a hello and say what I typed below then also be able to hit the clear button to clear everything as if refreshed I also have to have call a function on my other page named display Hello Message. I can only get it to display the hello and the first name and clear one thing. Here's what I have.</p>
<pre><code><!DOCTYPE html>
<html>
\
<head>
<title>JavaScript: Input & Output Assignment</title>
</head>
<body>
<h1>Hello Name - Input & Output</h1>
<div>
<label for="firstNameInput"> First Name</label>
<input type="text" id="firstNameInput" placeholder="Enter a first name" />
<label for="lastNameInput"> Last Name</label>
<input type="text" id="lastNameInput" placeholder="Enter a last name" />
<button onclick="displayHelloMessage()">Display</button> <button onclick="displayHelloMessage()">Clear</button>
</div>
<p id="helloNameOutput"></p>
<script src="/script.js"></script>
</body>
</html>
</code></pre>
| [
{
"answer_id": 74167072,
"author": "matoqq",
"author_id": 3597814,
"author_profile": "https://Stackoverflow.com/users/3597814",
"pm_score": 0,
"selected": false,
"text": "ax.plot_surface(X, Y, Z, cmap=\"coolwarm\", rstride=1, cstride=1, alpha=1)\n"
},
{
"answer_id": 74167252,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20307133/"
] |
74,166,929 | <p>I have an <em>unordered</em> sequence of timestamps. I need to be able calculate <em>min</em>, <em>max</em> and <em>average</em> difference between every subsequent timestamps. e.g. given:</p>
<pre><code>DateTimeOffset now = new DateTimeOffset(new DateTime(2022, 1, 1, 0, 0, 0, 0));
DateTimeOffset[] timestamps = new[] {
now,
now.AddSeconds(5),
now.AddSeconds(10),
now.AddSeconds(15),
now.AddSeconds(30),
now.AddSeconds(31)
};
IEnumerable<DateTimeOffset> timestampsSorted = timestamps.OrderByDescending(x => x);
</code></pre>
<p>Should produce:</p>
<pre><code>2022-01-01 00:00:31->2022-01-01 00:00:30 | 00:00:01
2022-01-01 00:00:30->2022-01-01 00:00:15 | 00:00:15
2022-01-01 00:00:15->2022-01-01 00:00:10 | 00:00:05
2022-01-01 00:00:10->2022-01-01 00:00:05 | 00:00:05
2022-01-01 00:00:05->2022-01-01 00:00:00 | 00:00:05
Min 00:00:01
Max 00:00:15
Avg 00:00:06.2000000
</code></pre>
<p>The procedural solution I have come up with is below, it would be great if I can simplify this using LINQ.</p>
<pre><code>TimeSpan min = TimeSpan.MaxValue;
TimeSpan max = TimeSpan.MinValue;
List<TimeSpan> deltas = new();
for (int i = timestampsSorted.Length - 1; i > 0; i--)
{
DateTimeOffset later = timestamps[i];
DateTimeOffset prev = timestamps[i - 1];
TimeSpan delta = later - prev;
if (delta > max) { max = delta; }
if (delta < min) { min = delta; }
deltas.Add(delta);
Console.WriteLine($"{later:yyyy-MM-dd HH:mm:ss}->{prev:yyyy-MM-dd HH:mm:ss} | {delta}");
}
var result = new {
Min = min,
Max = max,
Avg = TimeSpan.FromMilliseconds(deltas.Average(d => d.TotalMilliseconds))
};
</code></pre>
| [
{
"answer_id": 74167271,
"author": "pfx",
"author_id": 9200675,
"author_profile": "https://Stackoverflow.com/users/9200675",
"pm_score": 1,
"selected": false,
"text": "LINQ"
},
{
"answer_id": 74168433,
"author": "Lance U. Matthews",
"author_id": 150605,
"author_profil... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1226568/"
] |
74,166,936 | <p>I'm trying to sum values based on two criteria: category and month (Renew).
I want to sum categories by renew month.
So, for things renewed in March, sum separately by category, but what is monthly and have the same category, must be summed too.</p>
<p><a href="https://i.stack.imgur.com/NPCbu.png" rel="nofollow noreferrer">Example table</a></p>
<p>For example:
I have Softwares / Apps / Sites category that have different renew dates (March, April, May, June, September and also monthly).
So, I need to separate and sum values by month, but what are "monthly" have to be summed on all months.
Like this:</p>
<h3></h3>
<blockquote>
<h4>Softwares / Apps / Sites category</h4>
<ul>
<li>march: 26,50</li>
<li>april: 24,90</li>
<li>may: 30,60</li>
<li>june: 64</li>
<li>september: 24,90</li>
</ul>
</blockquote>
<p>Hope I made it clear...
I'm going crazy with that... please, help me...</p>
| [
{
"answer_id": 74167271,
"author": "pfx",
"author_id": 9200675,
"author_profile": "https://Stackoverflow.com/users/9200675",
"pm_score": 1,
"selected": false,
"text": "LINQ"
},
{
"answer_id": 74168433,
"author": "Lance U. Matthews",
"author_id": 150605,
"author_profil... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310229/"
] |
74,166,937 | <p>I keep getting a "<strong>could not open read-write messages</strong>" when creating a table or inserting rows?</p>
<p><em>2022-10-21T17:27:11.336011Z I i.q.c.l.t.LineTcpMeasurementScheduler could not create table [tableName=cpu, ex=could not open read-write</em></p>
<p><em>io.questdb.cairo.CairoException: [22] could not open read-only [file=/root/.questdb/db/cpu/service.k]</em></p>
<p>I have tried the troubleshoot solution given in QuestDB forums but it does not work.
If you could explain why it does not work along with the solution, I would appreciate it.</p>
| [
{
"answer_id": 74167271,
"author": "pfx",
"author_id": 9200675,
"author_profile": "https://Stackoverflow.com/users/9200675",
"pm_score": 1,
"selected": false,
"text": "LINQ"
},
{
"answer_id": 74168433,
"author": "Lance U. Matthews",
"author_id": 150605,
"author_profil... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20306597/"
] |
74,166,968 | <p>I was trying to set Timeout to my extension popup .I see after the work is done, it doesn't get automatically closed until clicked on somewhere on the page. I was trying to set timeout for auto closing of my extension popup. Below is my code.</p>
<pre><code>a.addEventListener("click", async () => {
button.style.backgroundColor = 'white';
document.getElementById("button").style.backgroundColor = 'white';
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: codeWork,
});
});
</code></pre>
<p>I followed many suggestions available but it is throwing the error shown in <a href="https://stackoverflow.com/questions/70747982/uncaught-evalerror-refused-to-evaluate-a-string-as-javascript-because-unsafe-e">Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in Content Security Pol</a></p>
<p>Please help me on how to set timer to my popup function.</p>
<p>Also my func:codeWork return response. The response might contain error. I want to change the color of the button based on the response . How to do that ?
Any help is really appreciated!!!!</p>
| [
{
"answer_id": 74167271,
"author": "pfx",
"author_id": 9200675,
"author_profile": "https://Stackoverflow.com/users/9200675",
"pm_score": 1,
"selected": false,
"text": "LINQ"
},
{
"answer_id": 74168433,
"author": "Lance U. Matthews",
"author_id": 150605,
"author_profil... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13114960/"
] |
74,166,977 | <p>I have managed to pull a list from a data source. The list elements are formatted like this (note the first number is NOT the index):</p>
<pre><code>0 cheese 100
1 cheddar cheese 1100
2 gorgonzola 1300
3 smoked cheese 200
</code></pre>
<p>etc.</p>
<p>This means when printed, one line contains "<code>0 cheese 100</code>", with all the spaces.</p>
<p>What I would like to do is parse each entry to divide it into two lists. I don't need the first number. Instead, I want the cheese type and the number after.</p>
<p>For instance:</p>
<pre><code>cheese
cheddar cheese
gorgonzola
smoked cheese
</code></pre>
<p>and:</p>
<pre><code>100
1100
1300
200
</code></pre>
<p>The ultimate goal is to be able to attribute the two lists to columns in a pd.DataFrame so they can be processed in their own individual way.</p>
<p>Any help is much appreciated.</p>
| [
{
"answer_id": 74167056,
"author": "Luis",
"author_id": 16014407,
"author_profile": "https://Stackoverflow.com/users/16014407",
"pm_score": 1,
"selected": false,
"text": "import pandas as pd\nimport re\nmylist=['0 cheese 100','1 cheddar cheese 200']\n\n\nnumbers = '[0-9]'\n\nlist1=[i.spl... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74166977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19828448/"
] |
74,167,012 | <p>Just learning how to use files in python. I created a word document "mydoc.docx", opens properly before I execute the code below:</p>
<pre><code>myfile = open('mydoc.docx','w')
myfile.write ("hello"+'\n')
myfile.close()
</code></pre>
<p>After I ran the code above, the word document cannot be opened any more showing "Word experienced an error trying to open the file."</p>
<p><a href="https://i.stack.imgur.com/MfQg7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MfQg7.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74167045,
"author": "doxdeveloper",
"author_id": 16561009,
"author_profile": "https://Stackoverflow.com/users/16561009",
"pm_score": 1,
"selected": false,
"text": "open()"
},
{
"answer_id": 74167066,
"author": "topal",
"author_id": 13813625,
"author_pro... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12077297/"
] |
74,167,018 | <p>I'm on react and I have the next css and html. When I open the console it pushes to the edge of the page. What can i do to make the div be static?</p>
<pre><code>home.js
<div className="global">
<div className="box">
<h1>PY-ROBOT</h1>
</div>
<div className='box1'>
<button type="button" className='button' onClick={handleOnClickLog}>Log in</button>
<button type="button" className='button' onClick={handleOnClickReg}>Register</button>
</div>
</div>
home.css
.global{
background-color: rgb(46, 43, 43);
width: 1200px;
height: 700px;
margin:100px auto
}
</code></pre>
| [
{
"answer_id": 74167045,
"author": "doxdeveloper",
"author_id": 16561009,
"author_profile": "https://Stackoverflow.com/users/16561009",
"pm_score": 1,
"selected": false,
"text": "open()"
},
{
"answer_id": 74167066,
"author": "topal",
"author_id": 13813625,
"author_pro... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19079542/"
] |
74,167,019 | <p>What is the command to display the chart in <a href="https://yahooquery.dpguthrie.com/guide/ticker/historical/" rel="nofollow noreferrer">https://yahooquery.dpguthrie.com/guide/ticker/historical/</a></p>
<p><img src="https://user-images.githubusercontent.com/71358025/197361020-2427ce07-c7b9-4ace-a55f-d95fa9c9c816.png" alt="image" /></p>
<p>I tried this code</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
from yahooquery import Ticker
tickers = Ticker('aapl nflx', asynchronous=True)
df = tickers.history()
df["adjclose"].plot()
plt.xticks(rotation=90)
plt.show()
</code></pre>
<p>But it is just showing one series in the chart, like this:</p>
<p><img src="https://user-images.githubusercontent.com/71358025/197361201-ee22e3da-da06-4784-818f-a88550222707.png" alt="image" /></p>
<p>How can I create aapl and nflx as two series on the one chart?</p>
| [
{
"answer_id": 74167045,
"author": "doxdeveloper",
"author_id": 16561009,
"author_profile": "https://Stackoverflow.com/users/16561009",
"pm_score": 1,
"selected": false,
"text": "open()"
},
{
"answer_id": 74167066,
"author": "topal",
"author_id": 13813625,
"author_pro... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11684064/"
] |
74,167,020 | <p>I have a database where I create a new table every day and fill it with data (I know this isn't ideal, but I can't change this). Each table is of the form "TESTdata_xxxxx_DB", where xxxxx is incremented by 1 every day.</p>
<p>I need a simple way to select the top 1000 rows (where a specific condition is met) across many of those tables (i.e. across many dates). For example, I need to query across tables TESTdata_45800_DB, TESTdata_45801, ..., TESTdata_45850_DB.</p>
<p>I have tried the following query, but clearly adding "to" doesn't work, and separating them by comma doesn't combine them the way I want:</p>
<pre><code>SELECT TOP 1000
[ItemIndex],
[Data1],
[Data2],
[Data3]
FROM
[TESTDB1].[dbo].[TESTdata_45800_DB] (to...) [TESTdata_45850_DB]
WHERE
Data1 LIKE 'High' OR Data1 LIKE 'Medium'
ORDER BY
Data1
;
</code></pre>
<p>Any help would be appreciated.</p>
| [
{
"answer_id": 74167045,
"author": "doxdeveloper",
"author_id": 16561009,
"author_profile": "https://Stackoverflow.com/users/16561009",
"pm_score": 1,
"selected": false,
"text": "open()"
},
{
"answer_id": 74167066,
"author": "topal",
"author_id": 13813625,
"author_pro... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14565266/"
] |
74,167,023 | <pre><code>def CreditPay(rate, payment, verbose):
balance = 1000 # Amount currently owed
month = 1 #Number of months
paid = 0 # Amount paid so far
while balance > payment:
balance = balance + balance*rate/100 - payment
paid += payment
if verbose:
print(f'Balance after month {month} is $ {balance}.')
month += 1
print(f"Final payment is $ {balance}")
print(f'Final amount paid is $ {balance+paid}')
return month
nmonths = CreditPay(2.5,100,False)
print("Number of months to pay off is", nmonths)
nmonths = CreditPay(2.5,100,True)
print("Number of months to pay off is", nmonths)
^
</code></pre>
<p>SyntaxError: invalid syntax
martin@Martins-Air ~ % python -u "/Users/martin/Downloads/assignment7"
File "/Users/martin/Downloads/assignment7", line 19
print(f'Balance after month {month} is $ {balance}.')
^</p>
| [
{
"answer_id": 74167122,
"author": "Nara Tekchuen",
"author_id": 12097404,
"author_profile": "https://Stackoverflow.com/users/12097404",
"pm_score": 1,
"selected": true,
"text": ">Python: Select Interpreter and then simply click on any Python 3.x.x\n"
},
{
"answer_id": 74167310,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17628911/"
] |
74,167,025 | <p>I'm tiring to Pass a success message after pup checks the database and confirms the data
how do I display a message in case of a wrong password entry ,I tried many solutions with no success ,I tried using ajax solutions and JavaScript with no success as I don't know the basics on ajax and my background in JavaScript is basic
Here's my code</p>
<p>LoginTest.html</p>
<pre><code><html>
<link rel="stylesheet" href="LoginStyle.css">
<head>
<title>Login</title>
</head>
<body>
<div class="login-box">
<h2>Login</h2>
<form action="http://localhost/Test2/dbloginTest.php" method="post" name="loginform" class="loginform">
<div class="user-box">
<input type="number" name="civilid" required="">
<label>Civil ID</label>
</div>
<div class="user-box">
<input type="password" name="password" required="">
<label>Password</label>
</div>
<input type="submit" name="submit" Value="Login">
</form>
<a href="Registration.html">
<input type="submit" name="register" Value="Register">
</a>
</div>
</body>
</html>
</code></pre>
<p>dbloginTest.php</p>
<pre><code> <?php
require 'C:\Windows\System32\vendor\autoload.php';
if (isset( $_POST['submit'] ) && isset( $_POST['civilid'] ) && isset( $_POST['password'] ) ) {
$civilid = ( $_POST['civilid'] );
$password = ( $_POST['password'] );
$hashpass = "";
$return = array();
//echo extension_loaded( "mongodb" ) ? "loaded\n" : "not loaded\n";
$con = new MongoDB\Client( 'mongodb+srv://Admin:Pass123@cluster0.ivtq9gb.mongodb.net/?retryWrites=true&w=majority' );
// Select Database
if ( $con ) {
$db = $con->VoterDatabase;
// Select Collection
$collection = $db->Voters;
$cursor = $collection->find( array( 'civilid' => $civilid ) );
foreach ( $cursor as $row ) {
ob_start();
echo $row->password;
$hashpass = ob_get_clean();
}
if ( password_verify($password,$hashpass) ) {
echo "You Have Successully Logged In";
header( 'Location:Voters.html' );
exit;
} else {
echo "Your Civil ID or Password is Incorrect";
header( 'Location:LoginTest.html' );
exit;
}
} else {
die( "Mongo DB not connected" );
}
}
?>
</code></pre>
| [
{
"answer_id": 74167122,
"author": "Nara Tekchuen",
"author_id": 12097404,
"author_profile": "https://Stackoverflow.com/users/12097404",
"pm_score": 1,
"selected": true,
"text": ">Python: Select Interpreter and then simply click on any Python 3.x.x\n"
},
{
"answer_id": 74167310,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9754905/"
] |
74,167,039 | <p>I'm trying to add some conditional logic to the modifier parameter in my custom composable before using it. How can this be done? For example</p>
<pre><code>@Composable
fun MyComposable(index: Int, myModifier: Modifier = Modifier) {
if (index == 0) {
myModifier.background(Color.Red)
} else {
myModifier.background(Color.Blue)
}
Column(modifier = myModifier) {
...
}
</code></pre>
<p>Compose simply ignores changes made to <code>myModifier</code></p>
<p>For now, I'm creating a new variable of type Modifier and using that instead, but I'm wondering if there is a better way using the original passed-in modifier.</p>
| [
{
"answer_id": 74167122,
"author": "Nara Tekchuen",
"author_id": 12097404,
"author_profile": "https://Stackoverflow.com/users/12097404",
"pm_score": 1,
"selected": true,
"text": ">Python: Select Interpreter and then simply click on any Python 3.x.x\n"
},
{
"answer_id": 74167310,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2640004/"
] |
74,167,048 | <p>I have an interface <code>I</code> with a method that allows it to interact with another <code>I</code>:</p>
<pre><code>public interface I {
I interactWith(I other);
}
</code></pre>
<p>Then I have a few classes that implement this interface, let's say <code>A</code>, <code>B</code>, <code>C</code> and <code>D</code>. Some of these interact with any other in the same way, so the implementation of the method is easy. Some others interact in different ways instead depending on the type of the other object, so i.e the interaction <code>B</code>-<code>A</code> is different from <code>B</code>-<code>C</code> and <code>B</code>-<code>D</code>. The naive implementation of the method for <code>B</code> would be a mess of typechecking/<code>instanceof</code> and feels like there's a better solution, so what's the correct approach?</p>
<p>I tried adding a default method <code>interactWith(A other)</code> in both the interface and the <code>B</code> class but it never gets called. Why is overloading not choosing the more specific method?</p>
<p>Edit: added sample code, also available here: <a href="https://onlinegdb.com/fakHVDDpSX" rel="nofollow noreferrer">https://onlinegdb.com/fakHVDDpSX</a></p>
<pre><code>public interface I {
I interactWith(A other);
I interactWith(I other);
}
</code></pre>
<pre><code>public class B implements I {
public I interactWith(A other) {
System.out.println("I'd like this to get called");
}
public I interactWith(I other) {
System.out.println("this get called even when other is of type A");
}
}
</code></pre>
<pre><code>public static void main(String []args) {
List<I> list = Arrays.asList(new A(), new B());
list.get(1).interactWith(list.get(0));
}
</code></pre>
| [
{
"answer_id": 74167205,
"author": "anqit",
"author_id": 4234254,
"author_profile": "https://Stackoverflow.com/users/4234254",
"pm_score": 2,
"selected": true,
"text": "ublic class Main {\n public static void main(String[] args) {\n I a = new A(); // runtime type is `A` but st... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5337213/"
] |
74,167,054 | <p>I want to implement my own Dependency Injection like <strong>Fastapi</strong> <strong>Depends()</strong> do actually without using external package or framework. What will be the approach?
Code example will be helpful for me.
Thanks in advance.</p>
<pre><code>from typing import Callable, Optional, Any
class Depends:
def __init__(self, dependencies= Optional[Callable[..., Any]]):
self.dependencies = dependencies
def get_db():
pass
def get_token():
pass
def get_current_user(db= Depends(get_db), token= Depends(get_token)):
pass
</code></pre>
| [
{
"answer_id": 74169329,
"author": "MinatoNamikaze91",
"author_id": 16727992,
"author_profile": "https://Stackoverflow.com/users/16727992",
"pm_score": -1,
"selected": false,
"text": "async def get_db(db_con=Depends(get_db_con)) -> AsyncIterable[Session]:\n session = Session(bind=db_c... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13336615/"
] |
74,167,109 | <p>In short, the question is, how do I force React Admin to always render input values in an Edit form according to the state of the data returned from the API?</p>
<p>Background Info:</p>
<p>In my user create & edit forms, I have a password field.</p>
<p>My API never returns a password key/value.</p>
<p>After User Create, I am redirected to User Edit and the password input is filled in with the password I set in the create form, not the value from the API response.</p>
<p>This is not desired.</p>
<p>I presume this is all due to React Admin's "optimistic rendering"... but in the case of the user edit form, I would always like React Admin to respect the state of the data coming from the API.</p>
<p>I've set mutationMode to "pessimistic", but this does not effect the input values when redirected from Create, and Create has no "mutationMode".</p>
<p>So, anyone know how to always force Edit to pull its data from the API response?</p>
| [
{
"answer_id": 74169329,
"author": "MinatoNamikaze91",
"author_id": 16727992,
"author_profile": "https://Stackoverflow.com/users/16727992",
"pm_score": -1,
"selected": false,
"text": "async def get_db(db_con=Depends(get_db_con)) -> AsyncIterable[Session]:\n session = Session(bind=db_c... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6412353/"
] |
74,167,127 | <p>i have 4 List and i want to change them by tapping on gesturedetector on tap event, but i receive an error. I tried call setState , but as i understood only stateful widget can do it. This lists already receive i just want to rebuild widget, i tried use it from state, but it also won't work.</p>
<p><a href="https://i.stack.imgur.com/lFpaU.png" rel="nofollow noreferrer">error</a></p>
<pre><code>import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:vltest/Models/_request.dart';
import 'package:vltest/settings.dart';
import 'package:http/http.dart' as http;
import 'Models/_workers.dart';
import 'database.dart';
List<Requests> ActiveRequests = List.empty();
List<Requests> ClosedRequests = List.empty();
List<Requests> ActiveRequestsTO = List.empty();
List<Requests> ClosedRequestsTO = List.empty();
class RequestsPage extends StatefulWidget {
const RequestsPage();
@override
_RequestsPageState createState() => _RequestsPageState();
}
class _RequestsPageState extends State<RequestsPage> {
ScrollController controller = ScrollController();
bool closeTopContainer = false;
double topContainer = 0;
List<Widget> itemsData = [];
void getPostsData(List<Requests> list) {
List<Requests> responseList = list;
List<Widget> listItems = [];
responseList.forEach((post) {
listItems.add(Container(
height: 150,
margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
color: Colors.white,
boxShadow: [
BoxShadow(color: Colors.black.withAlpha(100), blurRadius: 10.0),
]),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
post.shopAddress,
style: const TextStyle(
fontSize: 15, fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
post.problemPart,
style: const TextStyle(
fontSize: 12,
color: Colors.red,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
post.serialNumber,
style: const TextStyle(
fontSize: 15,
color: Colors.black,
fontWeight: FontWeight.bold),
)
],
),
//requestPhoto(post)
],
),
)));
});
setState(() {
itemsData = listItems;
});
}
void updatePostsData(List<Requests> list) {
List<Requests> responseList = list;
List<Widget> listItems = [];
responseList.forEach((post) {
GenerateRequestCards(listItems, post);
});
}
void GenerateRequestCards(List<Widget> listItems, Requests post) {
listItems.add(Container(
height: 150,
margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
color: Colors.white,
boxShadow: [
BoxShadow(color: Colors.black.withAlpha(100), blurRadius: 10.0),
]),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
post.shopAddress,
style: const TextStyle(
fontSize: 15, fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
post.problemPart,
style: const TextStyle(
fontSize: 12,
color: Colors.red,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
post.serialNumber,
style: const TextStyle(
fontSize: 15,
color: Colors.black,
fontWeight: FontWeight.bold),
)
],
),
//requestPhoto(post)
],
),
)));
setState(() {
itemsData = listItems;
});
}
Image requestPhoto(Requests post) {
if (post.imageUrl == "") {
return Image.network(
post.imageUrl,
height: double.infinity,
);
} else {
return Image.network(
"https://i.ibb.co/TctYZfx/Logo-Main-3-1.jpg",
height: double.infinity,
);
}
}
@override
void initState() {
super.initState();
WidgetsBinding.instance
.addPostFrameCallback((_) => loadUserInfo().then((value) {
setState(() {});
}));
controller.addListener(() {
double value = controller.offset / 119;
setState(() {
topContainer = value;
closeTopContainer = controller.offset > 50;
});
});
}
@override
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
final double categoryHeight = size.height * 0.30;
return SafeArea(
child: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.white,
leading: Icon(
Icons.arrow_back,
color: Colors.black,
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search, color: Colors.black),
onPressed: () {},
),
IconButton(
icon: Icon(Icons.person, color: Colors.black),
onPressed: () {},
)
],
),
body: Container(
height: size.height,
child: Column(
children: <Widget>[
const SizedBox(
height: 10,
),
AnimatedOpacity(
duration: const Duration(milliseconds: 200),
opacity: closeTopContainer ? 0 : 1,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
width: size.width,
alignment: Alignment.topCenter,
height: closeTopContainer ? 0 : categoryHeight,
child: CategoriesScroller(
ActiveRequests: ActiveRequests,
ClosedRequests: ClosedRequests,
ActiveRequestsTO: ActiveRequestsTO,
ClosedRequestsTO: ClosedRequestsTO),
),
),
Expanded(
child: ListView.builder(
controller: controller,
itemCount: itemsData.length,
physics: BouncingScrollPhysics(),
itemBuilder: (context, index) {
double scale = 1.0;
if (topContainer > 0.5) {
scale = index + 0.5 - topContainer;
if (scale < 0) {
scale = 0;
} else if (scale > 1) {
scale = 1;
}
}
return Opacity(
opacity: scale,
child: Transform(
transform: Matrix4.identity()..scale(scale, scale),
alignment: Alignment.bottomCenter,
child: Align(
heightFactor: 0.7,
alignment: Alignment.topCenter,
child: itemsData[index]),
),
);
})),
],
),
),
),
);
}
Future<void> loadUserInfo() async {
Workers workers = await DBProvider.db.getWorkerInfo();
ActiveRequests = await getRequestsInfo(workers, "repair", "active");
ClosedRequests = await getRequestsInfo(workers, "repair", "closed");
ActiveRequestsTO = await getRequestsInfo(workers, "maintenance", "active");
ClosedRequestsTO = await getRequestsInfo(workers, "maintenance", "closed");
getPostsData(ActiveRequests);
setState(() {});
}
Future<void> updateLoadersData() async {
Workers workers = await DBProvider.db.getWorkerInfo();
ActiveRequests = await getRequestsInfo(workers, "repair", "active");
ClosedRequests = await getRequestsInfo(workers, "repair", "closed");
ActiveRequestsTO = await getRequestsInfo(workers, "maintenance", "active");
ClosedRequestsTO = await getRequestsInfo(workers, "maintenance", "closed");
setState(() {});
}
Future<List<Requests>> getRequestsInfo(
Workers workers, String type, String status) async {
Map data = {
'login': workers.login,
'type': type,
'status': status,
};
//encode Map to JSON
var body = json.encode(data);
final response = await http.post(
Uri.parse(GlobalSettings.serverHTTP + 'api/requests/list'),
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer ${workers.token}"
},
body: body);
if (response.statusCode == 200) {
Iterable l = json.decode(response.body);
List<Requests> loaders =
List<Requests>.from(l.map((model) => Requests.fromJson(model)));
return loaders;
} else {
throw Exception('Failed to load album');
}
}
List<T> map<T>(List list, Function handler) {
List<T> result = [];
for (var i = 0; i < list.length; i++) {
result.add(handler(i, list[i]));
}
return result;
}
}
class CategoriesScroller extends StatelessWidget {
const CategoriesScroller({
Key? key,
required this.ActiveRequests,
required this.ClosedRequests,
required this.ActiveRequestsTO,
required this.ClosedRequestsTO,
}) : super(key: key);
final List<Requests> ActiveRequests;
final List<Requests> ClosedRequests;
final List<Requests> ActiveRequestsTO;
final List<Requests> ClosedRequestsTO;
@override
Widget build(BuildContext context) {
final double categoryHeight =
MediaQuery.of(context).size.height * 0.30 - 50;
return SingleChildScrollView(
physics: BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 20, horizontal: 20),
child: FittedBox(
fit: BoxFit.fill,
alignment: Alignment.topCenter,
child: Row(
children: <Widget>[
Container(
width: 150,
margin: EdgeInsets.only(right: 20),
height: categoryHeight,
decoration: BoxDecoration(
color: Colors.orange.shade400,
borderRadius: BorderRadius.all(Radius.circular(20.0))),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: GestureDetector(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Active",
style: TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
"Repair",
style: TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
ActiveRequests.length.toString(),
style: TextStyle(fontSize: 16, color: Colors.white),
),
],
),
onTap: () {
List<Widget> list = [];
ActiveRequests.forEach((element) {
_RequestsPageState()
.GenerateRequestCards(list, element);
});
},
),
),
),
Container(
width: 150,
margin: EdgeInsets.only(right: 20),
height: categoryHeight,
decoration: BoxDecoration(
color: Colors.orange.shade400,
borderRadius: BorderRadius.all(Radius.circular(20.0))),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: GestureDetector(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Closed",
style: TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
"Repair",
style: TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
ClosedRequests.length.toString(),
style: TextStyle(fontSize: 16, color: Colors.white),
),
],
),
onTap: () {
List<Widget> list = [];
ClosedRequests.forEach((element) {
_RequestsPageState()
.GenerateRequestCards(list, element);
});
},
),
),
),
Container(
width: 150,
margin: EdgeInsets.only(right: 20),
height: categoryHeight,
decoration: BoxDecoration(
color: Colors.orange.shade400,
borderRadius: BorderRadius.all(Radius.circular(20.0))),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: GestureDetector(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Active",
style: TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
"Maintenance",
style: TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
ActiveRequestsTO.length.toString(),
style: TextStyle(fontSize: 16, color: Colors.white),
),
],
),
onTap: () {
List<Widget> list = [];
ActiveRequestsTO.forEach((element) {
_RequestsPageState()
.GenerateRequestCards(list, element);
});
},
),
),
),
Container(
width: 150,
margin: EdgeInsets.only(right: 20),
height: categoryHeight,
decoration: BoxDecoration(
color: Colors.orange.shade400,
borderRadius: BorderRadius.all(Radius.circular(20.0))),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: GestureDetector(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Closed",
style: TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
"Maintenance",
style: TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
ClosedRequestsTO.length.toString(),
style: TextStyle(fontSize: 16, color: Colors.white),
),
],
),
onTap: () {
List<Widget> list = [];
ClosedRequestsTO.forEach((element) {
_RequestsPageState()
.GenerateRequestCards(list, element);
});
},
),
),
),
],
),
),
),
);
}
}
</code></pre>
<p>Give me an advice please...</p>
| [
{
"answer_id": 74169329,
"author": "MinatoNamikaze91",
"author_id": 16727992,
"author_profile": "https://Stackoverflow.com/users/16727992",
"pm_score": -1,
"selected": false,
"text": "async def get_db(db_con=Depends(get_db_con)) -> AsyncIterable[Session]:\n session = Session(bind=db_c... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16993625/"
] |
74,167,154 | <p>I'm writing code for a project and I am just finishing up the menu, where there are 5 options and the user inputs a number to select said option. Here's my code:</p>
<pre><code> display_menu(True)
command = input("Enter a number (0 to exit): ")
while command != 0:
if command == 1:
namefile = input("Enter word list filename: ")
wordlist = make_list(namefile)
print('Word list is loaded.')
elif command == 2:
namefile = input('Enter movie review filename:')
moviedict = make_dict(namefile)
print('Movie reviews are loaded.')
elif command == 3:
searchword = input('Enter a word to search: ')
count1, score1 = search_word(searchword)
print(searchword + ' appears ' + count1 + ' times')
print('The average score for the reviews containing the word terrific is: ' + score1)
elif command == 4:
print_lists(list, list_scores)
elif command == 5:
pass
display_menu(True)
command = input("Enter a number (0 to exit): ")
</code></pre>
<p>it definitely prints the list but when I enter a command input it doesn't actually work.</p>
| [
{
"answer_id": 74167174,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "command"
},
{
"answer_id": 74167330,
"author": "user3435121",
"author_id": 3435121,
"author_profi... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310901/"
] |
74,167,156 | <p>I have to go to <a href="https://ipindiaservices.gov.in/PublicSearch/" rel="nofollow noreferrer">here</a></p>
<p>Here I have to choose applicant name = “ltd”</p>
<p>But here before submitting the page, I have to solve a captcha. How to fetch the next page's information(application number, application title, date, application status etc.....) in an excel format using web scrapping?</p>
<p>---------------- Running the following script, getting error -----</p>
<pre><code>import csv
import json
from time import sleep, time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
def save_to_csv(data: list) -> None:
with open(file='ipindiaservices.csv', mode='a', encoding="utf-8") as f:
writer = csv.writer(f, lineterminator='\n')
writer.writerow([*data])
def start_from_page(page_number: int, driver: WebDriver) -> None:
driver.execute_script(
f"""
document.querySelector('button.next').value = {page_number};
document.querySelector('button.next').click();
"""
)
def titles_validation(driver: WebDriver) -> None:
"""replace empty title name with '_'"""
driver.execute_script(
"""
let titles = document.querySelectorAll('input+.tab-pane tr:not(:first-child)>td:last-child')
Array.from(titles).forEach((e) => {
if (!e.textContent.trim()) {
e.textContent = '_';
}
});
"""
)
def get_network_data(log: dict, driver: WebDriver) -> dict:
log = json.loads(log["message"])["message"]
if all([
"Network.responseReceived" in log["method"],
"params" in log.keys(),
'CaptchaAudio' in str(log["params"].values())
]):
return driver.execute_cdp_cmd('Network.getResponseBody', {'requestId': log["params"]["requestId"]})
def get_captcha_text(driver: WebDriver, timeout: float) -> str:
"""Return captcha text
Arguments:
- driver: WebDriver
- timeout: pause before receiving data from the web driver log
"""
driver.execute_script(
"""
// document.querySelector('img[title="Captcha"]').click()
document.querySelector('img[title="Captcha Audio"]').click()
"""
)
sleep(timeout)
logs = driver.get_log('performance')
responses = [get_network_data(log, driver) for log in logs if get_network_data(log, driver)]
if responses:
return json.loads(responses[0]['body'])['CaptchaImageText']
else:
get_captcha_text(driver)
def submit_captcha(captcha_text: str, btn_name: str) -> None:
"""Submit captcha
Arguments:
- btn_name: captcha send button name["submit" or "search"]
"""
if btn_name == 'search':
captcha_locator = (By.CSS_SELECTOR, 'input[name="submit"]')
elif btn_name == 'submit':
captcha_locator = (By.ID, 'btnSubmit')
wait.until(EC.visibility_of_element_located((By.ID, 'CaptchaText'))).send_keys(captcha_text)
wait.until(EC.visibility_of_element_located(captcha_locator)).click()
# options = webdriver.ChromeOptions()
# options.add_argument('--headless')
# options.add_experimental_option("excludeSwitches", ["enable-automation", "enable-logging"])
# capabilities = DesiredCapabilities.CHROME
# capabilities["goog:loggingPrefs"] = {"performance": "ALL"}
# service = Service(executable_path="path/to/your/chromedriver.exe")
# # driver = webdriver.Chrome(service=service, options=options, desired_capabilities=capabilities)
wait = WebDriverWait(driver, 15)
table_values_locator = (By.CSS_SELECTOR, 'input+.tab-pane tr:not(:first-child)>td:last-child')
applicant_name_locator = (By.ID, 'TextField6')
page_number_locator = (By.CSS_SELECTOR, 'span.Selected')
app_satus_locator = (By.CSS_SELECTOR, 'button.btn')
next_btn_locator = (By.CSS_SELECTOR, 'button.next')
driver.get('https://ipindiaservices.gov.in/PublicSearch/')
# sometimes an alert with an error message("") may appear, so a small pause is used
sleep(1)
wait.until(EC.visibility_of_element_located(applicant_name_locator)).send_keys('ltd')
# on the start page and the page with the table, the names of the buttons are different
captcha_text = get_captcha_text(driver, 1)
submit_captcha(captcha_text, "search")
# the page where the search starts
start_from_page(1, driver)
while True:
start = time()
# get current page number
current_page = wait.until(EC.visibility_of_element_located(page_number_locator)).text
print(f"Current page: {current_page}")
# get all application status WebElements
app_status_elements = wait.until(EC.visibility_of_all_elements_located(app_satus_locator))
for element in range(len(app_status_elements)):
print(f"App number: {element}")
# update application status WebElements
app_status_elements = wait.until(EC.visibility_of_all_elements_located(app_satus_locator))
# click on application status
wait.until(EC.visibility_of(app_status_elements[element])).click()
# wait 2 seconds for the captcha to change
sleep(2)
# get text and submit captcha
captcha_text = get_captcha_text(driver, 1)
submit_captcha(captcha_text, "submit")
try:
# get all table data values(without titles) WebElements
table_data_values = wait.until(EC.visibility_of_all_elements_located(table_values_locator))
# if there are empty rows in the table replace them with "_"
titles_validation(driver)
# save data to csv
save_to_csv([val.text.replace('\n', ' ') for val in table_data_values])
except TimeoutException:
print("Application Number does not exist")
finally:
driver.back()
# print the current page number to the console
print(f"Time per page: {round(time()-start, 3)}")
# if the current page is equal to the specified one, then stop the search and close the driver
if current_page == '3776':
break
# click next page
wait.until(EC.visibility_of_element_located(next_btn_locator)).click()
driver.quit()
</code></pre>
<p><a href="https://i.stack.imgur.com/6i19P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6i19P.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74199234,
"author": "Brze",
"author_id": 10848420,
"author_profile": "https://Stackoverflow.com/users/10848420",
"pm_score": 3,
"selected": true,
"text": "https://ipindiaservices.gov.in/PublicSearch/Captcha/CaptchaAudio"
}
] | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14889151/"
] |
74,167,171 | <p>This is my first foray into .NET Core. <strong>The following code works, and has worked for years</strong> in regular ASP.NET applications. But in my first .NET Core app, the extension methods are reporting undefined.</p>
<pre><code>namespace CoreAPI1 {
class SQL_Data {
public SqlDataReader DBReader(string query) {
using (SqlCommand cmd = new SqlCommand(query,cn)) {
return cmd.ExecuteReader();
}
}
}
public static class SQLExtentions {
public static bool Exists(this SqlDataReader rs, bool closeAfterReading = true) {
bool hasRows = rs.HasRows;
if (closeAfterReading) {
rs.Close();
}
return hasRows;
}
}
}
</code></pre>
<p>But later, when I attempt to actually USE the extension:</p>
<pre><code>var exists = new SQL_Data().DBReader("SELECT * FROM ...").Exists();
</code></pre>
<p>I get:</p>
<blockquote>
<p>.SqlDataReader does not contain a definition for 'Exists'</p>
</blockquote>
<p>Even though <code>SQL_Data()</code> class, and it's <code>.DBReader()</code> method are both found and working, the extension method is not.</p>
<p>Any ideas? Again, this is my first attempt at a .NET Core, so I do not know if there are peculiarities in config files, or properties dialogs that I've missed.</p>
<p>Both the <code>SQL_Data()</code> class, and the <code>SQLExtentions</code> class are in the same module: <code>SQLClass.cs</code>, in the same namespace, <code>CoreAPI1</code>.</p>
| [
{
"answer_id": 74167789,
"author": "Dulanjan Madusanka",
"author_id": 19127142,
"author_profile": "https://Stackoverflow.com/users/19127142",
"pm_score": -1,
"selected": false,
"text": "using (SqlCommand cmd = new SqlCommand(query,cn)) {\n return cmd.ExecuteReader();\n ... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592937/"
] |
74,167,178 | <p>I'm developing in flutter and am trying to add firebase to my flutter project.</p>
<p>Firebase login works, auth works, dart pub global activate flutterfire_cli works and flutterfire. I can call on firebase or flutterfire and it will list the options I have so I know the paths and installs are working.</p>
<p>But when I run flutterfire configure I always get this:</p>
<p>'''</p>
<blockquote>
<p>flutterfire configure
i Found 0 Firebase projects.
FirebaseCommandException: An error occured on the Firebase CLI when attempting to run a command.
COMMAND: firebase --version
ERROR: The FlutterFire CLI currently requires the official Firebase CLI to also be installed, see <a href="https://firebase.google.com/docs/cli#install_the_firebase_cli" rel="nofollow noreferrer">https://firebase.google.com/docs/cli#install_the_firebase_cli</a> for how to install it.
'''</p>
</blockquote>
<p>I've been struggling with this for a few days now and have tried firebase binary, npm, nodejs, and anything else I can find. Nothing seems to be working.</p>
<p>Thanks ahead of time!</p>
<p>Lance</p>
| [
{
"answer_id": 74167616,
"author": "THEODORE",
"author_id": 9185856,
"author_profile": "https://Stackoverflow.com/users/9185856",
"pm_score": 3,
"selected": true,
"text": "dart pub global activate flutterfire_cli\n\nflutterfire configure\n"
},
{
"answer_id": 74316985,
"author... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3226158/"
] |
74,167,185 | <p>I'm trying to create a bar chart showing employment by firm size for two different years where I want the years to have separate bars. Right now I used a fill argument just to show the year distinction. The bins are also not in the correct order and I'm having trouble trying to fix that. I've attached my code, the a photo of how the data is arranged and the current output.</p>
<pre><code>firm_size %>%
ggplot(aes(`firm size`, total, fill = year)) +
geom_col() +
theme_minimal() +
labs(title = "Firm Size Distribution",
subtitle = "2021",
x = "Number of Employees at Firm",
y = "% of Total Santa Barbara Employment")
</code></pre>
<p><a href="https://i.stack.imgur.com/AI6K1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AI6K1.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/Kj8Zs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Kj8Zs.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74167352,
"author": "br00t",
"author_id": 4028717,
"author_profile": "https://Stackoverflow.com/users/4028717",
"pm_score": 1,
"selected": false,
"text": "library(stringr)\nlibrary(ggplot2)\n\nfirm_size <- data.frame(\n firm.size = c(\"0-4\", \"5-9\", \"10-19\", \"20-49\"... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19778283/"
] |
74,167,212 | <p>I am trying to print an element of the <code>cube_pattern</code> string, but when I execute my code nothing is printed to the console and my code freezes for a few seconds:</p>
<pre><code>#include <stdio.h>
#define SOLVED_CUBE "UUUUUUUUURRRRRRRRRFFFFFFFFFDDDDDDDDDLLLLLLLLLBBBBBBBBB"
char cube_pattern[54] = SOLVED_CUBE
void print_pattern() {
printf("%s", cube_state[0]);
}
void main() {
print_pattern();
}
</code></pre>
<p>I tried calling <code>fflush(stdout)</code> but it still doesn't work:</p>
<pre><code>void print_pattern() {
printf("%s", cube_state[0]);
fflush(stdout);
}
</code></pre>
| [
{
"answer_id": 74167352,
"author": "br00t",
"author_id": 4028717,
"author_profile": "https://Stackoverflow.com/users/4028717",
"pm_score": 1,
"selected": false,
"text": "library(stringr)\nlibrary(ggplot2)\n\nfirm_size <- data.frame(\n firm.size = c(\"0-4\", \"5-9\", \"10-19\", \"20-49\"... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,167,216 | <p>I have CSV containing multiple emails in multiple columns extracted from my email inbox.
emails are held within pointy brackets such as this:</p>
<p><code><name-name.name@domain.com>, name.name@domain.com</code>
emails are also listed inside text of emails I would like to pull out</p>
<p>I would like to extract each name fragment and just list them in a text file.</p>
<p>I know I need to use regex - could someone help me, please? Thanks!</p>
<pre class="lang-py prettyprint-override"><code>import re
s = """
<name-name.name@domain.com>, name.name@domain.com
"""
emails = re.findall(r'[:,]\s*=?\s*(?:([A-Z][a-z]+(?:\s[A-Z][a-z]+)?))?\s*=?\s*.*?([\w.]+@[\w.-]+)', s)
</code></pre>
| [
{
"answer_id": 74167352,
"author": "br00t",
"author_id": 4028717,
"author_profile": "https://Stackoverflow.com/users/4028717",
"pm_score": 1,
"selected": false,
"text": "library(stringr)\nlibrary(ggplot2)\n\nfirm_size <- data.frame(\n firm.size = c(\"0-4\", \"5-9\", \"10-19\", \"20-49\"... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15116425/"
] |
74,167,223 | <p>I can do <code>!pip list</code> to see a list of all the packages.</p>
<p>I can do this to count all the sub folders in the <code>python 3.7</code> folder:</p>
<pre class="lang-py prettyprint-override"><code>import os
containing_folder = '/usr/local/lib/python3.7/dist-packages'
f = []
for (dirpath, dirnames, filenames) in os.walk(containing_folder):
f.extend(dirnames)
break
print('there are', len(f), 'folders in the python 3.7 module')
</code></pre>
<p>but the number of folders does not equate to the number of modules as there appear to be more files than modules.</p>
<p>So how can i identify all the modules (and not folders) ?
(ie. count all the pip installed folders).</p>
| [
{
"answer_id": 74167282,
"author": "CryptoFool",
"author_id": 7631480,
"author_profile": "https://Stackoverflow.com/users/7631480",
"pm_score": 2,
"selected": true,
"text": "__init__.py"
},
{
"answer_id": 74170082,
"author": "tripleee",
"author_id": 874188,
"author_pr... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7318120/"
] |
74,167,238 | <p>When I press a <code><button></code>, I want to wait for an asynchronous function, then add some classes to the <code><button></code>, but it doesn't work. I want to use jQuery to do this.</p>
<p>Here is my code:</p>
<pre><code>$("#btnSta").addEventListener("click", () => {
getAccount().then(addresses => {
$("#btnSta").classList.add('opacity-50 cursor-not-allowed');
});
});
</code></pre>
| [
{
"answer_id": 74167291,
"author": "Michael M.",
"author_id": 13376511,
"author_profile": "https://Stackoverflow.com/users/13376511",
"pm_score": 1,
"selected": false,
"text": ".classList"
},
{
"answer_id": 74169423,
"author": "Kostis",
"author_id": 11974173,
"author_... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17122691/"
] |
74,167,279 | <p>I would like to have the same result as this example.</p>
<p><a href="https://i.stack.imgur.com/ftlnB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ftlnB.png" alt="enter image description here" /></a></p>
<ol>
<li>For the sub-menus (portfolio, contact, etc...): a background that takes the whole width.</li>
<li>The titles of the submenus are almost centered</li>
</ol>
<p>In my sidebar, I have two rubrics: <code>Category</code> and <code>Markets</code>.</p>
<p>Here is my example...</p>
<p><a href="https://i.stack.imgur.com/dLRWz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dLRWz.png" alt="enter image description here" /></a></p>
<p>My problem is that the width of the submenus (Portfolio, Contact, Indice, etc..) are not wide.
There is white to the left.</p>
<p>I would also like to center the menu subtitles like the example I showed you.</p>
<p>I made an illustration of the menu here -> <a href="https://stackblitz.com/github/kora1348/exemple1?file=src/styles.css" rel="nofollow noreferrer">Stackblitz</a></p>
<p>Thank you a lot for your help and your time.</p>
<p><em><strong>HTML</strong></em></p>
<pre><code><div class="sidebar" [class.sidebar-close]="!openSidebar" >
<div class="logo-details">
<img src="https://zupimages.net/up/22/42/refj.png" />
</div>
<ul class="nav-links" id="nav-links" >
<li *ngFor="let item of menuSidebar" #itemEl routerLinkActive="active">
<div *ngIf="item.sub_menu.length == 0" class="dropdown-title">
<a [routerLink]="[item.link]">
<i [class]="item.icon"></i>
<span class="link_name">{{item.link_name}}</span>
</a>
</div>
<div *ngIf="item.sub_menu.length > 0" class="dropdown-title" (click)="showSubmenu(itemEl)">
<a>
<i [class]="item.icon"></i>
<span class="link_name">{{item.link_name}}</span>
</a>
<i class='bx bxs-chevron-down arrow'></i>
</div>
<ul class="sub-menu" [class.blank]="item.sub_menu.length == 0">
<li><a class="link_name">{{item.link_name}}</a></li>
<li *ngFor="let item_sub of item.sub_menu" routerLinkActive="active">
<a [routerLink]="[item_sub.link]">{{item_sub.link_name}}</a>
</li>
</ul>
</li>
</ul>
</div>
</code></pre>
<p><em><strong>CSS</strong></em></p>
<pre><code>/* Sidebar */
.sidebar {
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 260px;
background: white;
z-index: 100;
transition: all 0.5s ease;
}
.sidebar.sidebar-close {
width: 60px;
}
.sidebar .logo-details{
width: 100%;
padding: 10px 10px 10px 10px;
}
.sidebar .logo-details img{
height: 50px;
width: 80%;
display: block;
margin: 0 auto;
}
.sidebar.sidebar-close .logo-details img {
width: 37px;
height: 50px;
transform: scale(1.2) translateX(-3px);
}
.sidebar .nav-links {
height: 100%;
width: 260px;
padding-bottom: 150px;
overflow: auto;
}
.sidebar .nav-links::-webkit-scrollbar {
display: none;
}
.sidebar .nav-links li {
list-style: none;
}
.sidebar .nav-links > li {
position: relative;
width: fit-content;
}
.sidebar .nav-links li:hover {
background: #ffa726;
}
.sidebar .nav-links li.active {
background-image: linear-gradient(to right, #ffa726, #ff5722);
}
/* Dropdown Title */
.sidebar .nav-links .dropdown-title {
width: 260px;
overflow: hidden;
transition: all 0.52s ease;
/* */
display: flex;
align-items: center;
justify-content: space-between;
position: relative;
}
.sidebar.sidebar-close .nav-links .dropdown-title {
width: 60px;
}
.sidebar .nav-links li i {
height: 50px;
min-width: 60px;
text-align: center;
line-height: 50px;
color: #ffa726;
font-size: 20px;
cursor: pointer;
transition: all 0.3s ease;
}
.sidebar .nav-links li:hover i,
.sidebar .nav-links li.active i {
color: white;
}
.sidebar .nav-links li.showMenu i.arrow {
transform: rotate(-180deg);
}
/* a Tag */
.sidebar .nav-links li a {
display: flex;
align-items: center;
text-decoration: none;
width: 100%;
}
/* Link Name */
.sidebar .nav-links li a .link_name {
font-size: 16px;
font-weight: 600;
color: #ffa726;
transition: all 0.4s ease;
}
.sidebar .nav-links li:hover a .link_name,
.sidebar .nav-links li.active a .link_name {
color: white;
}
.sidebar.sidebar-close .nav-links li a .link_name {
pointer-events: none;
}
/* Sub Menu */
.sidebar .nav-links li .sub-menu {
padding: 6px 6px 14px 70px;
/* margin-top: -10px; */
background: white;
display: none;
transition: all 0.4s ease;
}
.sidebar .nav-links li.showMenu .sub-menu {
display: block;
}
.sidebar .nav-links li .sub-menu a {
color: #ffa726;
font-size: 15px;
padding: 7px 0;
white-space: nowrap;
transition: all 0.3s ease;
}
.sidebar .nav-links li .sub-menu li {
padding-left: 10px;
}
.sidebar .nav-links li .sub-menu li:hover a,
.sidebar .nav-links li .sub-menu li.active a {
color: white;
}
.sidebar.sidebar-close .nav-links li .sub-menu {
position: absolute;
left: 100%;
top: -10px;
margin-top: 0;
padding: 0;
border-radius: 0 6px 6px 0;
opacity: 0;
display: block;
pointer-events: none;
transition: 0s;
overflow: hidden;
}
.sidebar.sidebar-close .nav-links li .sub-menu li {
padding: 6px 15px;
width: 200px;
}
.sidebar.sidebar-close .nav-links li:hover .sub-menu {
top: 0;
opacity: 1;
pointer-events: auto;
transition: all 0.4s ease;
}
.sidebar .nav-links li .sub-menu .link_name {
display: none;
}
.sidebar.sidebar-close .nav-links li .sub-menu .link_name {
font-size: 16px;
font-weight: 600;
/* opacity: 1; */
display: block;
}
/* li:first-child contain .link_name */
.sidebar.sidebar-close .nav-links li .sub-menu li:first-child {
background: white;
pointer-events: none;
}
.sidebar.sidebar-close .nav-links li .sub-menu li:first-child:hover .link_name,
.sidebar.sidebar-close .nav-links li .sub-menu li:first-child.active .link_name {
color: #ffa726;
}
.sidebar .nav-links li .sub-menu.blank {
pointer-events: auto;
/* padding: 3px 20px 6px 16px; */
opacity: 0;
pointer-events: none;
}
.sidebar .nav-links li:hover .sub-menu.blank,
.sidebar .nav-links li.active .sub-menu.blank {
top: 50%;
transform: translateY(-50%);
}
.sidebar.sidebar-close ~ .home-section {
left: 60px;
width: calc(100% - 60px);
}
</code></pre>
| [
{
"answer_id": 74167351,
"author": "pjk_ok",
"author_id": 5219761,
"author_profile": "https://Stackoverflow.com/users/5219761",
"pm_score": 1,
"selected": true,
"text": ".sidebar .nav-links li .sub-menu"
},
{
"answer_id": 74167367,
"author": "Hex",
"author_id": 14566355,
... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18216840/"
] |
74,167,295 | <p>I need modify a csv file with pandas. I have the following table:</p>
<pre><code>Interface Description
1 Used
2 Used
3 Used
4 Used
6 Used
8 Used
12 Used
17 Used
</code></pre>
<p>I need to match the "Interface" column with a range of 1, 20, complete the table with the missing numbers and place the word "free" in the "Description" column and order it like this:</p>
<pre><code>Interface Description
1 Used
2 Used
3 Used
4 Used
5 free
6 Used
7 free
8 Used
9 free
10 free
11 free
12 Used
13 free
14 free
15 free
16 free
17 Used
18 free
19 free
20 free
</code></pre>
| [
{
"answer_id": 74167336,
"author": "bitflip",
"author_id": 20027803,
"author_profile": "https://Stackoverflow.com/users/20027803",
"pm_score": 3,
"selected": true,
"text": "merge"
},
{
"answer_id": 74167458,
"author": "sammywemmy",
"author_id": 7175713,
"author_profil... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20178424/"
] |
74,167,340 | <pre><code>values = ['random word1', 20, 'random word2', 54…]
</code></pre>
<p>The list has a string then a value and again a string then afterwards a value. The amount of strings followed by values is random. The words are random and the values are random as well</p>
<p>I want to convert the list to something like this:</p>
<pre><code>values = [['random word1', 20], ['random word2', 54]…]
</code></pre>
| [
{
"answer_id": 74167359,
"author": "islam abdelmoumen",
"author_id": 19661530,
"author_profile": "https://Stackoverflow.com/users/19661530",
"pm_score": 2,
"selected": false,
"text": "values = ['random word1', 20, 'random word2', 54]\nvalues = [values[i:i+2] for i in range(0,len(values),... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19222846/"
] |
74,167,355 | <p>I have the following generic interface/classes</p>
<pre><code>public interface AnInterface <T>{
T convertToY();
String getName();
String getLastName();
}
public class Foo implements AnInterface<Foo>{
// some methods specific to Foo
}
public class Bar implements AnInterface<Bar>{
// some methods specific to Bar
}
</code></pre>
<p>I created a generic method as follows (I didn't think it would work but it does)</p>
<pre><code>public static <T> List<Person> getPersons(AnInterface<T> in) {
System.out.println(map.get(in));
List<Person> list = new ArrayList<>();
if (in instanceof Foo) {
Person p = new Person(in.getName(), in.getLastName());
p.setId(((Foo) in).getId());
list.add(p);
}
else if(in instanceof Bar) {
Person p = new Person(in.getName(), in.getLastName());
p.setCC(((Bar) in).getCC());
list.add(p);
}
return list;
}
</code></pre>
<p>The issue is that I did not create the classes so I am not sure if doing
<code>public class Foo implements AnInterface<Foo></code> is something usual or not.<br />
So what I am interested in is if there is any issue with the generic method and using <code>instanceof</code> and if there is any problems that can be created. E.g. if I recall correctly we can't use <code>instanceof</code> on collections so I was wondering if I might make it easy to introduce some other bug with this approach.</p>
<p><strong>Note:</strong>.
I can't modify <code>AnInterface</code> or <code>Foo</code> or <code>Bar</code></p>
| [
{
"answer_id": 74167411,
"author": "tgdavies",
"author_id": 11002,
"author_profile": "https://Stackoverflow.com/users/11002",
"pm_score": 1,
"selected": false,
"text": "applyToPerson"
},
{
"answer_id": 74167465,
"author": "Federico Beach",
"author_id": 11396765,
"auth... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9055634/"
] |
74,167,397 | <p>I am attempting to write a program where it takes a list input by the user and determines if the letter in the list is uppercase or not. This is the code I have so far.</p>
<pre><code># Write a Python function to count how many letters in a string are in uppercase.
print("Hey, do you wanna see a cool trick I can do? I can count how many letters in a list of letters are uppercase!")
print("Here, I can prove it!")
print("Gimme a list of letters!")
letter = input("Enter a list of letters, seperating each by a comma. (put both uppercase and lowercase!) ")
letter_list = letter.split(",")
print("The list you gave was...")
print(letter_list)
print("And if we seperate those, we get...")
for letter in letter_list:
print(letter)
print("Now, I'm going to count how many of those are uppercase!")
</code></pre>
<p>I am currently trying to get it to check if the letter is uppercase properly. I have tried an if statement nested in a for loop, but I'm unsure if I did it right, because it didn't work. The code I input was:</p>
<pre><code>for letter in letter_list:
if letter.isupper == True:
capital = capital + 1
</code></pre>
<p>capital is what is being printed back to the user showing the amount of capital letters.</p>
| [
{
"answer_id": 74167426,
"author": "Michael M.",
"author_id": 13376511,
"author_profile": "https://Stackoverflow.com/users/13376511",
"pm_score": 2,
"selected": true,
"text": "capital"
},
{
"answer_id": 74167432,
"author": "Jared Hanson",
"author_id": 20311057,
"autho... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20056396/"
] |
74,167,404 | <p>So I'm trying to print out only the year data because I want to perform some functions on it. the q var is coming form a html form so we don't know what will be the value of q the user will decide:</p>
<pre><code>filtered: [
{ Year: '2019', score1: 88 },
{ Year: '2020', score1: 89 },
{ Year: '2021', score1: 90 },
{ Year: '2022', score1: 91 },
{ Year: '2023', score1: 92 },
{ Year: '2023', score1: 100 }
]
var q = "Year";
for (let i = 0; i < filterd.length; i++) {
console.log(filterd[i].q);
}
</code></pre>
<pre><code> Output:
undefined
undefined
undefined
undefined
undefined
undefined
</code></pre>
| [
{
"answer_id": 74167487,
"author": "Konrad",
"author_id": 5089567,
"author_profile": "https://Stackoverflow.com/users/5089567",
"pm_score": 1,
"selected": false,
"text": "const filtered = [{\n Year: '2019',\n score1: 88\n },\n {\n Year: '2020',\n score1: 89\n },\n {\n ... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74167404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20311085/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.