qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,269,416 | <p>I have some integration tests that, in order to succesfully run, require a running postgres database, setup via docker-compose, and my go app running from <code>main.go</code>. Here is my docker-compose:</p>
<pre><code>version: "3.9"
services:
postgres:
image: postgres:12.5
user: postgres
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
POSTGRES_DB: my-db
ports:
- "5432:5432"
volumes:
- data:/var/lib/postgresql/data
- ./initdb:/docker-entrypoint-initdb.d
networks:
default:
driver: bridge
volumes:
data:
driver: local
</code></pre>
<p>and my Github Actions are as follows:</p>
<pre><code>jobs:
unit:
name: Test
runs-on: ubuntu-latest
services:
postgres:
image: postgres:12.5
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
POSTGRES_DB: my-db
ports:
- 5432:5432
env:
GOMODCACHE: "${{ github.workspace }}/.go/mod/cache"
TEST_RACE: true
steps:
- name: Initiate Database
run: psql -f initdb/init.sql postgresql://postgres:password@localhost:5432/my-db
- name: Set up Cloud SDK
uses: google-github-actions/setup-gcloud@v0
- name: Authenticate with GCP
id: auth
uses: "google-github-actions/auth@v0"
with: credentials_json: ${{ secrets.GCP_ACTIONS_SECRET }}
- name: Configure Docker
run: |
gcloud auth configure-docker "europe- docker.pkg.dev,gcr.io,eu.gcr.io"
- name: Set up Docker BuildX
uses: docker/setup-buildx-action@v1
- name: Start App
run: |
VERSION=latest make images
docker run -d -p 3000:3000 -e POSTGRES_DB_URL='//postgres:password@localhost:5432/my-db?sslmode=disable' --name='app' image/app
- name: Tests
env:
POSTGRES_DB_URL: //postgres:password@localhost:5432/my-db?sslmode=disable
GOMODCACHE: ${{ github.workspace }}/.go/pkg/mod
run: |
make test-integration
docker stop app
</code></pre>
<p>My tests run just fine locally firing off the docker-compose with <code>docker-compose up</code> and running the app from <code>main.go</code>. However, in Github actions I am getting the following error:</p>
<pre><code>failed to connect to `host=/tmp user=nonroot database=`: dial error (dial unix /tmp/.s.PGSQL.5432: connect: no such file or directory
</code></pre>
<p>What am I missing? Thanks</p>
| [
{
"answer_id": 74270003,
"author": "Angel Figuera",
"author_id": 20382647,
"author_profile": "https://Stackoverflow.com/users/20382647",
"pm_score": 1,
"selected": false,
"text": "function getWinnerHorse() {\n const horses = {\n Appaloosa: 1 === Math.floor(Math.random() * 6) + 1,\n ... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/397940/"
] |
74,269,441 | <p>I have a seemingly simple problem that I can't figure out. I have a dataset with fish counts via GoPros and am having some trouble subsetting using dplyr in R. The videos are nested into sets and each video set has a differing number of videos in it. I'm trying to subset using filter to only get the observations from the first 20 videos. The issue is that the number of rows for each unique video differ with the number of fish observed. Each row is a single observation (a count of 1 or 0), so if there were no fish in the video or only a single fish, then only 1 row is associated with unique video. But if there is a school of fish then there could be upwards of 100 rows associated with a single unique video. Because of this, I can't sample based on row length or location. I suppose I could do this by hand, but I'm assuming there's a more elegant solution that I'm just missing. Any help would be greatly appreciated!</p>
<p>Note: I have 1 video set with only 17 videos that I would like to keep, but I could always separate that out and rebind if that throws a wrench into the code. I think I've simulated this correctly in the sample data with video set 2, which is below the threshold for the number of videos I want.</p>
<pre><code>#create simulated data
data <- data.frame(Site= c('A', 'A', 'A', 'A', 'A', 'A','B', 'C', 'C', 'C', 'C', 'C'),
Video_Set=c(1,1,1,1,1,1,2,3,3,3,3, 3), #Unique ID for each video set
Video_Unique=c(1,2,3,3,3,3,4,5,6,6,7,8), #Unique ID for each video
Fish_Present=c('Yes', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes','No', 'Yes', 'Yes', 'Yes', 'Yes','No'))
print(data)
#Here's what I tried
sample <- data %>%
group_by(Video_Set) %>%
filter(n_distinct(Video_Unique) > 2) %>%
# here I just created a threshold of 2 instead of 20
ungroup()
#here's what I'm trying to get
goal <- data[c(1,2,7,8,9),]
print(goal)
</code></pre>
<p>Edit/clarification: Hi all, sorry for the confusion on what I want to subset. I'm hoping to get <em>all</em> associated observations for the first 20 unique videos in each video set. For example, if there are 100 rows associated with video 15 from video set 3, I would like all 100 rows.</p>
| [
{
"answer_id": 74270564,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 2,
"selected": true,
"text": "goal"
},
{
"answer_id": 74282927,
"author": "Dan Adams",
"author_id": 13210554,
"author_profile... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20382400/"
] |
74,269,477 | <p>I'm new with Typescript and I have a problem with using a variable to choose the property of an object.</p>
<p>I have a function that filters an array on a property passed as a parameter. The function receives 3 parameters: an array of objects, the characters sought and the property that will be filtered.
here is the function.</p>
<pre class="lang-ts prettyprint-override"><code>
type Data = {
[key: string]: string | number;
};
function filtreTexte(arr: Data[], searchCar: string, field: string): Data[] {
return arr.filter((el) => {
if (el[field] === "string") {
return el[field].toLowerCase().indexOf(searchCar.toLowerCase()) !== -1;
}
})
}
</code></pre>
<p>The problem on the .toLowerCase() which tells me that the method does not work on a number|string type even though I am testing if it is indeed a string.
If I change the el[field] to el.name, the error is no longer mentioned.
How should I do it ?
Thank you in advance for your help.</p>
| [
{
"answer_id": 74269509,
"author": "Dakeyras",
"author_id": 1857909,
"author_profile": "https://Stackoverflow.com/users/1857909",
"pm_score": 2,
"selected": false,
"text": "if (typeof el[field] === \"string\")"
},
{
"answer_id": 74269567,
"author": "Tobias S.",
"author_id... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20382928/"
] |
74,269,488 | <p>I am permuting a few list. How to print the result in a newline?</p>
<p>Code:</p>
<pre><code>import itertools
s=[ [ '1', '2','3'], ['a','b'],
['4','5','6','7'],
['f','g','e','y']]
print (list(itertools.product(*s,)))
</code></pre>
<p>Need Result:</p>
<pre class="lang-none prettyprint-override"><code>#-- with a newline
1 a 4 f
1 a 4 g
1 a 4 e
1 a 4 y
</code></pre>
<p>Current Result:</p>
<pre><code>#-- not very readable
[('1', 'a', '4', 'f'), ('1', 'a', '4', 'g'), ('1', 'a', '4', 'e'), ('1', 'a', '4', 'y')]
</code></pre>
| [
{
"answer_id": 74269528,
"author": "bn_ln",
"author_id": 10535824,
"author_profile": "https://Stackoverflow.com/users/10535824",
"pm_score": 1,
"selected": true,
"text": "\\n"
},
{
"answer_id": 74269545,
"author": "Ryno_XLI",
"author_id": 10141502,
"author_profile": "... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20325415/"
] |
74,269,491 | <p>I have 2 very similar structs and I wanted to ask if there is something similar like polymorphism in java/kotlin in rust?</p>
<pre><code>struct Player {
jump_power: f32,
color: Color,
size: (f32, f32),
pos: (f32, f32),
}
struct Pipe {
color: Color,
speed: f32,
size: (f32, f32),
pos: (f32, f32),
}
</code></pre>
<p>I'm not sure where exactly I should start.</p>
| [
{
"answer_id": 74269528,
"author": "bn_ln",
"author_id": 10535824,
"author_profile": "https://Stackoverflow.com/users/10535824",
"pm_score": 1,
"selected": true,
"text": "\\n"
},
{
"answer_id": 74269545,
"author": "Ryno_XLI",
"author_id": 10141502,
"author_profile": "... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18784628/"
] |
74,269,493 | <p>I am following this guide on how to extract data from Unstructured PDFs using PyMuPDF.</p>
<p><a href="https://www.analyticsvidhya.com/blog/2021/06/data-extraction-from-unstructured-pdfs/" rel="nofollow noreferrer">https://www.analyticsvidhya.com/blog/2021/06/data-extraction-from-unstructured-pdfs/</a></p>
<p>I am getting an AttributeError: 'NoneType' object has no attribute 'rect' error when I followed the code and not sure what is going on since I am new to Python.</p>
<pre><code>---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-2-7f394b979351> in <module>
1 first_annots=[]
2
----> 3 rec=page1.first_annot.rect
4
5 rec
AttributeError: 'NoneType' object has no attribute 'rect'
---------------------------------------------------------------------------
</code></pre>
<p>Code</p>
<pre><code>import fitz
import pandas as pd
doc = fitz.open('Mansfield--70-21009048 - ConvertToExcel.pdf')
page1 = doc[0]
words = page1.get_text("words")
words[0]
first_annots=[]
rec=page1.first_annot.rect
rec
#Information of words in first object is stored in mywords
mywords = [w for w in words if fitz.Rect(w[:4]) in rec]
ann= make_text(mywords)
first_annots.append(ann)
def make_text(words):
line_dict = {}
words.sort(key=lambda w: w[0])
for w in words:
y1 = round(w[3], 1)
word = w[4]
line = line_dict.get(y1, [])
line.append(word)
line_dict[y1] = line
lines = list(line_dict.items())
lines.sort()
return "n".join([" ".join(line[1]) for line in lines])
print(rec)
print(first_annots)
</code></pre>
| [
{
"answer_id": 74280669,
"author": "Jorj McKie",
"author_id": 4474869,
"author_profile": "https://Stackoverflow.com/users/4474869",
"pm_score": 1,
"selected": false,
"text": "first_annot"
},
{
"answer_id": 74290669,
"author": "Hema Jayachandran",
"author_id": 13163227,
... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13540185/"
] |
74,269,496 | <p>I want to compare the amount of values in a list of a list.
If there would be an empty list in the one of the "sub" lists, it should print "too short".
If the list is long enough, meaning that it has more or 1 value in it, it should print "good". how can I do this?
No library imports please.</p>
<p><a href="https://i.stack.imgur.com/Wr6hF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wr6hF.png" alt="listinlist_phyton" /></a></p>
| [
{
"answer_id": 74269607,
"author": "bn_ln",
"author_id": 10535824,
"author_profile": "https://Stackoverflow.com/users/10535824",
"pm_score": 1,
"selected": false,
"text": "len"
},
{
"answer_id": 74269634,
"author": "George",
"author_id": 20345563,
"author_profile": "h... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18607741/"
] |
74,269,501 | <p>I am using version 2 of Timber and I am now adding <a href="https://timber.github.io/docs/v2/guides/pagination/" rel="nofollow noreferrer">pagination</a> to my archives.</p>
<p>Timber, by default, returns 9 pages in the array for pagination. However, I'd rather only want to show first page, the last one and in between the current one with 2 surrounding pages.</p>
<p>The situation as I would like to see it:
For page 1:
<code>1 | 2 | 3 | ... | 300 | Next ></code></p>
<p>For example page 7:
<code>< Back | 1 | ... | 5 | 6 | 7 | 8| 9 | ... | 300 | Next ></code></p>
<p>However the default of Timber (at least for V2) is:
For page 1:
<code>1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 ... | 300 | Next ></code></p>
<p>For page 7:
<code>< Back | 1 | ... | 4 | 5 | 6 | 7 | 8 | 9 | 10 | ... | 300 | Next ></code></p>
<p>Because the array with <code>post.pagination.pages</code> always contains 9 entries.</p>
<p>I am using the following pagination.twig for that in my templates.</p>
<pre><code>{% if posts.pagination.pages is not empty %}
<nav class="pagination" role="navigation" aria-label="pagination">
<ol class="pagination__items">
{% if posts.pagination.prev %}
<li class="pagination__previous pagination__link">
<a href="{{ pagination.prev.link }}">&laquo; {{ __( 'Vorige', 'my-site' ) }}</a>
</li>
{% endif %}
{% for page in posts.pagination.pages %}
<li class="pagination__link {{ page.class }}">
{% if page.link %}
<a href="{{ page.link }}">
<span class="visually-hidden">{{ __( 'Pagina', 'my-site' ) }}</span> {{ page.title }}
</a>
{% else %}
<span>
<span class="visually-hidden">{{ __( 'Pagina', 'my-site' ) }}</span> {{ page.title }}
</span>
{% endif %}
</li>
{% endfor %}
{% if posts.pagination.next %}
<li class="pagination__next pagination__link">
<a href="{{ pagination.next.link }}">{{ __('Volgende', 'my-site') }}&raquo;</a>
</li>
{% endif %}
</ol>
</nav>
{% endif %}
</code></pre>
<p>I tried finding a good filter or action to change the settings for this, but unfortunately I can't seem to find one. It looks like version 1 did support this. with <code>pagination()</code> though. However I can't find an alternative for this for V2.</p>
| [
{
"answer_id": 74385601,
"author": "Radek",
"author_id": 1488241,
"author_profile": "https://Stackoverflow.com/users/1488241",
"pm_score": 0,
"selected": false,
"text": "use Timber\\Pagination;\n\n...\n\n$context['pagination'] = Pagination::get_pagination([\n 'mid_size' => 1,\n 'en... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8398885/"
] |
74,269,520 | <p>I'm trying to specify <code>name=""</code> when using <code>document.createElement</code> but isn't working.</p>
<p>Here is the code =></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var element = document.createElement("p");
element.className = "hello-there";
element.innerText = "It works";
element.name = "hello-there-name";
document.getElementById("main").appendChild(element);
console.log(document.querySelector("p").getAttribute("name"));</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="main"></div></code></pre>
</div>
</div>
</p>
<p>How can I fix that without using <code>id</code>? Thanks</p>
| [
{
"answer_id": 74269535,
"author": "caTS",
"author_id": 18244921,
"author_profile": "https://Stackoverflow.com/users/18244921",
"pm_score": 2,
"selected": false,
"text": "setAttribute"
},
{
"answer_id": 74269559,
"author": "Carsten Massmann",
"author_id": 2610061,
"au... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20216936/"
] |
74,269,558 | <p>How I can convert a array (in a column) with a set of elements in a JSON dataset to multiple columns with python, spark or pandas?
The data is structured in this form:</p>
<pre><code>root
|-- items: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- id: string (nullable = true)
| | |-- idAccount: long (nullable = true)
| | |-- infractionType: string (nullable = true)
| | |-- responseTime: string (nullable = true)
| | |-- status: string (nullable = true)
| | |-- transactionCode: string (nullable = true)
</code></pre>
<p>I'm expecting some kind of this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>idAccount</th>
</tr>
</thead>
<tbody>
<tr>
<td>value</td>
<td>value</td>
</tr>
<tr>
<td>value</td>
<td>value</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74271508,
"author": "Jonathan Lam",
"author_id": 10445333,
"author_profile": "https://Stackoverflow.com/users/10445333",
"pm_score": 0,
"selected": false,
"text": "ArrayType"
},
{
"answer_id": 74271796,
"author": "samkart",
"author_id": 8279585,
"author... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20348552/"
] |
74,269,568 | <p>I have a dataframe that looks like this</p>
<pre><code>d = {'total_time':[1,2,3,4],
'date': ['2022-09-11', '2022-09-11', '2022-09-13', '2022-09-13'],
'key': ['A', 'B', 'A', 'B']}
df_sample = pd.DataFrame(data=d)
df_sample.head()
</code></pre>
<p>I want to compare total_time across the data that should be in the x-axis but I want to compare these values by the associated 'key'.</p>
<p>Therefore I should have something that looks like this</p>
<p><a href="https://i.stack.imgur.com/XHduq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XHduq.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74269785,
"author": "Sheldon",
"author_id": 6440589,
"author_profile": "https://Stackoverflow.com/users/6440589",
"pm_score": 0,
"selected": false,
"text": "import numpy as np \nimport matplotlib.pyplot as plt \n \nX_axis = np.arange(len(df_sample.date.unique()))\n \nplt... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7700802/"
] |
74,269,574 | <p>I am reading this article about using DI inside ASP.NET Core @ <a href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-6.0" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-6.0</a> .. but i can not understand its benefit of providing abstraction level.</p>
<p>for example without DI, we will have those classes:-</p>
<pre><code>public class MyDependency
{
public void WriteMessage(string message)
{
Console.WriteLine($"MyDependency.WriteMessage called. Message: {message}");
}
}
public class IndexModel : PageModel
{
private readonly MyDependency _dependency = new MyDependency();
public void OnGet()
{
_dependency.WriteMessage("IndexModel.OnGet");
}
}
</code></pre>
<p>and with DI we will have those classes:-</p>
<pre><code>public interface IMyDependency
{
void WriteMessage(string message);
}
public class MyDependency : IMyDependency
{
public void WriteMessage(string message)
{
Console.WriteLine($"MyDependency.WriteMessage Message: {message}");
}
}
public class Index2Model : PageModel
{
private readonly IMyDependency _myDependency;
public Index2Model(IMyDependency myDependency)
{
_myDependency = myDependency;
}
public void OnGet()
{
_myDependency.WriteMessage("Index2Model.OnGet");
}
}
</code></pre>
<p>but at the end with DI or without DI if i want to modify the WriteMessage method, to accept 2 strings instead of one as follow:-</p>
<pre><code>public void WriteMessage(string message,string message2)
{
Console.WriteLine($"MyDependency.WriteMessage called. Message: {message}{message2}");
}
</code></pre>
<p>i will have to modify the related classes; without DI case:-</p>
<pre><code>public class IndexModel : PageModel
{
private readonly MyDependency _dependency = new MyDependency();
public void OnGet()
{
_dependency.WriteMessage("IndexModel.OnGet","two");
}
}
</code></pre>
<p>with DI case:-</p>
<pre><code>public class Index2Model : PageModel
{
private readonly IMyDependency _myDependency;
public Index2Model(IMyDependency myDependency)
{
_myDependency = myDependency;
}
public void OnGet()
{
_myDependency.WriteMessage("Index2Model.OnGet","two");
}
}
</code></pre>
<p>so not sure how using DI will create an abstraction between the <code>WriteMessage</code> implementation and the classes which consume it.. or i am understanding DI and its benefits wrongly?</p>
<p>Thanks</p>
| [
{
"answer_id": 74270454,
"author": "rlm96",
"author_id": 11779351,
"author_profile": "https://Stackoverflow.com/users/11779351",
"pm_score": 2,
"selected": false,
"text": "IMyDependency"
},
{
"answer_id": 74270673,
"author": "wjxie",
"author_id": 9976077,
"author_prof... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1146775/"
] |
74,269,590 | <p>I am trying to get a list of connectors, and their associated parameters in an MEP family. But i am not able to find a way to do that. Had it been a Family instance, i could have easily done the following:</p>
<pre><code>// famInst in an instance of a FamilySymbol.
famInst_conn_lst = famInst.MEPModel.ConnectorManager.Connectors.Cast<Connector>().ToList();
</code></pre>
<p>Is there a way to access the "MEPModel" or the "ConnectorManager" directly from a Family?</p>
<p><a href="https://i.stack.imgur.com/amEoe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/amEoe.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74270454,
"author": "rlm96",
"author_id": 11779351,
"author_profile": "https://Stackoverflow.com/users/11779351",
"pm_score": 2,
"selected": false,
"text": "IMyDependency"
},
{
"answer_id": 74270673,
"author": "wjxie",
"author_id": 9976077,
"author_prof... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6296776/"
] |
74,269,601 | <p>I'm trying to make a very simple query to a MySQL 5.7 database but the query is slow and the explain shows it is not using the index, although it lists it as a possible key. Below is the query, explain output, and table schema. Any ideas? Thanks</p>
<p>Query: <code>SELECT text FROM LogMessages where lotNumber = 5556677</code></p>
<p>Explain output:</p>
<pre><code>mysql> explain SELECT text FROM LogMessages where lotNumber = 5556677;
+----+-------------+------------------------------+------------+------+------------------------------------------------------------------------------+------+---------+------+----------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+------------------------------+------------+------+------------------------------------------------------------------------------+------+---------+------+----------+----------+-------------+
| 1 | SIMPLE | LogMessages | NULL | ALL | idx_LogMessages_lotNumber | NULL | NULL | NULL | 35086603 | 10.00 | Using where |
+----+-------------+------------------------------+------------+------+------------------------------------------------------------------------------+------+---------+------+----------+----------+-------------+
1 row in set, 5 warnings (0.07 sec)
</code></pre>
<p>Table schema:</p>
<pre><code>CREATE TABLE `LogMessages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`lotNumber` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`text` text COLLATE utf8mb4_unicode_ci,
PRIMARY KEY (`id`),
UNIQUE KEY `idLogMessages_UNIQUE` (`id`),
KEY `idx_LogMessages_lotNumber` (`lotNumber`)
) ENGINE=InnoDB AUTO_INCREMENT=37545325 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
</code></pre>
| [
{
"answer_id": 74270454,
"author": "rlm96",
"author_id": 11779351,
"author_profile": "https://Stackoverflow.com/users/11779351",
"pm_score": 2,
"selected": false,
"text": "IMyDependency"
},
{
"answer_id": 74270673,
"author": "wjxie",
"author_id": 9976077,
"author_prof... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17075738/"
] |
74,269,611 | <p>I have columns in my dataframe df1 like this where the columns starting with 20 were generated dynamically.</p>
<p><a href="https://i.stack.imgur.com/4xVuQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4xVuQ.png" alt="enter image description here" /></a></p>
<p>I could rename the columns starting with 20 to 2019_p, 2020_p, 2021_p dynamically using</p>
<pre><code>df.select(*[col(c).alias(f"${c}_p") if c.startswith("20") else col(c) for c in df.columns])
</code></pre>
<p><a href="https://i.stack.imgur.com/2nvJx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2nvJx.png" alt="enter image description here" /></a></p>
<p>Now I have 2 dataframes one with original dataframe and another data frame with columns starting with 20 and ending with _p. I want to final select the columns based on whichever is not null either without _p or with_p.
How do I achieve this?</p>
| [
{
"answer_id": 74269636,
"author": "Robert Kossendey",
"author_id": 12638118,
"author_profile": "https://Stackoverflow.com/users/12638118",
"pm_score": 0,
"selected": false,
"text": "df.select(*[col(c).alias(f\"${c}_p\") if c.startswith(\"20\") and NEW CONDITION else col(c) for c in df.c... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4057692/"
] |
74,269,667 | <p>I am trying to write a function (char-count) which takes a pattern and a string, then returns a number (count) which represents how many times any of the characters in the pattern appear in the string.</p>
<p>For example:</p>
<p><code>(char-count "Bb" "Best buy")</code></p>
<p>would return <code>2</code> since there is 1 match for <code>B</code> and 1 match for <code>b</code>, so added together we get <code>2</code></p>
<p><code>(char-count "AaR" "A Tale of Recursion")</code></p>
<p>would return <code>3</code> and so on</p>
<hr />
<p>I tried using <code>re-seq</code> in my function, but it seems to work only for continuous strings. As in <code>(re-seq #Bb "Best Buy)</code> only looks for the pattern <code>Bb</code>, not for each individual character.</p>
<p>This is what my function looks like so far:</p>
<pre><code>(defn char-count [pattern text]
(count (re-seq (#(pattern)) text)))
</code></pre>
<p>But it does not do what I want. Can anybody help?</p>
<p>P.s. Very new to clojure (and functional programming in general).</p>
| [
{
"answer_id": 74269706,
"author": "Eugene Pakhomov",
"author_id": 564509,
"author_profile": "https://Stackoverflow.com/users/564509",
"pm_score": 1,
"selected": true,
"text": "[...]"
},
{
"answer_id": 74269963,
"author": "amalloy",
"author_id": 625403,
"author_profil... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15431663/"
] |
74,269,696 | <p>I have an array of objects, and I want to select a number of properties out from each one, creating a new object with those properties to return, as well as add a few more values to the new object. How can I do it better than this? I have also thought about having a list of properties to pull off of <code>thing</code> to make it easier. But looking for a better way.
e.g.</p>
<pre><code> const a = things.map((thing) => {
let {obj1, obj2, obj3} = thing;
return {obj1, obj2, obj3, newVal: null, otherNewVal: null}
});
return a;
</code></pre>
| [
{
"answer_id": 74269706,
"author": "Eugene Pakhomov",
"author_id": 564509,
"author_profile": "https://Stackoverflow.com/users/564509",
"pm_score": 1,
"selected": true,
"text": "[...]"
},
{
"answer_id": 74269963,
"author": "amalloy",
"author_id": 625403,
"author_profil... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7514409/"
] |
74,269,705 | <pre><code> Adress Rooms m2 Price Floor
196 Skanstes 29a 5 325 2800 24/24
12 AusekΔΌa 4 5 195 2660 7/7
7 Antonijas 17A 3 86 2200 6/6
31 BlaumaΕa 16 4 136 1800 4/6
186 RΕ«pniecΔ«bas 21k2 5 160 1700 7/7
233 Vesetas 24 4 133 1700 10/10
187 RΕ«pniecΔ«bas 34 5 157 1600 3/6
91 Elizabetes 31Π° 8 203 1600 1/5
35 BlaumaΕa 9 3 90 1600 3/5
60 CΔsu 9 3 133 1550 6/7
</code></pre>
<p>I got the data set that I want to test the theory on if the higher the floor the more expensive the property rent price.</p>
<pre><code>Adress object
Rooms int64
m2 int64
Price int64
Floor object
dtype: object
</code></pre>
<p>tbh I am stuck, not even sure how to start with this. Is there any way I can loop through the first number and compare it to the second? Like if 24=24 then it's in the new category 'Top Floor'?? And create 'mid-floor' and 'ground floor' categories as well.</p>
<p>GOT this far.</p>
<pre><code>df_sorted= df.sort_values("Price",ascending=False)
print(df_sorted.head(10))
for e in df_sorted['Floor']:
parts=e.split('/')
print(parts)
</code></pre>
<p>but the second part is not working</p>
<pre><code>if parts[0]==parts[-1]:
return "Top Floor" if parts[0]=="1":
return "Bottom Floor" else: "Mid Floor"
</code></pre>
| [
{
"answer_id": 74269758,
"author": "Ilya",
"author_id": 11089170,
"author_profile": "https://Stackoverflow.com/users/11089170",
"pm_score": 0,
"selected": false,
"text": "def split_floors(floor):\n if floor.split('/')[0] == '1':\n return 'Bottom'\n if floor.split('/')[0] == ... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20283962/"
] |
74,269,722 | <p>With this bit of VBA code in MS Access I'm getting an error if its executed too often. The only way I've found to clear it is reboot my computer. Any idea why and what can I do?</p>
<p><a href="https://i.stack.imgur.com/oSIYH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oSIYH.png" alt="enter image description here" /></a></p>
<pre><code>Public Function HasOutlookAcct(strEmail As String) As Boolean
Dim OutMail As Object
Dim OutApp As OutLook.Application
Dim objNs As OutLook.NameSpace
Dim objAcc As Object
'https://stackoverflow.com/questions/67284852/outlook-vba-select-sender-account-when-new-email-is-created
Set OutApp = CreateObject("Outlook.Application")
Set objNs = OutApp.GetNamespace("MAPI")
For Each objAcc In objNs.Accounts
If objAcc.SmtpAddress = strEmail Then
HasOutlookAcct = True
Exit For
End If
Next
OutApp.Quit
Set objAcc = Nothing
Set objNs = Nothing
End Function
</code></pre>
| [
{
"answer_id": 74282286,
"author": "Eugene Astafiev",
"author_id": 1603351,
"author_profile": "https://Stackoverflow.com/users/1603351",
"pm_score": 1,
"selected": false,
"text": "Accounts"
},
{
"answer_id": 74290528,
"author": "niton",
"author_id": 1571407,
"author_p... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14137914/"
] |
74,269,723 | <p>I have written a function to calculate the mean values from monthly data within a year (starting in the previous Dec to the current Sep). Each dataframe (and there are many) that I'm feeding through this function is presently named for the variable that I'm interested in. But I want the output to use the name of the dataframe as the variable.</p>
<p>Example:</p>
<pre><code>year <- c(2000:2020)
`1` <- runif(21, 0,10)
`2` <- runif(21, 0,10)
`3` <- runif(21, 0,10)
`4` <- runif(21, 0,10)
`5` <- runif(21, 0,10)
`6` <- runif(21, 0,10)
`7` <- runif(21, 0,10)
`8` <- runif(21, 0,10)
`9` <- runif(21, 0,10)
`10` <- runif(21, 0,10)
`11` <- runif(21, 0,10)
`12` <- runif(21, 0,10)
dogs <- as.data.frame(cbind(year, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `10`, `11`, `12`))
fun_annual <- function(df) {
name = deparse(substitute(df)) #I know I can use this to get the name of the dataframe
df %>%
mutate(lag12 = lag(`12`)) %>%
rowwise() %>% # complete next calculations row by row
mutate(name = mean(c_across(c(`1`:`9`, lag12)))) %>% #mean from prev Dec to Sep
select(year, name) #by this point 'name' should be 'dogs' (name of original dataframe
}
# Final function should return a dataframe with 2 variables: year and dogs
</code></pre>
<p><strong>Bonus points</strong> if someone can also help be figure out how to put the months in the function, so I don't have to change the months within the function each time! Especially if I use more months from the previous year (beyond Dec)</p>
| [
{
"answer_id": 74282286,
"author": "Eugene Astafiev",
"author_id": 1603351,
"author_profile": "https://Stackoverflow.com/users/1603351",
"pm_score": 1,
"selected": false,
"text": "Accounts"
},
{
"answer_id": 74290528,
"author": "niton",
"author_id": 1571407,
"author_p... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3220999/"
] |
74,269,725 | <p>I got a working SQL query : <code>select p.name, p.id from acv_project p join acv_product prod on prod.project_id = p.id where prod.weight <> 0 and p.green_user_id = 18</code></p>
<p>If i pass it into a `</p>
<pre><code>$stmt = $em->getConnection()->prepare($rawSql);
$stmt->execute([]);
$projects = $stmt->fetchAll();
</code></pre>
<p>It works but i'd like to pass it by adding the "green_user_id" as a parameter and not always 18.</p>
<p>When i try with this code : `</p>
<pre><code>$sql2 = "select p from ArtoAcvBundle:Project p join prod ArtoAcvBundle:Product on prod.project_id = p.id where prod.weight <> 0 and p.green_user_id =:userId";
$query2 = $em->createQuery($sql2)->setParameters(
array('userId' => $userId));
$projects = $query2->getResult();
</code></pre>
<p>I get <code>[Semantical Error] line 0, col 48 near 'ArtoAcvBundle:Product': Error: Identification Variable prod used in join path expression but was not defined before.</code></p>
<p>And with QueryBuilder, i tried lots of thing but fails to understand how to write it.</p>
<p>Here are some links to my 2 Doctrine entities :</p>
<p><a href="https://drive.google.com/file/d/1s-LbZxJd9oMHZ-6ZhNRN1WHJn2rQhgxM/view?usp=share_link" rel="nofollow noreferrer">Entity Product</a></p>
<p><a href="https://drive.google.com/file/d/1qJUyG5LRSY38KpMGMtMJIrEXr4ofa5HI/view?usp=share_link" rel="nofollow noreferrer">Entity Project</a></p>
<p>Thanks for help !</p>
| [
{
"answer_id": 74282286,
"author": "Eugene Astafiev",
"author_id": 1603351,
"author_profile": "https://Stackoverflow.com/users/1603351",
"pm_score": 1,
"selected": false,
"text": "Accounts"
},
{
"answer_id": 74290528,
"author": "niton",
"author_id": 1571407,
"author_p... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3735247/"
] |
74,269,734 | <p>I'm trying to run an API call in React Native on Android with Expo using Axios, but I'm encountering a network error. I tried some solutions, but nothing seems to work. This is the error displayed in the console:</p>
<pre><code>Network Error
at node_modules\\axios\\lib\\core\\AxiosError.js:3:0in \<global\>
at node_modules\\axios\\lib\\adapters\\xhr.js:138:8 in handleAbort
at node_modules\\event-target-shim\\dist\\event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent
at node_modules\\react-native\\Libraries\\Network\\XMLHttpRequest.js:647:10 in setReadyState
at node_modules\\react-native\\Libraries\\Network\\XMLHttpRequest.js:396:6 in didCompleteResponse
at node_modules\\react-native\\Libraries\\vendor\\emitter_EventEmitter.js:150:10 in EventEmitter#emit
at node_modules\\react-native\\Libraries\\BatchedBridge\\MessageQueue.js:417:4 in callFunction
at node_modules\\react-native\\Libraries\\BatchedBridge\\MessageQueue.js:114:6 in guard$argument_0
at node_modules\\react-native\\Libraries\\BatchedBridge\\MessageQueue.js:368:10 in guard
at node_modules\\react-native\\Libraries\\BatchedBridge\\MessageQueue.js:113:4 in callFunctionReturnFlushedQueue
</code></pre>
<p>I tried changing the localhost in the API link to my IP address, as well as to 10.0.2.2, but nothing worked. I checked my internet permission in AndroidManifest and made some other permission changes to the file, but nothing seemed to resolve it. I hope to find a solution to the problem soon.</p>
| [
{
"answer_id": 74451376,
"author": "Nibeza kevin",
"author_id": 14380214,
"author_profile": "https://Stackoverflow.com/users/14380214",
"pm_score": 0,
"selected": false,
"text": "axiosError: Network error"
}
] | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20198977/"
] |
74,269,739 | <p>I am trying to add a product to a shopping cart in mongodb but the code I have written does not work. It was previously working but when I switched from local mongodb to mongodb atlas cloud and then back to local mongodb it started having issues because it will not use the cart that gets created when redirected to '/' root and instead will keep creating a new cart with a new req.session.cartId belonging to it each time a product is added to cart. I have had so many issues with this one section and it is the final part of my project to get working before live hosting. Any help is appreciated. thank you.</p>
<pre><code>const express = require('express');
const Carts = require('../repo/carts');
const Product = require('../repo/products');
const cartShowTemplate = require('../views/carts/show');
const router = express.Router();
let cart;
router.post('/cart/products', async (req, res) => {
try {
cart = await Carts.findById(req.session.cartId);
// Check if cart exists
if (!cart) {
// Create new cart
cart = await Carts.create({
_id: req.session.cartId,
items: [],
});
}
// Check if product is present
const productIndex = cart.items.findIndex(
(item) => item._id === req.body.productId
);
if (productIndex === -1) {
// Create new product
cart.items.push({
_id: req.body.productId,
quantity: 1,
});
} else {
// Update existing product
cart.items[productIndex].quantity += 1;
}
// Save updated cart
await cart.save();
console.log(cart);
res.status(200).send('product added to cart!!');
} catch (err) {
res.status(500).send('there was an error');
}
});
module.exports = router;
</code></pre>
<p>example of the array<br />
the correct product gets added but a new cart with a new id gets created each time instead of using the same cart. I am not sure if this helps but what I noticed when I console.log(req.sessionID) it will show the same ID each time its console.logged but when console.logging (req.session.cartId) that will show as undefined when before it was showing an id.</p>
<p><a href="https://i.stack.imgur.com/F0sy3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F0sy3.png" alt="enter image description here" /></a></p>
<p>carts schema</p>
<pre><code>const mongoose = require('mongoose');
const cartSchema = new mongoose.Schema({
_id: String,
items: [
{ quantity: Number, _id: String }
]
});
const Carts = new mongoose.model('Carts', cartSchema);
module.exports = Carts;
</code></pre>
| [
{
"answer_id": 74451376,
"author": "Nibeza kevin",
"author_id": 14380214,
"author_profile": "https://Stackoverflow.com/users/14380214",
"pm_score": 0,
"selected": false,
"text": "axiosError: Network error"
}
] | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16582373/"
] |
74,269,765 | <p>I've looked around and I'm surprised no one else has asked this yet, but I am trying to use User Secrets with my Azure Function app (.NET 6, v4). The value is never populated with I run locally from Visual Studio.</p>
<p><code>Function1.cs</code></p>
<pre class="lang-cs prettyprint-override"><code>public static class Function1
{
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
var secret = Environment.GetEnvironmentVariable("mysecret");
return new OkObjectResult($"Secret is: {secret}");
}
}
</code></pre>
<p><code>local.settings.json</code></p>
<pre class="lang-json prettyprint-override"><code>{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}
</code></pre>
<p><code>secrets.json</code></p>
<pre class="lang-json prettyprint-override"><code>{
"mysecret": "test1",
"Values:mysecret": "test2"
}
</code></pre>
<p><code>FunctionApp1.csproj</code></p>
<pre class="lang-xml prettyprint-override"><code><Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
<UserSecretsId>24c7ab90-4094-49a9-94ef-c511ac530526</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="5.0.0" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.1.1" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
</code></pre>
<p>The endpoint returns: "Secret is: " and I would expect it to return either "Secret is: test1" or "Secret is: test2"</p>
<p>However, when I change my <code>local.settings.json</code> to this it works:</p>
<pre class="lang-json prettyprint-override"><code>{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"mysecret": "test3"
}
}
</code></pre>
<p>How can I get the user secrets to pass to local.settings.json correctly? I'm guessing they don't show up as environment variables.</p>
| [
{
"answer_id": 74451376,
"author": "Nibeza kevin",
"author_id": 14380214,
"author_profile": "https://Stackoverflow.com/users/14380214",
"pm_score": 0,
"selected": false,
"text": "axiosError: Network error"
}
] | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6031889/"
] |
74,269,808 | <p>When the webpage loads in, the door goes down, and when the button is pressed, the door should go back up.</p>
<p>The fan and the background should first be seen, then the door should slide down, then clicking on the door raises it.</p>
<p>Is there a way for this to be improved?</p>
<p>code <a href="https://jsfiddle.net/jt9vpeyx/" rel="nofollow noreferrer">https://jsfiddle.net/jt9vpeyx/</a></p>
<pre><code>.video-one {
top: -101%;
transition: all 10s ease-in 0s;
transition-delay: 1s;
}
.video-one.slide {
top: 0%;
}
.curtain.slide .video-one {
transition-delay: 3s;
transform: translateY(calc(-100% - 1px));
}
let videoOne = document.querySelector('.video-one')
requestAnimationFrame(() => {
videoOne.classList.add("slide");
})
</code></pre>
<p>How the code works is, on page load the wall comes down, then on button click the wall goes up.</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 videoOne = document.querySelector('.video-one')
requestAnimationFrame(() => {
videoOne.classList.add("slide");
})
const manageCover = (function makeManageCover() {
function show(el) {
el.classList.remove("hide");
}
function hide(el) {
el.classList.add("hide");
}
function openCurtain(cover) {
hide(cover);
const curtain = document.querySelector(".curtain");
curtain.classList.add("slide");
return curtain;
}
function showVideo(curtain) {
const thewrap = curtain.parentElement.querySelector(".wrap");
show(thewrap);
}
function coverClickHandler(evt) {
const cover = evt.currentTarget;
const curtain = openCurtain(cover);
showVideo(curtain);
cover.dispatchEvent(new Event("afterClick"));
}
function init(callback) {
const cover = document.querySelector(".play");
cover.addEventListener("click", coverClickHandler);
cover.addEventListener("afterClick", callback);
}
return {
init
};
}());
const videoPlayer = (function makeVideoPlayer() {
let playlist;
let player;
function loadIframeScript() {
const tag = document.createElement("script");
tag.src = "https://www.youtube.com/iframe_api";
const firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
function onYouTubeIframeAPIReady() {
const cover = document.querySelector(".play");
const wrapper = cover.parentElement;
const frameContainer = wrapper.querySelector(".video");
addPlayer(frameContainer, playlist);
}
function shufflePlaylist(player) {
player.setShuffle(true);
player.playVideoAt(0);
player.stopVideo();
}
function onPlayerReady(event) {
player = event.target;
player.setVolume(100);
shufflePlaylist(player);
}
function createPlaylist(videoIds) {
return videoIds.join();
}
function createOptions(videoIds) {
const options = {
height: 360,
host: "https://www.youtube-nocookie.com",
width: 640
};
options.playerVars = {
autoplay: 0,
cc_load_policy: 0,
controls: 1,
disablekb: 1,
fs: 0,
iv_load_policy: 3,
rel: 0
};
options.events = {
"onReady": onPlayerReady
};
options.playerVars.loop = 1;
options.playerVars.playlist = createPlaylist(videoIds);
return options;
}
function createVideoOptions(ids) {
const options = createOptions(ids);
return options;
}
function addPlayer(video, ids) {
const options = createVideoOptions(ids);
player = new YT.Player(video, options);
return player;
}
function play() {
if (player && player.playVideo) {
player.playVideo();
}
}
function init(videoIds) {
player = null;
loadIframeScript();
window.onYouTubeIframeAPIReady = onYouTubeIframeAPIReady;
playlist = videoIds;
return play;
}
return {
init,
play
};
}());
manageCover.init(videoPlayer.init([
"0dgNc5S8cLI",
]));</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
height: 100%;
margin: 0;
padding: 0;
}
body {
background-image: repeating-linear-gradient(135deg, rgb(0, 0, 0) 0px, rgb(0, 0, 0) 10px, transparent 10px, transparent 11px), repeating-linear-gradient(22.5deg, rgb(0, 0, 0) 0px, rgb(0, 0, 0) 10px, transparent 10px, transparent 11px), linear-gradient(90deg, rgb(0, 89, 221), rgb(0, 89, 221), rgb(0, 89, 221), rgb(0, 89, 221), rgb(0, 89, 221));
}
.container {
position: absolute;
left: 0;
right: 0;
min-height: 100%;
min-width: 255px;
display: flex;
padding: 8px 8px;
}
.curtain {
flex: 1 0 0;
margin: auto;
max-width: 640px;
border: 21px solid;
border-radius: 3.2px;
border-color: #000 #101010 #000 #101010;
position: relative;
}
.curtain::before {
content: '';
position: absolute;
top: -2px;
left: -2px;
right: -2px;
bottom: -2px;
background: #0a0a0a;
border: 1px solid;
border-color: #000 #101010 #000 #101010;
;
}
.curtain::after {
content: "";
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 0;
outline: 1px solid #f91f6e;
pointer-events: none;
}
.curtain.slide::after {
outline: 1px solid #0059dd;
transition: outline 2s ease-in;
/* add this */
/*background-image: none;*/
}
:root {
--wide: 32px;
--angle1: 0;
--angle2: -90;
}
.video-one {
position: absolute;
height: 100%;
width: 100%;
top: 0;
background: repeating-linear-gradient( calc(var(--angle1) * 1deg), #ffffff00 0, #ffffff00 var(--wide), #ffffff1a calc(var(--wide) + 1px), #0000004d calc(var(--wide) + 2px), #ffffff00 calc(var(--wide) + 5px)), repeating-linear-gradient( calc(calc(var(--angle2) + 90) * 1deg), #ffffff00 0, #ffffff00 var(--wide), #ffffff1a calc(var(--wide) + 1px), #0000004d calc(var(--wide) + 2px), #ffffff00 calc(var(--wide) + 5px));
background-color: #222;
border-bottom: 2px solid red;
background-repeat: no-repeat;
z-index: 0;
}
.video-one::after {
content: "";
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 0;
background: url("https://via.placeholder.com/264x264");
background-position: center;
background-size: 41.25% 73.33%;
background-repeat: no-repeat;
}
.ratio-keeper {
position: relative;
height: 0;
padding-top: 56.25%;
margin: auto;
overflow: hidden;
}
.fence {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
background: linear-gradient(45deg, transparent, transparent 7px, rgb(113, 121, 126) 7px, rgb(113, 121, 126) 7.5px, transparent 7.5px, transparent 10px), linear-gradient(-45deg, transparent, transparent 7px, rgb(113, 121, 126) 7px, rgb(113, 121, 126) 7.5px, transparent 7.5px, transparent 10px);
background-size: 10px 10px;
filter: drop-shadow(0 0 5px #000);
clip-path: circle(25% at center);
}
.fence>div {
position: absolute;
/*top: 0;*/
left: 0;
right: 0;
/*width: 100%;*/
height: 0.55%;
/*height: 2px;*/
background: green;
}
.fence>div:nth-child(1) {
top: 10%;
}
.fence>div:nth-child(2) {
top: 20%;
}
.fence>div:nth-child(3) {
top: 30%;
}
.fence>div:nth-child(4) {
top: 40%;
}
.fence>div:nth-child(5) {
top: 50%;
}
.fence>div:nth-child(6) {
top: 60%;
}
.fence>div:nth-child(7) {
top: 70%;
}
.fence>div:nth-child(8) {
top: 80%;
}
.fence>div:nth-child(9) {
top: 90%;
}
.fan svg {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: 70%;
height: 70%;
margin: auto;
}
.slide .fan svg {
animation: fan-spin linear;
animation-duration: 12s;
animation-iteration-count: 1;
animation-delay: 3s;
}
@keyframes fan-spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.video-frame {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
iframe {
display: block;
animation: iframe 6s ease forwards;
animation-delay: 6s;
opacity: 0;
}
@keyframes iframe {
to {
opacity: 1;
}
}
iframe {
user-select: none;
}
.play {
-webkit-appearance: none;
appearance: none;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
display: flex;
justify-content: center;
align-items: center;
width: 90px;
height: 90px;
border-radius: 50%;
cursor: pointer;
border: 9px solid;
z-index: 1;
background: transparent;
filter: drop-shadow(3px 3px 3px #000000b3);
border-color: blue;
animation: fadeInPlay 2s ease-in 2s forwards;
animation-delay: 10s;
opacity: 0;
cursor: default;
pointer-events:none;
}
@keyframes fadeInPlay {
0% {
opacity: 0;
}
99.9% {
opacity: 1;
pointer-events:none;
}
100% {
opacity: 1;
cursor: pointer;
pointer-events:initial;
}
}
.play::before {
content: "";
width: 0;
height: 0;
border-top: 20px solid transparent;
border-bottom: 20px solid transparent;
border-left: 27px solid;
transform: translateX(4px);
border-left-color: blue;
}
.play:hover {
box-shadow: 0 0 0 5px rgba(20, 179, 33, 0.5);
}
.play:focus {
outline: 0;
box-shadow: 0 0 0 5px rgba(111, 0, 255, 0.5);
}
.exit {
position: absolute;
top: auto;
bottom: -47.63px;
margin: auto;
right: 0;
left: 0;
width: 47px;
height: 47px;
cursor: pointer;
border-radius: 100%;
background: transparent;
border: 5px solid red;
box-sizing: border-box;
opacity: 0;
pointer-events: none;
clip-path: circle(50%);
}
.slide .exit {
animation: fadeInExit 4s forwards 7.5s;
}
@keyframes fadeInExit {
99% {
pointer-events: none;
}
100% {
pointer-events: initial;
opacity: 1;
}
}
.exit::before,
.exit::after {
content: "";
background-color: red;
width: 47px;
height: 5px;
position: absolute;
top: 0px;
left: -5px;
right: 0;
bottom: 0;
margin: auto;
}
.exit::before {
transform: rotate(45deg);
}
.exit::after {
transform: rotate(-45deg);
}
.hide {
display: none;
}
.video-one {
top: -101%;
transition: all 10s ease-in 0s;
transition-delay: 1s;
}
.video-one.slide {
top: 0%;
}
.curtain.slide .video-one {
transition-delay: 3s;
transform: translateY(calc(-100% - 1px));
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="curtain">
<div class="ratio-keeper">
<div class="fence">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
<div class="fan">
<svg width="70%" height="70%" viewBox="76 130 381 381">
<g id="fan">
<path fill="#000" stroke="#000"
d="m166.3352 168.6294c5.5396 2.4448 45.2339 54.394 72.7499 91.0151-9.1901-44.8757-21.7959-109.0279-19.9558-114.796 4.1462-12.9949 33.7039-13.5172 41.5845-13.7579 7.8827-.2415 37.4165-1.5221 42.3488 11.1948 2.1872 5.6436-6.4773 70.4506-12.9142 115.8007 25.2309-38.2323 61.6818-92.5089 67.0612-95.2865 12.119-6.2568 33.3898 14.2749 39.1337 19.6768 5.7424 5.402 27.5341 25.3815 22.0294 37.859-2.4441 5.5389-54.3954 45.2354-91.0172 72.7506 44.8757-9.1901 109.0293-21.7959 114.7974-19.9559 12.9927 4.1442 13.5193 33.7032 13.7586 41.5838.2422 7.8819 1.5221 37.4165-11.192 42.3473-5.6471 2.1894-70.4541-6.4765-115.8049-12.9127 38.2323 25.2323 92.5081 61.6783 95.2871 67.0605 6.2581 12.1175-14.2742 33.3877-19.6776 39.133-5.4027 5.7432-25.3815 27.5341-37.8563 22.0279-5.5396-2.4434-45.2361-54.3961-72.7534-91.0143 9.1901 44.8757 21.7952 109.0287 19.9551 114.7953-4.1434 12.9934-33.7026 13.5157-41.5852 13.7586-7.8799.24-37.4165 1.5221-42.3431-11.1936-2.1887-5.6464 6.4779-70.4541 12.9133-115.8071-25.2323 38.2323-61.6824 92.5124-67.0639 95.2908-12.1169 6.256-33.3891-14.2728-39.1337-19.6754-5.7432-5.4027-27.5313-25.383-22.0251-37.8578 2.4434-5.5396 54.394-45.2339 91.0136-72.7526-44.8764 9.1908-109.0266 21.7944-114.7967 19.9566-12.9934-4.1434-13.5171-33.7025-13.7586-41.5852-.2407-7.8806-1.5221-37.4165 11.1963-42.346 5.6443-2.1879 70.4498 6.4752 115.8 12.9121-38.233-25.2316-92.5081-61.6783-95.2865-67.0612-6.256-12.1169 14.2748-33.3913 19.6768-39.1337 5.4006-5.7438 25.3794-27.5333 37.8584-22.0272z" />
</g>
</svg>
</div>
<div class="cross"></div>
<div class="wrap hide">
<div class="video video-frame" data-id=""></div>
</div>
<div class="video-one"></div>
</div>
<a href="https://www.google.com/">
<div class="exit"></div>
</a>
</div>
<button class="play" type="button" aria-label="Open"></button>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74417416,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": -1,
"selected": false,
"text": ".video-one {\n top: -101%;\n}\n.video-one.closed {\n top: 0%;\n}\n"
},
{
"answer_id": 74420997,
"autho... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17631451/"
] |
74,269,830 | <pre><code>import React from "react";
import "./profile.css";
const Notifications = () => {
function changeText() {
themebox.textContent =
"Nice";
}
function changeText2() {
themebox.textContent =
"Fair";
}
function changeText3() {
themebox.textContent = "Aggressive";
}
function changeText4() {
themebox.textContent =
"Threatening";
}
return (
<div className="notification-container">
<h3>Notifications</h3>
<div className="notif-picker">
<p className="Selected" onClick={changeText}>
Nice
</p>
<p onClick={changeText2}>Fair</p>
<p onClick={changeText3}> Aggressive</p>
<p onClick={changeText4}>Threatening</p>
</div>
<div className="theme-show-box">
<div className="theme-box" id="themebox"></div>
</div>
</div>
);
};
export default Notifications;
</code></pre>
<p>When i click on one of p tags it shows the text that i put in a function which is displayed in the div with classname "theme-box" and id "themebox". Everything seems to work fine, but i get an error in react saying themebox is not defined. Any idea how i can solve that error? :)</p>
| [
{
"answer_id": 74417416,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": -1,
"selected": false,
"text": ".video-one {\n top: -101%;\n}\n.video-one.closed {\n top: 0%;\n}\n"
},
{
"answer_id": 74420997,
"autho... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20383238/"
] |
74,269,867 | <p>I have this table in SnowFlake:</p>
<p><a href="https://i.stack.imgur.com/vmZ9d.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vmZ9d.jpg" alt="enter image description here" /></a></p>
<p>What I want to do is to incrementally update the <code>row_id</code> by <code>internal_id</code>. E.g. for <code>internal_id = CHE20220708134003004472</code>, the row_id should take the values from 1 to 3 respectively, and so on for the other ids.</p>
<p>Here is an example of the desired output:</p>
<p><a href="https://i.stack.imgur.com/zCfmH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zCfmH.png" alt="enter image description here" /></a></p>
<p>I've tried to do that by using the following code:</p>
<pre><code>execute immediate $$
declare
counter integer default 1;
total_rows integer default (SELECT COUNT(*) FROM "DB_MX_DEV"."STAGING"."stg_chedraui_inv_day" WHERE internall_id = 'CHE20220708134003004472');
begin
for i in 1 to total_rows do
counter := counter + 1;
UPDATE "DB_MX_DEV"."STAGING"."stg_chedraui_inv_day" SET row_id = counter where internall_id = 'CHE20220708134003004472';
end for;
return counter;
end;
$$;
</code></pre>
<p>However, I got this error:
<code>Uncaught exception of type 'STATEMENT_ERROR' on line 8 at position 4 : SQL compilation error: error line 1 at position 65 invalid identifier 'COUNTER'</code></p>
<p>Note: At the moment, the code above is only trying to update the <code>row_id</code> for a specific <code>internal_id</code>, I'm still trying to figure out how to do it for all ids.</p>
| [
{
"answer_id": 74270038,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": false,
"text": "ROW_NUMBER()"
},
{
"answer_id": 74309791,
"author": "Felipe Hoffa",
"author_id": 132438,
... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13254554/"
] |
74,269,882 | <p>I have a json string. Like this:</p>
<p><code>"{"http_requests":[{"http_requests":{"code":"400","method":"PUT","value":89}},{"http_requests":{"code":"200","method":"PUT","value":45}}]}"</code></p>
<p>I want to insert this json to mongodb. But I have error in my code.
The error is "cannot transform type string to a BSON Document: WriteString can only write while positioned on a Element or Value but is positioned on a TopLevel"</p>
<pre><code>func insertJson(json_value string) {
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb+srv://abc:123@cluster0.wrzj3zo.mongodb.net/?retryWrites=true&w=majority"))
if err != nil {
log.Fatal(err)
}
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(ctx)
myDatabase := client.Database("my_db")
myCollection := myDatabase.Collection("my_collection")
myResult, err := myCollection.InsertOne(ctx, json_value)
if err != nil {
log.Fatal(err)
}
fmt.Println(myResult.InsertedID)
}
</code></pre>
<p>How do I insert this json string to mongodb?</p>
| [
{
"answer_id": 74270007,
"author": "Cozer",
"author_id": 17795480,
"author_profile": "https://Stackoverflow.com/users/17795480",
"pm_score": 0,
"selected": false,
"text": "db.collection.insertOne(\n <document>,\n {\n writeConcern: <document> (optional)\n }\n)\n"
},
{
"... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17511715/"
] |
74,269,900 | <p>I wanted to allow users to change the theme of the application by picking which theme they want the body's background color changes and all button colors. But the problem is that whenever I use document.querySelectorAll('.btn-theme-1').style.backgroundColor it tells me that it cannot read those properties.</p>
<p>I know of useRef() but in my case I am trying to select all buttons throughout the entire application. Not just one element in the current component. So I would like to know if there is a way to fix what I am attempting or if I am doing this the wrong way.</p>
<p>Here is the code for what I tried. This is my pick theme component:</p>
<pre><code>import ColorThemes from '../data/ColorThemes';
import { useEffect } from 'react';
const PickTheme = () => {
const changeTheme = (c) => {
document.body.style.background = c.default || c.bgColor;
document.body.style.color = c.bodyColor;
document.querySelector('.bi-quote').style.color = c.buttonBg;
document.querySelectorAll('.text-color').forEach(el => el.style.color = c.fontColor)
document.querySelectorAll('.btn-theme-1').forEach(el => {
el.style.color = c.buttonColor;
el.style.backgroundColor = c.buttonBg;
});
};
useEffect(() => {
},[changeTheme]);
return(
ColorThemes.background.map(c => {
if(c.bgColor) {
return(
<button type="button" key={c.bgColor} className="btn btn-light me-2 p-3 rounded-5" onClick={() => changeTheme(c)} style={{backgroundColor: c.bgColor}}></button>
);
} else {
return(
<><br/><button type="button" key={c.default} className="btn btn-light me-2 mt-2 rounded-5" onClick={() => changeTheme(c)}>Default</button></>
);
}
})
);
};
export default PickTheme;
</code></pre>
<p>It successfully changes the bodys color and background color but not the other classes. I tried with and without useEffect and still receive the same issue.</p>
<p>If I comment out everything except the last selector, the buttons then change colors. So maybe it is conflicting or cannot change everything at once, for example:</p>
<pre><code>
const changeTheme = (c) => {
// document.body.style.background = c.default || c.bgColor;
// document.body.style.color = c.bodyColor;
// document.querySelector('.bi-quote').style.color = c.buttonBg;
// document.querySelectorAll('.text-color').forEach(el => el.style.color = c.fontColor)
document.querySelectorAll('.btn-theme-1').forEach(el => {
el.style.color = c.buttonColor;
el.style.backgroundColor = c.buttonBg;
});
};
</code></pre>
<p>This changes the buttons background and color after commenting out the other parts.</p>
| [
{
"answer_id": 74270007,
"author": "Cozer",
"author_id": 17795480,
"author_profile": "https://Stackoverflow.com/users/17795480",
"pm_score": 0,
"selected": false,
"text": "db.collection.insertOne(\n <document>,\n {\n writeConcern: <document> (optional)\n }\n)\n"
},
{
"... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18515495/"
] |
74,269,938 | <p>I am doing a simulation of yearly cash flows and having interest applied to each year's cumulative balance. My current algorithm is done by looping through each row to calculate the interest and add the interest to the end balance for next year's starting balance. The issue is that I need to have this run for many simulation years many times, and the run time becomes increasingly longer. Is there a way vectorize this algorithm or to implement other workarounds to reduce run time? Thanks!</p>
<p>This example is done with an interest rate of 5%
<a href="https://i.stack.imgur.com/qMZv9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qMZv9.png" alt="reduced simulation example" /></a></p>
<p>I've looked into using the lag() function to calculate the cumulative balance and interest each simulation year, but this would require using lag() a number of times equal to the number of simulated years in order to calculate the end balance and runs into the same issue of run time.</p>
<p>A SAS implementation uses the RETAIN statement in the DATA step. The algorithm runs quickly in SAS but I'm looking for an R implementation.</p>
| [
{
"answer_id": 74270240,
"author": "Martin Morgan",
"author_id": 547331,
"author_profile": "https://Stackoverflow.com/users/547331",
"pm_score": 1,
"selected": false,
"text": "set.seed(123)\nn_rep = 100000; n_year = 100\nstarting_balance <- rep(0, n_rep)\nfor (i in 1:n_year) {\n rando... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20383290/"
] |
74,269,941 | <p>What I am trying to do is take my current string and remove all data from it that doesn't contain the actual software version. Here is the string I am currently working with:</p>
<pre><code>print (CurrentVersion)
</code></pre>
<p>Delivers the output:</p>
<pre><code>2018, \\\\some\\directory\\is\\here, \\\\some\\directory\\is\\here, 2019, \\\\here\\is\\another\\directory, \\\\here\\is\\another\\directory, 2021, \\\\here\\is\\another\\path_2021, 2020, http://some.will/even/look/like/this, 2022r2, 2023
</code></pre>
<p>When what I really want is this for an output:</p>
<pre><code>2018, 2019, 2020, 2021, 2022r2, 2023
</code></pre>
<p>What I have tried was to come up with a regular expression to remove the excess data. It looks like '[0-9, ]' will pull out the numbers and commas getting me closer to my goal. So I came up with this code:</p>
<pre><code>RegexVersion = re.compile(r'[0-9, ]')
CurrentVersion = RegexVersion.search(CurrentVersion)
print (CurrentVersion.group())
</code></pre>
<p>But this only prints out an output of "2". Based on a regex calculator it looked like it was going to be a little closer to my expected output. From there I was planning on using .replace to get rid of the extra commas and spaces, but I can't seem to get that far.</p>
<p>So the question is, how do I go from the current output of "CurrentVersion" stripped down to only versions, preferably in numerical order?</p>
| [
{
"answer_id": 74269976,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 2,
"selected": true,
"text": "(?:^|,\\s*)(\\d{4}\\w*)(?=,|$)\n"
},
{
"answer_id": 74270106,
"author": "NonBinaryProgrammer",
... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17212057/"
] |
74,269,964 | <p>For a project I'm trying to get out of the Arduino loop() function and 'loop' in another function. I'm trying to make a sort of menu where the user can loop through and press an OK-button to confirm.
My setup is as follows;</p>
<p>Up button, OK button, Down button, set temperature button</p>
<p>Whenever the user pushes the temperature button, I'd like to give the user 2 options (using a LCD); change the minimum or the maximum temperature. I'd like to cycle through these options using the up and down button and give the user the option to confirm either of these temperature changes with the OK button. For some reason the Arduino doesn't listen to any button presses after I press the temperature button anymore. See code example below.</p>
<pre><code>const int UpButton = 3;
const int OKButton = 4;
const int DownButton = 5;
const int ChangeTemperatureButton = 6;
void setup() {
pinMode(UpButton, INPUT_PULLUP);
pinMode(OKButton, INPUT_PULLUP);
pinMode(DownButton, INPUT_PULLUP);
pinMode(ChangeTemperatureButton, INPUT_PULLUP);
}
void loop() {
if (!digitalRead(ChangeTemperatureButton)) {
changeTemperature();
}
if (!digitalRead(OKButton)) {
// set LCD to 'not good'
}
}
void changeTemperature() {
// set LCD to 'Changing temperature'
if (!digitalRead(OKButton)) {
// set LCD to 'Set max temperature'
}
}
</code></pre>
<p>Whenever I press the button to change the temperature it does set the LCD to 'Changing temperature'. After that I press the OK button and instead of it changing to 'Set max temperature' it changes to 'not good', which is in the loop. I think I fundamentally understand something wrong here, can anyone help me out with this one?</p>
<p>TL;DR: I'm trying to get and stay out of the loop when I press a certain button so my button can do something else than is defined in the loop. After everything in the changeTemperature function is set and done, I'd like to return to the loop function.</p>
| [
{
"answer_id": 74269976,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 2,
"selected": true,
"text": "(?:^|,\\s*)(\\d{4}\\w*)(?=,|$)\n"
},
{
"answer_id": 74270106,
"author": "NonBinaryProgrammer",
... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7385440/"
] |
74,269,973 | <p>The problem is that I get log that file has been created and uploaded, but nothing actually changes, I'm novice in working with google api, so I can't figure out what I do wrong.</p>
<pre><code><?php
include '../vendor/autoload.php';
function handleGoogleDrive($file)
{
//connecting to google drive
$client = new \Google_Client();
$client->setApplicationName('Somesite');
$client->setScopes([\Google_Service_Drive::DRIVE]);
$client->setAccessType('offline');
$client->setAuthConfig('./credentials.json');
$client->setClientId('2445617429-6k99ikago0s0jdh5q5k3o37de6lqtsd3.apps.googleusercontent.com');
$client->setClientSecret('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');
$service = new Google_Service_Drive($client);
//counting amount of files in folder, there is no real reason in doing that
//it is just a test of connecting
$folder_id = '1eQtNOJjlA2CalZYb90bEs34IaP6v9ZHM';
$options = [
'q' => "'" . $folder_id . "' in parents",
'fields' => 'files(id, name)'
];
//printing result
$results = $service->files->listFiles($options);
echo count($results->getFiles());
//trying to add file
$data = file_get_contents("../test.jpg");
$file = new Google_Service_Drive_DriveFile();
$file->setName(uniqid(). '.jpg');
$file->setDescription('A test document');
$file->setMimeType('image/jpeg');
$new_file = $service->files->create($file, [
'data' => $data,
'mimeType' => 'image/jpeg',
'uploadType' => 'multipart',
]);
print_r($new_file);
}
</code></pre>
<p>What I get after print_r:</p>
<pre><code>Google\Service\Drive\DriveFile Object ( [collection_key:protected] => spaces [appProperties] => [capabilitiesType:protected] => Google\Service\Drive\DriveFileCapabilities [capabilitiesDataType:protected] => [contentHintsType:protected] => Google\Service\Drive\DriveFileContentHints [contentHintsDataType:protected] => [contentRestrictionsType:protected] => Google\Service\Drive\ContentRestriction [contentRestrictionsDataType:protected] => array [copyRequiresWriterPermission] => [createdTime] => [description] => [driveId] => [explicitlyTrashed] => [exportLinks] => [fileExtension] => [folderColorRgb] => [fullFileExtension] => [hasAugmentedPermissions] => [hasThumbnail] => [headRevisionId] => [iconLink] => [id] => 15ZN1wdlSfbXauvuGVnO1nTMC3fbQWMNF [imageMediaMetadataType:protected] => Google\Service\Drive\DriveFileImageMediaMetadata [imageMediaMetadataDataType:protected] => [isAppAuthorized] => [kind] => drive#file [labelInfoType:protected] => Google\Service\Drive\DriveFileLabelInfo [labelInfoDataType:protected] => [lastModifyingUserType:protected] => Google\Service\Drive\User [lastModifyingUserDataType:protected] => [linkShareMetadataType:protected] => Google\Service\Drive\DriveFileLinkShareMetadata [linkShareMetadataDataType:protected] => [md5Checksum] => [mimeType] => image/jpeg [modifiedByMe] => [modifiedByMeTime] => [modifiedTime] => [name] => 6360554211ca3.jpg [originalFilename] => [ownedByMe] => [ownersType:protected] => Google\Service\Drive\User [ownersDataType:protected] => array [parents] => [permissionIds] => [permissionsType:protected] => Google\Service\Drive\Permission [permissionsDataType:protected] => array [properties] => [quotaBytesUsed] => [resourceKey] => [sha1Checksum] => [sha256Checksum] => [shared] => [sharedWithMeTime] => [sharingUserType:protected] => Google\Service\Drive\User [sharingUserDataType:protected] => [shortcutDetailsType:protected] => Google\Service\Drive\DriveFileShortcutDetails [shortcutDetailsDataType:protected] => [size] => [spaces] => [starred] => [teamDriveId] => [thumbnailLink] => [thumbnailVersion] => [trashed] => [trashedTime] => [trashingUserType:protected] => Google\Service\Drive\User [trashingUserDataType:protected] => [version] => [videoMediaMetadataType:protected] => Google\Service\Drive\DriveFileVideoMediaMetadata [videoMediaMetadataDataType:protected] => [viewedByMe] => [viewedByMeTime] => [viewersCanCopyContent] => [webContentLink] => [webViewLink] => [writersCanShare] => [internal_gapi_mappings:protected] => Array ( ) [modelData:protected] => Array ( ) [processed:protected] => Array ( ) )
</code></pre>
| [
{
"answer_id": 74274347,
"author": "DaImTo",
"author_id": 1841839,
"author_profile": "https://Stackoverflow.com/users/1841839",
"pm_score": 3,
"selected": true,
"text": "'uploadType' => 'multipart',"
},
{
"answer_id": 74274980,
"author": "Lendwye",
"author_id": 19324146,
... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19324146/"
] |
74,269,979 | <p>I am working on AutoCAD plugin. Trying to implement function where it first looks for already running EXCEL instances so I just Add new workbook to existing instance instead of always creating new process.</p>
<p>My code fails at the point where it tries to find running process. For some reason it always detects running EXCEL process, I checked it at task manager, it is not there so that's why my plugin crashes at Marchal.GetActiveObject method because it's trying to get that running process...</p>
<p>My functions' code so far:</p>
<pre><code>Private Function GetExcelWorksheet() As Excel.Worksheet
Dim excel As Excel.Application
Dim activeWorksheet As Excel.Worksheet = Nothing
Dim wb As Excel.Workbook = Nothing
Dim ws As Excel.Worksheet = Nothing
Dim ExcelInstances As Process() = Process.GetProcessesByName("EXCEL")
If ExcelInstances.Count() = 0 Then
Exit Function
End If
excel = TryCast(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
If excel Is Nothing Then Exit Function
excel.Visible = True
wb = excel.Workbooks.Add
ws = wb.Worksheets(1)
Return ws
End Function
</code></pre>
| [
{
"answer_id": 74270544,
"author": "Lundt",
"author_id": 19564057,
"author_profile": "https://Stackoverflow.com/users/19564057",
"pm_score": 1,
"selected": false,
"text": "'Excel.vb\nImports System\nImports System.Runtime.InteropServices\n\nPublic Module AnythingYouWantToCallIt\n\n\n ... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2157126/"
] |
74,269,995 | <p>The code down below shows my work in react, where i freshly startet my project and i am still pretty new in this kind of area. I have one simple question that i am just cant comprehend. Its probalby something simple. I expected the h1 with the text Hi too get rendered or to get foo as output, but my website isnt showing any text at all</p>
<p>App.js</p>
<pre><code>import './App.css';
import Navbar from './Components/Navbar';
import {BrowserRouter as Router, Routes, Route } from 'react-router-dom'
function App() {
return (
<div className='App'>
<h1> Hi </h1>
<>
<Router>
<Navbar/>
<Routes>
<Route path='/' exact/>
</Routes>
</Router>
</>
</div>
);
}
export default App;
</code></pre>
<p>Navbar.js</p>
<pre><code>import './Navbar.css';
import React, {useState} from 'react'
import { Link } from 'react-router-dom';
function Navbar() {
return (
<nav className='navbar'>
<div className='navbar-container'>
<Link to="/" >foo</Link>
</div>
</nav>
)
}
export default Navbar;
</code></pre>
<p>index.js</p>
<pre><code>import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
</code></pre>
<p>After further testing it has shown that when i delete everything in the return function of App.js except the h1 Hi gets rendered.</p>
| [
{
"answer_id": 74270544,
"author": "Lundt",
"author_id": 19564057,
"author_profile": "https://Stackoverflow.com/users/19564057",
"pm_score": 1,
"selected": false,
"text": "'Excel.vb\nImports System\nImports System.Runtime.InteropServices\n\nPublic Module AnythingYouWantToCallIt\n\n\n ... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74269995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,270,002 | <p>I am joining multiple adjoining polygons together and removing any holes from the now single polygon using <code>fill_holes</code> in <code>smoothr</code>. However, if a hole has another polygon (or island) within it, the outline of that polygon remains. Is there a way these outlines can be removed/dissolved?</p>
<pre><code>library(sf)
library(smoothr)
download.file("https://drive.google.com/uc?export=download&id=1-KcZce0jgIV0fwG797mq7FB5WjxwtKqX" , destfile="Zones.zip")
unzip("Zones.zip")
Zones <- st_read("Zones.gpkg")
Threshold <- units::set_units(1000, km^2)
Zones_No_Holes <- fill_holes(Zones %>% st_union, threshold = Threshold)
plot(Zones_No_Holes, col="aliceblue")
</code></pre>
<p><a href="https://i.stack.imgur.com/t9a2l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t9a2l.png" alt="current output" /></a></p>
| [
{
"answer_id": 74270357,
"author": "mrhellmann",
"author_id": 7547327,
"author_profile": "https://Stackoverflow.com/users/7547327",
"pm_score": 3,
"selected": true,
"text": "zones_no_holes"
},
{
"answer_id": 74313965,
"author": "Chris",
"author_id": 1968484,
"author_p... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74270002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1968484/"
] |
74,270,014 | <p>I tried taking each string elements out of the list which contains 10 elements and pass it to the isPalindrome method to check whether it is palindrome or not. But the output gives me "It is palindrome." to an infinite times that it crashes the kernel.</p>
<p>`</p>
<pre><code>class Palindrome():
def isPalindrome(self, x):
stack = []
#for strings with even length
if len(x)%2==0:
for i in range(0,len(x)):
if i<int(len(x)/2):
stack.append(x[i])
elif stack.pop()!=x[i]:
return False
if len(stack)>0:
return false
return True
#for strings with odd length
else:
for i in range(0,len(x)):
if i==int(len(x)/2):
continue
elif i<int(len(x)/2):
stack.append(x[i])
elif stack.pop()!=x[i]:
return False
if len(stack)>0:
return false
return True
def __init__(self):
while True:
string=["mom","dad","madam","redivider","civic","radar","refer","racecar","level","rotor"]
for i in range(len(string)):
if self.isPalindrome(string[i]):
print(string[i]," is a palindrome")
else:
print(string[i]," is not a palindrome")
if __name__ == '__main__':
WS = Palindrome()
</code></pre>
<p>`</p>
| [
{
"answer_id": 74270048,
"author": "Elijah Nicol",
"author_id": 14895492,
"author_profile": "https://Stackoverflow.com/users/14895492",
"pm_score": 1,
"selected": false,
"text": "__init__()"
},
{
"answer_id": 74270100,
"author": "NoDakker",
"author_id": 6032177,
"auth... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74270014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15666347/"
] |
74,270,017 | <p>have been looking for a way to properly render an icon in my component but ended up with an error from the title.</p>
<p><code>Profile.tsx:</code></p>
<pre><code><ul>
{socialLinks.map((socialLink) => (
<li key={socialLink.href}>
<a href={socialLink.href}>{socialLink.icon}</a>
</li>
))}
</ul>
</code></pre>
<p><code>data.ts</code></p>
<pre><code>import { FaDiscord, FaGithub, FaTwitter } from "react-icons/fa";
export const socialLinks = [
{
name: "github",
href: "#",
icon: FaGithub,
},
{
name: "twitter",
href: "#",
icon: FaTwitter,
},
{
name: "discord",
href: "#",
icon: FaDiscord,
},
];
</code></pre>
<p>is there a way to fix this?</p>
| [
{
"answer_id": 74270048,
"author": "Elijah Nicol",
"author_id": 14895492,
"author_profile": "https://Stackoverflow.com/users/14895492",
"pm_score": 1,
"selected": false,
"text": "__init__()"
},
{
"answer_id": 74270100,
"author": "NoDakker",
"author_id": 6032177,
"auth... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74270017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19381090/"
] |
74,270,030 | <p>I have a website that allows users to send themselves a message at a date they choose, but I have no idea how to send it at that specific time. I know there exist CronJobs, but here, I'm not doing anything recurring. It's a one-time event trigger that I need.</p>
<p>I first tried using the native <code>setTimeout</code> like this:</p>
<pre><code>const dueTimestamp = ...;
const timeLeft = dueTimestamp - Date().now();
const timeoutId = setTimeout(() => sendMessage(message), timeLeft);
</code></pre>
<p>It works perfectly for short periods, however, I'm not sure if it is reliable for long periods such as years or even decades. Moreover, it doesn't offer much control because if I'd like to modify the <code>dueDate</code> or the message's content, I'd have to stop the Timeout and start a new one.</p>
<p><strong>Is there any package, a library, or a service that allows you to run a NodeJS function at a scheduled time?</strong> or do you have any solutions? I've heard of Google Cloud Schedule or Cronhooks, but I'm not sure.</p>
| [
{
"answer_id": 74270048,
"author": "Elijah Nicol",
"author_id": 14895492,
"author_profile": "https://Stackoverflow.com/users/14895492",
"pm_score": 1,
"selected": false,
"text": "__init__()"
},
{
"answer_id": 74270100,
"author": "NoDakker",
"author_id": 6032177,
"auth... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74270030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19003871/"
] |
74,270,035 | <p>I'm trying to extend the class <code>A</code> which is written in Java to class <code>B</code> in Scala.</p>
<pre><code>class A {
private Pattern pattern;
private String regex= "folder1/folder2/folder3/.*";
A(...){
this.regex = regex;
this.pattern = Pattern.compile(getRegex());
}
public String getRegex() {
return regex;
}
}
class B(...) extends A(...) {
val regex: String= "folder4/.*";
override def getRegex(): String = {
return regex;
}
}
</code></pre>
<p>However it seems that the <code>Pattern.compile(getRegex())</code> is getting <code>null</code> value from the <code>B</code> class. I'm also not allowed to pass the override regex through the constructor. Not sure how I can resolve this issue.</p>
| [
{
"answer_id": 74271266,
"author": "Dmytro Mitin",
"author_id": 5249621,
"author_profile": "https://Stackoverflow.com/users/5249621",
"pm_score": 0,
"selected": false,
"text": "this"
},
{
"answer_id": 74271577,
"author": "rzwitserloot",
"author_id": 768644,
"author_pr... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74270035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18859913/"
] |
74,270,090 | <p>I am new to scala, trying to figure out a way to pass the values of array of string as repeated parameter of String in scala.
There is a method which accepts (String,String*) as arguments.
I have array that has the values that i need to pass to the above method, how can i do that ?</p>
| [
{
"answer_id": 74270123,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "https://Stackoverflow.com/users/2288659",
"pm_score": 3,
"selected": true,
"text": "myMethod(firstArg, arrayArg: _*)\n"
},
{
"answer_id": 74270781,
"author": "BccHnw",
"author_id"... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74270090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5978483/"
] |
74,270,108 | <p>If I have a component that will have a prop value or children as other JSX functional components and I want to make sure that those components have certain props passed
<a href="https://i.stack.imgur.com/idT3f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/idT3f.png" alt="enter image description here" /></a></p>
<p>so here I want to make sure if another developer used the component the inputs will have like <code><Trail value=''/></code></p>
| [
{
"answer_id": 74270123,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "https://Stackoverflow.com/users/2288659",
"pm_score": 3,
"selected": true,
"text": "myMethod(firstArg, arrayArg: _*)\n"
},
{
"answer_id": 74270781,
"author": "BccHnw",
"author_id"... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74270108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14917976/"
] |
74,270,160 | <p>i use this code to rotate my gameobject, but the problem is when i first click , the gameobject rotate to the difference angle.then work find.</p>
<pre><code> private Vector3 _prevPos;
private Vector2 ret;
if (Input.GetMouseButton(0))
{
ret = Input.mousePosition - _prevPos;
_prevPos = Input.mousePosition;
transform.Rotate(ret.y / 10, 0, ret.x );
}
</code></pre>
<p>In debug , "ret.y" 's number is no 0 when i first click.</p>
<p>how can i fix this problem??</p>
| [
{
"answer_id": 74270123,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "https://Stackoverflow.com/users/2288659",
"pm_score": 3,
"selected": true,
"text": "myMethod(firstArg, arrayArg: _*)\n"
},
{
"answer_id": 74270781,
"author": "BccHnw",
"author_id"... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74270160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20138466/"
] |
74,270,174 | <p>I want to create a list given a string such as 'b123+xyz=1+z1$' so that the list equals ['b123', '+', 'xyz', '=', '1', '+', 'z1', '$']</p>
<p>Without spaces or a single repeating pattern, I do not know how to split the string into a list.</p>
<p>I tried creating if statements in a for loop to append the string when it reaches a character that is not a digit or letter through isdigit and isalpha but could not differentiate between variables and digits.</p>
| [
{
"answer_id": 74270237,
"author": "Chris Doyle",
"author_id": 1212401,
"author_profile": "https://Stackoverflow.com/users/1212401",
"pm_score": 3,
"selected": true,
"text": "import re\n\nsample = \"b123+xyz=1+z1$\"\nsplit_sample = re.split(\"(?=\\W)|(?:(?<=\\W)(?!$))\", sample)\nprint(s... | 2022/10/31 | [
"https://Stackoverflow.com/questions/74270174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18764520/"
] |
74,270,221 | <p>I have one data frame. I am sorting out particular values from it and want to input that row of data. In this case the time, which is the index, and the action of which is happening. I have the row number that I want to input however, when I try doing this,</p>
<pre><code>a = a.append(data.values[i])
</code></pre>
<p>or</p>
<pre><code>a = a.append(data.iloc[i])
</code></pre>
<p>I receive the error append() missing one required positional argument: 'other'</p>
<p>This may be a very simple problem. However, I am knew to this library and data structure, and looking for some insight.</p>
| [
{
"answer_id": 74270237,
"author": "Chris Doyle",
"author_id": 1212401,
"author_profile": "https://Stackoverflow.com/users/1212401",
"pm_score": 3,
"selected": true,
"text": "import re\n\nsample = \"b123+xyz=1+z1$\"\nsplit_sample = re.split(\"(?=\\W)|(?:(?<=\\W)(?!$))\", sample)\nprint(s... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14954949/"
] |
74,270,285 | <p>Good afternoon.
I've found great peace of code for my project. For states developer used data attribute manipulation in vanilla Javascript in order to change state.
Could someone help to translate plain JS to React</p>
<pre class="lang-html prettyprint-override"><code>
<div className='hero' data-nav="true">
<main></main>
<header data-nav="true">
<nav>
<div id="nav-links">
<a className="nav-link" href="#">
<h2 className="nav-link-label rubik-font">Home</h2>
<img className="nav-link-image" src="https://images.unsplash.com/photo-1666091863721-54331a5db52d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=987&q=80" />
</a>
<a className="nav-link" href="#">
<h2 className="nav-link-label rubik-font">Work</h2>
<img className="nav-link-image" src="https://images.unsplash.com/photo-1666055642230-1595470b98fd?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=995&q=80" />
</a>
<a className="nav-link" href="#">
<h2 className="nav-link-label rubik-font">About</h2>
<img className="nav-link-image" src="https://images.unsplash.com/photo-1666005487638-61f45819c975?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=987&q=80" />
</a>
<a className="nav-link" href="#">
<h2 className="nav-link-label rubik-font">Contact</h2>
<img className="nav-link-image" src="https://images.unsplash.com/photo-1665910407771-bc84ad45676b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=776&q=80" />
</a>
<a className="nav-link" href="#">
<h2 className="nav-link-label rubik-font">Join Us</h2>
<img className="nav-link-image" src="https://images.unsplash.com/photo-1553356084-58ef4a67b2a7?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=987&q=80" />
</a>
</div>
</nav>
</header>
<button id="nav-toggle" type="button" onClick={toggleNav}>
<i className="open fa-light fa-bars-staggered"></i>
<i className="close fa-light fa-xmark-large"></i>
</button>
</div>
</code></pre>
<h2>JavaScript</h2>
<pre class="lang-js prettyprint-override"><code>const toggleNav = () => {
document.body.dataset.nav = document.body.dataset.nav === "true" ? "false" : "true";
}
</code></pre>
<h2>Part of CSS</h2>
<pre class="lang-css prettyprint-override"><code>
.hero[data-nav="true"] > main {
transform: translateY(-50%);
}
nav {
height: 50vh;
width: 100%;
position: absolute;
left: 0px;
bottom: 0px;
z-index: 1;
overflow: hidden;
}
header[data-nav="true"] > nav > #nav-links {
transform: translateY(0%) scale(1);
}
#nav-links > .nav-link {
text-decoration: none;
}
</code></pre>
<p>Would love to hear clever solutions
Thank you</p>
<p>I've tried the event approach</p>
<pre class="lang-js prettyprint-override"><code> const toggleNav = (event) => {
event.target.setAttribute('data-nav', 'false')
}
</code></pre>
| [
{
"answer_id": 74270237,
"author": "Chris Doyle",
"author_id": 1212401,
"author_profile": "https://Stackoverflow.com/users/1212401",
"pm_score": 3,
"selected": true,
"text": "import re\n\nsample = \"b123+xyz=1+z1$\"\nsplit_sample = re.split(\"(?=\\W)|(?:(?<=\\W)(?!$))\", sample)\nprint(s... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19761546/"
] |
74,270,288 | <p>I've made a program for my brother's restaurant, that sends a <code>.txt</code> file to the Thermal printer. The problem that I am having (or at least, what I am thinking of) is in the file's length.</p>
<p>This is the code that I used for the printing procedure (It's from <a href="https://stackoverflow.com/questions/6809478/">Help needed about printing text file with delphi</a>)</p>
<pre class="lang-pascal prettyprint-override"><code>procedure TForm1.PrintTextFile(const FileName: string; const Numbering: boolean = true);
const
FONT_NAME = 'Times New Roman';
FONT_SIZE = 14;
var
MARGIN: integer;
sl1: TStringList;
i, h: Integer;
r, rFooter: TRect;
s: string;
DocEnd: integer;
begin
with TPrintDialog.Create(nil) do
try
if not Execute then
Exit;
finally
Free;
end;
sl1 := TStringList.Create;
try
sl1.LoadFromFile(FileName);
Printer.BeginDoc;
Printer.Title := FileName; // or application name or sth else
Printer.Canvas.Font.Name := FONT_NAME;
Printer.Canvas.Font.Size := FONT_SIZE;
MARGIN := 1*Printer.Canvas.TextWidth('M');
DocEnd := Printer.PageHeight - MARGIN;
if Numbering then
begin
dec(DocEnd, 2*Printer.Canvas.TextHeight('8'));
rFooter := Rect(0, DocEnd, Printer.PageWidth, Printer.PageHeight - MARGIN);
DrawText(Printer.Canvas.Handle,
PChar(IntToStr(Printer.PageNumber)),
length(IntToStr(Printer.PageNumber)),
rFooter,
DT_SINGLELINE or DT_CENTER or DT_BOTTOM);
end;
r.Left := MARGIN;
r.Top := MARGIN;
for i := 0 to sl1.Count - 1 do
begin
r.Right := Printer.PageWidth - MARGIN;
r.Bottom := DocEnd;
s := sl1.Strings[i];
if s = '' then s := ' ';
h := DrawText(Printer.Canvas.Handle, // Height of paragraph on paper
PChar(s),
length(s),
r,
DT_LEFT or DT_TOP or DT_WORDBREAK or DT_CALCRECT);
if r.Top + h >= DocEnd then
begin
Printer.NewPage;
if Numbering then
DrawText(Printer.Canvas.Handle,
PChar(IntToStr(Printer.PageNumber)),
length(IntToStr(Printer.PageNumber)),
rFooter,
DT_SINGLELINE or DT_CENTER or DT_BOTTOM);
r.Top := MARGIN;
r.Bottom := DocEnd;
end;
if h > Printer.PageHeight - 2*MARGIN then
raise Exception.Create('Line too long to fit on single page.');
DrawText(Printer.Canvas.Handle,
PChar(s),
length(s),
r,
DT_LEFT or DT_TOP or DT_WORDBREAK);
inc(r.Top, h);
end;
Printer.EndDoc;
finally
sl1.Free;
end;
end;
</code></pre>
<p>This is the <code>.txt</code> file that is sent to the thermal printer:</p>
<p><a href="https://i.stack.imgur.com/IX5CL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IX5CL.png" alt="Prt sc of the txt file" /></a></p>
<p>And this is how it is being printed out:</p>
<p><a href="https://i.stack.imgur.com/xKVdW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xKVdW.png" alt="Long ticket" /></a></p>
| [
{
"answer_id": 74270237,
"author": "Chris Doyle",
"author_id": 1212401,
"author_profile": "https://Stackoverflow.com/users/1212401",
"pm_score": 3,
"selected": true,
"text": "import re\n\nsample = \"b123+xyz=1+z1$\"\nsplit_sample = re.split(\"(?=\\W)|(?:(?<=\\W)(?!$))\", sample)\nprint(s... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20383357/"
] |
74,270,304 | <p>So I have a large json file (approximately 20k hosts) and for each host, I need to find FieldA and replace it's value with a unique value which I can then swap back later.</p>
<p>For instance:</p>
<p><code>root> cat file.json | jq . </code></p>
<pre><code>
[
{
"id": 1,
"uptime": 0
"computer_name": "Computer01"
},
{
"id": 2,
"uptime": 0
"computer_name": "Computer02"
}
]
</code></pre>
<p>I need to iterate through this list of 20k hosts, replace every computer_name with a dummy value:</p>
<pre><code>[
{
"id": 1,
"uptime": 0
"computer_name": "Dummy01"
},
{
"id": 2,
"uptime": 0
"computer_name": "Dummy02"
}
]
</code></pre>
<p>And if possible, export the dummy value and original value to a table side by side linking them up.</p>
<p>The dummy values I want to generate automatically such as:
for each computer_name replace value with Dummy?????? where ????? is a number from 00000 to 99999 and it just iterates through this.</p>
<p>I attempted to use: <code>cat file.json | jq .computer_name</code> OR <code>jq.computer_name file.json</code> to filter this down and then work on replacing the values, but when I use .computer_name as the value, I get this error:</p>
<p>jq: error : Cannot index array with string "computer_name".</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 74271080,
"author": "peak",
"author_id": 997358,
"author_profile": "https://Stackoverflow.com/users/997358",
"pm_score": 0,
"selected": false,
"text": " def lpad($len; $fill): tostring | ($len - length) as $l | ($fill * $l)[:$l] + .;\n\n . as $in\n | ([length|tostring|l... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20383615/"
] |
74,270,307 | <p>After working for more than 10 years, today a code caught my eye, I am unable to understand the function name defined inside a function gets printed in the output/log without being passed as an argument in macro or being defined as a global variable. Please help me understanding the internal. Please see the screenshot for the reference.</p>
<pre><code>/*...*/
#include <stdio.h>
#define x printf("%s", f);
int main() {
char *f = "MAIN";
printf("Hello World");
x;
return 0;
}
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>Hello WorldMAIN
</code></pre>
| [
{
"answer_id": 74270342,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "#include <stdio.h>\n#define x printf(\"%s\", f);\n\nint main()\n{ \n char* f = \"MAIN\"; \n printf (\"Hello Wo... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1105805/"
] |
74,270,333 | <p>I have this C# code in a nullable context:</p>
<pre><code>public string? GetValue(int key, bool errorIfInvalidKey)
{
string result = <get the value identified by the key argument, or null if not found>;
if (result == null && errorIfInvalidKey) {
throw new InvalidOperationException("Bad key");
} else {
return result;
}
}
</code></pre>
<p>If the caller specifies an invalid <code>key</code>, the <code>errorIfInvalidKey</code> argument specifies whether to return null or throw an exception. So, <strong>this code is guaranteed to return non-null if <code>errorIfInvalidKey</code> is true</strong>.</p>
<p>Is there a way to annotate this code to tell the compiler that a routine that returns a maybe-null will return a non-null if an argument contains a particular value?</p>
| [
{
"answer_id": 74270342,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "#include <stdio.h>\n#define x printf(\"%s\", f);\n\nint main()\n{ \n char* f = \"MAIN\"; \n printf (\"Hello Wo... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1637105/"
] |
74,270,345 | <p>I have a somewhat strange setup:
I have a libmylib.so I cannot modify, but, since the interface is rather convoluted, I wrote a simple wrapper directly into <code>ffbuilder.set_source()</code></p>
<p>My full <code>lib_builder.py</code> is:</p>
<pre class="lang-py prettyprint-override"><code>import os
from cffi import FFI
ffibuilder = FFI()
ffibuilder.cdef("""
int start(int port);
int ready(void);
int publish(char *buf, int len);
int stop(void);
""")
ffibuilder.set_source('_mylib_cffi', """
#include "mylib.h"
static uint32_t handle = 0xffffffff;
int start(int port) {
mylib_init(0);
mylib_register_publisher("127.0.0.1", port, &handle, 0);
return 1;
}
int ready(void) {
return handle != 0xffffffff;
}
int publish(char *buf, int len) {
return mylib_publish(handle, buf, len);
}
int stop(void) {
mylib_shutdown();
return 1;
}
""", libraries=['mylib'], library_dirs=[os.path.dirname(__file__)])
if __name__ == '__main__':
ffibuilder.compile(verbose=True)
</code></pre>
<p>This works as expected but my test code:</p>
<pre class="lang-py prettyprint-override"><code>import _mylib_cffi
...
</code></pre>
<p>bombs because <code>libmylib.so</code> is not found (it is in current directory, exactly where generated <code>_mylib_cffi.cpython-310-x86_64-linux-gnu.so</code> is located).</p>
<p>I can make it work either moving <code>libmylib.so</code> to <code>/usr/lib</code> (or other directory in the system lib search path) or adding current directory to <code>LD_LIBRARY_PATH</code>.</p>
<p>Both solutions are not particularly appealing to me because I don't want to pollute system settings with needs of a single program.</p>
<p>Is there some way to dynamically load needed lib from within Python?</p>
<p>Note: I'm trying to learn Python-CFFI, so any advice is welcome.</p>
| [
{
"answer_id": 74270342,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "#include <stdio.h>\n#define x printf(\"%s\", f);\n\nint main()\n{ \n char* f = \"MAIN\"; \n printf (\"Hello Wo... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1714490/"
] |
74,270,347 | <p>I have a simple reducer/context system to store states. Everything is working fine except that I cannot update fields individually without affect the state of the others.</p>
<p>The problem is that, when I change one of the <code>AppData</code> fields, the other fields go blank. I don't know what I am doing wrong and I would like to be able to update an individual value whilst preserving the value of the other fields.</p>
<p>For example: if I only update the <code>appData.headerTitle</code> value, then the <code>appData.testValue</code> and <code>appData.userHasLoggedOut</code> values will get erased. If I update the 3 values at the same time, then nothing will be erased. I want to be able to update only one field without erasing the rest.</p>
<pre class="lang-js prettyprint-override"><code>export function AppReducer(state: AppState, action: Actions): AppState {
switch (action.type) {
case 'setAppData':
return {
...state,
appData: action.payload
};
case 'changeAppData':
return {
...state,
appData: {
...state.appData,
headerTitle: action.payload,
testValue: action.payload,
userHasLoggedOut: action.payload
}
};
}
}
</code></pre>
<p>Sandbox with the full working code: <a href="https://codesandbox.io/s/frosty-cache-c6yqgx?file=/src/middlewares/reducer/AppReducer.tsx" rel="nofollow noreferrer">https://codesandbox.io/s/frosty-cache-c6yqgx?file=/src/middlewares/reducer/AppReducer.tsx</a></p>
<p>Thank you!</p>
<p>I'm not sure what to try here...</p>
| [
{
"answer_id": 74270342,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "#include <stdio.h>\n#define x printf(\"%s\", f);\n\nint main()\n{ \n char* f = \"MAIN\"; \n printf (\"Hello Wo... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13649797/"
] |
74,270,350 | <p>For example:
we have 3*2 duplicated rows as follows:</p>
<pre><code>name identity gender
Mary student female
Mary student female
Mary student female
Jack teacher male
Jack teacher male
Jack teacher male
</code></pre>
<p>I wanna make those 3 rows as follows:</p>
<pre><code>name identity gender
Mary1 student female
Mary2 student female
Mary3 student female
Jack1 teacher male
Jack2 teacher male
Jack3 teacher male
</code></pre>
<p>How could I do it? Thanks</p>
<p>I try to use create function tvValues, but it didn't work.</p>
| [
{
"answer_id": 74270408,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 2,
"selected": true,
"text": "row_number()"
},
{
"answer_id": 74270426,
"author": "Avogadro",
"author_id": 1233144,
"author_profi... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17876937/"
] |
74,270,370 | <p>I am trying to create a Binary Search Tree (BST) for a really large txt file (around 150000 lines), but my BST is not sorting properly. My current theory is, when I fetch the key from the txt file, it doesn't register properly, making it fetch a random number from memory. Other than that, I have no idea whats wrong.</p>
<p>NOTE: the txt file has the following format (key on left, value on right)</p>
<pre class="lang-none prettyprint-override"><code>0016718719 #:@-;QZL=!9v
0140100781 5:`ziuiCMMUC
0544371484 W{<_|b5Qd534
0672094320 QcvX=;[lpR("
0494074201 FB[?T5VHc7Oc
0317651971 K`9@Qn{@h]1z
0635368102 KGVm-?hX{Rv7
0107206064 =n1AsY32_.J9
0844660357 L4qL)x{>5e8H
0699014627 v/<4%"sJ4eHR
0786095462 G!cl'YMAL*@S
0067578317 6{"W,j2>@{p*
0730012647 rAi?q<X5NaKT
0715302988 ,8SrSw0rEEc&
0234601050 PRg$$:b|B0'x
0537081097 fgoDc05rc,n|
0226858124 OV##d6th'<us
1059497442 2,'n}YmK,s^i
0597822915 LhicQ#r<Yh\8
0742176394 g`XkLi.>}s+Q
0984120927 DyB:-u*}E&X)
0202768627 8(&zqlPV@DCb
0089402669 tv-vTkn"AIxt
1045610730 hOxZQ<"yyew`
0671297494 )r7gD;:9FHrq
0245267004 f0oO:/Zul0<"
0766946589 n/03!]3t0Lux
0521860458 _D+$,j#YT$cS
0891617938 t%gYiWV17Z/'
0566759626 r2A'PB'xhfw@
0221374897 e[-Nf"@<o9^p
0428608071 46S4!vZA.S&.
0755431241 mgE?2IewG!=g
0534588781 %P|b"_d'VF0S
0030447903 Q&Dow27tkc9+
0957065636 [pHMrM*q*ED7
0739800529 wR;u\Ct/-Vzo
0556668090 =|T.z]?.:DnC
0649777919 2}5M=.u'@1,L
0464018855 x+JImm6w/eG]
0460707117 lxY}\Cdn%!rs
0273053706 s9GmIAE."j|2
0596408906 %'1|R%3tI-Tz
0473143619 k,h&_7rT)?Nb
0922139211 [e0Q1].<Qb;[
0207160144 t!&lXR7`eW#n
0128147823 L,d'7]ZTvPDQ
0178779865 (&--sQ..)7d'
0531711943 4o'^xS6rK]yl
0429655621 eyd7UwKQ][%i
0566959905 k{)d*OH&w2P<
0472331841 DiZF(W"wO42H
0589473577 V0$9-X%YD_kD
0272100993 i%c&R{^#SM$@
0956804045 BtY'cQ){wR{{
0635780805 dWnP0sP2]Tu[
0874803681 swn\*HS08v<w
1027292189 w#E:LaCg(L(I
0592836099 ]&Q({r^(/H%0
0882899568 zb_4acX8E<2-
0542667063 n'xbSaoXArp6
0289624942 G5X#aqr7+*pb
0682188682 H^o)>1\4o5WV
0984355947 =Z{wmP'Z(@2r
0459720821 1vNg_4`3IUUJ
0563538441 uA>QKi]Z31#x
1032927818 $jReN<b/(e{E
0299897321 j=PAkNj#H(L^
0428967901 8lszH<!m\C`w
0668128293 SO("{Rm29l@Y
0354915591 2coM%<Iiwwn<
0672908146 r3VRE;Q3)zi>
0435139431 d_q_)mM"X]N-
0728369037 >X_!}vtc;G(M
0982520682 {h\5gbvzsqGZ
0396776915 $py=A?iNde7(
0511806860 #T+Y0HI9/U6K
0013335601 <$8f|iV\=/RD
0511264736 NFI-#xssP)F*
0727884351 5ZMcmA0[K3P2
0460487630 .D'h(f"LV]@x
0178037927 o3a&fO}="I.S
</code></pre>
<p>Here is my Main file:</p>
<pre><code>#include "LAB3BST2.h"
#include <string.h>
#define HEIGHT_WRITTEN 1
#define FINDPARENTHELPER_WRITTEN 1
#define DELETE_WRITTEN 1
#define LOOKUP_written 1
int digit(char *key) {
int number = 0;//create a
while (*key != '\0') {//loop until the end of the string (number)
number = 10 * number + *key - '0';//(10*number) this represents moving the current value of key one up
//(*key - '0') the current char subtracted by '0' or the value of 48
// example: (char '1') - '0' == int 1. Reference ASCII chart to see hexadecimal logic
*key++;
}
return number;
}
int main(void) {
Node *n = NULL; // eliminates compiler warning
FILE *fp;
int c;
Tree *t = NULL;
char *pbuff = (char *)malloc(256);
char *p, *key, *pass;
int temp = 0;
long bst_node = 0;
fp = fopen("IDENTS.txt", "r");
if (!fp) {
printf("File Open Failed\n");
return 0;
}//initialize the head of the tree
while (1) {
p = fgets(pbuff, 256, fp);
if (p == NULL)
break; //memory not allocated, or end of file
while (*p == ' ')
p++; //if spaces, iterate through string
key = p;
p++;
while ((*p) >= 48 && (*p) <= 57)
p++;//if a digit character (47<p<58 or 0-9), iterate through key
*p = '\0';//null everything after the key (digits)
p++; //iterate onto the password
while (*p == ' ')
p++;//if spaces, iterate through string
pass = p;
p++;
while ((*p) != '\r' && (*p) != '\n') {
p++;
}// iterate until the end of the string ('\n')
*p = '\0';//null the rest, and reset "p"
temp = digit(key);
if (temp < 0) {
continue;
}
if (temp == 170696526) {
//nothing
}
if (t == NULL) {
t = initTree(temp, pass);
} else
insert(temp, pass, t->root);//WE NEED TO BE ABLE TO CREATE A PASS THAT DOES NOT CHANGE
bst_node++;
}
printf("\nBST NODES: %ld", bst_node);
fclose(fp);
/*
printf("Original Tree: \n");
printTree(t->root);
printf("\n\n");
if (HEIGHT_WRITTEN == 1) {
printf("Height of tree: %d\n\n", height(t->root));
}
*/
if (DELETE_WRITTEN == 1) {
FILE *fp_del;
fp_del = fopen("DELETES.txt", "r");
while (1) {
p = fgets(pbuff, 256, fp_del);
if (p == NULL)
break;
while (*p == ' ')
p++;
key = p;
p++;
while (*p != '\r' && *p != '\n') {
p++;
}
*p = '\0';
int k = withdraw(digit(key), t->root);
if (k)
bst_node--;
}
}
printf("\nNODES AFTER DELETES: %ld \n", bst_node);
if (!bst_check(t->root))
printf("NOT BST\n");
else
printf("IS A BST\n");
if (LOOKUP_written) {
FILE *fp_look;
fp_look = fopen("LOOKUPS.txt", "r");
int nnkey = 0;
while (1) {
p = fgets(pbuff, 256, fp_look);
if (p == NULL)
break;
while (*p == ' ')
p++;
key = p;
p++;
while (*p != '\r' && *p != '\n') {
p++;
}
*p = '\0';
nnkey = digit(key);
Node* k = find(nnkey, t->root);
if (!k) {
printf("ID: %13d PASSWORD: <NOT FOUND>\n", nnkey);
} else {
printf("ID: %13d PASSWORD: %s\n", nnkey, k->value);
}
}
}
return 0;
}//main()
</code></pre>
<p>Here is my function file</p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "LAB3BST2.h"
Node *initNode(Key k, char *v)
// Allocate memory for new node and initialize fields.
// Returns pointer to node created.
{
Node *n = malloc(sizeof(Node));
// initialize node if memory obtained
if (n != NULL) {
n->key = k;
n->value = strdup(v);
n->leftChild = NULL;
n->rightChild = NULL;
}
return n;
}//initNode()
Tree *initTree(Key k, char *v)
// Set up new tree. Allocates memory for Tree structure, then
// calls initNode() to allocate first node.
{
Tree *t = malloc(sizeof(Tree));
if (t != NULL)
t->root = initNode(k, v);
return t;
}//initTree()
void printTreeExplanation(void)
// Prints hint to reader what to expect on screen
{
static int done = 0;
if (!done) {
printf("First time explanation of tree display:\n");
printf("Every node is displayed as a comma-separated pair within brackets:");
printf(" (kk,vv)\n");
printf("where kk is the key and vv is the value\n");
printf("A tree starts with a curly bracket { and ends with a curly bracket }.\n");
printf("An empty tree will be {}\n");
printf("A tree with no children will be { (kk,vv),{},{} }\n");
printf("If either subtree is populated, it will be shown using the same ");
printf("technique as described above\n");
printf("(Hint: Start at root - and then match up all the remaining\n");
printf("brackets, then interpret what those bracket pairs are telling\n");
printf("you.)\n============\n\n");
done = 1;
}
}//printTreeExplanation()
void printTree(Node *root)
// Print whole tree. We cannot make it look pretty graphically, so we add some
// characters to make it a little easier to understand. We also don't really
// know what the value field is - it is declared to be a void pointer - so we
// treat it as though it points to an integer.
{
// assume printTree magically knows the types in the tree node
printTreeExplanation();
// start of this tree
printf("{");
// values in the root node (assuming value is pointing to an integer)
printf("(%d,%s),", root->key, root->value);
// Now show left subtree or {} if there is no left subtree
if (root->leftChild != NULL)
printTree(root->leftChild);
else
printf("{}");
// Marker between left and right subtrees
printf(",");
// Now show right subtree or {} if there is no right subtree
if (root->rightChild != NULL)
printTree(root->rightChild);
else
printf("{}");
// Close display of this tree with closing curly bracket
printf("}");
}//printTree()
Node *find(Key k, Node *root)
{
// termination conditions - either true, search is ended
if ((root == NULL) || (root->key == k))
return root;
if (k > root->key) //traverse through the right subtree (larger)
return find(k, root->rightChild);
else //traverse through the right
return find(k, root->leftChild);
}//find()
int insert(Key k, char *v, Node *root)
{
int result = BST_FAIL;
// this if statement can only be true with first root (root of whole tree)
if (root == NULL) {
Node *n = initNode(k, v);
root = n;
return BST_SUCCESS;
}
if (root->key == k)
root->value = strdup(v);//replace password
else
if (k < root->key) {
// key value less than key value in root node - try to insert into left
// subtree, if it exists.
if (root->leftChild != NULL)
// there is a left subtree - insert it
result = insert(k, v, root->leftChild);
else {
// new Node becomes the left subtree
Node *n = initNode(k, v);
root->leftChild = n;
result = BST_SUCCESS;
}
} else
if (k > root->key) { // test actually redundant
// key is greater than this nodes key value, so value goes into right
// subtree, if it exists
if (root->rightChild != NULL)
// there is a right subtree - insert new node
result = insert(k, v, root->rightChild);
else {
// no right subtree - new node becomes right subtree
Node *n = initNode(k, v);
root->rightChild = n;
result = BST_SUCCESS;
}
}
return result;
}//insert()
int intmax(int a, int b) {
return (a >= b) ? a : b;
}//intmax()
int height(Node *root)
// Height definition:
// Height of an empty tree is -1. Height of a leaf node is 0. Height of other
// nodes is 1 more than larger height of node's two subtrees.
{
int nodeheight = -1;
int right, left;// default returned for empty tree
if (root != NULL) {
left = height(root->leftChild);
right = height(root->rightChild);
nodeheight = intmax(left, right);
}
return nodeheight;
}//height()
Node *findParentHelper(Key k, Node *root)
// Help find parent of node with key == k. Parameter root is node with
// at least one child (see findParent()).
{
if (root->leftChild != NULL) {
if (root->leftChild->key == k)
return root;
}
if (root->rightChild != NULL) {
if (root->rightChild->key == k)
return root;
}
if (k > root->key)
return findParentHelper(k, root->rightChild);
else
return findParentHelper(k, root->leftChild);
}//findparenthelper()
Node *findParent(Key k, Node *root)
// root
{
// Deal with special special cases which could only happen for root
// of whole tree
if (root == NULL)
return root;
// real root doesn't have parent so we make it parent of itself
if (root->key == k)
return root;
// root has no children
if ((root->leftChild == NULL) && (root->rightChild == NULL))
return NULL;
// Deal with cases where root has at least one child
return findParentHelper(k, root);
}//findParent()
Node *findMin(Node *root) {
if (root->leftChild == NULL)
return root;
return findMin(root->leftChild);
}
Node *findMax(Node *root) {
if (root->rightChild == NULL)
return root;
return findMax(root->rightChild);
}
int check(Node *p, Node *n) {
if (p->rightChild == n)
return 1; //1==right, 0==left
return 0;
}
void delete(Node *p, Node *n)
// Delete node pointed to by n.
// Parameters:
// n - points to node to be deleted
// p - points to parent of node to be deleted.
{
// Deletion has 3 cases - no subtrees, only left or right subtree, or both
// left and right subtrees.
if (p == n) { //if the root is the node to be deleted
Node *temp;
int key;
char *pass;
if (p->rightChild) {
temp = findMin(p->rightChild);
key = temp->key;
pass = strdup(temp->value);
delete(findParent(temp->key, n), temp);
p->key = key;
p->value = pass;
} else
if (p->leftChild) {
temp = findMax(p->leftChild);
key = temp->key;
pass = strdup(temp->value);
delete(findParent(temp->key, n), temp);
p->key = key;
p->value = pass;
}
return;
}
if (n->leftChild != NULL) { // there is left child
if (n->rightChild) { //if both
Node *temp = findMin(n->rightChild);
n->key = temp->key;
n->value = strdup(temp->value);
delete(findParent(temp->key, n), temp);//delete the min value found (which is a leaf on the left most right branch)
} else { //if only left
if (check(p, n)) {
p->rightChild = n->leftChild;
} else
p->leftChild = n->leftChild;
free(n);
}
} else
if (n->rightChild) { // there is only a right child
if (check(p, n)) {
p->rightChild = n->rightChild;
} else
p->leftChild = n->rightChild;
free(n);
} else {// no children
if (check(p, n)) {
p->rightChild = NULL;
} else
p->leftChild = NULL;
free(n);
}
}//delete()
int withdraw(Key k, Node *root)
// Withdraw does two things:
// return a copy of the node with key k (and value v)
// Delete the node with key k from the tree while ensuring the tree remains valid
{
Node *p, *m;
m = find(k, root);
if (m != NULL) {
// create a copy of the node with the same key and value
//n = initNode(m->key, m->value);
p = findParent(k, root);
// can delete the node
delete(p, m);
return 1;
}
return 0;
}//withdraw()
int bst_check(Node *root) {
if (root == NULL)
return 1; // if on a leaf (return back up to root) //170696526
if (root->leftChild != NULL && root->leftChild->key > root->key)
//if the left child exists and its key is greater than the root
return 0;
if (root->rightChild != NULL && root->rightChild->key < root->key)
// if the right child exists and is smaller than the root
return 0;
if (!bst_check(root->leftChild) || !bst_check(root->rightChild))
//if the check was unsuccessful for both the right and left subtrees
//also recursively checks the left and right child
return 0;
//if all pass, then the tree was a bst
return 1;
}
</code></pre>
<p>Here is my function file (.h file):</p>
<pre><code>// LAB3_BST.H
// Header file to be used with code for ELEC278 Lab 3.
//
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef int Key;
#define BST_FAIL 0 // return value when BST function fails
#define BST_SUCCESS 1 // return value when BST function succeeds
// Node in tree has key and pointer to value associated with key.
// Also contains structural components - two pointers to left and
// right subtrees.
typedef struct password {
char *word;
struct password *next;
} pnode;
typedef struct Node {
Key key;
char *value;
struct Node *leftChild, *rightChild;
} Node, pNode;
// Tree is basically pointer to top node in a tree.
typedef struct Tree {
Node *root;
} Tree;
Node *initNode(int k, char *v);
// Create new tree by creating new node with key = k and value = v
// and making it root
Tree *initTree(int k, char *v);
// Find node with key k in tree. Returns pointer to Node if found;
// Returns NULL if not found
Node *find(Key k, Node *root);
// Create new node with key=k, value=v and insert it into tree
// Returns 1 upon success, 0 failure
int insert(int k, char *v, Node *root);
// Print text representation of tree (starting at any Node)
void printTree(Node *root);
// Returns Maximum of two integer numbers
int intmax(int a, int b);
// Find parent of node n where n->key = k
// Returns pointer to parent node if found; Returns NULL if not found
Node *findParent(Key k, Node *root);
// 1. Make copy of node with key=k and returns it
// 2. Delete node with key=k from tree
// Return pointer of node created in 1; Returns NULL if no node
// with specified key value is found
int withdraw(Key k, Node *root);
// Return height of tree (height of specified root)
int height(Node *root);
// Helper function for findParent - see specification in lab
// instructions
Node *findParentHelper(Key k, Node *root);
// Delete node from tree while ensuring tree remains valid
void delete(Node *p, Node *n);
Node* inorder(Node *pn);
int bst_check(Node *root);
</code></pre>
<p>I dont know where to start.</p>
| [
{
"answer_id": 74270408,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 2,
"selected": true,
"text": "row_number()"
},
{
"answer_id": 74270426,
"author": "Avogadro",
"author_id": 1233144,
"author_profi... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20383697/"
] |
74,270,372 | <p>In a <code>aws_ssoadmin_permission_set_inline_policy</code> ressource, i'm using a <code>for_each</code> to parse a list of name corresponding to my data source name. It doesn't work when using the <code>each.key</code> but wokring when hard coding the value <code>inline_policy = data.aws_iam_policy_document.emobg-sso-billing-admin.json </code></p>
<pre><code>data "aws_iam_policy_document" "emobg-sso-billing-admin" {
statement {
sid = "VisualEditor0"
effect = "Allow"
actions = [
"aws-marketplace:*",
"aws-portal:*",
"budgets:*"
]
resources = [
"*",
]
}
}
data "aws_iam_policy_document" "emobg-sso-billing-audit" {
statement {
sid = "VisualEditor0"
effect = "Allow"
actions = [
"support:*",
"tag:*",
"s3:*"
]
resources = [
"*",
]
}
}
resource "aws_ssoadmin_permission_set" "emobg" {
for_each = toset(local.permission_sets_name)
name = each.key
description = each.key
instance_arn = local.sso_instance_arn
session_duration = local.session_duration
}
resource "aws_ssoadmin_permission_set_inline_policy" "emobg" {
for_each = toset(local.permission_sets_name)
inline_policy = format("data.aws_iam_policy_document.%s.json", each.key) # <-- doesn't works
# inline_policy = data.aws_iam_policy_document.emobg-sso-billing-admin.json # <-- works
instance_arn = local.sso_instance_arn
permission_set_arn = aws_ssoadmin_permission_set.emobg[each.key].arn
}
locals {
session_duration = "PT8H"
permission_sets_name = [
"emobg-sso-billing-admin",
"emobg-sso-billing-audit",
]
}
</code></pre>
<p><strong>The error message is:</strong></p>
<pre><code>2022-11-01T01:19:43.923+0100 [ERROR] vertex "aws_ssoadmin_permission_set_inline_policy.emobg[\"emobg-sso-billing-admin\"]" error: "inline_policy" contains an invalid JSON policy
2022-11-01T01:19:43.923+0100 [ERROR] vertex "aws_ssoadmin_permission_set_inline_policy.emobg (expand)" error: "inline_policy" contains an invalid JSON policy
β·
β Error: "inline_policy" contains an invalid JSON policy
β
β with aws_ssoadmin_permission_set_inline_policy.emobg["emobg-sso-billing-admin"],
β on permission_set.tf line 13, in resource "aws_ssoadmin_permission_set_inline_policy" "emobg":
β 13: inline_policy = format("data.aws_iam_policy_document.%s.json", each.value)
</code></pre>
<p>I really don't understand what's wrong with the JSON policy because it's the same.
Maybe I missed something ?</p>
| [
{
"answer_id": 74270536,
"author": "Marcin",
"author_id": 248823,
"author_profile": "https://Stackoverflow.com/users/248823",
"pm_score": 2,
"selected": true,
"text": "format(\"data.aws_iam_policy_document.%s.json\", each.key)"
},
{
"answer_id": 74279177,
"author": "Bakka",
... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10653829/"
] |
74,270,480 | <p>I would very much appreciate your help with the following question.</p>
<p>I am trying to understand the pseudocode for iterative postorder binary tree traversal from the Wikipedia page Tree traversal.</p>
<p><a href="https://i.stack.imgur.com/Xdi9l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xdi9l.png" alt="enter image description here" /></a></p>
<p>I am not sure why is this part "and lastNodeVisited β peekNode.right" in the second if-statement needed, i.e. I do not know when this part would evaluate to False.</p>
<p>Could anyone please provide an example of a binary tree in which "peekNode.right β null" would evaluate to True, but "lastNodeVisited β peekNode.right" would evaluate to False?</p>
<p>I tried creating a few binary trees of different shapes, but I could not find one in which, for a specific node, "peekNode.right β null" would evaluate to True, but "lastNodeVisited β peekNode.right" would evaluate to False.</p>
| [
{
"answer_id": 74270536,
"author": "Marcin",
"author_id": 248823,
"author_profile": "https://Stackoverflow.com/users/248823",
"pm_score": 2,
"selected": true,
"text": "format(\"data.aws_iam_policy_document.%s.json\", each.key)"
},
{
"answer_id": 74279177,
"author": "Bakka",
... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12454411/"
] |
74,270,521 | <p>I have this routes in rails, other developer i made that</p>
<pre><code>namespace :api do
namespace :v1 do
resources :articles do
resources :posts
end
end
end
</code></pre>
<p>now i want to test it by postman, but i dont understand how will be the url of the endpoint</p>
<p>i tested this url</p>
<p>http://localhost:3000/api/v1/articles?id=1&posts=1</p>
<p>but just i am getting this error</p>
<pre><code>"#<ActionController::RoutingError: uninitialized constant Api::V1::ArticlesController\n\n
</code></pre>
| [
{
"answer_id": 74271329,
"author": "kevinluo201",
"author_id": 8826293,
"author_profile": "https://Stackoverflow.com/users/8826293",
"pm_score": 3,
"selected": true,
"text": "rails routes"
},
{
"answer_id": 74271615,
"author": "benmercerdev",
"author_id": 8936789,
"au... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20344204/"
] |
74,270,537 | <p>A valid number is defined by the following rules:</p>
<ol>
<li><p>can have any number of digits, but it can have only digits and a decimal point and possibly a leading sign.</p>
</li>
<li><p>the decimal point is optional, but if it appears in the number, there must be only one, and it must have digits on its left and its right.</p>
</li>
<li><p>There should be whitespace or a beginning or end-of-line character on either side of a valid number.</p>
</li>
</ol>
<p><code>valid = re.findall(r'\s\d\.\d\s', text) </code></p>
<p>This is what I have right now.</p>
| [
{
"answer_id": 74271329,
"author": "kevinluo201",
"author_id": 8826293,
"author_profile": "https://Stackoverflow.com/users/8826293",
"pm_score": 3,
"selected": true,
"text": "rails routes"
},
{
"answer_id": 74271615,
"author": "benmercerdev",
"author_id": 8936789,
"au... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20383851/"
] |
74,270,582 | <p>I am at the last straw with trying to get a local json file into my Firestore database. No matter how I format my data, I get some sort of error. I even took the example right from the google firebase instructions and still no luck. Here is what I am doing:</p>
<p>*Note: I am using R. I don't want to, but I have to.</p>
<ol>
<li>Authenticate and get my bearer token.</li>
<li>Create the data in a json file (from the firestore example) and import it into R. Below is the file I am reading in.</li>
</ol>
<pre><code>{
"users": [
{
"id": "1",
"firstName": "Kristin",
"lastName": "Smith",
"occupation": "Teacher",
"reviewCount": "6",
"reviewScore": "5",
},
{
"id": "2",
"firstName": "Olivia",
"lastName": "Parker",
"occupation": "Teacher",
"reviewCount": "11",
"reviewScore": "5"
}
]
}
</code></pre>
<ol start="3">
<li>Call the function I have for writing data:</li>
</ol>
<pre><code>write.db <- function(db_endpoint, data, auth_token) {
r <- PATCH(db_endpoint,
add_headers("Content-Type" = "application/json",
"Authorization" = paste("Bearer", auth_token)), body = data)
return(r)
}
</code></pre>
<ol start="4">
<li>Experience the following error message:</li>
</ol>
<pre><code>{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"users\" at 'document': Cannot find field.",
"status": "INVALID_ARGUMENT",
"details": [
{
"@type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
...
</code></pre>
<p>The interesting thing is, if I try to write something simpler like the below (no array of objects), I can do so with no problem:</p>
<pre><code>{
"fields": {
"name": {
"stringValue": "Gabriel"
},
"favoriteNumber": {
"integerValue": "32343"
}
}
}
</code></pre>
<p>Can someone PLEASE explain to me what I am doing wrong here. I have tried reformatting my data a thousand different ways but nothing seems to work.</p>
| [
{
"answer_id": 74271329,
"author": "kevinluo201",
"author_id": 8826293,
"author_profile": "https://Stackoverflow.com/users/8826293",
"pm_score": 3,
"selected": true,
"text": "rails routes"
},
{
"answer_id": 74271615,
"author": "benmercerdev",
"author_id": 8936789,
"au... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7649705/"
] |
74,270,609 | <p>In Python, how do I expand this dataframe...</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>sect_id</th>
<th>sector</th>
<th>func_list</th>
<th>func_id</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>AAA</td>
<td>['A', 'B']</td>
<td>[1,2]</td>
</tr>
<tr>
<td>1</td>
<td>BBB</td>
<td>['C', 'D']</td>
<td>[3,4]</td>
</tr>
</tbody>
</table>
</div>
<p>To this format?</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>sect_id</th>
<th>sector</th>
<th>func_list</th>
<th>func_id</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>AAA</td>
<td>A</td>
<td>1</td>
</tr>
<tr>
<td>0</td>
<td>AAA</td>
<td>B</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>BBB</td>
<td>C</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>BBB</td>
<td>D</td>
<td>4</td>
</tr>
</tbody>
</table>
</div>
<p>Thanks for your advice.</p>
| [
{
"answer_id": 74271329,
"author": "kevinluo201",
"author_id": 8826293,
"author_profile": "https://Stackoverflow.com/users/8826293",
"pm_score": 3,
"selected": true,
"text": "rails routes"
},
{
"answer_id": 74271615,
"author": "benmercerdev",
"author_id": 8936789,
"au... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15850814/"
] |
74,270,648 | <ul>
<li>I'm still learning, so if there's any help, or the answer is really trivial like something I need to put before hand, an explanation of the reason why this is happening would be greatly appreciated!</li>
</ul>
<p>This has been a problem ever since I have started using it for weekend projects. Whenever I make a button, for example one that I have been trying to use is</p>
<pre><code> <button type="submit" id="btn" onclick="validate()">login</button>
</code></pre>
<p>However, when I click on the button, instead of showing me what its supposed to show, it just states this on a gray page.</p>
<p>This page isnβt working
If the problem continues, contact the site owner.
HTTP ERROR 405</p>
<p>HTML</p>
<pre><code> <div class="wrapper">
<form class="box" method="post">
<h3>login</h3>
<div class="username">
<input type="text" placeholder="enter username" id="username" name="usernmame" value="">
</div>
<div class="password">
<input type="password" placeholder="enter password" id="password"">
</div>
<button type="submit" id="btn" onclick="validate()">login</button>
</form>
</div>
</code></pre>
<p>JS
<em>//I do understand that this is not a good way of setting up a username and password ,since anyone can easily get it. Ive been just doing this as a weekend project, i just want it to show an alert if it works or not</em></p>
<pre><code>function validate(){
let username = document.getElementById('username');
value;
let password=document.getElementById('password');
value;
if(username =='please' && password == 'work')
{
alert('finally');
} else{
alert("NOOOO")
}
}
</code></pre>
<p>I have tried to see if it was a problem with my js, but nothing seems to change, so that is why im starting to suspect that it its the button thats causin the problem</p>
| [
{
"answer_id": 74271329,
"author": "kevinluo201",
"author_id": 8826293,
"author_profile": "https://Stackoverflow.com/users/8826293",
"pm_score": 3,
"selected": true,
"text": "rails routes"
},
{
"answer_id": 74271615,
"author": "benmercerdev",
"author_id": 8936789,
"au... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20383871/"
] |
74,270,667 | <p>Apologies if the wording of the title is confusing, it's difficult to describe exactly what I'm looking for. I've got some data with two date fields, let's call them <em>start_date</em> and <em>end_date</em>. I'm interested in knowing whether or not a particular observation "covered" June 30th of any given year (the data spans multiple years).</p>
<p>So, for instance, if <em>start_date</em> = "02-25-2021" and <em>end_date</em> = "01-12-2022", this observation would fit my criteria. By contrast, an observation with <em>start_date</em> = "07-02-2015" and <em>end_date</em> = "08-25-2015" would not, since June 30th does not occur in between the start and end date variables.</p>
<p>The issue is that because my data spans multiple years, it's not straightforward to me how I can identify cases which pass over a date regardless of year. How can I do this type of filtering without having to manually specify a range for every single year? Hope this is clear enough -- thanks for any assistance you can provide.</p>
| [
{
"answer_id": 74270813,
"author": "Seth",
"author_id": 19316600,
"author_profile": "https://Stackoverflow.com/users/19316600",
"pm_score": 2,
"selected": false,
"text": "lubridate"
},
{
"answer_id": 74275537,
"author": "MoltenLight",
"author_id": 12984772,
"author_pr... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18422717/"
] |
74,270,694 | <p>I make a dropdown for a form, I will show the code below. However, when I click the submit button, there is an error saying,<br />
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'brand' cannot be null (SQL: insert into <code>supplier_details</code>.<br />
The data that I chose from the dropdown is actually null. Actually, I'm new to Laravel.<br />
I don't want to make a dropdown list from a database, I just want to display the option and the option will be inserted into the database when the user clicks the submit button after filling in the form.</p>
<pre><code> <div class="form-group row">
<label style="font-size: 16px;" for="id" class = "col-sm-2">Item Brand </label>
<label for="supp_name" class = "col-sm-1">:</label>
<div class="col-sm-7">
<select name="brand" class="form-control js-example-basic-single" required>
<option >Please select item brand</option>
<option value="machine1"> Item Brand 1 </option>
<option value="machine1"> Item Brand 2 </option>
<option value="machine1"> Tem Brand 3 </option>
</select>
</div>
</div>
</code></pre>
<p>Controller</p>
<pre><code>public function createsupplierdetails()
{
return view ('frontend.praiBarcode.getweight');
}
public function supplierdetails(Request $r)
{
$details = new SupplierDetail;
$getuserPO = Supplier::where('PO',$r->PO)->first();
$details->brand = $getuserPO->brand;
$details->container_no = $getuserPO->container_no;
$details->date_received = $getuserPO->date_received;
$details->gross_weight = $getuserPO->gross_weight;
$details->tare_weight = $getuserPO->tare_weight;
$details->net_weight = $getuserPO->net_weight;
$details->save();
return view ('frontend.praiBarcode.viewsupplierdetails')
->with('details',$details);
}
</code></pre>
| [
{
"answer_id": 74270813,
"author": "Seth",
"author_id": 19316600,
"author_profile": "https://Stackoverflow.com/users/19316600",
"pm_score": 2,
"selected": false,
"text": "lubridate"
},
{
"answer_id": 74275537,
"author": "MoltenLight",
"author_id": 12984772,
"author_pr... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15702465/"
] |
74,270,707 | <p>I am looking at <a href="https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.3.2" rel="nofollow noreferrer">https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.3.2</a>
and i am wondering how does one display the correct form of a method that takes in 2 different types.</p>
<p>E.g.</p>
<pre><code>callthismethod(String a, ArrayMap<String aa, Task<String aaa> > )
</code></pre>
<p>where Task is imported from com.this.location</p>
<blockquote>
<p>The field descriptor of an instance variable of type <code>int</code> is simply <code>I</code>.</p>
<p>The field descriptor of an instance variable of type <code>Object</code> is <code>Ljava/lang/Object;</code>. Note that the internal form of the binary name for class <code>Object</code> is used.</p>
<p>The field descriptor of an instance variable that is a multidimensional <code>double</code> array, <code>double d[][][]</code>, is <code>[[[D</code>.</p>
</blockquote>
| [
{
"answer_id": 74271804,
"author": "Louis Wasserman",
"author_id": 869736,
"author_profile": "https://Stackoverflow.com/users/869736",
"pm_score": 0,
"selected": false,
"text": "Ljava/lang/String;Lwhatever/package/ArrayMap;"
},
{
"answer_id": 74273849,
"author": "Holger",
... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6428439/"
] |
74,270,765 | <p>I have some c++ code in msys2 that I am trying to link dynamically to show how a dynamic link library works.</p>
<p>In linux, showing the call is no problem. stepping in gdb, we can watch the call go through the jump vector, eventually landing in the desired function.</p>
<p>But in msys2, they wanted to eliminated dlls and all the libraries I can find are .dll.a, I think they are really static libraries.</p>
<p>I build a trivial little function like this:</p>
<pre><code>#include <cstdint>
extern "C" {
uint64_t f(uint64_t a, uint64_t b) {
return a + b;
}
}
</code></pre>
<p>compiling in the makefile with:</p>
<pre><code>g++ -g -fPIC -c lib1.cc
g++ -g -shared lib1.o -o libtest1.so
</code></pre>
<p>When I run the file utility, it says that:</p>
<pre><code>libtest1.so: PE32+ executable (DLL) (console) x86-64, for MS Windows
</code></pre>
<p>When I compile the code using it:</p>
<pre><code>g++ -g main.cc -ltest1 -o prog
</code></pre>
<p>The error is -ltest1 no such file or directory.</p>
| [
{
"answer_id": 74272377,
"author": "David Grayson",
"author_id": 28128,
"author_profile": "https://Stackoverflow.com/users/28128",
"pm_score": 0,
"selected": false,
"text": "-L."
},
{
"answer_id": 74272626,
"author": "HolyBlackCat",
"author_id": 2752075,
"author_profi... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233928/"
] |
74,270,780 | <p>I am working on a portfolio site, with various clients/projects I've worked on each having their own info page. I haven't quite worked out yet where I want to host images, but for now I'm building these individual project pages with hopes of just loading in images locally. Currently, I don't receive any errors with my code as written, but none of my images are being rendered in the browser. I suspect this might be because none of the <code><img></code> elements are being appended to anything, but honestly I'm not sure. What else could I be missing here? Would this have anything to do with Webpack configs?</p>
<p><strong>Note:</strong> The <code>src</code> attributes on the <code>img</code> tags are utilizing the correct path to the <code>public</code> folder as is.</p>
<p><strong>App.js</strong></p>
<pre><code>import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import './App.css';
import Landing from "./components/Landing";
import About from "./components/About";
import ProjectPage from "./components/ProjectPage";
import projects from "./utils/projectlists.js";
function App() {
return (
<div className="App">
<Router>
<Routes>
<Route element={<Landing />} exact path="/" />
<Route element={<About field="design" />} exact path="/design" />
<Route element={<About field="web"/>} exact path="/web" />
<Route element={<ProjectPage projects={projects} />} path={"/projects/:name"}/>
</Routes>
</Router>
</div>
);
}
export default App;
</code></pre>
<p><strong>projectlists.js</strong> (example info)</p>
<pre><code>const projects = [
{
id: 1,
name: "Project Name",
link: "project-name",
skills: "Project skills",
images: ["image1.png", "image2.png", "image3.png"],
}
export default projects;
</code></pre>
<p><strong>ProjectPage.js</strong> (where the div containing images I want to load in will go)</p>
<pre><code>import React from "react";
import { useParams } from "react-router";
import '../App.css';
export default function ProjectPage({ projects }) {
const { name } = useParams();
return (
<div className="project-layout">
<div className="photo-box">
{projects.filter(project => name === project.link).map(
project => (
project.images.forEach(image => (
<div key={project.id}>
<img className="proj-image" src={require(`../../public/assets/images/${image}`)} alt={""}></img>
</div>
)
)
))
}
</div>
</div>
);
};
</code></pre>
| [
{
"answer_id": 74272377,
"author": "David Grayson",
"author_id": 28128,
"author_profile": "https://Stackoverflow.com/users/28128",
"pm_score": 0,
"selected": false,
"text": "-L."
},
{
"answer_id": 74272626,
"author": "HolyBlackCat",
"author_id": 2752075,
"author_profi... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19552209/"
] |
74,270,785 | <p>I'm trying to return a few functions in react but I'm unable to perform as I wanted.</p>
<pre><code>return (
loadingMessage(),
errorMessage(),
loginForm(),
performRedirect()
)
}
</code></pre>
<p>I want to return my functions as above but when try this my app directly calls the last function <strong>performRedirect()</strong>. I don't know whether am I running this correctly or not.</p>
<p>please find the whole code below.</p>
<pre><code>import React, { useState } from "react";
import { Link, Navigate } from "react-router-dom";
import {signin, authenticate, isAutheticated} from "../auth/helper/index"
const Login = () => {
const [values, setValues] = useState({
username: "",
password: "",
error: "",
loading: false,
didRedirect: false,
});
const {username, password, error, loading, didRedirect} = values;
const {user} = isAutheticated();
const handleChange = name => event => {
setValues({ ...values, error: false, [name]: event.target.value });
};
const onSubmit = event => {
event.preventDefault();
setValues({ ...values, error: false, loading: true });
signin({ username, password })
.then(data => {
if (data.error) {
setValues({ ...values, error: data.error, loading: false });
} else {
authenticate(data, () => {
setValues({
...values,
didRedirect: true
});
});
}
})
.catch(console.log("signin request failed", error, user));
};
const performRedirect = () => {
//TODO: do a redirect here
if (didRedirect) {
if (user && user.role === 1) {
return <p>redirect to admin</p>;
} else {
return <p>redirect to user dashboard</p>;
}
}
if (isAutheticated()) {
return <Navigate to="/" />;
}
};
const loadingMessage = () => {
return (
loading && (
<div className="alert alert-info">
<h2>Loading...</h2>
</div>
)
);
};
const errorMessage = () => {
return (
<div className="row">
<div className="col-md-6 offset-sm-3 text-left">
<div
className="alert alert-danger"
style={{ display: error ? "" : "none" }}
>
{error}
</div>
</div>
</div>
);
};
const loginForm = () => {
return (
<div className='bg-gray-200'>
<div className="flex items-center h-screen w-full">
<div className="w-80 bg-white rounded-2xl p-6 m-0 md:max-w-sm md:mx-auto border border-slate-300 shadow-sm">
<div align='center' className='mt-3 mb-3 items-center content-center'> <img src={require('./../data/logo.jpg')} width="120px"/></div>
<span className="block w-full text-xl uppercase font-bold mb-4 text-center">Sign in to EMS
</span>
<form className="mb-0" action="/" method="post">
<div className="mb-4 md:w-full">
<label for="email" className="block text-xs mb-1 text-left text-gray-500">Username</label>
<input onChange={handleChange("username")} className="bg-gray-100 w-full border rounded-2xl px-4 py-2 outline-none focus:shadow-outline text-left text-xs" type="text" name="username" id="username" placeholder="Username" value={username}/>
</div>
<div className="mb-6 md:w-full relative">
<div className='flex w-full'>
<label for="password" className="block text-xs mb-1 text-center text-gray-500">Password</label>
<a className="text-xs text-right text-[#58a6ff] absolute right-0" href="/login">Forgot password?</a></div>
<input onChange={handleChange("password")} className="bg-gray-100 w-full border rounded-2xl px-4 py-2 outline-none focus:shadow-outline text-left text-xs" type="password" name="password" id="password" placeholder="Password" value={password}/>
</div>
<div className="mb-6 md:w-full relative">
<div className='flex w-full'>
<p className="block text-xs mb-1 text-center text-gray-500">{JSON.stringify(values)}</p>
</div>
<button className="bg-green-500 hover:bg-green-700 shadow-lg text-white uppercase text-sm font-semibold px-4 py-2 rounded-2xl text-center items-center w-full" onClick={onSubmit}>Login</button>
</form>
</div>
</div>
</div>
);
};
return (
loadingMessage(),
errorMessage(),
loginForm(),
performRedirect()
)
}
export default Login
</code></pre>
<p>Please someone help me on this?</p>
| [
{
"answer_id": 74271049,
"author": "Nick Vu",
"author_id": 9201587,
"author_profile": "https://Stackoverflow.com/users/9201587",
"pm_score": 2,
"selected": false,
"text": "[]"
},
{
"answer_id": 74271067,
"author": "Leon Huang",
"author_id": 19288414,
"author_profile":... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9799333/"
] |
74,270,790 | <p>I have an application in ASPCore MVC.</p>
<p>My goal was to adjust the model to automatically capitalize email addresses.
It seemed this would be better than adjusting each controller.</p>
<p>After some research, I came upon this solution below, to modify the property backers.</p>
<pre><code> public class PostFou
{
private string _name;
private string _email;
private string _address;
[Key]
public int FouId { get; set; }
[Display(Name = "Full Name")]
[RegularExpression(@"[a-zA-Z0-9""'\s-|\.\=\+\*\/\\]*$")]
[StringLength(45)]
public string FouName { get; set; }
[Display(Name = "Phone")]
[RegularExpression(@"[0-9]*$")]
[StringLength(20)]
[DataType(DataType.PhoneNumber)]
public string FouPhon { get; set; }
[Display(Name = "Email")]
[StringLength(45)]
public string FouEmai //{ get; set; }
{
get { return _email; }
set { _email = value.ToUpper(); }
}
}
</code></pre>
<p>The problem is that now all my linq queries are returning a nullReference exception one things that seem unrelated. for example, in my razor view, I have the following code</p>
<pre><code>@foreach (var item in Model) { //error occurs here
<tr>
<td>
@Html.DisplayFor(modelItem => item.FouZero)
</td>
<td>
@Html.DisplayFor(modelItem => item.FouName)
</td>
<td>
@Html.DisplayFor(modelItem => item.FouPhon)
</td>
<td>
@Html.DisplayFor(modelItem => item.FouEmai)
</td>
</code></pre>
<p>In the controller, for this view, there is a Linq simple query:</p>
<pre><code>public IActionResult Index(string searchString)
{
var titles = _context.PostFous.Where(m =>
m.FouZero.Contains(searchString) ||
m.FouName.Contains(searchString) ||
m.FouEmai.Contains(searchString)
);
//return View(await _context.PostFous.ToListAsync());
return View(titles);
}
</code></pre>
<p>in debugging, digging as deep as I know how, I found this message, consistently across the errors:</p>
<pre><code> at lambda_method(Closure , QueryContext , DbDataReader , ResultContext , Int32[] , ResultCoordinator )
</code></pre>
<p>I'm not sure what that means.</p>
<p>The question is, what is going wrong?
Given that that is a broad question, more narrowly, in adjusting the property backing, should I have also adjusted something else?
Follow up, is there a different way to accomplish my goal of auto-capitalizing the email addresses in the model?</p>
<p>I would like to avoid making changes to the db, and keep this within the application.</p>
| [
{
"answer_id": 74271049,
"author": "Nick Vu",
"author_id": 9201587,
"author_profile": "https://Stackoverflow.com/users/9201587",
"pm_score": 2,
"selected": false,
"text": "[]"
},
{
"answer_id": 74271067,
"author": "Leon Huang",
"author_id": 19288414,
"author_profile":... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2675618/"
] |
74,270,826 | <p>I am having issue with my code, the code is suppose to sort a set amount a number in ascending order, but every time I enter the 2nd last number the program ends, and in the place of what should be the 10th number is <code>-858993460</code></p>
<p>here is my code:</p>
<pre><code>#include<iostream>
using namespace std;
int main()
{
int x, y, arry[61], z, interim;
cout << "Please enter how many numbers you would like to sort:\n>> ";
cin >> x;
cout << "Please enter " << x << "numbers\n";
for (y = 0; y < (x - 1); y++)
cin >> arry[y];
cout << "Give bubble sort a minute to do its thing.....";
for (y = 0; y < (x - 1); y++)
{
for (z = 0; z < (x - y - 1); z++)
{
if (arry[z] > arry[z + 1])
{
interim = arry[z];
arry[z] = arry[z + 1];
arry[z + 1] = interim;
}
}
}
cout << "\nBubble sorted as went through the array in accending order\n Arry:";
for (y = 0; y < x; y++)
cout << arry[y] << " ";
cout << endl;
return 0;
}
</code></pre>
<p>I tried to change the value of the array but not really tried anything else, and I'm expecting it to be able to let me input that last number but it never does.</p>
| [
{
"answer_id": 74271000,
"author": "Al Timofeyev",
"author_id": 17047816,
"author_profile": "https://Stackoverflow.com/users/17047816",
"pm_score": 1,
"selected": false,
"text": "for..."
},
{
"answer_id": 74271035,
"author": "InternetHateMachine",
"author_id": 20384084,
... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20384084/"
] |
74,270,884 | <p><a href="https://i.stack.imgur.com/tflOZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tflOZ.png" alt="enter image description here" /></a></p>
<p>I am trying to left-align 'Add attachment' in the TextButton so it lines up with 'Starts' and 'Ends'.</p>
<pre><code>Container(
height: 50,
width: 350,
margin: const EdgeInsets.only(left: 20.0, right: 20.0),
decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(10.0)),
child: TextButton(
child: const Align(
child: Text(
'Add attachment...',
style: TextStyle(color: CupertinoColors.activeBlue, fontSize: 16),
textAlign: TextAlign.left
),
),
onPressed: () {},
)
),
</code></pre>
<p>I have tried adding <code>textAlign: TextAlign.left</code> to the TextButton but it is not working. I suspect the TextButton is not taking up the entire width of the Container.</p>
| [
{
"answer_id": 74270967,
"author": "ariga",
"author_id": 20384182,
"author_profile": "https://Stackoverflow.com/users/20384182",
"pm_score": 0,
"selected": false,
"text": "alignment: Alignment.centerleft,"
},
{
"answer_id": 74270993,
"author": "pmatatias",
"author_id": 12... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373971/"
] |
74,270,887 | <p>I have not seen any posts about this on here. I have a data frame with some data that i would like to replace the values with the values found in a dictionary. This could simply be done with <code>.replace</code> but I want to keep this dynamic and reference the df column names using a paired dictionary map.</p>
<pre><code>import pandas as pd
data=[['Alphabet', 'Indiana']]
df=pd.DataFrame(data,columns=['letters','State'])
replace_dict={
"states":
{"Illinois": "IL", "Indiana": "IN"},
"abc":
{"Alphabet":"ABC", "Alphabet end":"XYZ"}}
def replace_dict():
return
df_map={
"letters": [replace_dict],
"State": [replace_dict]
}
#replace the df values with the replace_dict values
</code></pre>
<p>I hope this makes sense but to explain more i want to replace the data under columns 'letters' and 'State' with the values found in replace_dict but referencing the column names from the keys found in df_map. I know this is overcomplicated for this example but i want to provide an easier example to understand.</p>
<p>I need help making the function 'replace_dict' to do the operations above.</p>
<p>Expected output is:</p>
<pre><code>data=[['ABC', 'IN']]
df=pd.DataFrame(data,columns=['letters','State'])
</code></pre>
<p>by creating a function and then running the function with something along these lines</p>
<pre><code>for i in df_map:
for j in df_map[i]:
df= j(i, df)
</code></pre>
<p>how would i create a function to run these operations? I have not seen anyone try to do this with multiple dictionary keys in the replace_dict</p>
| [
{
"answer_id": 74271691,
"author": "Jason Baker",
"author_id": 3249641,
"author_profile": "https://Stackoverflow.com/users/3249641",
"pm_score": 1,
"selected": false,
"text": "def map_from_dict(data: pd.DataFrame, cols: list, mapping: dict) -> pd.DataFrame:\n return pd.DataFrame([data... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20384102/"
] |
74,270,892 | <p>Iβm currently learning a couple of programming languages, but I need to make something like a function that works as the following:</p>
<p>Imagine youβve a bag where you know youβve 5 blue balls, 2 yellow balls, 1 pink ball. And you want to take one ball out of the bag and check itβs color. So the ideia is that the array should be [blue, yellow, pink] and not [blue, blue, blueβ¦, yellow, yellow, pink]</p>
<p>Is it possible?</p>
<p>Iβm still learning the basics.</p>
| [
{
"answer_id": 74271691,
"author": "Jason Baker",
"author_id": 3249641,
"author_profile": "https://Stackoverflow.com/users/3249641",
"pm_score": 1,
"selected": false,
"text": "def map_from_dict(data: pd.DataFrame, cols: list, mapping: dict) -> pd.DataFrame:\n return pd.DataFrame([data... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19552966/"
] |
74,270,901 | <p>I am trying to find a regex that will pull out information between two dashes, but after a dash has already existed.</p>
<pre><code>I will list a few examples:
a = BRAND NAME - 34953 Some Information, PPF - 00003 - (3.355pz.) 300%
b = 893535 - MX LMESJFG - 01001 - ST2 | ls.33.dg - OK
c = 4539883 - AB05 - AG03J238B - | D.87.yes.4/3 - OK
What I want to pull out:
a = 00003
b = 01001
c = AG03J238B
</code></pre>
<p>I would greatly appreciate any help.</p>
| [
{
"answer_id": 74270983,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 3,
"selected": true,
"text": "split()"
},
{
"answer_id": 74282430,
"author": "grifway",
"author_id": 10376499,
"author_... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17135667/"
] |
74,270,903 | <p>Using beautifulsoup it is possible to do the following:</p>
<pre><code>for heading in soup.find_all('h1'):
print(heading.text)
Top Rated Movies
</code></pre>
<p>However, is there a method to extract the tags themselves, given the text? A way of working backwards from the above example, something like:</p>
<pre><code>soup.find_tag('Top Rated Movies')
h1
</code></pre>
| [
{
"answer_id": 74271051,
"author": "Theo64",
"author_id": 18708372,
"author_profile": "https://Stackoverflow.com/users/18708372",
"pm_score": 0,
"selected": false,
"text": "for tag in soup.findAll(True, text=\"Top Rated Movies\"):\n print(tag.name)\n"
},
{
"answer_id": 7427134... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219322/"
] |
74,270,904 | <p>I'm currently trying to read a csv file, add/delete/rename some columns using Pandas dataframe, and then write it back to the same file. However, a few of the files I'm using contain records which look like this:</p>
<pre><code>Column 1,Column 2,Column 3,Column 4
123," ",ABCD,"This, that, and this"
</code></pre>
<p>I was able to successfully get Pandas to understand "This, that, and this" and write it back to the csv exactly the same with the quotation marks and commas. But unfortunately I can't seem to get the empty space surrounded by quotations " ". It will just write it back like this:</p>
<pre><code>Column 1,Column 2,Column 3,Column 4
123, ,ABC,"This, that, and this"
</code></pre>
<p>My read looks like:</p>
<pre><code>f = pd.read_csv((mypath + file), skipinitialspace=True, quotechar='"')
</code></pre>
<p>And my write looks like:</p>
<pre><code>f.to_csv((mypath + file), index=False)
</code></pre>
| [
{
"answer_id": 74271051,
"author": "Theo64",
"author_id": 18708372,
"author_profile": "https://Stackoverflow.com/users/18708372",
"pm_score": 0,
"selected": false,
"text": "for tag in soup.findAll(True, text=\"Top Rated Movies\"):\n print(tag.name)\n"
},
{
"answer_id": 7427134... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13144557/"
] |
74,270,916 | <p>I'm trying to build widget with what I imagined to be a fair simple layout.</p>
<pre><code> ___________________
| |
| Title. |
| Subtitle | Static Content (more or less)
|___________________|
| |
| 1 Today |
| |
| 2 Tomorrow | Dynamic Content
| |
| 3 In 1 hour |
|___________________|
</code></pre>
<p>The issue is if any of the dynamic content is too big, it <em>pushes</em> the top content bar out the top of the widget, whereas I'd rather it grew out of the bottom. I can demonstrate this with this example:</p>
<p><a href="https://i.stack.imgur.com/WzQRF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WzQRF.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/t9mUT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t9mUT.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/FpZe0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FpZe0.png" alt="enter image description here" /></a></p>
<p>As you can can see, as green gets too big, it pushes pink off the screen. I can't find a way to fix this.</p>
<p>I've tried <code>ZStack(alignment: .top)</code>, I've tried <code>layoutPriority</code>, I've tried <code>fixedSize</code> and I've tried <code>Spacer</code></p>
| [
{
"answer_id": 74271051,
"author": "Theo64",
"author_id": 18708372,
"author_profile": "https://Stackoverflow.com/users/18708372",
"pm_score": 0,
"selected": false,
"text": "for tag in soup.findAll(True, text=\"Top Rated Movies\"):\n print(tag.name)\n"
},
{
"answer_id": 7427134... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7102356/"
] |
74,270,977 | <p>I'm trying to scrape IMDB for a list of the top 1000 movies and get some details about them. However, when I run it, instead of getting the first 50 movies and going to the next page for the next 50, it repeats the loop and makes the same 50 entries 20 times in my database.</p>
<pre><code># Dataframe template
data = pd.DataFrame(columns=['ID','Title','Genre','Summary'])
#Get page data function
def getPageContent(start=1):
start = 1
url = 'https://www.imdb.com/search/title/?title_type=feature&year=1950-01-01,2019-12-31&sort=num_votes,desc&start='+str(start)
r = requests.get(url)
bs = bsp(r.text, "lxml")
return bs
#Run for top 1000
for start in range(1,1001,50):
getPageContent(start)
movies = bs.findAll("div", "lister-item-content")
for movie in movies:
id = movie.find("span", "lister-item-index").contents[0]
title = movie.find('a').contents[0]
genres = movie.find('span', 'genre').contents[0]
genres = [g.strip() for g in genres.split(',')]
summary = movie.find("p", "text-muted").find_next_sibling("p").contents
i = data.shape[0]
data.loc[i] = [id,title,genres,summary]
#Clean data
# data.ID = [float(re.sub('.','',str(i))) for i in data.ID] #remove . from ID
data.head(51)
</code></pre>
<p>0 1. The Shawshank Redemption [Drama] [\nTwo imprisoned men bond over a number of ye...
1 2. The Dark Knight [Action, Crime, Drama] [\nWhen the menace known as the Joker wreaks h...
2 3. Inception [Action, Adventure, Sci-Fi] [\nA thief who steals corporate secrets throug...
3 4. Fight Club [Drama] [\nAn insomniac office worker and a devil-may-...
...
46 47. The Usual Suspects [Crime, Drama, Mystery] [\nA sole survivor tells of the twisty events ...
47 48. The Truman Show [Comedy, Drama] [\nAn insurance salesman discovers his whole l...
48 49. Avengers: Infinity War [Action, Adventure, Sci-Fi] [\nThe Avengers and their allies must be willi...
49 50. Iron Man [Action, Adventure, Sci-Fi] [\nAfter being held captive in an Afghan cave,...
50 1. The Shawshank Redemption [Drama] [\nTwo imprisoned men bond over a number of ye...</p>
| [
{
"answer_id": 74271158,
"author": "Carl_M",
"author_id": 7803702,
"author_profile": "https://Stackoverflow.com/users/7803702",
"pm_score": 0,
"selected": false,
"text": "# Dataframe template\ndata = pd.DataFrame(columns=['ID', 'Title', 'Genre', 'Summary'])\n\n\n# Get page data function\... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20384198/"
] |
74,270,979 | <p>I have this array of object, I want to extract its ids.</p>
<pre><code>const arr = [
{
"id": "1",
},
{
"id": "2",
"options": [
{
"id": "2.1",
}
]
},
]
</code></pre>
<p>I did this</p>
<pre><code>const one = arr.map(ob => ob.id)
const two = arr.flatMap(ob => ob.options).map(ob => ob?.id).filter(Boolean)
console.log([...one, ...two])
</code></pre>
<p>which worked fine, it prints <code>['1', '2', '2.1']</code> which is what I wanted but is there any simpler or shorter way to do it?</p>
| [
{
"answer_id": 74271008,
"author": "CertainPerformance",
"author_id": 9515207,
"author_profile": "https://Stackoverflow.com/users/9515207",
"pm_score": 2,
"selected": true,
"text": ".concat"
},
{
"answer_id": 74271469,
"author": "Andrew Parks",
"author_id": 5898421,
"... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19637481/"
] |
74,270,987 | <p>How to find the number of rows and columns in QGridlayout ?, In my code, I have Buttons arranged in QGridLayout. Now I need to find out the total number of columns and the total number of rows.</p>
<pre><code>from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class Widget(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("QGridlayout")
self.btn1 = QPushButton("Button_1")
self.btn2 = QPushButton("Button_2")
self.btn3 = QPushButton("Button_3")
self.btn4 = QPushButton("Button_4")
self.btn4.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.MinimumExpanding)
self.btn5 = QPushButton("Button_5")
self.btn6 = QPushButton("Button_6")
self.btn7 = QPushButton("Button_7")
self.btn8 = QPushButton("Button_8")
self.btn9 = QPushButton("Button_9")
self.gl = QGridLayout()
self.gl.addWidget(self.btn1,1,0,1,1,Qt.AlignCenter)
self.gl.addWidget(self.btn2,0,1,1,1)
self.gl.addWidget(self.btn3,0,2,1,1)
self.gl.addWidget(self.btn4,0,3,2,1)
self.gl.addWidget(self.btn5,1,0,1,2)
self.gl.addWidget(self.btn6,2,0,1,3)
self.gl.addWidget(self.btn7,3,0,1,4)
self.gl.addWidget(self.btn8,1,2,1,1)
self.gl.setRowStretch(4,1)
self.gl.setColumnStretch(2,1)
self.gl.setSpacing(1)
self.setLayout(self.gl)
print(self.gl.count())
# print(self.gl.rowcount())
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
</code></pre>
| [
{
"answer_id": 74271044,
"author": "Alexander",
"author_id": 17829451,
"author_profile": "https://Stackoverflow.com/users/17829451",
"pm_score": 2,
"selected": false,
"text": "QGridLayout.columnCount()"
},
{
"answer_id": 74271050,
"author": "Elijah Nicol",
"author_id": 14... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74270987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13496839/"
] |
74,271,010 | <p>hello i need some function going to run after a link before another page.</p>
<p>for example.</p>
<p>this is main.html</p>
<pre><code><div>
<a href="another.html" onclick="linkPopup()" target="_blank" title="popup"></a>
</div>
</code></pre>
<blockquote>
<p>and when click tag.</p>
</blockquote>
<p>another.html loaded and open popup inside in function exist already in another.html</p>
<p>another.html
open popup!</p>
<p>like this.</p>
| [
{
"answer_id": 74271044,
"author": "Alexander",
"author_id": 17829451,
"author_profile": "https://Stackoverflow.com/users/17829451",
"pm_score": 2,
"selected": false,
"text": "QGridLayout.columnCount()"
},
{
"answer_id": 74271050,
"author": "Elijah Nicol",
"author_id": 14... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18370873/"
] |
74,271,092 | <p>Any time I try to use more than 1 networking library in the same (CMake) project, there are many Winsock redefinition errors. These libraries are <code>asio</code>, <code>SteamAPI</code>, <code>libssh</code>, and <code>SDL_net</code> to name a few.</p>
<p><a href="https://i.stack.imgur.com/xzi4J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xzi4J.png" alt="redefinition errors" /></a></p>
<p>I turned to Google for answers, and there are many posts regarding this issue. Many people have proposed how to fix this such as defining <code>WIN32_LEAN_AND_MEAN</code> before including <code>Windows.h</code>, or not including <code>Windows.h</code> twice... I have removed all usages of <code>Windows.h</code>. I have also tried many variations of the answers in the hope of getting my program to compile. This makes no difference.</p>
<p>Among all of the available answers, there is not one single answer that solves this issue. Most of the answers do point to this being a WindowsAPI-only issue due to it trying to include the old <code>Winsock.h</code>.</p>
<p>Is there any way to use the networking libraries mentioned above simultaneously without these errors?</p>
| [
{
"answer_id": 74271093,
"author": "crazicrafter1",
"author_id": 9044814,
"author_profile": "https://Stackoverflow.com/users/9044814",
"pm_score": -1,
"selected": false,
"text": "Windows.h"
},
{
"answer_id": 74271312,
"author": "Remy Lebeau",
"author_id": 65863,
"auth... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9044814/"
] |
74,271,101 | <p>I am new to SwiftUI from UIKit and I have a question regarding the behavior of the TextField.</p>
<pre><code>struct ContentView: View {
@State private var text = ""
@State private var words: [String] = []
var body: some View {
Form {
Section {
TextField("Input", text: $text) {
words.insert(text, at: 0)
text = ""
}
}
Section {
Button("Clear") {
text = ""
}
}
Section {
ForEach(words, id: \.self) { word in
Text(word)
}
}
}
}
}
</code></pre>
<p>The behavior I would like to do is to clear the text and add it to a list. After the input the text field will be cleared. The problem now is that <code>text = ""</code> is called but it didn't clean up the field. However, by having a separate button below it works correctly.</p>
<p>For the context, I need to set the minimum deployment version to <code>iOS14</code> and I am using <code>Xcode 14.0.1</code>.</p>
<p><a href="https://i.stack.imgur.com/maJR4.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/maJR4.gif" alt="sample" /></a></p>
<p>I have tried to move it to a function but didn't help either.</p>
| [
{
"answer_id": 74271093,
"author": "crazicrafter1",
"author_id": 9044814,
"author_profile": "https://Stackoverflow.com/users/9044814",
"pm_score": -1,
"selected": false,
"text": "Windows.h"
},
{
"answer_id": 74271312,
"author": "Remy Lebeau",
"author_id": 65863,
"auth... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17671818/"
] |
74,271,106 | <p>Appreciate your help. I have an issue with the setValues in handleChange function, after the first onChange Event happens the form seems to reloaded and can't do more changes to the field. All I've been trying to do is to create a reusable form fields.</p>
<p>I have created a file BuildForm.js which has a custom hook that return the fields.</p>
<pre><code>import { useState } from 'react';
const BuildForm = () => {
const [values, setValues] = useState({});
const [errors, setErrors] = useState({});
const validate = (name, value) => {
switch (name) {
case 'first_name':
if(value.trim() === ''){
errors[name] = 'First Name is Rrequired.';
setErrors(errors);
}
else{
errors[name] = '';
setErrors(errors);
}
break;
case 'last_name':
if(value.trim() === ''){ setErrors({...errors, [name]:'Last Name is Rrequired.'}); }
else{
setErrors({...errors, [name]:''});
}
break;
default:
break;
}
};
const handleChange = (event) => {
// event.persist();
let name = event.target.name;
let value = event.target.value;
validate(name, value);
setValues({...values, [name]:value}); // this is line with the issue
console.log(name, value);
};
const Name = (props) => {
return(
<div className="fullwidth">
<p className="description"><strong>{props.label}</strong></p>
<div className="firstname halfwidth left">
<label htmlFor="first_name">FIRST</label>
<input type="text" name="first_name" onChange={handleChange}/>
{ errors.first_name && <p className="validation">{errors.first_name}</p> }
</div>
<div className="lastname halfwidth right">
<label htmlFor="last_name">LAST</label>
<input type="text" name="last_name" onChange={handleChange} />
{ errors.last_name && <p className="validation">{errors.last_name}</p> }
</div>
</div>
);
};
return {
Name,
}
};
export default BuildForm;
</code></pre>
<p>and in the other file FirstForm.js where my form goes, i have this code</p>
<pre><code>import './App.css';
import React, {useState} from 'react';
import { Link, Routes, Route, useNavigate } from 'react-router-dom';
import BuildForm from './Hooks/BuildForm';
function FirstForm() {
const navigate = useNavigate();
const MyForm = BuildForm();
return (
<div className="App">
<div id="header">
<img src={logo} className="logo" alt="logo"/>
</div>
<div id="pagebody">
<div id="formcontainer">
<form id="myForm">
<MyForm.Name label="Client Name"/>
<div className="submitbutton fullwidth"><input type="submit" /></div>
</form>
</div>
</div>
</div>
);
}
export default FirstForm;
</code></pre>
| [
{
"answer_id": 74271093,
"author": "crazicrafter1",
"author_id": 9044814,
"author_profile": "https://Stackoverflow.com/users/9044814",
"pm_score": -1,
"selected": false,
"text": "Windows.h"
},
{
"answer_id": 74271312,
"author": "Remy Lebeau",
"author_id": 65863,
"auth... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14411043/"
] |
74,271,123 | <p>I am working with WKWebView and loaded url in the same web-view which is having login page (email and password input text).</p>
<p>email input text field like this:</p>
<p><code><input class="input" type="email" placeholder="" data-automation-id="email" name="email" maxlength="256" value=""></code></p>
<p>Can someone guide me that how to get the value this input text?</p>
<pre><code> webView.evaluateJavaScript("document.getElementById('email').value", completionHandler: { (jsonRaw: Any?, error: Error?) in
guard let jsonString = jsonRaw as? String else { return }
print(js)
})
</code></pre>
<p>Tried this but not working :(</p>
<p>TIA</p>
| [
{
"answer_id": 74271161,
"author": "HangarRash",
"author_id": 20287183,
"author_profile": "https://Stackoverflow.com/users/20287183",
"pm_score": 0,
"selected": false,
"text": "input"
},
{
"answer_id": 74272142,
"author": "RTXGamer",
"author_id": 6576315,
"author_prof... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/788631/"
] |
74,271,134 | <p>I work on making a common function in PHP to update table because I have a lot of forms update MySQL tables. It is working fine and it update my table: below is my code with some comments:</p>
<pre><code><?php
include('../config.php');
if (isset($_POST['loginfo'])) {
$table = "users";
$creteria = "id =?";
if (update_table($table,$creteria)){
echo "<h1> Successfully Updated Table: ". $table. "</h1>";
}
}
function update_table($tablename,$creteria) {
$conn = new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE ".$tablename. " SET ";
$postdata = $_POST;
$count = count($postdata);
$nonempty = count(array_filter($postdata, function($x) { return ($x !== ""); }));
$i = 0;
$vartype = "";
foreach ($postdata as $key => $value) {
$i++;
if (!empty($value)) {
$nonempty--;
$sql .= " $key = ? ";
if ($nonempty >0) {
$sql .= " ,";
}
if(is_int($value)){
$vartype .= "i";
} else {
$vartype .= "s";
}
}
}
$sql .= "WHERE ".$creteria;
$vartype .= "i";
$stmt = $conn->prepare($sql);
$params = array(&$fullname, &$email, &$phone, &$id);// this line must be out side function
call_user_func_array(array($stmt, "bind_param"), array_merge(array($vartype), $params));
$fullname = $_POST['fullname']; // fullname,email,phone, id must be out of function
$email = $_POST['email'];
$phone = $_POST['phone'];
$id = $_POST['id'];
$stmt->execute();
$stmt->close();
$conn->close();
return true;
}
?>
</code></pre>
<p>How to put $params array, out side function? So I can pass different parameters regarding submitted form?</p>
| [
{
"answer_id": 74271620,
"author": "Tural Rzaxanov",
"author_id": 9922647,
"author_profile": "https://Stackoverflow.com/users/9922647",
"pm_score": -1,
"selected": false,
"text": "$paramsGlobal = ['name'=> 'Tural Rza'];\n\nfunction update_table($tablename,$creteria) {\n global $params... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19602457/"
] |
74,271,140 | <p>Let's say that I have <code>model</code> like:</p>
<pre class="lang-py prettyprint-override"><code>class User(AbstractUser):
...
seller = models.ForeignKey(Seller, related_name="user", on_delete=models.SET_NULL, null=True)
...
</code></pre>
<p>And I trying to get <code>seller</code> email address using this code:</p>
<pre class="lang-py prettyprint-override"><code>from app.models import User
from django_print_sql import print_sql
with print_sql(count_only=False):
users = User.objects.filter(is_active=True, seller_id__isnull=False).select_related().only('seller__email')
for u in users.iterator():
email = u.seller.email
send_email(email)
</code></pre>
<p>In this case I can see SQL queries like:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT `user`.`id`,
`user`.`seller_id`
FROM `user`
WHERE (`user`.`is_active`
AND `user`.`seller_id` IS NOT NULL)
...
SELECT `seller`.`id`,
...
`seller`.`email`,
...
FROM `seller`
WHERE `seller`.`id` = 1
...
</code></pre>
<p>The problem is Django ORM accessing DB at every iteration (<code>Select seller... where seller.id = ...</code>). So that will be too many queries (== DB connections) if we have many sellers.</p>
<p>In other way it is possible to replace <code>only</code> with <code>values</code>:</p>
<pre class="lang-py prettyprint-override"><code>from app.models import User
from django_print_sql import print_sql
with print_sql(count_only=False):
users = User.objects.filter(is_active=True, seller_id__isnull=False).select_related().values('seller__email')
for u in users.iterator():
email = u['seller__email']
send_email(email)
</code></pre>
<p>And I can see SQL query like:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT `seller`.`email`
FROM `user`
INNER JOIN `seller` ON (`user`.`seller_id` = `seller`.`id`)
WHERE (`user`.`is_active`
AND `user`.`seller_id` IS NOT NULL)
</code></pre>
<p>It is little bit better and we able to get emails by single DB query, but <code>iterator</code> is useless here because we load all emails once inside <code>dict</code> object and whole data exists inside memory.</p>
<p><strong>The question is</strong><br />
Is it possible to iterate by data chunks (Let say by 500 emails/single query) without create manual sub-loops limiting <code>User.objects.filter</code> query count? Or in other words, what is most effective iterator in this case?</p>
| [
{
"answer_id": 74271620,
"author": "Tural Rzaxanov",
"author_id": 9922647,
"author_profile": "https://Stackoverflow.com/users/9922647",
"pm_score": -1,
"selected": false,
"text": "$paramsGlobal = ['name'=> 'Tural Rza'];\n\nfunction update_table($tablename,$creteria) {\n global $params... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13946204/"
] |
74,271,153 | <p>I have a string of values separated by semicolon.</p>
<pre><code>$str = 'value 12; another value; yet one more one; val5';
</code></pre>
<p>I also have an array where the keys correspond to the values in the string above.</p>
<p>How do I replace the values in the string with the values from the array? Now, I think I can explode the string by semi-colon and trim the space</p>
<pre><code>$arr = array_map('trim', explode(';', $str));
</code></pre>
<p>Do I need to run the array through a loop and use the values as keys and then implode it back? Is there a faster way?</p>
| [
{
"answer_id": 74271620,
"author": "Tural Rzaxanov",
"author_id": 9922647,
"author_profile": "https://Stackoverflow.com/users/9922647",
"pm_score": -1,
"selected": false,
"text": "$paramsGlobal = ['name'=> 'Tural Rza'];\n\nfunction update_table($tablename,$creteria) {\n global $params... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/434218/"
] |
74,271,154 | <p>I intend to develop a command line tool by C in the CentOS, with the following code:</p>
<pre><code>// client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <termios.h>
int main(int argc, char *argv[])
{
char command[128];
while (1)
{
memset(command, 0, 128);
printf("cli > ");
if (fgets(command, 128, stdin) != NULL)
{
if (strcmp(command, "exit\n") == 0)
break;
if (strcmp(command, "\n") == 0)
continue;
printf("do something ... %s", command);
}
}
return 0;
}
</code></pre>
<p>The program can works, but it doesn't execute the way I expect it to when I press the arrow keys.</p>
<p>I have finished typing a simple SQL and now the cursor stays after the semicolon.</p>
<pre><code>[root@olap tests]# gcc client.c
[root@olap tests]# ./a.out
cli > selectt * from table_001;
</code></pre>
<p>But I misspelled the first keyword, it should be <code>select</code>, not <code>selectt</code>.
I am now pressing the left arrow key(β) to try to fix this mistake.
But the cursor didn't move properly as I expected, and it turned into the following.</p>
<pre><code>[root@olap tests]# gcc client.c
[root@olap tests]# ./a.out
cli > selectt * from table_001;^[[D^[[D^[[D^[[D^[[D^[[D^[[D
</code></pre>
<p>How should I modify the program to solve this problem?</p>
<p>I hope get help from people who are good at C development.</p>
<p>Thank you all</p>
| [
{
"answer_id": 74271620,
"author": "Tural Rzaxanov",
"author_id": 9922647,
"author_profile": "https://Stackoverflow.com/users/9922647",
"pm_score": -1,
"selected": false,
"text": "$paramsGlobal = ['name'=> 'Tural Rza'];\n\nfunction update_table($tablename,$creteria) {\n global $params... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10984855/"
] |
74,271,155 | <p>I am trying to resolve the error as highlighted in the picture below. I am able to print a tic-tac-toe board but the trailing whitespace affects the test case. I am not better yet at using strings to represent a list of numbers. The desired output is embedded in the image below:
<img src="https://i.stack.imgur.com/RjNMA.png" alt="test case error " /></p>
<pre><code>def printBoard(plane):#function to print out the current board
for w in range(len(plane)):
for e in range(len(plane)):
if plane[w][e]== 1:
print('{:^3}'.format('X'), end="")
elif plane[w][e] == -1:
print('{:^3}'.format('O'), end="")
elif plane[w][e] == 0:
print('{:^3d}'.format((len(plane)*w+e)), end="")
print()
</code></pre>
| [
{
"answer_id": 74271338,
"author": "Chris Lindseth",
"author_id": 16856522,
"author_profile": "https://Stackoverflow.com/users/16856522",
"pm_score": 1,
"selected": false,
"text": "print('{:3d}'.format((len(plane)*w+e)), end=\"\")\n"
},
{
"answer_id": 74271518,
"author": "Mar... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17990967/"
] |
74,271,180 | <pre><code>param (
[string]$ComputerName="Server01",
[string[]]$SEARCHTERMS=@("Unifi","Edge"),
[string]$IPAddress='10.11.12.243', #Dangling comma that i never see.
)
</code></pre>
<p>There must be a ... AND 1=1; trick like what is commonly done in sql statements to move parameters around without much thought.</p>
| [
{
"answer_id": 74271335,
"author": "mklement0",
"author_id": 45375,
"author_profile": "https://Stackoverflow.com/users/45375",
"pm_score": 2,
"selected": false,
"text": "PROBLEMS"
},
{
"answer_id": 74271687,
"author": "rjt",
"author_id": 711422,
"author_profile": "htt... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/711422/"
] |
74,271,183 | <p>could someone please explain why this code produces. i was able to narrow the error to this segment regardless of what I set the map value to.</p>
<blockquote>
<p>C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.33.31629\include\xstddef(117,1): error C2784: 'bool std::operator <(std::nullptr_t,const std::shared_ptr<_Ty> &) noexcept': could not deduce template argument for 'const std::shared_ptr<_Ty> &' from 'const _Ty'</p>
</blockquote>
<pre><code>struct Vector2i
{
int x;
int y;
};
std::map<Vector2i, Chunk*> map{};
map.insert({ Vector2i{0,0}, nullptr });
</code></pre>
<p>thanks :)</p>
<p>I tried commenting out all other instances of the Vector2i struct and this segment seemed to be the only place that causes this error.</p>
| [
{
"answer_id": 74271206,
"author": "paddy",
"author_id": 1553090,
"author_profile": "https://Stackoverflow.com/users/1553090",
"pm_score": 2,
"selected": false,
"text": "operator<"
},
{
"answer_id": 74271270,
"author": "GAVD",
"author_id": 4983082,
"author_profile": "... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18535146/"
] |
74,271,193 | <p>Say I have a 2-D numpy array,</p>
<pre class="lang-py prettyprint-override"><code>A = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] # Shape: (3, 4)
</code></pre>
<p>and I have another 1-D array,</p>
<pre class="lang-py prettyprint-override"><code>B = [0, 2, 1] # Shape: (3,)
</code></pre>
<p>I want to extract an element from the index of A's ith row corresponding to B's ith element.
Meaning, if we consider the 3nd element in B, output will be 2nd element of 3rd row of A (that is, 9).</p>
<p>Thus, the desired output is:</p>
<pre class="lang-py prettyprint-override"><code>C = [0, 6, 9]
</code></pre>
<p>Now, this can easily be done using a <code>for loop</code>, however, I am looking for some other optimized ways of doing this.</p>
<p>I tried <code>np.take()</code>, however it's not working as desired.</p>
| [
{
"answer_id": 74271298,
"author": "Michael Delgado",
"author_id": 3888719,
"author_profile": "https://Stackoverflow.com/users/3888719",
"pm_score": 2,
"selected": true,
"text": "In [4]: A[range(A.shape[0]), B]\nOut[4]: array([0, 6, 9])\n"
},
{
"answer_id": 74271305,
"author"... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13657037/"
] |
74,271,226 | <p>I have this snip in two different projects, and for some reason its not working on my current project:</p>
<pre><code> Padding(
padding: const EdgeInsets.only(left: 80, right: 80),
child: Image.asset('assets/images/logo.png'),
),
</code></pre>
<p>Here is the structure of the files</p>
<p><a href="https://i.stack.imgur.com/Gsuwg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gsuwg.png" alt="tree" /></a></p>
<p>The error below says the asset is not found?</p>
<p>I also tried to move the image into the same file but it didnt work</p>
<pre><code>ββββββββ Exception caught by image resource service ββββββββββββββββββββββββββββ
The following assertion was thrown resolving an image codec:
Unable to load asset: assets/images/logo.png.
When the exception was thrown, this was the stack
#0 PlatformAssetBundle.loadBuffer
#1 AssetBundleImageProvider._loadAsync
#2 AssetBundleImageProvider.loadBuffer
#3 ImageProvider.resolveStreamForKey.<anonymous closure>
#4 ImageCache.putIfAbsent
#5 ImageProvider.resolveStreamForKey
#6 ScrollAwareImageProvider.resolveStreamForKey
#7 ImageProvider.resolve.<anonymous closure>
#8 ImageProvider._createErrorHandlerAndKey.<anonymous closure>
#9 SynchronousFuture.then
#10 ImageProvider._createErrorHandlerAndKey
#11 ImageProvider.resolve
#12 _ImageState._resolveImage
#13 _ImageState.reassemble
#14 StatefulElement.reassemble
#15 Element.reassemble.<anonymous closure>
#16 SingleChildRenderObjectElement.visitChildren
#17 Element.reassemble
#18 Element.reassemble.<anonymous closure>
#19 SingleChildRenderObjectElement.visitChildren
#20 Element.reassemble
#21 Element.reassemble.<anonymous closure>
#22 SingleChildRenderObjectElement.visitChildren
....
....
...
#595 BindingBase.registerSignalServiceExtension.<anonymous closure>
#596 BindingBase.registerServiceExtension.<anonymous closure>
<asynchronous suspension>
Image provider: AssetImage(bundle: null, name: "assets/images/logo.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#3359f(), name: "assets/images/logo.png", scale: 1.0)
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Reloaded 1 of 1363 libraries in 356ms (compile: 20 ms, reload: 128 ms, reassemble: 177 ms).
D/EGL_emulation( 6231): app_time_stats: avg=1439.65ms min=27.34ms max=2851.96ms count=2
ββββββββ Exception caught by image resource service ββββββββββββββββββββββββββββ
Unable to load asset: assets/images/logo.png.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
</code></pre>
<p>this is the pubspec.yaml file::
assets:
- lib/assets/images/
- lib/assets/images/logo.png</p>
| [
{
"answer_id": 74271277,
"author": "pmatatias",
"author_id": 12838877,
"author_profile": "https://Stackoverflow.com/users/12838877",
"pm_score": 2,
"selected": false,
"text": "pubspec.yaml"
},
{
"answer_id": 74283642,
"author": "Juan Casas",
"author_id": 17281101,
"au... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17281101/"
] |
74,271,237 | <p>I have I have a column <code>address</code> with the string like this:</p>
<p><code>Tow 10 Floor 223, Ward AA BB, District CC DD, City E F</code></p>
<p>and</p>
<p><code>Tow 110 Floor 23, Ward BB AA, District DD CC, City F E</code></p>
<p><code>...</code></p>
<p>(more than 10000 lines)</p>
<p>I want to split this string into separate columns, remove the characters after the 2nd comma and insert column with split value into my table.</p>
<p>Look like this:</p>
<hr />
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Tow</th>
<th>Floor</th>
<th>Ward</th>
</tr>
</thead>
<tbody>
<tr>
<td>10</td>
<td>223</td>
<td>AA BB</td>
</tr>
<tr>
<td>110</td>
<td>23</td>
<td>BB AA</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74271277,
"author": "pmatatias",
"author_id": 12838877,
"author_profile": "https://Stackoverflow.com/users/12838877",
"pm_score": 2,
"selected": false,
"text": "pubspec.yaml"
},
{
"answer_id": 74283642,
"author": "Juan Casas",
"author_id": 17281101,
"au... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19532517/"
] |
74,271,261 | <p>I am using tinymce in inline mode and am new to the tool.
I've gotten my text field input to look how I want with minimal editing buttons.
However, I am stumped on how to remove the "Upgrade" button from the toolbar when the text field is active.</p>
<p><a href="https://i.stack.imgur.com/rS7KR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rS7KR.png" alt="enter image description here" /></a></p>
<p>Is this even possible?</p>
<p>Here is the initialization that I am using.
I am using a self-hosted community installation on a WAMP server.</p>
<p>`</p>
<pre><code><script>
tinymce.init({
selector: '#addressinput',
inline: true,
toolbar: 'bold underline italic superscript',
menubar: '',
branding: false,
force_br_newlines : true,
min_height: 100
});
</script>
</code></pre>
<p>`</p>
| [
{
"answer_id": 74271428,
"author": "RobinJoe",
"author_id": 16551229,
"author_profile": "https://Stackoverflow.com/users/16551229",
"pm_score": 2,
"selected": false,
"text": "tinymce.init({\n//other configuration,\npromotion: false\n});\n\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20384417/"
] |
74,271,267 | <p>It's my first time in this forum and I wanted to start with this question.
For what I know, in C, a char data type is 8 bits long, but when you are using this data type in order to transmit ASCII information, is still 8 bits long but 1 bit is a parity bit, is that right?</p>
<p>And if that's correct, my question is, can you transmit an ASCII char to a receiver including the parity bit? Because if my code is:
.....
char x=0b01111000;
.....
it is received 'x', but if my code is:
....
char x=0b11111000;
....
it isn't received 'x', but the parity bit is in 1, and there are 4 '1' in my 'x' data, so I don't get when to use the parity bit or what I'm doing wrong.
Thanks in advance for your answers!</p>
<p>.........................</p>
| [
{
"answer_id": 74271539,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 2,
"selected": false,
"text": "char"
},
{
"answer_id": 74271611,
"author": "JaMiT",
"author_id": 9837301,
"author_profil... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20384406/"
] |
74,271,300 | <p>I've been working on do loops for python although there isn't one for the language. I am trying to get the average of certain integers entered until a negative integer is entered. I was able to get the program working, instead it gives me the wrong results after entering the numbers and getting the average. For instance, if I provide a set of 5 numbers, and then enter a negative number to calculate it, it gives me an answer of 1.0. I would like some advice on how to get rid of this issue to get the accurate answers for finding the average from the 5 set of numbers entered.</p>
<blockquote>
<p>Will process and calculate the average
totalScore = 0
getTestScore: int = 0
total = getTestScore + 1
count = getTestScore
count: int = count + 1
totalScore = getTestScore()
averageTestScore = float(totalScore) / count</p>
<p>return averageTestScore</p>
</blockquote>
<pre class="lang-py prettyprint-override"><code> # Do loop function
total = 0
count = 0
totalTestScore = total + 1
average = calculateAverage(totalTestScore, count)
while True: #This simulates a Do Loop
testScore = getTestScore()
totalTestScore = total + 1
count = count + 1
if not(testScore >= 0): break #Exit loop
calculateAverage(totalTestScore, count)
return average
</code></pre>
<p>I'm unsure of where I went wrong to get the same answer, 1.0 for every different number I enter.</p>
<p>I tried changing around the positions of where they were on the line and how they were indented to make sure it was corrects. The program plan I wrote is very simple and I'm trying not to drastically change it to not match my program plan.</p>
| [
{
"answer_id": 74271539,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 2,
"selected": false,
"text": "char"
},
{
"answer_id": 74271611,
"author": "JaMiT",
"author_id": 9837301,
"author_profil... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20006407/"
] |
74,271,324 | <p>I am trying to create a Log in and Registration for a Django Rest Framework but I keep getting <code>django.urls.exceptions.NoReverseMatch: 'user' is not a registered namespace</code> not sure what is the reason for getting this error and how to fix it?</p>
<p>Here is the serializers.py:</p>
<pre><code>class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["id", "first_name", "last_name", "username"]
class RegisterSerializer(serializers.ModelSerializer):
email = serializers.EmailField(
required=True,
validators=[UniqueValidator(queryset=User.objects.all())]
)
password = serializers.CharField(
write_only=True, required=True, validators=[validate_password])
password2 = serializers.CharField(write_only=True, required=True)
class Meta:
model = User
fields = ('username', 'password', 'password2',
'email', 'first_name', 'last_name')
extra_kwargs = {
'first_name': {'required': True},
'last_name': {'required': True}
}
def validate(self, attrs):
if attrs['password'] != attrs['password2']:
raise serializers.ValidationError(
{"password": "Password fields didn't match."})
return attrs
def create(self, validated_data):
user = User.objects.create(
username=validated_data['username'],
email=validated_data['email'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name']
)
user.set_password(validated_data['password'])
user.save()
return user
</code></pre>
<p>Here is the views.py:</p>
<pre><code>class UserDetailAPI(APIView):
authentication_classes = (TokenAuthentication,)
permission_classes = (AllowAny,)
def get(self,request,*args,**kwargs):
user = User.objects.get(id=request.user.id)
serializer = UserSerializer(user)
return Response(serializer.data)
class RegisterUserAPIView(generics.CreateAPIView):
permission_classes = (AllowAny,)
serializer_class = RegisterSerializer
</code></pre>
<p>Here is the urls.py</p>
<pre><code> path('get-details/', UserDetailAPI.as_view()),
path('register', RegisterUserAPIView.as_view()),
</code></pre>
<p>Here is the traceback:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inne
r
response = get_response(request)
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_res
ponse
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\views\generic\base.py", line 103, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\contrib\auth\mixins.py", line 72, in dispatch
return self.handle_no_permission()
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\contrib\auth\mixins.py", line 51, in handle_n
o_permission
resolved_login_url = resolve_url(self.get_login_url())
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\shortcuts.py", line 145, in resolve_url
return reverse(to, args=args, kwargs=kwargs)
File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\urls\base.py", line 82, in reverse
raise NoReverseMatch("%s is not a registered namespace" % key)
django.urls.exceptions.NoReverseMatch: 'user' is not a registered namespace
</code></pre>
| [
{
"answer_id": 74271969,
"author": "Sunderam Dubey",
"author_id": 17562044,
"author_profile": "https://Stackoverflow.com/users/17562044",
"pm_score": 3,
"selected": true,
"text": "app_name=\"user\""
},
{
"answer_id": 74272339,
"author": "Ubaydullo Ibrohimov",
"author_id":... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13176726/"
] |
74,271,330 | <p>I have a dataframe where each respondent provides a score to two profiles. Here is how the data is formated. I am looking to remove the NAs such that <code>score_1</code> and <code>score_2</code> are only scores, without NAs. Obviously this would reduce the number of rows, eliminate the profile column, and reduce the id column to one index per respondent (instead of the actual 2). Is there anyway to do this?</p>
<pre><code>df <- data.frame(
score_1 = c(1, NA, 4, NA, 9, NA, 12, NA),
score_2 = c(NA, 4, NA, 29, NA, 12, NA, 9),
profile = c(1, 2, 1, 2, 1, 2, 1, 2),
id = c(1, 1, 2, 2, 3, 3, 4, 4),
id_attribute = c(2, 2, 4, 4, 8, 8, 5, 5)
)
score_1 score_2 profile id id_attribute
1 1 NA 1 1 2
2 NA 4 2 1 2
3 4 NA 1 2 4
4 NA 29 2 2 4
5 9 NA 1 3 8
6 NA 12 2 3 8
7 12 NA 1 4 5
8 NA 9 2 4 5
</code></pre>
<p>This is how I see the final df:</p>
<pre><code>df_final <- data.frame(
score_1 = c(1, 4, 9, 12),
score_2 = c(4, 29, 12, 9),
id = c(1, 2, 3, 4),
id_attribute = c(2, 4, 8, 5)
)
score_1 score_2 id id_attribute
1 1 4 1 2
2 4 29 2 4
3 9 12 3 8
4 12 9 4 5
</code></pre>
<p>My intention is to substract each score with the <code>id_attribute</code>, which I can only do if NAs are removed.</p>
| [
{
"answer_id": 74271400,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "tidyr::fill()"
},
{
"answer_id": 74271497,
"author": "KaiLi",
"author_id": 13866098,
"author_pr... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12087716/"
] |
74,271,377 | <p>In my project i am trying to fetch in one time more than 5 API's together, but when i fetch using useEffect, it's continuously fetching, never stop fetching. so for that i want to set a limit for that.</p>
<p>is that possible to set a limit on useEffect to fetch 10 times and then it will stop fetching automatically?</p>
<p>Here is my codes:</p>
<pre><code>
const [dosa, setDosa] = useState([]);
const hola= () => {
const haspi = dv?.map((id) => {
fetch(`https://www.roads.com/roads/roadscontroll/${id}`)
.then((response) => response.json())
.then((dosa) => setDosa((prev) => [...prev, [dosa]))
.catch((error) => console.error(error))
})
return haspi ;
}
useEffect(() => {
hola();
});
</code></pre>
<p>here it's fetching continuously, so i want to set a limit for that.
how can i do that for my codes? any one can help me to do that.
Thanks for your helping in advance!</p>
<p><strong>Note: for security reason i am using here false API.</strong></p>
| [
{
"answer_id": 74271400,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "tidyr::fill()"
},
{
"answer_id": 74271497,
"author": "KaiLi",
"author_id": 13866098,
"author_pr... | 2022/11/01 | [
"https://Stackoverflow.com/questions/74271377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20376152/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.