qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,245,859 | <p>image-1:</p>
<p><a href="https://i.stack.imgur.com/FPwMO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FPwMO.png" alt="enter image description here" /></a></p>
<p>image-2:</p>
<p><a href="https://i.stack.imgur.com/0EuB8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0EuB8.png" alt="enter image description here" /></a></p>
<p>I have a project that contains several interfaces, and among these interfaces there is an interface that displays two tables through “Tabs”, when I click on the first tab it displays the first table and when I click on the second tab it displays the second table, but my problem is only in the style of the Tabs and not my problem In the content, I want the style of the second image to be the same as the style of the first image</p>
<p>file.tsx:</p>
<pre><code>import _ from 'lodash';
import { FunctionComponent } from 'react';
import { Tabs } from 'antd';
import AllPatients from './components/all-patients';
import AllPresentPatient from './components/present-patients';
import { FormattedMessage } from 'react-intl';
const { TabPane } = Tabs;
interface PatientListPageProps { }
const PatientListPage: FunctionComponent<PatientListPageProps> = () => {
return (
<>
<div style={{ background: '#fff', padding: '16px', borderColor: 'transparent', borderRadius: '4px' }}>
<Tabs type="card">
<Tabs.TabPane
tab={<FormattedMessage id='all' />} key="1">
<AllPatients />
</Tabs.TabPane>
<Tabs.TabPane tab={<FormattedMessage id='attendees' />} key="2">
<AllPresentPatient />
</Tabs.TabPane>
</Tabs>
</div>
</>
);
};
export default PatientListPage;
</code></pre>
| [
{
"answer_id": 74245873,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": false,
"text": "widget."
},
{
"answer_id": 74245985,
"author": "Yeasin Sheikh",
"author_id": 10157127,
"au... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74245859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16377085/"
] |
74,245,864 | <p>I need to select from a table (user_id, i_id) only those values that match both user_ids.</p>
<p>Table structure:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">user_id</th>
<th style="text-align: left;">i_id</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">713870562</td>
<td style="text-align: left;">2</td>
</tr>
<tr>
<td style="text-align: left;">713870562</td>
<td style="text-align: left;">3</td>
</tr>
<tr>
<td style="text-align: left;">713870562</td>
<td style="text-align: left;">4</td>
</tr>
<tr>
<td style="text-align: left;">713870562</td>
<td style="text-align: left;">5</td>
</tr>
<tr>
<td style="text-align: left;">713870562</td>
<td style="text-align: left;">6</td>
</tr>
<tr>
<td style="text-align: left;">713870562</td>
<td style="text-align: left;">7</td>
</tr>
<tr>
<td style="text-align: left;">713870562</td>
<td style="text-align: left;">8</td>
</tr>
<tr>
<td style="text-align: left;">713870562</td>
<td style="text-align: left;">9</td>
</tr>
<tr>
<td style="text-align: left;">22131245</td>
<td style="text-align: left;">6</td>
</tr>
<tr>
<td style="text-align: left;">22131245</td>
<td style="text-align: left;">7</td>
</tr>
<tr>
<td style="text-align: left;">22131245</td>
<td style="text-align: left;">8</td>
</tr>
<tr>
<td style="text-align: left;">22131245</td>
<td style="text-align: left;">9</td>
</tr>
<tr>
<td style="text-align: left;">22131245</td>
<td style="text-align: left;">10</td>
</tr>
<tr>
<td style="text-align: left;">22131245</td>
<td style="text-align: left;">11</td>
</tr>
<tr>
<td style="text-align: left;">22131245</td>
<td style="text-align: left;">12</td>
</tr>
<tr>
<td style="text-align: left;">22637245</td>
<td style="text-align: left;">32</td>
</tr>
</tbody>
</table>
</div>
<p>I tried to do it with SELECT DISTINCT, but it selects all the data</p>
<pre class="lang-sql prettyprint-override"><code>SELECT DISTINCT interest_relations.user_id, interest_relations.i_id
FROM interest_relations
WHERE interest_relations.user_id IN (713870562,22131245) GROUP BY user_id, i_id
</code></pre>
<p>I expect to get only those values that are the same for both users</p>
<p><strong>UPD.</strong>
There will be a lot of user IDs in the table. I need to filter only certain 2.
For example in the table above 3 id's are presented. I want to filter only <code>713870562</code> and <code>22131245</code> and receive data like this:</p>
<pre><code>i_id
6
7
8
9
</code></pre>
| [
{
"answer_id": 74245910,
"author": "Luuk",
"author_id": 724039,
"author_profile": "https://Stackoverflow.com/users/724039",
"pm_score": 0,
"selected": false,
"text": "user_id"
},
{
"answer_id": 74246830,
"author": "Stefanov.sm",
"author_id": 2302032,
"author_profile":... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74245864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17087957/"
] |
74,245,869 | <p>I work on a large project which has optimization disabled. The vast majority of the devs prefer it this way because our project is I/O bound anyway and it makes dump analysis easier. Recently I've started looking replacing our <code>printf</code> based tracing mechanism with <code>std::format</code>. However, there's a problem, in my profiling, std::format is faster than our current tracing with optimization on but more than 2000% slower with optimization off. Using it would actually make a significant performance dent.</p>
<p>This has lead me to wonder if I could turn optimization on for just one function or perhaps just one static library. However, I'm struggling to work out how. The problem is that the nature <code>std::format</code> means that any tracing function you wrote to use it would have to forward on the template arguments and must therefore be a template its self. E.g.:</p>
<pre><code>template<typename... Args>
void Trace(std::_Fmt_wstring<Args& ...> fmt, Args& ...args)
{
wchar_t buf[0x1000];
std::format_to(buf, fmt, args...);
// Pass the buffer to the tracing framework
}
</code></pre>
<p>Because it's a template, it's header based and I can't put the compiled tracing code in a static library. It'll get instantiated in the non-optimized code where it's called.</p>
<p>How can I make this function optimized? I've tried <code>#pragma optimize</code> however it doesn't help because I need to not only optimize the function its self but the code generated by <code>std::format_to</code>.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 74249640,
"author": "rainbow.gekota",
"author_id": 20170164,
"author_profile": "https://Stackoverflow.com/users/20170164",
"pm_score": 2,
"selected": false,
"text": "extern"
}
] | 2022/10/29 | [
"https://Stackoverflow.com/questions/74245869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/193128/"
] |
74,245,878 | <p>I am building an app using Kotlin with the MVVM approach, and my Recycler View using multiple view types.</p>
<p>Inside my List Adapter inside the override fun onBindViewHolder, I have a code that detects the first click on the row, the second click to the same row and the first click to the different row.</p>
<p>The click detection works correctly. My goal here is to save the correct view id when I click on the row the first time, then when I click on a different row I would like to find the first row and put back the original background.
I know that this is a recycler view, but I do not scroll the view I just would like to sort the click and put back the original background.
I already saw a lot of examples where someone hardcoded the background colour, but this is not what I am looking for.</p>
<p>I already tried to save the view id, but seems to me I am saving the wrong id because when I try to restore the current view id is the same as the saved view id.</p>
<p>The code that should find the previouse view is this:</p>
<pre class="lang-kotlin prettyprint-override"><code> val prevConstrainLayoutView = holder.itemView.findViewById<ConstraintLayout>(prevClickedItemViewId)
}
</code></pre>
<ol>
<li><strong>How to save the correct view id or something else and then restore the previously clicked row with the original background colour?</strong></li>
</ol>
<h3>Current Androdi Handheld Screen</h3>
<p><a href="https://i.stack.imgur.com/anNPr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/anNPr.png" alt="enter image description here" /></a></p>
<h3>onBindViewHolder</h3>
<pre class="lang-js prettyprint-override"><code> override fun onBindViewHolder(holder: WordViewHolder, position: Int) {
val current = getItem(position)
holder.bind(current)
Log.d("onBindViewHolder->", "Views")
// apply the click listener for the item
holder.itemView.setOnClickListener {
// that should check if something was selected, but not sure
if (holder.bindingAdapterPosition != RecyclerView.NO_POSITION) {
onClickListener.onClick(current)
if (clicked == 1 && clickedItem != current.id) {
prevClickedItem = clickedItem
prevClickedItemType = clickedItemType
prevClickedItemViewId = clickedItemViewId
prevClickedItemRootBackgroundDrawable = clickedItemRootBackgroundDrawable
prevClickedItemRootBackgroundColour = clickedItemRootBackgroundColour
prevClickedItemView = clickedItemView
clicked = 1
clickedItemRootBackgroundDrawable = holder.itemView.background.current
clickedItemRootBackgroundColour = holder.itemView.solidColor
clickedItemViewId = holder.itemView.id
clickedItemType = current.orderBy
clickedItem = current.id
clickedItemView = holder.itemView
clickedItemView.tag = 2
if (clickedItem!=prevClickedItem && prevClickedItemViewId!=null && prevClickedItemType!=-1 && clickedConstraintLayout!=null) {
val prevConstrainLayoutView = holder.itemView.findViewById<ConstraintLayout>(prevClickedItemViewId)
Log.d("onBindViewHolder->", "Clicked second time different row")
Log.d("onBindViewHolder->", "$prevConstrainLayoutView and $prevClickedItemType")
when (prevClickedItemType) {
TYPE_ZERO -> {
prevConstrainLayoutView.setBackgroundColor(ContextCompat.getColor(holder.itemView.context, R.color.green_sushi))
Log.d("onBindViewHolder->", "Clicked second time different row, set the prev view to: green_sushi")
}
TYPE_ONE -> {
prevConstrainLayoutView.setBackgroundColor(ContextCompat.getColor(holder.itemView.context, R.color.yellow_background))
Log.d("onBindViewHolder->", "Clicked second time different row, set the prev view to: yellow_background")
}
TYPE_TWO -> {
prevConstrainLayoutView.setBackgroundColor(ContextCompat.getColor(holder.itemView.context, R.color.white_text))
Log.d("onBindViewHolder->", "Clicked second time different row, set the prev view to: white_text")
}
TYPE_THREE -> {
prevConstrainLayoutView.setBackgroundColor(ContextCompat.getColor(holder.itemView.context, R.color.blue_heather))
Log.d("onBindViewHolder->", "Clicked second time different row, set the prev view to: blue_heather")
}
TYPE_FOUR -> {
prevConstrainLayoutView.setBackgroundResource(R.drawable.purple_orange_background)
Log.d("onBindViewHolder->", "Clicked second time different row, set the prev view to: purple_orange_background")
}
else -> {
prevConstrainLayoutView.setBackgroundColor(ContextCompat.getColor(holder.itemView.context, R.color.green_sushi))
Log.d("onBindViewHolder->", "Clicked second time different row, set the prev view to: green_sushi")
}
}
}
holder.itemView.setBackgroundColor(
ContextCompat.getColor(
holder.itemView.context,
R.color.blue_background
)
)
} else if (clicked == 1 && clickedItem == current.id) {
// second click the same row
clicked = 0
clickedItem = current.id
} else if (clicked == 0) {
// first click
clicked = 1
clickedItem = current.id
clickedItemType = current.orderBy
clickedItemViewId = holder.itemView.id
holder.itemView.tag = 1
clickedItemRootBackgroundDrawable = holder.itemView.background.current
clickedItemRootBackgroundColour = holder.itemView.solidColor
clickedItemView = holder.itemView
clickedConstraintLayout = holder.itemView.findViewById<ConstraintLayout>(R.id.root)
Log.d("onBindViewHolder->", "Clicked first time, set the view to: blue_background, " +
"\nconstraint layout:$clickedConstraintLayout")
holder.itemView.setBackgroundColor(
ContextCompat.getColor(
holder.itemView.context,
R.color.blue_background
)
)
}
}
}
}
</code></pre>
<h3>item view layout</h3>
<pre class="lang-js prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/purple_orange_background"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:gravity="center_vertical"
android:text="View 6 TextView"
android:textColor="@color/white"
android:textSize="24sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code></pre>
<p>This is what I am using in my ListAdapter:</p>
<pre class="lang-kotlin prettyprint-override"><code>class WordListAdapter(private val onClickListener: MyRecyclerViewOnClickListener) :
ListAdapter<Word, WordListAdapter.WordViewHolder>(WordsComparator()) {
</code></pre>
<p>This is part of the code from View Model:</p>
<pre class="lang-kotlin prettyprint-override"><code>val allOrderedWords: LiveData<List<Word>> = repository.allOrderedWords.asLiveData()
</code></pre>
<p>This is in my Activity:</p>
<pre class="lang-kotlin prettyprint-override"><code>wordViewModel.allOrderedWords.observe(this, Observer { words ->
// Update the cached copy of the words in the adapter.
words?.let { adapter.submitList(it) }
})
</code></pre>
| [
{
"answer_id": 74249640,
"author": "rainbow.gekota",
"author_id": 20170164,
"author_profile": "https://Stackoverflow.com/users/20170164",
"pm_score": 2,
"selected": false,
"text": "extern"
}
] | 2022/10/29 | [
"https://Stackoverflow.com/questions/74245878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9003215/"
] |
74,245,889 | <p>I have below data set, I need to extract 9 numeric ID from the "Notes" column.
below some of the code I tried, but sometimes I don't get the correct output. sometimes there are few spaces between numbers, or a symbol, or sometimes there are numeric values that are not part of the ID etc.. any idea how to do this more efficient?</p>
<pre><code>DF['Output'] = DF['Notes'].str.replace(' '+' '+' '+'-', '')
DF['Output'] = DF['Notes'].str.replace(' '+' '+'-', '')
DF['Output'] = DF['Notes'].str.replace(' '+'-', '')
DF['Output'] = DF['Notes'].str.replace('-', '')
DF['Output'] = DF['Notes'].str.replace('\D', ' ')
DF['Output'] = DF['Notes'].str.findall(r'(\d{9,})').apply(', '.join)
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Notes</th>
<th style="text-align: center;">Expected Output</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">ab. 325% xyz</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td style="text-align: left;">GHY12345678 9</td>
<td style="text-align: center;">123456789</td>
</tr>
<tr>
<td style="text-align: left;">FTY 234567 891</td>
<td style="text-align: center;">234567891</td>
</tr>
<tr>
<td style="text-align: left;">BNM 567 891 524; 123 Ltd</td>
<td style="text-align: center;">567891524</td>
</tr>
<tr>
<td style="text-align: left;">2.5%mnkl, 3234 56 78 9; TGH 1235 z</td>
<td style="text-align: center;">323456789</td>
</tr>
<tr>
<td style="text-align: left;">RTF 956 327-12 8 TYP</td>
<td style="text-align: center;">956327128</td>
</tr>
<tr>
<td style="text-align: left;">X Y Z 1.59% 2345 567 81; one 35 in</td>
<td style="text-align: center;">234556781</td>
</tr>
<tr>
<td style="text-align: left;">VTO 126%, 12345 67</td>
<td style="text-align: center;">0</td>
</tr>
<tr>
<td style="text-align: left;">2.6% 1234 ABC 3456 1 2 4 91</td>
<td style="text-align: center;">345612491</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74249640,
"author": "rainbow.gekota",
"author_id": 20170164,
"author_profile": "https://Stackoverflow.com/users/20170164",
"pm_score": 2,
"selected": false,
"text": "extern"
}
] | 2022/10/29 | [
"https://Stackoverflow.com/questions/74245889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10560098/"
] |
74,245,922 | <p>I have a problem how to calculate the days how many days has passed since previous order.</p>
<p>My code:</p>
<pre><code>select
order_id,
order_date
from
oe.orders
where customer_id = 838
order by
order_date desc
</code></pre>
<p>The order_id and order_date are like below:</p>
<ol>
<li>order_id = 1920 & order_date= 25-MAR-19 15.45.38.000000000</li>
<li>order_id = 1618 & order_date= 08-FEB-19 12.51.39.000000000</li>
<li>order_id = 1592 & order_date= 04-FEB-19 07.35.46.000000000
...</li>
</ol>
<p>I am new user of sql and no idea how to do it. Thank you for your help!</p>
| [
{
"answer_id": 74246092,
"author": "d r",
"author_id": 19023353,
"author_profile": "https://Stackoverflow.com/users/19023353",
"pm_score": 2,
"selected": false,
"text": "WITH\n tbl AS\n (\n Select 1 \"ID\", To_Date('25-MAR-19 15.45.38', 'dd-MON-yy hh24:mi:ss') \"A_DA... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74245922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20366031/"
] |
74,245,929 | <p>I want separate numbers and operator signs from a string.</p>
<p><strong>Example:</strong></p>
<p>input - <code>"12+34=46"</code>
output - <code>12, +, 34, 46</code></p>
<p><strong>Code Used:</strong></p>
<pre><code>def seperator(runes):
runes = list(runes)
operators = ["-", "+", "/", "*"]
index1 = 0
index2 = 0
for i in range(len(runes)):
cond1 = runes[i-1] >"-1" and runes[i-1] < "10"
cond2 = runes[i-1] == "?"
if runes[i] in operators and (cond1 or cond2):
index1 = i
if runes[i] == "=":
index2 = i
num1 = runes[:index1]
operator = runes[index1]
num2 = runes[index1+1: index2]
output = runes[index2+1:len(runes)]
return num1, operator, num2, output
</code></pre>
<p><strong>Inputs</strong></p>
<pre><code>print(seperator("1+1=2"))
print(seperator("123*456=56088"))
print(seperator("-58*-1=50"))
</code></pre>
<p><strong>Results</strong></p>
<ol>
<li><code>('1', '+', '1', '2')</code></li>
<li><code>('', '1', '23*456', '56088')</code></li>
<li><code>('-50', '*', '-1', '50')</code></li>
</ol>
<p><strong>Problem</strong></p>
<p>I was wondering why I am getting the wrong output for the 2nd result.</p>
<p>I tried to remove the conditions cond1 and cond2 which seems to work for 2nd result but fail for others.</p>
| [
{
"answer_id": 74245963,
"author": "Michael M.",
"author_id": 13376511,
"author_profile": "https://Stackoverflow.com/users/13376511",
"pm_score": 1,
"selected": false,
"text": "import re\n\n\ndef seperator(runes):\n match = re.search('(-?[0-9]+)([+\\-*\\/])(-?[0-9]+)(=)(-?[0-9]+)', ru... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74245929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19878261/"
] |
74,245,931 | <p>I did a helm install of Nginx like this</p>
<pre><code>helm install ingress-nginx ingress-nginx/ingress-nginx \
--namespace ingress-nginx \
--create-namespace \
--version 4.2.0 \
--set controller.ingressClass=nginx \
--set rbac.create=true \
--values /tmp/ingress-nginx.yaml
</code></pre>
<p>everythng got deployed fine</p>
<pre><code>[rke@k8gui apps]$ kubectl get all -n ingress-nginx
NAME READY STATUS RESTARTS AGE
pod/ingress-nginx-controller-248rc 1/1 Running 0 3m15s
pod/ingress-nginx-controller-hpv8h 1/1 Running 0 3m15s
pod/ingress-nginx-controller-jwzjn 1/1 Running 0 3m15s
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/ingress-nginx-controller LoadBalancer 10.43.117.177 192.168.33.100 80:31678/TCP,443:32340/TCP 3m4s
service/ingress-nginx-controller-admission ClusterIP 10.43.119.134 <none> 443/TCP 3m4s
NAME DESIRED CURRENT READY UP-TO-DATE AVAILABLE NODE SELECTOR AGE
daemonset.apps/ingress-nginx-controller 3 3 3 3 3 kubernetes.io/os=linux 3m4s
[rke@k8gui apps]$ curl http://192.168.33.100
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx</center>
</body>
</html>
</code></pre>
<p>but curling on the loadbalancer ext ip show 404 not found</p>
<p>any idea?</p>
| [
{
"answer_id": 74251028,
"author": "Harsh Manvar",
"author_id": 5525824,
"author_profile": "https://Stackoverflow.com/users/5525824",
"pm_score": 1,
"selected": false,
"text": "<hr><center>nginx</center>\n"
}
] | 2022/10/29 | [
"https://Stackoverflow.com/questions/74245931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20063951/"
] |
74,245,934 | <p>I want to use "order" on an included model in sequelize</p>
<p>Here's the code :</p>
<pre><code>let category = await Category.findOne({
where: {
slug: req.params.slug,
},
include: [
{
model: Category,
as: "subcategories",
},
{
model: Product,
as: "products",
include: [
{
model: File,
as: "files",
},
{
model: Product,
as: "variations",
},
],
},
],
order: [{ model: Product, as: "variations" }, "price", "DESC"]
});
</code></pre>
<p>This code returns : Unable to find a valid association for model, 'Product'.
I have tried many solutions but don't find one working, and don't find much documentation on this.</p>
| [
{
"answer_id": 74251028,
"author": "Harsh Manvar",
"author_id": 5525824,
"author_profile": "https://Stackoverflow.com/users/5525824",
"pm_score": 1,
"selected": false,
"text": "<hr><center>nginx</center>\n"
}
] | 2022/10/29 | [
"https://Stackoverflow.com/questions/74245934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12663960/"
] |
74,245,952 | <p>I have a text file named <code>myfile</code> with one line text, containing some specials characters <code>\n</code> (new line character) or some escaped of this characters <code>\\n</code>,</p>
<p>myfile content:</p>
<pre><code>thiss is\n a string\\n bla bla
</code></pre>
<p>I want to read this file but keep the semantic meaning of these special characters.</p>
<p>I tried to read the file without any special work, but all these special characters are interpreted as a raw string.</p>
<pre><code>public class Main {
public static void main(String[] args) {
String path = Main.class.getResource("/myfile").getPath();
try (BufferedReader in = new BufferedReader( new FileReader(path))) {
String line = in.readLine();
System.out.println(line); // printed as a raw string, `\n` not interpreted as a new line char
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
</code></pre>
<p>I also tried using the <code>String.replace()</code> method, but it only works for <code>\n</code> but not for <code>\\n</code>.</p>
<pre><code>line.replace("\\n", "\n");
</code></pre>
| [
{
"answer_id": 74246202,
"author": "cwellm",
"author_id": 14836289,
"author_profile": "https://Stackoverflow.com/users/14836289",
"pm_score": -1,
"selected": false,
"text": "line = line.replace(\"\\\\\\\\n\", \"\\n\");\nline = line.replace(\"\\\\n\", \"\\n\");\n"
},
{
"answer_id"... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74245952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11949116/"
] |
74,245,957 | <p>I'm trying to make this chat app where i want to add an unsend option (allowing the users to delete the messages they sent). I succeeded in getting the unsend option selected but now I cant figure out how to do these few things.</p>
<ol>
<li>delete message (somehow get document id of selected message and delete it)</li>
<li>see if the message to be deleted was sent by the logged in user (this i can figure out on my own ig)</li>
</ol>
<p>I cant seem to get hang of how to figure out the document id.</p>
<p>Heres the chat screen's code:</p>
<pre><code>import 'package:flutter/material.dart';
import 'package:messenger/constants.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
final _fireStore = FirebaseFirestore.instance;
late User loggedInUser;
class ChatScreen extends StatefulWidget {
const ChatScreen({super.key});
static String id = '/chat';
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final messageTextController = TextEditingController();
final _auth = FirebaseAuth.instance;
late String messageText;
void getCurrentUser() async {
try {
final user = await _auth.currentUser;
if (user != null) {
loggedInUser = user;
}
} catch (e) {
print(e);
}
}
@override
void initState() {
super.initState();
getCurrentUser();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: null,
actions: <Widget>[
IconButton(
icon: const Icon(Icons.close),
onPressed: () {
_auth.signOut();
Navigator.pop(context);
}),
],
title: const Text('⚡️Chat'),
backgroundColor: Colors.lightBlueAccent,
),
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
const MessagesStream(),
Container(
decoration: kMessageContainerDecoration,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: TextField(
controller: messageTextController,
onChanged: (value) {
messageText = value;
},
decoration: kTextFieldDecoration,
),
),
TextButton(
onPressed: () {
messageTextController.clear();
_fireStore.collection('messages').add({
'text': messageText,
'sender': loggedInUser.email,
'timestamp': FieldValue.serverTimestamp(),
});
},
child: const Text(
'Send',
style: kSendButtonTextStyle,
),
),
],
),
),
],
),
),
);
}
}
class MessagesStream extends StatelessWidget {
const MessagesStream({super.key});
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream:
_fireStore.collection('messages').orderBy('timestamp').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(
backgroundColor: Colors.lightBlueAccent,
),
);
}
final messages = snapshot.data!.docs.reversed;
List<Messagebubble> messageBubbles = [];
for (var message in messages) {
final messageText = message.get('text');
final messageSender = message.get('sender');
final currentUser = loggedInUser.email;
final messageBubble = Messagebubble(
sender: messageSender,
text: messageText,
isMe: currentUser == messageSender,
);
messageBubbles.add(messageBubble);
}
return Expanded(
child: ListView(
reverse: true,
padding: const EdgeInsets.symmetric(
horizontal: 10.0,
vertical: 20.0,
),
children: messageBubbles,
),
);
},
);
}
}
class Messagebubble extends StatefulWidget {
const Messagebubble(
{required this.sender,
required this.text,
required this.isMe,
super.key});
final String sender;
final String text;
final bool isMe;
@override
State<Messagebubble> createState() => _MessagebubbleState();
}
class _MessagebubbleState extends State<Messagebubble> {
late Offset tapXY;
late RenderBox overlay;
// void _getTapPosition(TapDownDetails details) {
// final RenderBox referenceBox = context.findRenderObject() as RenderBox;
// setState(() {
// tapXY = referenceBox.globalToLocal(details.globalPosition);
// });
// }
void _getTapPosition(TapDownDetails detail) {
tapXY = detail.globalPosition;
}
void _showContextMenu(BuildContext context) async {
final RenderObject? overlay =
Overlay.of(context)?.context.findRenderObject();
final result = await showMenu(
context: context,
// Show the context menu at the tap location
position: RelativeRect.fromRect(
Rect.fromLTWH(tapXY.dx, tapXY.dy, 30, 30),
Rect.fromLTWH(0, 0, overlay!.paintBounds.size.width,
overlay.paintBounds.size.height)),
// set a list of choices for the context menu
items: [
const PopupMenuItem(
value: 'unsend',
child: Text('Unsend Message'),
),
]);
// Implement the logic for each choice here
switch (result) {
case 'unsend':
debugPrint('Add To Favorites');
break;
}
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment:
widget.isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
children: [
Text(
widget.sender,
style: const TextStyle(
fontSize: 12.0,
color: Colors.black,
),
),
GestureDetector(
onTapDown: (details) => _getTapPosition(details),
onLongPress: () => _showContextMenu(context),
child: Material(
elevation: 5.0,
borderRadius: BorderRadius.only(
topLeft: widget.isMe
? const Radius.circular(30)
: const Radius.circular(0),
topRight: widget.isMe
? const Radius.circular(0)
: const Radius.circular(30),
bottomLeft: const Radius.circular(30),
bottomRight: const Radius.circular(30),
),
color: widget.isMe ? Colors.lightBlueAccent : Colors.white,
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 10.0, horizontal: 10.0),
child: Text(
widget.text,
style: const TextStyle(
fontSize: 15.0,
),
),
),
),
),
],
),
);
}
}
</code></pre>
| [
{
"answer_id": 74246202,
"author": "cwellm",
"author_id": 14836289,
"author_profile": "https://Stackoverflow.com/users/14836289",
"pm_score": -1,
"selected": false,
"text": "line = line.replace(\"\\\\\\\\n\", \"\\n\");\nline = line.replace(\"\\\\n\", \"\\n\");\n"
},
{
"answer_id"... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74245957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19728013/"
] |
74,245,962 | <p>[![enter image description here][1]][1]how can i map multiple arrays to display the information on table style fetched from this two api's? right now my code displays the information but in two separate tables. i want it to display it in one table.</p>
<p>[1] How is displaying right now -- > <a href="https://i.stack.imgur.com/9D14i.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/9D14i.jpg</a> ,
[2] How it should display -- > <a href="https://i.stack.imgur.com/DoauM.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/DoauM.jpg</a> , [3] API information -- >
<a href="https://i.stack.imgur.com/VVvgG.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/VVvgG.jpg</a> ,
<a href="https://i.stack.imgur.com/ETb99.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/ETb99.jpg</a></p>
<p><em><strong>MY CODE</strong></em></p>
<pre><code>import axios from "axios";
import React, { useState, useEffect } from "react";
const Ranking = () => {
const [playerName, setPlayerName] = useState([]);
const [playerRank, setPlayerRank] = useState([]);
const fetchData = () => {
const playerAPI = 'http://localhost:3008/api/players';
const playerRank = 'http://localhost:3008/api/highscore/players';
const getINFOPlayer = axios.get(playerAPI)
const getPlayerRank = axios.get(playerRank)
axios.all([getINFOPlayer, getPlayerRank]).then(
axios.spread((...allData) => {
const allDataPlayer = allData[0].data.players
const getINFOPlayerRank = allData[1].data.players
setPlayerName(allDataPlayer)
setPlayerRank(getINFOPlayerRank)
})
)
}
useEffect(() => {
fetchData()
}, [])
return (
<table class="table table-bordered">
<tr>
<th>Rank</th>
<th>Name</th>
<th>Points</th>
</tr>
<tbody>
{playerRank && playerName?.map((player) => {
return (
<tr key={player.name}>
<td>{player.name}</td>
<td>{player.score}</td>
</tr>
)
})}
</tbody>
{playerRank?.map((player) => {
return (
<tr key={player.name}>
<td>{player.id}</td>
<td>{player.position}</td>
<td>{player.score}</td>
</tr>
)
})}
</table>
)
}
export default Ranking
</code></pre>
<p><em><strong>THIS DOES NOT WORKS</strong></em></p>
<pre><code> {playerRank && playerName?.map((player) => {
return (
<tr key={player.name}>
<td>{player.name}</td>
<td>{player.score}</td>
</tr>
)
})}
</code></pre>
<p><em><strong>THIS WORKS but it displays two tables because of this code</strong></em>
how can i fetch both information inside one table?</p>
<pre><code> return (
<table class="table table-bordered">
<tr>
<th>Rank</th>
<th>Name</th>
<th>Points</th>
</tr>
<tbody>
{playerName?.map((player) => {
return (
<tr key={player.name}>
<td>{player.name}</td>
<td>{player.score}</td>
</tr>
)
})}
</tbody>
{playerRank?.map((player) => {
return (
<tr key={player.name}>
<td>{player.id}</td>
<td>{player.position}</td>
<td>{player.score}</td>
</tr>
)
})}
</table>
)
}
</code></pre>
| [
{
"answer_id": 74246202,
"author": "cwellm",
"author_id": 14836289,
"author_profile": "https://Stackoverflow.com/users/14836289",
"pm_score": -1,
"selected": false,
"text": "line = line.replace(\"\\\\\\\\n\", \"\\n\");\nline = line.replace(\"\\\\n\", \"\\n\");\n"
},
{
"answer_id"... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74245962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20250017/"
] |
74,245,975 | <p>I have this app but I want to set the Background color of the entire scaffold as a linear Gradient (0xffF6FECE and 0xffB6C0C8) instead of the typical one color that you can achieve by doing</p>
<pre><code>backgroundColor: Color(0xffF6FECE).
</code></pre>
<p>I want a linear Gradient like this:<a href="https://i.stack.imgur.com/402Y6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/402Y6.png" alt="enter image description here" /></a></p>
<p>The first lines of my code are as follows:</p>
<pre><code>import 'dart:ui';
import 'package:flutter/material.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0.0,
leading: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(13.0),
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey, spreadRadius: 0.5, blurRadius: 1.0)
]),
child: Center(
child: Image.asset(
"assets/menu.png",
height: 25.0,
width: 25.0,
),
),
),
), ...etc
</code></pre>
| [
{
"answer_id": 74246051,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "class TestingDesign2 extends StatefulWidget {\n const TestingDesign2({super.key});\n\n @override\n State<Tes... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74245975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19517726/"
] |
74,245,996 | <p>am tying to calling user to appear in profile page the app block when i fixed it i faced other problem which is this one if there any solution can help me</p>
<pre class="lang-dart prettyprint-override"><code>import 'package:flutter/foundation.dart';
class UserModel {
String? uid;
String? Username;
String? email;
String? photoUrl;
UserModel(
{this.uid, this.email, this.Username, this.photoUrl});
// receving data from the server
factory UserModel.fromMap(Map) {
return UserModel(
uid: Map['userId'],
Username: Map['Username'],
email: Map['email'],
photoUrl: Map['photoUrl'],
);
}
// /// sending data to firestore
Map<String, dynamic> toMap() {
return {
'userId': uid,
'Username': Username,
'email': email,
'photoUrl': photoUrl,
};
}
}
</code></pre>
<p><strong>the error picture</strong>
<a href="https://i.stack.imgur.com/nWqAZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nWqAZ.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74246051,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 2,
"selected": true,
"text": "class TestingDesign2 extends StatefulWidget {\n const TestingDesign2({super.key});\n\n @override\n State<Tes... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74245996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16571275/"
] |
74,246,003 | <p>Could somebody share some suggestion about how to insert data "T" into the line less then two column.</p>
<p>initial data:</p>
<pre><code>A,a1
B,c
1,2
3
a
M,n
</code></pre>
<p>Expected Data:</p>
<pre><code>A,a1
B,c
1,2
T,3
T,a
M,n
</code></pre>
<p>Thanks a ton and have a good weekend.</p>
| [
{
"answer_id": 74246443,
"author": "cwellm",
"author_id": 14836289,
"author_profile": "https://Stackoverflow.com/users/14836289",
"pm_score": -1,
"selected": false,
"text": "input=$(cat test.txt)\nwhile IFS= read -r line; do\n substr=$(echo \"$line\" | cut -d',' -f 1 -s)\n if [[ \"... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19623474/"
] |
74,246,019 | <p>`</p>
<pre><code>#include <unistd.h>
int ft_atoi(char *str)
{
int c;
int sign;
int result;
c = 0;
sign = 1;
result = 0;
while ((str[c] >= '\t' && str[c] <= '\r') || str[c] == ' ')
{
c++;
}
while (str[c] == '+' || str[c] == '-')
{
if (str[c] == '-')
sign *= -1;
c++;
}
while (str[c] >= '0' && str[c] <= '9')
{
result = (str[c] - '0') + (result * 10);
c++;
}
return (result * sign);
}
#include <stdio.h>
int main(void)
{
char *s = " ---+--+1234ab567";
printf("%d", ft_atoi(s));
}
</code></pre>
<p>`</p>
<p>This line: result = (str[c] - '0') + (result * 10);
Why do we subtract zero and multiply by 10? How its convert ascii to int with this operations?
Thanks...</p>
| [
{
"answer_id": 74246443,
"author": "cwellm",
"author_id": 14836289,
"author_profile": "https://Stackoverflow.com/users/14836289",
"pm_score": -1,
"selected": false,
"text": "input=$(cat test.txt)\nwhile IFS= read -r line; do\n substr=$(echo \"$line\" | cut -d',' -f 1 -s)\n if [[ \"... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20273395/"
] |
74,246,116 | <p>Say i have a dictionary named <strong>"DictionaryOfRoutes"</strong> that includes <strong>lists</strong> like in the following example:</p>
<pre><code>'DictionaryOfRoutes'= {'RouteOfVehicle_1': [0, 6, 1, 5, 0],
'RouteOfVehicle_2': [0, 4, 3, 0],
'RouteOfVehicle_3': [0, 2, 0]
}
</code></pre>
<p>The lists in the values of it correspond to routes and the integers inside them to indices of points.
For the points i have the following data in the form of lists:</p>
<pre><code>allIds = [0, 1, 2, 3, 4, 5, 6]
allxs = [50, 18, 33, 98, 84, 13, 50]
allys = [50, 73, 16, 58, 49, 63, 56]
</code></pre>
<p>For example the first point has an id of 0, x coordinates of 50, and y coordinates of 50, and so on..
I want to plot these routes like in the following png:
<a href="https://i.stack.imgur.com/TR0pE.png" rel="nofollow noreferrer">Example of Routes Visualized and Colorized</a></p>
<p>So far i have only managed to visualize one route (list) but not all of them, by using the following code:</p>
<pre><code>def SolutionPlot(xx, yy, all_ids, matrix, final_route):
'''
xx = [50, 18, 33, 98, 84, 13, 50]
yy = [50, 73, 16, 58, 49, 63, 56]
all_ids = [0, 1, 2, 3, 4, 5, 6]
matrix = a numpy array of arrays (a distance matrix)
final_route = [0, 5, 4, 3, 2, 1]
'''
fig, ax = plt.subplots()
fig.set_size_inches(6, 6)
allxs = np.array(xx)
allys = np.array(yy)
final_route = np.array(final_route)
ax.plot(allxs[final_route], allys[final_route], ls="-", marker="o", markersize=6)
plt.xlim([0, 100])
plt.ylim([0, 100])
plt.title("Travelling Salesman (Nearest Neighbor Algorithm)")
for xi, yi, pidi in zip(xx, yy, all_ids):
ax.annotate(str(pidi), xy=(xi,yi))
plt.show()
</code></pre>
<p>which returns the following plot:
<a href="https://i.stack.imgur.com/epblX.png" rel="nofollow noreferrer">Plot i made so far</a></p>
| [
{
"answer_id": 74246491,
"author": "user6752871",
"author_id": 6752871,
"author_profile": "https://Stackoverflow.com/users/6752871",
"pm_score": 0,
"selected": false,
"text": "final_routes=[]\nfor key in DictionaryOfRoutes.keys(): \n temp=[]\n for index in DictionaryOfRou... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18354667/"
] |
74,246,199 | <p>I have a function that is supposed to loop through an array and count the values in the array that are true. in the example below, I am expecting a value of 4, since the values 6, 3, 30, and 7 are all truthy values while 0 is false.</p>
<pre><code>function countTruthy(arr) {
var arrayLength = arr.length;
var truthy = 0;
for (var i = 0; i < arrayLength; i++) {
if(arr[i] == true) {
truthy++
}
}
return console.log(truthy)
}
countTruthy([6, 3, 0, 30, 7])
</code></pre>
<p>But the code above doesn't work and I keep getting 0 instead</p>
| [
{
"answer_id": 74246232,
"author": "Michael M.",
"author_id": 13376511,
"author_profile": "https://Stackoverflow.com/users/13376511",
"pm_score": 3,
"selected": true,
"text": "true"
},
{
"answer_id": 74246272,
"author": "trincot",
"author_id": 5459839,
"author_profile... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6148320/"
] |
74,246,208 | <p>Hello I have a Dataframe like this in pandas</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'date': ['2022-10-01', '2022-10-04', '2022-10-17'],
'value': [100, 110, 95]})
</code></pre>
<p>How can I subtract the date from a default value?</p>
<p>I've tried it like this</p>
<pre><code>'2022-10-20' - df['date']
</code></pre>
<p>but got an error</p>
<pre><code>TypeError: unsupported operand type(s) for -: 'str' and 'str'
</code></pre>
<p>I want to calculate the values 19, 16, 3</p>
| [
{
"answer_id": 74246232,
"author": "Michael M.",
"author_id": 13376511,
"author_profile": "https://Stackoverflow.com/users/13376511",
"pm_score": 3,
"selected": true,
"text": "true"
},
{
"answer_id": 74246272,
"author": "trincot",
"author_id": 5459839,
"author_profile... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,246,240 | <p>I'm trying to add autoplaying music to a tumblr theme, but Chrome and Firefox both prevent autoplaying audio by default. How do I circumvent this?</p>
<p>Currently, to hear the autoplaying music, a user would have to change their personal browser settings to allow autoplay. Is there a workaround I can use to make the page play audio even if they have sound set to automatic (in Chrome) or autoplay blocked (in Firefox)?</p>
<p>Tumblr themes allow HTML, CSS, and Javascript, so I'd be happy for a solution using any of those. Ideally I would like my autoplay solution to allow multiple songs in a playlist, if possible.</p>
<p>I tried adding an invisible iframe, but that didn't work; I'm not sure whether it was the third-party audio player I'm using, or just that the iframe technique doesn't work at all anymore.</p>
| [
{
"answer_id": 74246893,
"author": "Fishbite",
"author_id": 11815954,
"author_profile": "https://Stackoverflow.com/users/11815954",
"pm_score": 1,
"selected": false,
"text": "<audio>"
},
{
"answer_id": 74261176,
"author": "Pr77Pr77",
"author_id": 20366446,
"author_pro... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14075572/"
] |
74,246,310 | <p>I have the following SQL Server code which I would like to do in C# code.
The logic is - to remove leading zeros
please help me to translate the code into C#.</p>
<pre><code>
DECLARE @TESTVariable as varchar(500)
Set @TESTVariable = '00013025990'
SELECT Substring(@TESTVariable, Patindex('%[^0 ]%', @TESTVariable + ' '), Len(@TESTVariable))
</code></pre>
<p>output expected</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>input</th>
<th>output</th>
</tr>
</thead>
<tbody>
<tr>
<td>'001'</td>
<td>'1'</td>
</tr>
<tr>
<td>'00'</td>
<td>'0'</td>
</tr>
<tr>
<td>'00013025990'</td>
<td>'13025990'</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74246893,
"author": "Fishbite",
"author_id": 11815954,
"author_profile": "https://Stackoverflow.com/users/11815954",
"pm_score": 1,
"selected": false,
"text": "<audio>"
},
{
"answer_id": 74261176,
"author": "Pr77Pr77",
"author_id": 20366446,
"author_pro... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11635063/"
] |
74,246,337 | <p>I have a button that changes an element's style. Can I have this button auto-reset the CSS changed, back to default? Here is the code:</p>
<pre><code><div class="coinboxcontainer"><img id="coin1" src="/wp-content/uploads/2022/10/coin.png" alt="box" width="40" height="40">
<a onclick="tosscoin()"><img src="/wp-content/uploads/2022/10/coinbox.png" alt="box" width="40" height="40"></a>
<audio id="audio" src="/wp-content/uploads/2022/10/coinsound.mp3"></audio>
<script>
function tosscoin() {
document.getElementById("coin1").style.transform = "translatey(-70px)";
var audio = document.getElementById("audio");
audio.play();
}
</script>
</div>
</code></pre>
| [
{
"answer_id": 74246893,
"author": "Fishbite",
"author_id": 11815954,
"author_profile": "https://Stackoverflow.com/users/11815954",
"pm_score": 1,
"selected": false,
"text": "<audio>"
},
{
"answer_id": 74261176,
"author": "Pr77Pr77",
"author_id": 20366446,
"author_pro... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15846302/"
] |
74,246,454 | <p>I have Student, Class and StudentClass models. I would like a student to be able to join a new class by inputting the class_code into a form. To join a class the user's student_id and the class_code is saved to the StudentClass model. The student_id isn't a form field so should be obtained by querying the Student model with the logged-in user's username and returning the student_id.</p>
<p>models.py:</p>
<pre><code>class StudentClass(models.Model):
class Meta:
unique_together = (('class_code', 'student_id'),)
class_code = models.ForeignKey(Class, on_delete=models.CASCADE)
student_id = models.ForeignKey(Student, on_delete=models.CASCADE)
</code></pre>
<p>forms.py:</p>
<pre><code>class JoinClassForm(forms.ModelForm):
class Meta:
model = StudentClass
fields = ['class_code']
exclude = ('student_id',)
</code></pre>
<p>views.py</p>
<pre><code>@login_required
def join_class(request):
if request.method == "POST":
joinclass_form = JoinClassForm(request.POST or None)
if joinclass_form.is_valid():
formclass_code = joinclass_form.data.get('class_code')
if Class.objects.filter(class_code=formclass_code).exists():
joinclass_form.save(commit=False)
joinclass_form.student_id =
Student.objects.filter(username=request.user.username).values_list('student_id', flat=True)
joinclass_form.save()
return redirect('assignments')
else:
messages.success(request, ("This class doesn't exist!"))
else:
joinclass_form = JoinClassForm
return render(request, 'join_class.html', {'joinclass_form': joinclass_form})
</code></pre>
<p>I've tried using a hidden_field for student_id, excluding student_id from the form fields and saving as commit=False, and I've gotten the same error: IntegrityError Not NULL constraint failed. Is there an error in my code that I have missed or am I using the wrong method?
Thanks in advance</p>
<p>Edit: Forgive me but copy-paste went kinda awry on the last set of code and I have no idea how to fix it</p>
| [
{
"answer_id": 74246893,
"author": "Fishbite",
"author_id": 11815954,
"author_profile": "https://Stackoverflow.com/users/11815954",
"pm_score": 1,
"selected": false,
"text": "<audio>"
},
{
"answer_id": 74261176,
"author": "Pr77Pr77",
"author_id": 20366446,
"author_pro... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20352073/"
] |
74,246,474 | <p>I'm relatively new to R. I downloaded a dataset about clinical trial data, but it occurred to me, that t<strong>he format of the dates in the relative column are mixed up</strong>: most of them are like "September 1, 2012", but some are missing the day information (e.g. October 2015).</p>
<p>I want to express them all in the same way (eg. yyyy-mm-dd), to work with them. That went fine, the only problem that is missing is the name of the output column. In the last function (date_correction) I planned to include an argument "output_col" which I can <strong>pass the intended name for the created (formatted) column, but it only prints output_col all the time.</strong></p>
<ol>
<li>Do you know, how I could handle this? To pass the intended name of the output column right into the function?</li>
<li>Is there a better way to solve my problem?
-> I even tried to manage more complex orders-argument for lubricate::parse_date_time like</li>
</ol>
<p><code>parse_date_time(input_col, orders="mdy", "my")</code></p>
<p>but this didn't work.</p>
<p>Here's the code:</p>
<pre><code>library("tidyverse")
library("lubridate")
Observation <- c(seq(1:5))
Date_original <- c("October 2014","August 2014","June 2013",
"June 24, 2010","January 2005")
df_dates <- data.frame(Observation, Date_original)
# looking for a comma in the cell
comma_detect <- function(a_string){
str_detect(a_string, ",")
}
# if comma: assume "mdy", if not apply "my" -> return formatted value
date_correction_row <- function(input_col){
if_else(comma_detect(input_col),
parse_date_time(input_col, orders="mdy"),
parse_date_time(input_col, orders="my"))
}
# prepare function for dataframe:
date_correction <- function(df, input_col, output_col){
mutate(df, output_col = date_correction_row(input_col))
}
df_dates %>% date_correction(df_dates$Date_original, date_formatted) %>% view()
OUTPUT
Observation Date_original output_col
1 1 October 2014 2014-10-01
2 2 August 2014 2014-08-01
3 3 June 2013 2013-06-01
4 4 June 24, 2010 2010-06-24
5 5 January 2005 2005-01-01
</code></pre>
| [
{
"answer_id": 74246893,
"author": "Fishbite",
"author_id": 11815954,
"author_profile": "https://Stackoverflow.com/users/11815954",
"pm_score": 1,
"selected": false,
"text": "<audio>"
},
{
"answer_id": 74261176,
"author": "Pr77Pr77",
"author_id": 20366446,
"author_pro... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20366390/"
] |
74,246,505 | <p>Let's say, that we have a <code>numpy</code> array storing large objects. My goal is to delete one of these objects from memory, but retain the initial structure of the array. The cell, under which this object was stored might be filled for example with <code>None</code>.</p>
<p>Example simplified behaviour, where I replaced large objects with characters:</p>
<pre><code>arr = numpy.asarray(['a', 'b', 'c']) # arr = ['a', 'b', 'c']
delete_in_place(arr, 0) # arr = [None, 'b', 'c']
</code></pre>
<p>I can't do this by calling <code>numpy.delete()</code>, because it will just return a new array without one element, which will take additional space in memory. This will also change the shape (by getting rid of given index), which I want to avoid.</p>
<p>My other idea was to just set <code>arr[0] = None</code> and call the garbage collector, but I'm not sure what the exact behaviour of such procedure would be.</p>
<p>Do you have any ideas on how to do it?</p>
| [
{
"answer_id": 74246615,
"author": "Muntasir Aonik",
"author_id": 8663492,
"author_profile": "https://Stackoverflow.com/users/8663492",
"pm_score": 3,
"selected": true,
"text": "numpy"
},
{
"answer_id": 74247026,
"author": "tijko",
"author_id": 1230086,
"author_profil... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4903882/"
] |
74,246,520 | <p>I want to give the users to the ability to update their info on database. I made the button to for the software to take the name from one of the textboxes and send it to the database.</p>
<pre><code>public void Updatebtn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\Ray-a\\Downloads\\New folder (2)\\Blood Donation\\Blood Donation\\App_Data\\BloodDonationDB.mdf\";Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("Update Users set First_Name=@fn WHERE ID = '2' ", con);
cmd.Parameters.AddWithValue("@fn", UFirstName.Text);
cmd.ExecuteNonQuery();
con.Close();
}
</code></pre>
<p>I watched a YouTube video and followed step by step. But it didn't work.
The button works and executes command. But something is wrong with either sql command or connection because the database doesn't get updated</p>
| [
{
"answer_id": 74246615,
"author": "Muntasir Aonik",
"author_id": 8663492,
"author_profile": "https://Stackoverflow.com/users/8663492",
"pm_score": 3,
"selected": true,
"text": "numpy"
},
{
"answer_id": 74247026,
"author": "tijko",
"author_id": 1230086,
"author_profil... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20366486/"
] |
74,246,523 | <p>I want to change the frontend font size from the admin panel in Laravel. Suppose there is a</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2 class="intro">Introduction to PHP...?? </h2>
in style.css-->>>>
.intro{
font-size:20px;
}</code></pre>
</div>
</div>
</p>
<p>I want this font size dynamic from admin panel by catching the class. If i need 25px i use that or any size I need I will use that.</p>
<p>How can I do that in laravel??? Give me some suggestions to step up...</p>
| [
{
"answer_id": 74246615,
"author": "Muntasir Aonik",
"author_id": 8663492,
"author_profile": "https://Stackoverflow.com/users/8663492",
"pm_score": 3,
"selected": true,
"text": "numpy"
},
{
"answer_id": 74247026,
"author": "tijko",
"author_id": 1230086,
"author_profil... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13127640/"
] |
74,246,536 | <p>i create a program that reads a sequence of numbers, determines how many different numbers there are (we count the repetitions once), and writes the result to the standard output.
my first code:</p>
<pre><code>f=int(input("String of numbers: "))
l=[]
for x in range(f):
string_numbers = int(input(f'Enter {x+1} string of numbers: '))
l.append(string_numbers)
mylist = list(dict.fromkeys(l))
print(len(mylist))
</code></pre>
<p>I wanted to take into account if the user entered a string too short or too long than declared. I wanted the user to type everything on one line. When I enter an incorrect string number, I get duplicated "incorrect string lengthincorrect string length"</p>
<pre><code>f=int(input("String of numbers: "))
my_list = input('Enter numbers in the string, separated by spaces: ').split()
list_of_integers=[]
l=len(str(list_of_integers))
for i in my_list:
list_of_integers.append((i))
mylist = list(dict.fromkeys(list_of_integers))
for i in range(f):
if i < l:
print("incorrect string length", end='')
elif i > l:
print("incorrect string length", end='')
else:
</code></pre>
| [
{
"answer_id": 74246601,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 3,
"selected": true,
"text": "f"
},
{
"answer_id": 74246635,
"author": "tijko",
"author_id": 1230086,
"author_profile": "https:... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15030535/"
] |
74,246,546 | <p>I frequently have a collection that might be either undefined or empty. So I write this:</p>
<pre><code>if ((thingies?.length ?? 0) > 0) ...
</code></pre>
<p>I guess that's not so bad in the grand scheme, but it ain't pretty. What I <em>really</em> want is a Bash-like operator that means "this variable exists, is an array, and has at least one element":</p>
<pre><code>if (thingies#) ... // it's safe to access thingies[0]
</code></pre>
<p>Pretty sure that's not a thing. But what's the most concise Typescript expression of this?</p>
| [
{
"answer_id": 74246733,
"author": "Pierre Thalamy",
"author_id": 3582770,
"author_profile": "https://Stackoverflow.com/users/3582770",
"pm_score": 1,
"selected": false,
"text": "undefined"
},
{
"answer_id": 74246816,
"author": "Guillaume Brunerie",
"author_id": 521624,
... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4185992/"
] |
74,246,595 | <p>In VS Code (Windows), my python interpreter points to version 3.11.
<code>python -V</code> in terminal gives me Python 3.11.0</p>
<p>I create a virtual environment with <code>python3 -m venv virtual</code> called virtual, and activate it with <code>.\virtual\Scripts\activate</code>.
Now in my environment, checking <code>python -V</code> gives me Python 3.9.13 instead.</p>
<p>How do I get venv to create a Python 3.11 environment?</p>
| [
{
"answer_id": 74246841,
"author": "Althaf",
"author_id": 17400858,
"author_profile": "https://Stackoverflow.com/users/17400858",
"pm_score": 2,
"selected": true,
"text": "python3"
}
] | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11485370/"
] |
74,246,627 | <p>I have the following component:</p>
<pre><code>const testLog = () => {
console.log('aaa - test') ;
}
const MyComponent = () => (
<img onLoad={() => testLog()} />
);
</code></pre>
<p>I then reference the component in my main app:</p>
<pre><code><MyComponent />
</code></pre>
<p>I can see that the component definitely appears on the screen - I can see the image component, however, the issue I have is that the log message never fires.</p>
<p>At first, I thought I'd maybe need to bind it, so tried this:</p>
<pre><code>const MyComponent = () => (
<img onLoad={() => this.testLog.bind(this)} />
);
</code></pre>
<p>But it then just tells me that <code>testLog</code> is not used.</p>
| [
{
"answer_id": 74246648,
"author": "hhpr98",
"author_id": 14194981,
"author_profile": "https://Stackoverflow.com/users/14194981",
"pm_score": -1,
"selected": false,
"text": "useEffect(()=>{\n // TODO: your code here\n this.testLog.bind(this)\n},[]);\n"
},
{
"answer_id": 7424683... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19446708/"
] |
74,246,676 | <p>This is the simplified version or representative of the SQL Server query that I am attempting:</p>
<pre><code>WITH T1 AS (
SELECT DocNum, CardCode, CardName FROM OINV
)
SELECT CardName AS 'Customer Name', DocNum FROM T1
UNION ALL
SELECT 'Grand Total', COUNT(DocNum) FROM T1
ORDER BY "Customer Name"
</code></pre>
<p>In the real query, I cannot avoid using CTE as I need to reference the results of one CTE in another CTE in the same query and there are multiple CTEs.</p>
<p>My main requirement is to have a Grand Total row at the end of the query. The Grand Total row would show some summary figures, like Count, Sum, etc. In the real query, the Grand Total row would itself derive its summary figures based on one of the CTE results.</p>
<p>In the above simplified query, how can I achieve Grand Total at the bottom of the query without adding any additional column in the query result.</p>
<p>In my real query, the 1st CTE gets the list of all the documents with their outstanding balances and the ageing days;</p>
<p>The 2nd query adds additional columns by joining few other tables and categorizes the outstanding amount into ageing buckets like 0-30 days, 30-60 days and so on</p>
<p>And I need to add a Grand Total row to the results of the 2nd query, which should provide total outstanding of all the customers and the totals for each of the ageing buckets categorized in CTE2.</p>
| [
{
"answer_id": 74246648,
"author": "hhpr98",
"author_id": 14194981,
"author_profile": "https://Stackoverflow.com/users/14194981",
"pm_score": -1,
"selected": false,
"text": "useEffect(()=>{\n // TODO: your code here\n this.testLog.bind(this)\n},[]);\n"
},
{
"answer_id": 7424683... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1113579/"
] |
74,246,687 | <pre><code>Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id = '1'' at line 1
at Query.Sequence._packetToError (D:\Softwares\usermana\Nodejs-UserManagement-Express-Hbs-MySQL\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Query.ErrorPacket (D:\Softwares\usermana\Nodejs-UserManagement-Express-Hbs-MySQL\node_modules\mysql\lib\protocol\sequences\Query.js:79:18)
at Protocol._parsePacket (D:\Softwares\usermana\Nodejs-UserManagement-Express-Hbs-MySQL\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (D:\Softwares\usermana\Nodejs-UserManagement-Express-Hbs-MySQL\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (D:\Softwares\usermana\Nodejs-UserManagement-Express-Hbs-MySQL\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (D:\Softwares\usermana\Nodejs-UserManagement-Express-Hbs-MySQL\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (D:\Softwares\usermana\Nodejs-UserManagement-Express-Hbs-MySQL\node_modules\mysql\lib\Connection.js:88:28)
at Socket.<anonymous> (D:\Softwares\usermana\Nodejs-UserManagement-Express-Hbs-MySQL\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (node:events:390:28)
at addChunk (node:internal/streams/readable:315:12)
--------------------
at Protocol._enqueue (D:\Softwares\usermana\Nodejs-UserManagement-Express-Hbs-MySQL\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Connection.query (D:\Softwares\usermana\Nodejs-UserManagement-Express-Hbs-MySQL\node_modules\mysql\lib\Connection.js:198:25)
at exports.update (D:\Softwares\usermana\Nodejs-UserManagement-Express-Hbs-MySQL\server\controllers\userController.js:81:14)
at Layer.handle [as handle_request] (D:\Softwares\usermana\Nodejs-UserManagement-Express-Hbs-MySQL\node_modules\express\lib\router\layer.js:95:5)
at next (D:\Softwares\usermana\Nodejs-UserManagement-Express-Hbs-MySQL\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (D:\Softwares\usermana\Nodejs-UserManagement-Express-Hbs-MySQL\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (D:\Softwares\usermana\Nodejs-UserManagement-Express-Hbs-MySQL\node_modules\express\lib\router\layer.js:95:5)
at D:\Softwares\usermana\Nodejs-UserManagement-Express-Hbs-MySQL\node_modules\express\lib\router\index.js:284:15
at param (D:\Softwares\usermana\Nodejs-UserManagement-Express-Hbs-MySQL\node_modules\express\lib\router\index.js:365:14)
at param (D:\Softwares\usermana\Nodejs-UserManagement-Express-Hbs-MySQL\node_modules\express\lib\router\index.js:376:14) {
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id = '1'' at line 1",
sqlState: '42000',
index: 0,
}
The data from user table:
undefined
</code></pre>
<p>Im trying to update my login detatils dynamically from the admin page but it throws an error when I click on submit</p>
<p>Heres my database structure</p>
<pre><code>[
</code></pre>
| [
{
"answer_id": 74246648,
"author": "hhpr98",
"author_id": 14194981,
"author_profile": "https://Stackoverflow.com/users/14194981",
"pm_score": -1,
"selected": false,
"text": "useEffect(()=>{\n // TODO: your code here\n this.testLog.bind(this)\n},[]);\n"
},
{
"answer_id": 7424683... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20073137/"
] |
74,246,710 | <p>I am working on a prescription order form, and the client wants to be able to enter the quantity of medication taken per dose, the frequency of dose, and the duration of this dosage schedule, and then have the results of those fields used to calculate the quantity of medication needed. For example, if they selected "2 pills", "3 times per day", and "14 days", they want the <strong>quantity</strong> input to be set to 2*3*14 = "84" .</p>
<p>The entering of the <strong>quantity per dose</strong>, <strong>frequency of dose</strong>, and <strong>duration of doses</strong> are all done with <code><select></code>, so there is a strict set of values that can be entered.</p>
<p>Is there a way that I can grab the values of quantity per dose, frequency of dose, and duration of doses with PHP <strong>before the form is submitted</strong>, and set the value of the quantity field on the fly based upon those values?</p>
<p>Here is the HTML for the section of the form where the fields mentioned above are located.</p>
<pre><code><label for="qtyperdose">Qty per Dose</label>
<select id="qtyperdose">
<option value="0.25">1/4</option>
<option value="0.5">1/2</option>
<option value="1" selected>1</option>
<option value="2">2</option>
</select>
<label for="frequency">Frequency Of Dose</label>
<select id="frequency">
<option value="twice per day">twice per day</option>
<option value="3 times per day">3 times per day</option>
<option value="once per day" selected>once per day</option>
</select>
<label for="duration">Duration</label>
<select id="duration">
<option value="7">7 days</option>
<option value="14" selected>14 days</option>
<option value="21">21 days</option>
</select>
<label for="total_quantity">Quantity: </label>
<input type="number" id="quantity" max="100"> <!-- Default needs to be calculated from qtyperdose * frequency * duration -->
</code></pre>
| [
{
"answer_id": 74246648,
"author": "hhpr98",
"author_id": 14194981,
"author_profile": "https://Stackoverflow.com/users/14194981",
"pm_score": -1,
"selected": false,
"text": "useEffect(()=>{\n // TODO: your code here\n this.testLog.bind(this)\n},[]);\n"
},
{
"answer_id": 7424683... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20366656/"
] |
74,246,727 | <p>Still pretty new to threads so I'm sure it is one of those little gotchas and a repeat question, but I have been unable to find the answer browsing the threads.</p>
<p>I have a port scanner app in C#.
I'm using threadpools to spin up a new TcpClient for each port and probe if it's open.
After suffering through the concepts of closures and thread synchronization, I am having an issue where when multiple threads try to save their results to different indexes in the <code>Orchestrator.hosts</code> (List).</p>
<p>I have multiple threads trying to update a single List results object. My understanding is this is fine as long as I lock the object on write, however I'm finding that on some updates, multiple entries are getting the same update.
IE, Thread #1 supposed to update <code>Hosts[0].Ports[0].Status</code> to "Open",
What happens:
Thread #1 updates multiple host with the port result despite passing a specific index for Hosts.
<code>Hosts[0].Ports[0].Status</code> to "Open",
<code>Hosts[1].Ports[0].Status</code> to "Open",
<code>Hosts[2].Ports[0].Status</code> to "Open",</p>
<p>Not sure where my problem is. The Static method I'm calling to perform a probe of a given port</p>
<pre><code> public static void ScanTCPPorts()
{
// Create a list of portsToScan objects to send to thread workers
//List<ScanPortRequest> portsToScan = new List<ScanPortRequest>();
using (ManualResetEvent resetEvent = new ManualResetEvent(false))
{
int toProcess = 0;
for (var i = 0; i < hostCount; i++) // Starting at Begining
{
int currentHostId = i;
// To hold our current hosts ID (Assign outside of threaded function to avoid race-condition)
if (hosts[i].IsAlive || scanDefinition.isForced())
{
int portCount = hosts[i].Ports.Count;
for (int p = 0; p < portCount; p++)
{
// Thread-safe Increment our workQueue counter
Interlocked.Increment(ref toProcess);
int currentPortPosition = p;
// We need to send the arrayIndex in to the thread function
PortScanRequestResponse portRequestResponse = new PortScanRequestResponse(hosts[currentHostId], currentHostId, hosts[currentHostId].Ports[currentPortPosition], currentPortPosition);
ThreadPool.QueueUserWorkItem(
new WaitCallback(threadedRequestResponseInstance => {
PortScanRequestResponse portToScan = threadedRequestResponseInstance as PortScanRequestResponse;
PortScanRequestResponse threadResult = PortScanner.scanTCPPort(portToScan);
// Lock so Thread-safe update to result
lock (Orchestrator.hosts[portToScan.hostResultIndex])
{
if (threadResult.port.status == PortStatus.Open)
{
// Update result
Orchestrator.hosts[portToScan.hostResultIndex].Ports[portToScan.portResultIndex].status = PortStatus.Open;
//Logger.Log(hosts[currentHostId].IPAddress + " " + hosts[currentHostId].Ports[currentPortPosition].type + " " + hosts[currentHostId].Ports[currentPortPosition].portNumber + " is open");
}
else
{
Orchestrator.hosts[portToScan.hostResultIndex].Ports[portToScan.portResultIndex].status = PortStatus.Closed;
}
// Check if this was the last scan for the given host
if (Orchestrator.hosts[portToScan.hostResultIndex].PortScanComplete != true)
{
if (Orchestrator.hosts[portToScan.hostResultIndex].isCompleted())
{
Orchestrator.hosts[portToScan.hostResultIndex].PortScanComplete = true;
// Logger.Log(hosts[currentHostId].IPAddress + " has completed a port scan");
Orchestrator.hosts[portToScan.hostResultIndex].PrintPortSummery();
}
}
}
// Safely decrement the counter
if (Interlocked.Decrement(ref toProcess) == 0)
resetEvent.Set();
}), portRequestResponse); // Pass in our Port to scan
}
}
}
resetEvent.WaitOne();
}
}
</code></pre>
<p>Here is the worker process in a separate public static class.</p>
<pre><code> public static PortScanRequestResponse scanTCPPort(object portScanRequest) {
PortScanRequestResponse portScanResponse = portScanRequest as PortScanRequestResponse;
HostDefinition host = portScanResponse.host;
ScanPort port = portScanResponse.port;
try
{
using (TcpClient threadedClient = new TcpClient())
{
try
{
IAsyncResult result = threadedClient.BeginConnect(host.IPAddress, port.portNumber, null, null);
Boolean success = result.AsyncWaitHandle.WaitOne(Orchestrator.scanDefinition.GetPortTimeout(), false);
if (threadedClient.Client != null)
{
if (success)
{
threadedClient.EndConnect(result);
threadedClient.Close();
portScanResponse.port.status = PortStatus.Open;
return portScanResponse;
}
}
} catch { }
}
}
catch
{ }
portScanResponse.port.status = PortStatus.Closed;
return portScanResponse;
}
</code></pre>
<p>Originally I was pulling the host index from a free variable, thinking this was the problem moved it to inside the delegate.
I tried locking the Hosts object everywhere there was a write.
I have tried different thread sync techniques (<code>CountdownEvent</code> and <code>ManualResetEvent</code>).</p>
<p>I think there is just some fundamental threading principal I have not been introduced to yet, or I have made a very simple logic mistake.</p>
| [
{
"answer_id": 74246648,
"author": "hhpr98",
"author_id": 14194981,
"author_profile": "https://Stackoverflow.com/users/14194981",
"pm_score": -1,
"selected": false,
"text": "useEffect(()=>{\n // TODO: your code here\n this.testLog.bind(this)\n},[]);\n"
},
{
"answer_id": 7424683... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20366513/"
] |
74,246,739 | <p>The first pic what it looks like on csv file:
<a href="https://i.stack.imgur.com/LzAbb.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>The second pic is what it reads in R:
<a href="https://i.stack.imgur.com/MbXCq.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>The first date is changed from "2007.1" to "2007.10". If the month is January it will be changed to October when I read in the csv file. I am trying to make this variable into a data frame. Can someone help?</p>
<p>Then my code looks like this:</p>
<pre><code>df <- read.csv("PS_09_orangutans.csv")
n.time <- paste(df$date, ".01", sep = '') # add day
n.time
n.time <- as.Date(n.time) # make Date class
</code></pre>
<p>The error is: Error in charToDate(x) : character string is not in a standard unambiguous format</p>
| [
{
"answer_id": 74246648,
"author": "hhpr98",
"author_id": 14194981,
"author_profile": "https://Stackoverflow.com/users/14194981",
"pm_score": -1,
"selected": false,
"text": "useEffect(()=>{\n // TODO: your code here\n this.testLog.bind(this)\n},[]);\n"
},
{
"answer_id": 7424683... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20366648/"
] |
74,246,748 | <p>I want to extract columns depending on their data type from a table.
From this table I want to only end up with columns containing only integers.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Price.</th>
<th>Food</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>5</td>
<td>Bread</td>
<td>6</td>
</tr>
<tr>
<td>3</td>
<td>Cereal</td>
<td>7</td>
</tr>
</tbody>
</table>
</div>
<p>This is the desired output:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Price.</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>3</td>
<td>7</td>
</tr>
</tbody>
</table>
</div>
<p>How would I go about doing this?</p>
<p>I have tried to use string_agg() to use the column names in a select statement but it did not create the output I desired.</p>
<pre><code>select(
select
string_agg(column_name, ',')
from information_schema.columns
where table_name = 'table_name' and data_type = 'integer')
from table_name
</code></pre>
| [
{
"answer_id": 74247938,
"author": "Ramin Faracov",
"author_id": 17296084,
"author_profile": "https://Stackoverflow.com/users/17296084",
"pm_score": -1,
"selected": false,
"text": "select 'select ' || string_agg(column_name, ', ') || ' from ' || table_schema || '.' || table_name \nfrom i... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20366735/"
] |
74,246,794 | <p>The /var/opt/gitlab/gitlab-workhorse/ folder is missing a socket and is generally almost empty.</p>
<p>I'm trying to set up GitLab + nginx proxy. When I try to load the page, I get a 502 error.
Having figured out what exactly does not work for me, I realized (gitlab-ctl status):</p>
<p><code>down: gitlab-workhorse: 0s, normally up, want up; run: log: (pid 3756258) 12450s</code></p>
<p>Then I decided to look at my workhorse socket and this is what I saw in the /var/opt/gitlab/gitlab-workhorse folder (ls -ap /var/opt/gitlab/gitlab-workhorse/):</p>
<p><code>./ ../ config.toml VERSION</code></p>
<p>My gitlab settings:</p>
<pre><code>nginx['enable'] = false
web_server['external_users'] = ['www-data']
gitlab_rails['trusted_proxies'] = ['127.0.0.1', <external-server-ip>]
gitlab_workhorse['listen_network'] = "unix"
gitlab_workhorse['listen_addr'] = "/var/opt/gitlab/gitlab-workhorse/sockets/socket"
</code></pre>
<p>nginx log:</p>
<p><code>connect() to unix:/var/opt/gitlab/gitlab-workhorse/sockets/socket failed (13: Permission denied) while connecting to upstream</code></p>
<p>As I understand it, I am missing the required software or some files. Where can I get them if that's the problem. If not, why might my workhorse not work?</p>
<p>p.s. sorry for google translate :)</p>
<p>upd. (/var/log/gitlab/gitlab-workhorse/current):</p>
<pre><code>{"build_time":"20221024.191252","level":"info","msg":"Starting","time":"2022-10-30T20:05:21+03:00","version":"v15.5.1"}
{"address":"localhost:9229","level":"info","msg":"Running metrics server","network":"tcp","time":"2022-10-30T20:05:21+03:00"}
{"level":"info","msg":"keywatcher: starting process loop","time":"2022-10-30T20:05:21+03:00"}
{"address":"/var/opt/gitlab/redis/redis.socket","level":"info","msg":"redis: dialing","network":"unix","time":"2022-10-30T20:05:21+03:00"}
{"address":"/var/opt/gitlab/gitlab-workhorse/sockets/socket","level":"info","msg":"Running upstream server","network":"unix","time":"2022-10-30T20:05:21+03:00"}
{"error":"listen unix /var/opt/gitlab/gitlab-workhorse/sockets/socket: bind: no such file or directory","level":"fatal","msg":"shutting down","time":"2022-10-30T20:05:21+03:00"
</code></pre>
| [
{
"answer_id": 74247938,
"author": "Ramin Faracov",
"author_id": 17296084,
"author_profile": "https://Stackoverflow.com/users/17296084",
"pm_score": -1,
"selected": false,
"text": "select 'select ' || string_agg(column_name, ', ') || ' from ' || table_schema || '.' || table_name \nfrom i... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20366643/"
] |
74,246,804 | <p>I have some layout like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.foo {
display: flex;
flex-wrap: wrap;
}
.bar {
padding: 1rem 6rem;
text-align: center;
background: #A0E7E5;
}
.active {
background: #B4F8C8;
order: 99;
width: 100%;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="foo">
<div class="bar">1</div>
<div class="bar">2</div>
<div class="bar active">3</div>
<div class="bar">4</div>
<div class="bar">5</div>
</div></code></pre>
</div>
</div>
</p>
<p>Is there a way to prevent wrapping of the blue divs and instead show a scrollbar for the first row (preferably without layout modification)? Basically any of the items (<code>.bar</code>) can be marked as <code>.active</code> and I want to show the active one on a separate row at end.</p>
| [
{
"answer_id": 74247938,
"author": "Ramin Faracov",
"author_id": 17296084,
"author_profile": "https://Stackoverflow.com/users/17296084",
"pm_score": -1,
"selected": false,
"text": "select 'select ' || string_agg(column_name, ', ') || ' from ' || table_schema || '.' || table_name \nfrom i... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11613622/"
] |
74,246,814 | <p>When clicking the colored boxes on <a href="https://mdn.github.io/learning-area/html/forms/image-type-example/xy-coordinates-example.html" rel="nofollow noreferrer">this MDN example page</a>, the URL shows the coordinates of the click.</p>
<p>When using <code>document.querySelector("input").click()</code>, the URL shows coordinates of <code>x=0&y=0</code>.</p>
<p>I want to programmatically click the button, using the console or a userscript, such that the URL shows the coordinates I specify.</p>
<p>What I’ve tried:</p>
<pre class="lang-js prettyprint-override"><code>document.querySelector("input").dispatchEvent(new MouseEvent("click", {
x: 55, // And also `offsetX` and `clientX`.
y: 55
}));
</code></pre>
<p>The documentation on <a href="//developer.mozilla.org/en/docs/Web/API/MouseEvent/MouseEvent" rel="nofollow noreferrer"><code>MouseEvent</code></a> notes that these don’t actually move the cursor, which is fine.</p>
<p>I tried putting a <code><div></code> over it, passing the click through.</p>
<pre class="lang-js prettyprint-override"><code>const newdiv = document.createElement("div");
newdiv.style.position = "fixed";
newdiv.style.height = "1px";
newdiv.style.width = "1px";
newdiv.style.top = "55px";
newdiv.style.left = "55px";
newdiv.style.pointerEvents = "none";
document.querySelector("div").prepend(newdiv);
newdiv.click();
</code></pre>
<p>This works for manual clicks, but <code>.click()</code> doesn’t do anything (because it’s a sibling?).
<code>document.querySelector("input").prepend(newdiv);</code> will bubble, but it’s still (0, 0).</p>
<p>How can I click at a coordinate?</p>
<p>I had already tried the answers of the suggested question <a href="/q/3277369/20366663">How to simulate a click by using x,y coordinates in JavaScript?</a> before asking this question (it was one of the first Google results I found). This question is not a duplicate because the marked answer, firstly gets the element, <em>then</em> clicks it:</p>
<pre class="lang-js prettyprint-override"><code>document.elementFromPoint(x, y).click();
</code></pre>
<p>which is exactly the same as</p>
<pre class="lang-js prettyprint-override"><code>document.querySelector("input").click();
</code></pre>
<p>Comments suggest this is not possible, because it could make users click ads. Can it truly not be done?</p>
<p>Other solutions “click” the page / element, but do not submit the form (the URL does not change to show where the button was clicked).</p>
| [
{
"answer_id": 74248306,
"author": "Paxon Kymissis",
"author_id": 19925946,
"author_profile": "https://Stackoverflow.com/users/19925946",
"pm_score": 0,
"selected": false,
"text": "// detect the mouse movement\ndocument.addEventListener('click', function (event){\nconsole.log(event.clien... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20366663/"
] |
74,246,826 | <p>I know I can change the data type of columns by passing the column names, for example</p>
<p><code>df = df.astype({'col1': 'object', 'col2': 'int'})</code></p>
<p>but what if I want to change multiple columns by a given range? My df contains 50+ columns so I don't want to change them all by name. I want to set columns 17 to 41 as ints and I've tried a few variations, for example:</p>
<p><code>df = df.astype([17:41], 'int64')</code>
but can't get the syntax to work. Any ideas?</p>
| [
{
"answer_id": 74246846,
"author": "Rahul Raina",
"author_id": 8337352,
"author_profile": "https://Stackoverflow.com/users/8337352",
"pm_score": 2,
"selected": false,
"text": "df.iloc[:,16:42] = df.iloc[:,16:42].apply(pd.to_numeric)\n"
},
{
"answer_id": 74246888,
"author": "t... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17588688/"
] |
74,246,873 | <p>Purely as a learning experience I've started a basic Python script. At the moment, it's supposed to simulate a shuffled deck of standard playing cards. My script works as expected, except for the shuffling part.</p>
<pre><code>import random
deck = list()
# play_deck = list()
suits = ['hearts', 'clubs', 'diamonds', 'spades']
card = {'suit':'', 'faceval': ''}
i = 0
for suit in suits:
j = 1
while j < 14:
card = {'suit': suit, 'faceval': str(j)}
deck.append(card)
j+=1
i+=1
deck = random.shuffle(deck)
for card in deck:
print(card['suit'])
print(card['faceval'])
</code></pre>
<p>I create the deck using a list of suits and a for loop to get four suits of 13 cards each, and then print each deck list memberm (card) to the console to see that it's working as expectecd.</p>
<p>But when I add random.shuffle() into the code, I get this error:</p>
<blockquote>
<p>TypeError: 'NoneType' object is not iterable</p>
</blockquote>
<p>I've tried these techniques:</p>
<pre><code>deck = random.shuffle(deck)
play_deck = random.shuffle(deck)
</code></pre>
<p>Why I can't iterate over the deck after running it through random.shuffle() function? Am I missing something?</p>
| [
{
"answer_id": 74246885,
"author": "AKX",
"author_id": 51685,
"author_profile": "https://Stackoverflow.com/users/51685",
"pm_score": 0,
"selected": false,
"text": "random.shuffle(lst)"
}
] | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2512677/"
] |
74,246,928 | <p>I am using batch file to send uploaded pdf document from my mobile to usb printer using dropbox folder. I use free PDFtoPrinter program to print and scheduled task to periodically run a batch file. The batch file contains following code.</p>
<pre><code>"C:\Dropbox\PDFtoPrinter" "C:\Dropbox\Sent files\*.pdf"
move "c:\Dropbox\Sent files\*.pdf" "C:\Dropbox\printed"
</code></pre>
<p>The script function well if sent files folder contains pdf file but if it is empty, it gets stuck.
I would like to use if statement to check if folder contains pdf file. The script should exist if none is found. I am not a programmer. Kindly help</p>
<pre><code>"C:\Dropbox\PDFtoPrinter" "C:\Dropbox\Sent files\*.pdf"
move "c:\Dropbox\Sent files\*.*" "C:\Dropbox\printed"
</code></pre>
<p>Problem : if sent file folder is empty, the script gets stuck. Scheduled task next time does not work</p>
| [
{
"answer_id": 74247211,
"author": "Magoo",
"author_id": 2128947,
"author_profile": "https://Stackoverflow.com/users/2128947",
"pm_score": 1,
"selected": false,
"text": "if exist \"C:\\Dropbox\\Sent files\\*.pdf\" \"C:\\Dropbox\\PDFtoPrinter\" \"C:\\Dropbox\\Sent files\\*.pdf\"\n\nmove \... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20366828/"
] |
74,246,930 | <p>I am trying to sign into a website (<a href="https://myaccount.play-cricket.com/" rel="nofollow noreferrer">https://myaccount.play-cricket.com/</a>) using selenium in python.</p>
<p>I am struggling to send text (from the password variable in the python code) to the password textbox field on the website.</p>
<p>Here is my code:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
username = 'example@hotmail.com'
password = 'password123'
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get('https://myaccount.play-cricket.com/')
time.sleep(5)
driver.find_element(By.NAME, 'email').send_keys(username)
wait = WebDriverWait(driver, 20)
wait.until(EC.element_to_be_clickable((By.NAME,
'password'))).send_keys(password)
</code></pre>
<p>Here is the error:</p>
<p><a href="https://i.stack.imgur.com/FmUyD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FmUyD.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74247211,
"author": "Magoo",
"author_id": 2128947,
"author_profile": "https://Stackoverflow.com/users/2128947",
"pm_score": 1,
"selected": false,
"text": "if exist \"C:\\Dropbox\\Sent files\\*.pdf\" \"C:\\Dropbox\\PDFtoPrinter\" \"C:\\Dropbox\\Sent files\\*.pdf\"\n\nmove \... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20366776/"
] |
74,246,953 | <p>I have an old xcode project from iPhone4 and iPhone3GS era.
It uses location service.</p>
<p>When I run the app, it seems it does not get locations.
Even it does not ask "it uses your current locastion. do you allow it?"</p>
<p>How can I enable location service?
Note: it did not have any problems to get locations on iPhone3GS.</p>
<p>Thank you very much!
Have a nice weekend :)</p>
<p>Xcode 14.0.0.</p>
| [
{
"answer_id": 74254925,
"author": "doctor",
"author_id": 6909164,
"author_profile": "https://Stackoverflow.com/users/6909164",
"pm_score": 0,
"selected": false,
"text": "if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)\n [self.locationManager requestWhenInUseAuthoriz... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6909164/"
] |
74,246,980 | <p>Does anybody know how to reduce the space of an <code>hr</code> to the element above? My current style looks like this:</p>
<pre><code>hr.hrabt {
border: 5px solid black;
border-radius: 5px;
width: 7%;
margin-left: 0;
}
</code></pre>
<p>As result, I get following:</p>
<p><a href="https://i.stack.imgur.com/LwbkG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LwbkG.png" alt="Before" /></a></p>
<p>I would like it to look like this though:
<a href="https://i.stack.imgur.com/hLjjV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hLjjV.png" alt="After" /></a>
I already tried several things not working, like setting the top margin to 0.</p>
| [
{
"answer_id": 74254925,
"author": "doctor",
"author_id": 6909164,
"author_profile": "https://Stackoverflow.com/users/6909164",
"pm_score": 0,
"selected": false,
"text": "if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)\n [self.locationManager requestWhenInUseAuthoriz... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19377344/"
] |
74,246,997 | <p>Im not sure weather or not to use Time.deltaTime I think it would be good to implement it but im not sure how to, I've already tried but I've messed something up</p>
<pre><code>using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float horSpeed;
[SerializeField] private float vertSpeed;
private Rigidbody2D rb;
private bool isJumping;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
// we store the initial velocity, which is a struct.
var v = rb.velocity;
if (Input.GetKey(KeyCode.Space) && !isJumping)
{
v.y = vertSpeed * Time.deltaTime;
isJumping = true;
}
if (Input.GetKey(KeyCode.A))
v.x = -horSpeed * Time.deltaTime;
if (Input.GetKey(KeyCode.D))
v.x = horSpeed * Time.deltaTime;
if (Input.GetKey(KeyCode.S))
v.y = -vertSpeed * Time.deltaTime;
rb.velocity = v;
if(Input.GetKey(KeyCode.Escape))
SceneManager.LoadScene(0);
}
private void OnCollisionEnter2D(Collision2D collision)
{
isJumping = false;
}
}
</code></pre>
<p>When I tried to add it my character just moved extremely slow</p>
| [
{
"answer_id": 74247363,
"author": "Rafawat Sholaiman Alphi",
"author_id": 16685389,
"author_profile": "https://Stackoverflow.com/users/16685389",
"pm_score": -1,
"selected": false,
"text": "public float speed = 2f;\nprivate Rigidbody2D rb;\nprivate Vector2 moveDelta;\n//Inputs\nprivate ... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74246997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20266551/"
] |
74,247,000 | <p>I have a list of 58 dataframes under the list named nafilt_persample.ngsrep. Inside it are 58 df, named according to individual IDs: SVT_01...58. Each df contains 15 columns with either characters or numbers like:</p>
<pre><code> Tumor_Sample_Barcode Hugo_Symbol Chromosome Start_Position End_Position Variant_Type Variant_Classification coverage VAF
1: SVT_01 DNMT3A chr2 25464495 25464495 SNP Missense_Mutation 2835 0.011
2: SVT_01 JAK2 chr9 5073770 5073770 SNP Missense_Mutation 2533 0.028
cDNA_Change Protein_Change Reference_Allele Tumor_Seq_Allele2 ref_reads var_reads
1: c.2018G>T p.Gly673Val C A 2808 27
2: c.1849G>T p.V617F G T 2455 78
</code></pre>
<p>I need to add to each df in the list two columns lCI and uCI with values coming from a second list that is ordered according to the same ID, (SVT_) and gene and looks like this (called cint):</p>
<pre><code>$DNMT3A
[1] 0.006285366 0.013826599
attr(,"conf.level")
[1] 0.95
$JAK2
[1] 0.02441547 0.03828421
attr(,"conf.level")
[1] 0.95
</code></pre>
<p>I would like to obtain a result like this:</p>
<pre><code> Tumor_Sample_Barcode Hugo_Symbol Chromosome Start_Position End_Position Variant_Type Variant_Classification coverage VAF
1: SVT_01 DNMT3A chr2 25464495 25464495 SNP Missense_Mutation 2835 0.011
2: SVT_01 JAK2 chr9 5073770 5073770 SNP Missense_Mutation 2533 0.028
cDNA_Change Protein_Change Reference_Allele Tumor_Seq_Allele2 ref_reads var_reads lCI uCI
1: c.2018G>T p.Gly673Val C A 2808 27 0.06 0.013
2: c.1849G>T p.V617F G T 2455 78 0.024 0.038
</code></pre>
<p>So far I have tried this but without success:</p>
<pre><code>merged.list <- list()
for (i in names(nafilt_persample.ngsrep)){ for (k in nafilt_persample.ngsrep[[i]]$Hugo_Symbol){
merged.list[[i]] <- cbind(nafilt_persample.ngsrep[[i]], cint[[i]][[k]][1], cint[[i]][[k]][2])
}
}
</code></pre>
<p>The error here is that despite the two columns are added, only values from the last cycle item are added, So in the example of SVT_01 shown above this is the result:</p>
<pre><code> Tumor_Sample_Barcode Hugo_Symbol Chromosome Start_Position End_Position Variant_Type Variant_Classification coverage VAF
1: SVT_01 DNMT3A chr2 25464495 25464495 SNP Missense_Mutation 2835 0.011
2: SVT_01 JAK2 chr9 5073770 5073770 SNP Missense_Mutation 2533 0.028
cDNA_Change Protein_Change Reference_Allele Tumor_Seq_Allele2 ref_reads var_reads lCI uCI
1: c.2018G>T p.Gly673Val C A 2808 27 0.024 0.038
2: c.1849G>T p.V617F G T 2455 78 0.024 0.038
</code></pre>
<p>That is: the CI of JAK2 is duplicated onto the DNMT3A row.
How can I fix this?
Hope I provided enough info</p>
| [
{
"answer_id": 74247224,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "nafilt_persample.ngsrep <- Map(function(dat, nm), \n {\n dat[c(\"lCI\", \"uCI\")] <- nm[dat$Hugo_Symbol]\n da... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17114315/"
] |
74,247,005 | <p>In <a href="https://stackoverflow.com/questions/39538473/using-settimeout-on-promise-chain">this post</a> it is mentioned that I can create a custom Promise with <code>setTimeout</code> like below:</p>
<pre class="lang-js prettyprint-override"><code>const delay = t => new Promise(resolve => setTimeout(resolve, t));
</code></pre>
<p>My operation needs to be executed after 100ms so <code>t</code> will be <code>100</code> in my scenario.</p>
<p>I'm confused on how to use this though. The normal format of a Promise is <code>new Promise (resolve, reject)</code> but in the <code>delay</code> function only the <code>resolve</code> has been defined.
Here's my attempt:</p>
<pre class="lang-js prettyprint-override"><code>function numbersValidation(number1, number2) {
if (!Number.isFinite(number1) || !Number.isFinite(number2)) {
throw new Error('Only numbers are allowed');
}
}
function add(number1, number2) {
numbersValidation(number1, number2);
return number1 + number2;
}
const addPromise = (number1, number2) => {
delay(100)
.then(result => result = add(number1, number2));
.catch(err => reject(err));
};
// -----Test------
describe.only('promise calculator', () => {
it('add works fine', done => {
calculator.addPromise(1, 2).then(result => {
try {
assert.equal(3, result);
done();
} catch (e) {
done(e);
}
});
});
});
// AssertionError [ERR_ASSERTION]: 3 == false
</code></pre>
<p>This is quite wrong since my IDE is complaining about the structure, but can someone please point me in the right direction on how to use the delay function so that I make my <code>addPromise</code> function work?
Thank you</p>
| [
{
"answer_id": 74247224,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "nafilt_persample.ngsrep <- Map(function(dat, nm), \n {\n dat[c(\"lCI\", \"uCI\")] <- nm[dat$Hugo_Symbol]\n da... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19640633/"
] |
74,247,011 | <p>How can I log out active session of banned user with Symfony?</p>
<p><strong>This is not working</strong></p>
<pre><code>security:
always_authenticate_before_granting: true
</code></pre>
<p>this is error</p>
<pre><code> The security option "always_authenticate_before_granting" cannot be used when "enable_authenticator_manager" is set to true. If you rely on this behavior, set it to false
</code></pre>
| [
{
"answer_id": 74247224,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 1,
"selected": false,
"text": "nafilt_persample.ngsrep <- Map(function(dat, nm), \n {\n dat[c(\"lCI\", \"uCI\")] <- nm[dat$Hugo_Symbol]\n da... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19533337/"
] |
74,247,050 | <p>I have this method:</p>
<pre><code>def filter_verdi_total_fruit_cost(file_name):
output = []
for token in file_name.split('\n'):
items = token.split()
if len(items) > 2 and items[1] in fruit_words:
output.append((items[1], items[-1]))
for _, v in output:
return v
print(filter_verdi_total_fruit_cost(verdi50))
</code></pre>
<p>And it prints just one value: 123,20.</p>
<p>But when I replace return v with: <code>print(v) </code> it prints all the values, when I am calling the method: <code>print(filter_verdi_total_fruit_cost(verdi50))</code></p>
<pre><code>123,20
2.772,00
46,20
577,50
69,30
3.488,16
137,50
500,00
1.000,00
2.000,00
1.000,00
381,2
</code></pre>
<p>But this I don't understand. I just return v. and then it prints just one value. If I do a print(v) it prints all the values.</p>
<p>Question: How can I return all the values in the method, without the print statement?</p>
| [
{
"answer_id": 74247066,
"author": "Rodrigo Guzman",
"author_id": 13315525,
"author_profile": "https://Stackoverflow.com/users/13315525",
"pm_score": 2,
"selected": false,
"text": "return"
},
{
"answer_id": 74247076,
"author": "Samwise",
"author_id": 3799759,
"author_... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7713770/"
] |
74,247,069 | <p>I got this error while trying to get variable from a DataBase in MySql</p>
<pre><code>0x000002A MySQL Connection Error!
</code></pre>
<p>MySql error is provided when version/value we're trying to get from database is not a number</p>
<p>output when trying to print value Program is trying to get from database:
<code>None</code></p>
<p>I tried to get variable named: "gameVersion" from DataBase Named: "gameversions", using Name of game but Instead of getting variable which has: "beta" I got mysql connector error</p>
<p>file and code that caused this error: functions.py:</p>
<pre><code>import mysql.connector
database = mysql.connector.connect(
host = "localhost",
user = "root",
passwd = "s+W2DrcPQK5dada2^!dV!RUSZ@2$PbEX*3eacT",
database = "PythonDB",
)
my_cursor = database.cursor(buffered=True)
user = ""
game = ""
db_version = my_cursor.execute(f"SELECT gameVersion FROM gameversions WHERE gameName = 'Grand Thiefs'")
sqlStuff = "INSERT INTO users (usersUid, usersEmail, usersPwd, UsersPerms, usersMoney, gameVersion) VALUES (%s, %s, %s, %s, %s, %s)"
sqlStuffv = "INSERT INTO gameversions (gameVersion, gameName) VALUES (%s, %s)"
def CreateDataBase(name):
my_cursor.execute(f"CREATE DATABASE {name}")
#my_cursor.execute("CREATE TABLE gameVersions (gameVersion varchar(255) NOT NULL, gameName varchar(255) NOT NULL);")
def ShowTables():
my_cursor.execute("SHOW TABLES")
def ShowDataBases():
my_cursor.execute("SHOW DATABASES")
def CreateUser(Name, Password, Email, Version):
global user
user = [{Name}, {Email}, {Password}, "User", "0", {Version}]
my_cursor.execute(sqlStuff, user)
database.commit()
def checkversion(version, name):
if version != db_version:
if type(db_version) == float:
return "Failure"
else:
return "MySQL Connection Error"
else:
return "Correct"
</code></pre>
| [
{
"answer_id": 74247066,
"author": "Rodrigo Guzman",
"author_id": 13315525,
"author_profile": "https://Stackoverflow.com/users/13315525",
"pm_score": 2,
"selected": false,
"text": "return"
},
{
"answer_id": 74247076,
"author": "Samwise",
"author_id": 3799759,
"author_... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20239851/"
] |
74,247,072 | <p>I want to use <strong>NPM</strong> package in my <code>index.js</code> file without installing it with package manager, i don't have a <strong>HTML</strong> file, i only have <code>index.js</code> file which is executed with <code>node index.js</code> command when i have to use this file anywhere, so i can't use <strong>CDN</strong>. Is there any way i can use the package in my js file without installing it and without using <strong>CDN</strong>. Or is there any way we can require or import a package locally in js file.</p>
| [
{
"answer_id": 74247066,
"author": "Rodrigo Guzman",
"author_id": 13315525,
"author_profile": "https://Stackoverflow.com/users/13315525",
"pm_score": 2,
"selected": false,
"text": "return"
},
{
"answer_id": 74247076,
"author": "Samwise",
"author_id": 3799759,
"author_... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9663776/"
] |
74,247,103 | <p>I want to sum up a value from all cells in column H, where the value in K is bigger than the value in F. I thought I could do this like that:</p>
<p>=SUMIFS(Gains!H:H;Gains!E:E;"sold";Gains!K:K;">="&Gains!F:F)</p>
<p>But the last criterion is problematic:</p>
<p>Gains!K:K;">="&Gains!F:F</p>
<p>How can I express this correctly?</p>
| [
{
"answer_id": 74247255,
"author": "anefeletos",
"author_id": 1237786,
"author_profile": "https://Stackoverflow.com/users/1237786",
"pm_score": 3,
"selected": true,
"text": "=SUM(H:H*(K:K>=F:F)*(E:E=\"sold\"))"
},
{
"answer_id": 74247409,
"author": "Prema",
"author_id": 1... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4683883/"
] |
74,247,104 | <p>I am trying to delete a record from an entered position, from a dynamically allocated array in c++, and when i try to run the program it throws an error stating</p>
<pre class="lang-none prettyprint-override"><code>terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
</code></pre>
<p>The insertion and displaying of the records are running perfectly fine, the only thing that throws an error is delete operation.</p>
<p>The Code</p>
<pre><code>#include <iostream>
using namespace std;
struct employee{
string name;
int empId;
string dept;
int age;
};
employee *emp = new employee[5];
void insertData(){
for (int i = 0; i<5; i++){
cout<<"Enter the Employee name"<<endl;
cin>>emp -> name;
cout<<"Enter the Employee Id"<<endl;
cin>>emp -> empId;
cout<<"Enter the Employee Department"<<endl;
cin>>emp -> dept;
cout<<"Enter the Employee age"<<endl;
cin>>emp -> age;
}
}
void displayData(){
for (int i = 0; i < 5; ++i) {
cout<<"Employee"<<i+1<<" Data"<<endl;
cout<<"Name : "<<emp -> name<<endl;
cout<<" Employe ID : "<<emp -> empId<<endl;
cout<<"Department : "<<emp -> dept<<endl;
cout<<"Age : "<<emp -> age<<endl<<endl;
}
}
void deleteData(){
int pos;
cout<<"Enter the position you want to delete Data";
cin>>pos;
if (pos>5){
cout<<"Invalid Size please enter a size smaller than 5";
}
for (int i = pos; i < 5; ++i) {
emp[i] = emp[i+1];
}
}
int menu(){
int x;
do {
int n;
cout << "Please enter the number corresponding to an operation you want to perform\n";
cout << "1. Insert Data" << endl;
cout << "2. Display Data" << endl;
cout << "3. Delete Data" << endl;
cout << "4. Exit" << endl;
cin >> n;
switch (n) {
case 1: {
insertData();
break;
}
case 2: {
displayData();
break;
}
case 3: {
deleteData();
break;
}
case 4: {
exit(0);
}
default:
cout << "Invalid Choice, Enter a valid choice";
return 1;
}
cout<<"Press 1 to continue or 0 to exit";
cin>>x;
} while (x == 1);
}
int main() {
menu();
return 0;
}
</code></pre>
| [
{
"answer_id": 74247483,
"author": "Andreas Hadjigeorgiou",
"author_id": 12372001,
"author_profile": "https://Stackoverflow.com/users/12372001",
"pm_score": -1,
"selected": false,
"text": "employee *emp = new employee[5]; \n"
},
{
"answer_id": 74247979,
"author": "Chris",
... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16650691/"
] |
74,247,105 | <p>I have a SQL Server query which <code>COUNT</code>s based on the values of <code>id</code> columns.</p>
<p>Like this:</p>
<pre><code>SELECT
[id],
COUNT(*) AS IdCount,
FROM
myTable
WHERE
DATEDIFF(day, [Time], GETDATE()) < 30
GROUP BY
[id]
</code></pre>
<p>I want to add the value of the <code>COUNT</code> result in the <code>WHERE</code> condition. How can I do that?</p>
<pre><code>SELECT
[id],
COUNT(*) AS IdCount,
RANK() OVER (ORDER BY IdCount) CountRank
FROM
myTable
WHERE
DATEDIFF(day, [Time], GETDATE()) < 30
AND {Count values is > 100}
GROUP BY
[id]
</code></pre>
| [
{
"answer_id": 74247483,
"author": "Andreas Hadjigeorgiou",
"author_id": 12372001,
"author_profile": "https://Stackoverflow.com/users/12372001",
"pm_score": -1,
"selected": false,
"text": "employee *emp = new employee[5]; \n"
},
{
"answer_id": 74247979,
"author": "Chris",
... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18443805/"
] |
74,247,135 | <p>Let's say I have the following tables:</p>
<pre class="lang-sql prettyprint-override"><code>create table user (
id int
);
create table transaction (
user_id int,
date timestamp,
amount int
);
</code></pre>
<p>I have an array of 100 users (result from another query). I'd like to get the 100 last transactions of each user from my input array.</p>
<p>I've tried a simple query wrapped in a for loop in a script, but I'm thinking there must be a way to do this with a <code>where in</code> in pure SQL.</p>
| [
{
"answer_id": 74247483,
"author": "Andreas Hadjigeorgiou",
"author_id": 12372001,
"author_profile": "https://Stackoverflow.com/users/12372001",
"pm_score": -1,
"selected": false,
"text": "employee *emp = new employee[5]; \n"
},
{
"answer_id": 74247979,
"author": "Chris",
... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10333882/"
] |
74,247,146 | <p>I'm trying to make a C# method to fulfill this user story.</p>
<p>These are the 2 acceptance criteria</p>
<ul>
<li>Start time must be at least one hour later than the current system time.</li>
<li>End time must be at last one hour after start time.</li>
</ul>
<p>Both of the start and end time must be DateTime values, so I can parse it with the TryParse method.</p>
<p>Here's what I have in my code so far:</p>
<p>`</p>
<pre><code>
private DateTime datetime;
public DateTime datetimeStart { get; set; }
public DateTime datetimeEnd { get; set; }
while (true) {
Util.GetInput("Delivery window start (dd/mm/yyyy hh:mm)");
string userInput = ReadLine();
if(DateTime.TryParse(userInput, out datetime))
{
if (datetime.TimeOfDay.Hours - DateTime.Now.TimeOfDay.Hours >= 1) {
datetimeStart = datetime;
}
break;
}
else
{
WriteLine("\tDelivery window start must be at least one hour in the future.");
}
}
while (true) {
Util.GetInput("Delivery window end (dd/mm/yyyy hh:mm)");
string userInput = ReadLine();
if(DateTime.TryParse(userInput, out datetime))
{
if (datetime.TimeOfDay.Hours - datetimeStart.TimeOfDay.Hours >= 1) {
datetimeEnd = datetime;
}
break;
}
else
{
WriteLine("\tDelivery window end must be at least one hour later than the start.");
}
}
</code></pre>
<p>`</p>
<p>I'm not fully sure how the DateTime type works yet, but later on, I'd need to get an output string with this format:
"The pickup window for your order will be 04:00 on 30/10/2022 and 20:00 on 30/10/2022", and just replace the data in the string with values from datetimeStart and datetimeEnd</p>
| [
{
"answer_id": 74247383,
"author": "Dmitry Egorov",
"author_id": 4295017,
"author_profile": "https://Stackoverflow.com/users/4295017",
"pm_score": 2,
"selected": true,
"text": "DateTime"
},
{
"answer_id": 74247410,
"author": "Rick Davin",
"author_id": 2152078,
"author... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19268293/"
] |
74,247,177 | <pre class="lang-py prettyprint-override"><code>i,a = 1,1
for i in range(1,6):
print(i, end = " ")
i =+1
print()
for a in range(1,11):
if a % 2 == False:
print(a, end = " ")
</code></pre>
<p>I have this result:</p>
<pre><code> 1 2 3 4 5
2 4 6 8 10
</code></pre>
<p>I want this:</p>
<pre><code> 1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
</code></pre>
<p>As you can see I am stuck at line 3 and don't know how to progress</p>
<p>I tried</p>
<pre class="lang-py prettyprint-override"><code>i,a = 1,1
for i in range(1,6):
print(i, end = " ")
i =+1
print()
for a in range(1,11):
if a % 2 == False:
print(a, end = " ")
for b in range(3,16):
print(b + 2, end = " ")
</code></pre>
<p>I expected this =</p>
<pre><code>1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
</code></pre>
<p>But I got an error.</p>
| [
{
"answer_id": 74247234,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 2,
"selected": false,
"text": "for i in range(1, 6):\n for j in range(i, i * 5 + 1, i):\n print(j, end=\" \")\n print()\n"
},
{
... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20153625/"
] |
74,247,205 | <p>I'm new to tensorflow and object detetion, and <strong>any</strong> help would be greatly appreciated! I got a database of 50 photos, used <a href="https://youtu.be/aimSGOAUI8Y" rel="nofollow noreferrer">this</a> video to get me started, and it <strong>DID</strong> work with Google's Sample Model (I'm using a RPi4B with 8 GB of RAM), then I wanted to create my own model. I tried a couple of options, but ultimately failed since the type of files I needed were a .TFLITE and a .txt one with the labels. I only managed to get a .LITE file which from what I tested didn't work</p>
<p>I tried his <a href="https://colab.research.google.com/github/EdjeElectronics/TensorFlow-Lite-Object-Detection-on-Android-and-Raspberry-Pi/blob/master/Train_TFLite2_Object_Detction_Model.ipynb?authuser=1#scrollTo=tMr139pqH-uh&uniqifier=1" rel="nofollow noreferrer">google collab sheet</a> but the terminal got stuck at step 5 when I pressed the button to train the model, so I tried <a href="https://studio.edgeimpulse.com/studio/select-project" rel="nofollow noreferrer">Edge Impulse</a> but the output models were all in a <strong>.LITE</strong> file, and didn't provide a <em>labelmap.txt</em> file for the code. I tried manually changing the extension <strong>from .LITE to .TFLITE</strong> since according to <a href="https://stackoverflow.com/questions/52121533/what-is-the-difference-between-the-lite-and-the-tflite-formats">this </a> thread it was supposed to work, but it didn't!</p>
<p>I need this to be ready in 3 days from now... Isn't there a more beginner-friendly way to do this? <strong>How can I get a valid .TFLITE model to work with my RPI4?</strong> If I have to, I will change the code for this to work. Here's the code the tutorial provided:</p>
<pre><code>######## Webcam Object Detection Using Tensorflow-trained Classifier #########
#
# Author: Evan Juras
# Date: 10/27/19
# Description:
# This program uses a TensorFlow Lite model to perform object detection on a live webcam
# feed. It draws boxes and scores around the objects of interest in each frame from the
# webcam. To improve FPS, the webcam object runs in a separate thread from the main program.
# This script will work with either a Picamera or regular USB webcam.
#
# This code is based off the TensorFlow Lite image classification example at:
# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/examples/python/label_image.py
#
# I added my own method of drawing boxes and labels using OpenCV.
# Import packages
import os
import argparse
import cv2
import numpy as np
import sys
import time
from threading import Thread
import importlib.util
# Define VideoStream class to handle streaming of video from webcam in separate processing thread
# Source - Adrian Rosebrock, PyImageSearch: https://www.pyimagesearch.com/2015/12/28/increasing-raspberry-pi-fps-with-python-and-opencv/
class VideoStream:
"""Camera object that controls video streaming from the Picamera"""
def _init_(self,resolution=(640,480),framerate=30):
# Initialize the PiCamera and the camera image stream
self.stream = cv2.VideoCapture(0)
ret = self.stream.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))
ret = self.stream.set(3,resolution[0])
ret = self.stream.set(4,resolution[1])
# Read first frame from the stream
(self.grabbed, self.frame) = self.stream.read()
# Variable to control when the camera is stopped
self.stopped = False
def start(self):
# Start the thread that reads frames from the video stream
Thread(target=self.update,args=()).start()
return self
def update(self):
# Keep looping indefinitely until the thread is stopped
while True:
# If the camera is stopped, stop the thread
if self.stopped:
# Close camera resources
self.stream.release()
return
# Otherwise, grab the next frame from the stream
(self.grabbed, self.frame) = self.stream.read()
def read(self):
# Return the most recent frame
return self.frame
def stop(self):
# Indicate that the camera and thread should be stopped
self.stopped = True
# Define and parse input arguments
parser = argparse.ArgumentParser()
parser.add_argument('--modeldir', help='Folder the .tflite file is located in',
required=True)
parser.add_argument('--graph', help='Name of the .tflite file, if different than detect.tflite',
default='detect.lite')
parser.add_argument('--labels', help='Name of the labelmap file, if different than labelmap.txt',
default='labelmap.txt')
parser.add_argument('--threshold', help='Minimum confidence threshold for displaying detected objects',
default=0.5)
parser.add_argument('--resolution', help='Desired webcam resolution in WxH. If the webcam does not support the resolution entered, errors may occur.',
default='1280x720')
parser.add_argument('--edgetpu', help='Use Coral Edge TPU Accelerator to speed up detection',
action='store_true')
args = parser.parse_args()
MODEL_NAME = args.modeldir
GRAPH_NAME = args.graph
LABELMAP_NAME = args.labels
min_conf_threshold = float(args.threshold)
resW, resH = args.resolution.split('x')
imW, imH = int(resW), int(resH)
use_TPU = args.edgetpu
# Import TensorFlow libraries
# If tflite_runtime is installed, import interpreter from tflite_runtime, else import from regular tensorflow
# If using Coral Edge TPU, import the load_delegate library
pkg = importlib.util.find_spec('tflite_runtime')
if pkg:
from tflite_runtime.interpreter import Interpreter
if use_TPU:
from tflite_runtime.interpreter import load_delegate
else:
from tensorflow.lite.python.interpreter import Interpreter
if use_TPU:
from tensorflow.lite.python.interpreter import load_delegate
# If using Edge TPU, assign filename for Edge TPU model
if use_TPU:
# If user has specified the name of the .tflite file, use that name, otherwise use default 'edgetpu.tflite'
if (GRAPH_NAME == 'detect.lite'):
GRAPH_NAME = 'edgetpu.tflite'
# Get path to current working directory
CWD_PATH = os.getcwd()
# Path to .tflite file, which contains the model that is used for object detection
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,GRAPH_NAME)
# Path to label map file
PATH_TO_LABELS = os.path.join(CWD_PATH,MODEL_NAME,LABELMAP_NAME)
# Load the label map
with open(PATH_TO_LABELS, 'r') as f:
labels = [line.strip() for line in f.readlines()]
# Have to do a weird fix for label map if using the COCO "starter model" from
# https://www.tensorflow.org/lite/models/object_detection/overview
# First label is '???', which has to be removed.
if labels[0] == '???':
del(labels[0])
# Load the Tensorflow Lite model.
# If using Edge TPU, use special load_delegate argument
if use_TPU:
interpreter = Interpreter(model_path=PATH_TO_CKPT,
experimental_delegates=[load_delegate('libedgetpu.so.1.0')])
print(PATH_TO_CKPT)
else:
interpreter = Interpreter(model_path=PATH_TO_CKPT)
interpreter.allocate_tensors()
# Get model details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
height = input_details[0]['shape'][1]
width = input_details[0]['shape'][2]
floating_model = (input_details[0]['dtype'] == np.float32)
input_mean = 127.5
input_std = 127.5
# Check output layer name to determine if this model was created with TF2 or TF1,
# because outputs are ordered differently for TF2 and TF1 models
outname = output_details[0]['name']
if ('StatefulPartitionedCall' in outname): # This is a TF2 model
boxes_idx, classes_idx, scores_idx = 1, 3, 0
else: # This is a TF1 model
boxes_idx, classes_idx, scores_idx = 0, 1, 2
# Initialize frame rate calculation
frame_rate_calc = 1
freq = cv2.getTickFrequency()
# Initialize video stream
videostream = VideoStream(resolution=(imW,imH),framerate=30).start()
time.sleep(1)
#for frame1 in camera.capture_continuous(rawCapture, format="bgr",use_video_port=True):
while True:
# Start timer (for calculating frame rate)
t1 = cv2.getTickCount()
# Grab frame from video stream
frame1 = videostream.read()
# Acquire frame and resize to expected shape [1xHxWx3]
frame = frame1.copy()
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame_resized = cv2.resize(frame_rgb, (width, height))
input_data = np.expand_dims(frame_resized, axis=0)
# Normalize pixel values if using a floating model (i.e. if model is non-quantized)
if floating_model:
input_data = (np.float32(input_data) - input_mean) / input_std
# Perform the actual detection by running the model with the image as input
interpreter.set_tensor(input_details[0]['index'],input_data)
interpreter.invoke()
# Retrieve detection results
boxes = interpreter.get_tensor(output_details[boxes_idx]['index'])[0] # Bounding box coordinates of detected objects
classes = interpreter.get_tensor(output_details[classes_idx]['index'])[0] # Class index of detected objects
scores = interpreter.get_tensor(output_details[scores_idx]['index'])[0] # Confidence of detected objects
# Loop over all detections and draw detection box if confidence is above minimum threshold
for i in range(len(scores)):
if ((scores[i] > min_conf_threshold) and (scores[i] <= 1.0)):
# Get bounding box coordinates and draw box
# Interpreter can return coordinates that are outside of image dimensions, need to force them to be within image using max() and min()
ymin = int(max(1,(boxes[i][0] * imH)))
xmin = int(max(1,(boxes[i][1] * imW)))
ymax = int(min(imH,(boxes[i][2] * imH)))
xmax = int(min(imW,(boxes[i][3] * imW)))
cv2.rectangle(frame, (xmin,ymin), (xmax,ymax), (10, 255, 0), 2)
# Draw label
object_name = labels[int(classes[i])] # Look up object name from "labels" array using class index
label = '%s: %d%%' % (object_name, int(scores[i]*100)) # Example: 'person: 72%'
if object_name=='person' and int(scores[i]*100)>65:
print("YES")
else:
print("NO")
labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2) # Get font size
label_ymin = max(ymin, labelSize[1] + 10) # Make sure not to draw label too close to top of window
cv2.rectangle(frame, (xmin, label_ymin-labelSize[1]-10), (xmin+labelSize[0], label_ymin+baseLine-10), (255, 255, 255), cv2.FILLED) # Draw white box to put label text in
cv2.putText(frame, label, (xmin, label_ymin-7), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2) # Draw label text
# Draw framerate in corner of frame
cv2.putText(frame,'FPS: {0:.2f}'.format(frame_rate_calc),(30,50),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,0),2,cv2.LINE_AA)
# All the results have been drawn on the frame, so it's time to display it.
cv2.imshow('Object detector', frame)
# Calculate framerate
t2 = cv2.getTickCount()
time1 = (t2-t1)/freq
frame_rate_calc= 1/time1
# Press 'q' to quit
if cv2.waitKey(1) == ord('q'):
break
# Clean up
cv2.destroyAllWindows()
videostream.stop()
```
</code></pre>
| [
{
"answer_id": 74247234,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 2,
"selected": false,
"text": "for i in range(1, 6):\n for j in range(i, i * 5 + 1, i):\n print(j, end=\" \")\n print()\n"
},
{
... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19271648/"
] |
74,247,244 | <p>In my Java program, I have a string like <code>G C / F C / F C / F A / B / F / I</code></p>
<p>I am not much comfortable with Regex and would like to break the above string like below</p>
<p><strong>G</strong></p>
<p><strong>C / F</strong></p>
<p><strong>C / F</strong></p>
<p><strong>C / F</strong></p>
<p><strong>A / B / F / I</strong></p>
<p>Break it using some regex pattern like if character+space+character occurs, break the string.</p>
<hr />
<p><em>Added from the comments</em></p>
<p>By character I meant [A-Z]. Tried this</p>
<pre><code>(\s([a-zA-Z]\s)+)
</code></pre>
<p>but didn't work.</p>
| [
{
"answer_id": 74247744,
"author": "thisistemporary",
"author_id": 19275492,
"author_profile": "https://Stackoverflow.com/users/19275492",
"pm_score": 0,
"selected": false,
"text": "let regex = /([A-Za-z])\\s([A-Za-z])/g;\nlet str = 'G C / F C / F C / F A / B / F / I';\nstr = str.replace... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5770332/"
] |
74,247,350 | <p>I have a code with a class using many variables.i can't Access one of those variables to use it inside of a method of my code written in Python.</p>
<p>I tried to declare the variable as global to make the value being accessible at any point of the code but it is not ok. I am expecting to use the variable in a specific method</p>
| [
{
"answer_id": 74247744,
"author": "thisistemporary",
"author_id": 19275492,
"author_profile": "https://Stackoverflow.com/users/19275492",
"pm_score": 0,
"selected": false,
"text": "let regex = /([A-Za-z])\\s([A-Za-z])/g;\nlet str = 'G C / F C / F C / F A / B / F / I';\nstr = str.replace... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20352110/"
] |
74,247,376 | <p><strong>I have been trying for hours to solve this problem but I couldn't,
data is successfully displaying in the console but not rendering on the browser, I don't know why, Am I making some mistakes?
I have attached my code below if anyone could solve this issue.</strong></p>
<pre><code>import React, { useState, useEffect } from "react";
import "../Componentstyle/Main.css";
export default function Maindata() {
const [data, setData] = useState(null);
let weather = async () => {
const key = "1ab6ef20384db1d7d9d205d609f7eef0";
await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=dubai&appid=${key}&units=metric&formatted=0`
)
.then((response) => response.json())
.then((actualData)=> setData(actualData));
};
useEffect(() => {
weather()
}, []);
const link = `http://openweathermap.org/img/w/${data.weather[0].icon}.png`
return (
<div className="maindata">
<div className="city">{data.name}</div>
<div className="temp">{data.main.temp} C</div>
<div className="icon"><img src={link} alt="not found" /> </div>
<div className="feel">feels Like {data.main.feels_like} C</div>
<div className="wind">Wind {data.wind.speed} Km/hr</div>
<div className="cloudy">{data.weather[0].main}</div>
<div className="humidity">humidity {data.main.humidity}%</div>
<div className="sunrise">sunrise :- {(new Date((data.sys.sunrise)*1000).toUTCString())} </div>
<div className="sunset">sunset :- {new Date(data.sys.sunset*1000).toUTCString()}</div>
</div>
);
}
</code></pre>
| [
{
"answer_id": 74247472,
"author": "Dori Lahav Waisberg",
"author_id": 11360272,
"author_profile": "https://Stackoverflow.com/users/11360272",
"pm_score": 2,
"selected": true,
"text": "if (!data) {\n return <div>Loading...</div>;\n}\n"
},
{
"answer_id": 74247522,
"author": "... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16762504/"
] |
74,247,391 | <p>I want to create a table component made out of three parts.
The wrapper, the heads and the data.</p>
<p>While most of it works pretty well, I'm struggling with the order by functionality.</p>
<p>When the user clicks on a th tag, the data should be reordered and a little indicator should be shown.
The ordering works but the indicator doesn't.</p>
<p><strong>The actual problem</strong><br />
I know that it's bad to mutate a property inside the child although it's defined in the parent. Since I use slots, I can't use the normal $emit.<br />
Using the approach shown here brings me <code>Uncaught (in promise) TypeError: parent is null</code> and <code>Unhandled error during execution of scheduler flush</code>.</p>
<p>Although I already know that my current approach is wrong, I don't know how to do it right.<br />
Googling around, I found keywords like writable computed props and scoped slots, but I can't put it together.</p>
<p>So what's the right way to realize two-way-binding in a slotted environment?</p>
<p><strong>My Table.vue file</strong></p>
<pre><code><template>
<div class="px-4 sm:px-6 lg:px-8">
<div class="mt-8 flex flex-col">
<div class="-my-2 -mx-4 overflow-x-auto sm:-mx-6 lg:-mx-8">
<Search v-if="searchable" :filters="props.filters"></Search>
<div class="inline-block min-w-full py-2 align-middle">
<div class="overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg">
<table class="min-w-full divide-y divide-gray-300">
<thead class="bg-gray-50">
<tr>
<slot name="table-heads"></slot>
</tr>
</thead>
<tbody class="divide-y divide-gray-200 bg-white">
<slot name="table-body"></slot>
</tbody>
</table>
<Pagination v-if="paginationLinks" :links="paginationLinks"></Pagination>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup>
import Pagination from "@/Components/Tables/Pagination.vue";
import {provide} from "vue";
import Search from "@/Components/Tables/Search.vue";
import {Inertia} from "@inertiajs/inertia";
let name = "Table";
let props = defineProps({
paginationLinks: Array,
dataUrl: String,
filters: Object,
order: Object,
searchable: Boolean
});
provide('dataUrl', props.dataUrl);
provide('order', props.order);
</script>
<style scoped>
</style>
</code></pre>
<p><strong>My TableHead.vue file</strong></p>
<pre><code><template>
<th @click="orderByClicked" scope="col"
class="py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-6 cursor-pointer">
<div class="flex justify-between">
<slot></slot>
<span v-if="order.orderBy === props.orderKey">
<i v-if="order.orderDirection === 'asc'" class="fa-solid fa-chevron-up"></i>
<i v-if="order.orderDirection === 'desc'" class="fa-solid fa-chevron-down"></i>
</span>
</div>
</th>
</template>
<script setup>
import { inject } from "vue";
import { Inertia } from "@inertiajs/inertia";
let name = "TableHead";
let dataUrl = inject('dataUrl');
let order = inject('order');
let props = defineProps({
orderKey: String,
orderByClicked: Function
});
function orderByClicked() {
if (props.orderKey) {
if (order.orderBy === props.orderKey)
order.orderDirection = order.orderDirection === 'asc' ? 'desc' : 'asc';
else
order.orderDirection = "asc"
order.orderBy = props.orderKey;
Inertia.get(dataUrl, {orderBy: props.orderKey, orderDirection: order.orderDirection}, {
preserveState: true,
replace: true
});
}
}
</script>
<style scoped>
</style>
</code></pre>
<p><strong>My TableData.vue file (just to be complete)</strong></p>
<pre><code><template>
<td class="whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-6">
<slot></slot>
</td>
</template>
<script setup>
let name = "TableData";
</script>
<style scoped>
</style>
</code></pre>
<p><strong>putting it together</strong></p>
<pre><code> <Table :pagination-links="props.users.links" :data-url="'/users'" :searchable="true" :filters="props.filters" :order="props.order">
<template #table-heads>
<TableHead order-key="name">name</TableHead>
<TableHead order-key="email">email</TableHead>
<TableHead>Bearbeiten</TableHead>
</template>
<template #table-body>
<tr v-for="user in users.data" :key="user.id">
<TableData>{{ user.username }}</TableData>
<TableData>{{ user.email}}</TableData>
</tr>
</template>
</Table>
</code></pre>
| [
{
"answer_id": 74247472,
"author": "Dori Lahav Waisberg",
"author_id": 11360272,
"author_profile": "https://Stackoverflow.com/users/11360272",
"pm_score": 2,
"selected": true,
"text": "if (!data) {\n return <div>Loading...</div>;\n}\n"
},
{
"answer_id": 74247522,
"author": "... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9699530/"
] |
74,247,422 | <p>I'm trying to execute <code>sh</code> script from Windows on Remote SUSE Linux using WinSCP .NET assembly.</p>
<p>I've created a session as follow:</p>
<pre><code>$sessionOptions = New-Object WinSCP.SessionOptions -Property @
{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "RemoteIp"
UserName = "username"
Password = "password"
}
$session = New-Object WinSCP.Session
</code></pre>
<p>I run the <code>sh</code> script</p>
<pre><code>$session.ExecuteCommand("bash /home/script.sh" )
</code></pre>
<p>and I get permissions errors, for example:</p>
<blockquote>
<p>rm: cannot remove '/somefolder': Permission denied.</p>
</blockquote>
<p>Simple command like <code>uname</code> works fine.</p>
<p>Any idea how can I log in as root?</p>
| [
{
"answer_id": 74247472,
"author": "Dori Lahav Waisberg",
"author_id": 11360272,
"author_profile": "https://Stackoverflow.com/users/11360272",
"pm_score": 2,
"selected": true,
"text": "if (!data) {\n return <div>Loading...</div>;\n}\n"
},
{
"answer_id": 74247522,
"author": "... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14130850/"
] |
74,247,436 | <p>I'm just starting out using rails and I've come a across an issue I can't seem to solve or find the solution to. For some reason when I opened up the project today I kept getting this error</p>
<pre><code>ActionController::MissingExactTemplate (HomeController#index is missing a template for request formats: text/html)
</code></pre>
<p>This is my home_controller.rb under app/controllers</p>
<pre><code>class HomeController < ApplicationController
def index
end
end
</code></pre>
<p>This is my index.html.erb under app/views/home</p>
<pre class="lang-html prettyprint-override"><code><p>Index</p>
</code></pre>
<p>my routes.rb</p>
<pre><code>Rails.application.routes.draw do
root 'home#index'
end
</code></pre>
<p>I've also run rails app:update, to no success. I've looked around stackoverflow and other websites but can't seem to find a solution that has worked for me. Any help would be greatly appreciated.</p>
| [
{
"answer_id": 74247472,
"author": "Dori Lahav Waisberg",
"author_id": 11360272,
"author_profile": "https://Stackoverflow.com/users/11360272",
"pm_score": 2,
"selected": true,
"text": "if (!data) {\n return <div>Loading...</div>;\n}\n"
},
{
"answer_id": 74247522,
"author": "... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4383688/"
] |
74,247,463 | <p>I have a dataframe like this am I'm trying to count the words said by a specific author.</p>
<pre><code>Author Text Date
Jake hey hey my names Jake 1.04.1997
Mac hey my names Mac 1.02.2019
Sarah heymy names Sarah 5.07.2001
</code></pre>
<p>I've been trying to get it set up in a way where if i were to search for the word "hey" it would produce</p>
<pre><code>Author Count
Jake 2
Mac 1
</code></pre>
| [
{
"answer_id": 74247472,
"author": "Dori Lahav Waisberg",
"author_id": 11360272,
"author_profile": "https://Stackoverflow.com/users/11360272",
"pm_score": 2,
"selected": true,
"text": "if (!data) {\n return <div>Loading...</div>;\n}\n"
},
{
"answer_id": 74247522,
"author": "... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12599692/"
] |
74,247,471 | <p>I'm confused in this. I have created a screen in with list to products data is coming from an dummy API. no I have created the cards and I want to display product details in next screen. how can I show the same product details on second screen of pressed product.</p>
<p>I think we need to store index of api data in a variable somehow. this is the code</p>
<pre><code>import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_get_api/model.dart';
import 'package:flutter_get_api/product_detail.dart';
import 'package:http/http.dart' as http;
class Details extends StatefulWidget {
Details({Key? key}) : super(key: key);
@override
State<Details> createState() => _DetailsState();
}
class _DetailsState extends State<Details> {
Future<Model> getProductsApi() async {
final responce =
await http.get(Uri.parse('https://dummyjson.com/products'));
var data = jsonDecode(responce.body.toString());
if (responce.statusCode == 200) {
return Model.fromJson(data);
} else {
return Model.fromJson(data);
}
}
var s = '\$';
@override
Widget build(BuildContext context) {
return Scaffold(
drawer: Drawer(),
appBar: AppBar(
backgroundColor: Color.fromARGB(255, 32, 28, 80),
title: Text('Api Get'),
),
backgroundColor: Color.fromARGB(255, 32, 28, 80),
body: Column(
children: [
Expanded(
child: FutureBuilder<Model>(
future: getProductsApi(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.products!.length,
itemBuilder: (context, index) {
print(
snapshot.data!.products!.length,
);
return Column(
children: [
Padding(
padding: const EdgeInsets.all(5.0),
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProductDetails(),
));
},
child: Container(
height: 100,
width: 500,
child: Card(
color: Color.fromARGB(255, 185, 239, 243),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(
10, 25, 10, 10),
child: CircleAvatar(
backgroundImage: NetworkImage(snapshot
.data!.products![index].thumbnail!
.toString()),
),
),
Flexible(
child: Padding(
padding: const EdgeInsets.fromLTRB(
8, 10, 8, 0),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
mainAxisAlignment:
MainAxisAlignment.start,
children: [
Text(
snapshot
.data!.products![index].title
.toString(),
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 17),
),
Text(
snapshot
.data!.products![index].brand
.toString(),
style: TextStyle(
fontWeight: FontWeight.bold),
),
Text(
snapshot.data!.products![index]
.description
.toString(),
),
],
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text('\$' +
snapshot.data!.products![index].price
.toString()),
),
],
),
),
),
),
</code></pre>
| [
{
"answer_id": 74247472,
"author": "Dori Lahav Waisberg",
"author_id": 11360272,
"author_profile": "https://Stackoverflow.com/users/11360272",
"pm_score": 2,
"selected": true,
"text": "if (!data) {\n return <div>Loading...</div>;\n}\n"
},
{
"answer_id": 74247522,
"author": "... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20367275/"
] |
74,247,475 | <p>I have multiple blogs on my Shopify site. I'm trying to display posts from ALL blogs on the site in the featured section on the homepage. However, when I attempt to select them in the admin area, it only allows me to select one at a time.</p>
<p>What do I need to put in the <code>{% schema %}</code> (or template code) to allow me to select more than one blog in the theme's admin area, thus displaying posts from more than one blog in featured section in the template?</p>
<p><a href="https://i.stack.imgur.com/7EAsf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7EAsf.png" alt="enter image description here" /></a></p>
<p>Here is my current <code>{% schema %}</code>:</p>
<pre><code>{% schema %}
{
"name": "Blog posts",
"class": "index-section",
"settings": [
{
"type": "text",
"id": "title",
"label": "Heading",
"default": "Blog posts"
},
{
"id": "blog",
"type": "blog",
"label": "Blog"
},
{
"type": "range",
"id": "post_limit",
"label": "Posts",
"min": 3,
"max": 12,
"step": 3,
"default": 3
},
{
"type": "checkbox",
"id": "blog_show_author",
"label": "Show author",
"default": false
},
{
"type": "checkbox",
"id": "blog_show_date",
"label": "Show date",
"default": true
},
{
"type": "checkbox",
"id": "show_view_all",
"label": "Show 'View all' button",
"default": false
}
],
"presets": [
{
"name": "Blog posts",
"category": "Blog",
"settings": {
"blog": "News",
"post_limit": 3
}
}
]
}
{% endschema %}
</code></pre>
| [
{
"answer_id": 74247472,
"author": "Dori Lahav Waisberg",
"author_id": 11360272,
"author_profile": "https://Stackoverflow.com/users/11360272",
"pm_score": 2,
"selected": true,
"text": "if (!data) {\n return <div>Loading...</div>;\n}\n"
},
{
"answer_id": 74247522,
"author": "... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20133626/"
] |
74,247,490 | <p>How do i go about something like this, I want to check if a user exists against a table in python, and if the user exists , it should report that the particular user exists, else if the user does not, it should register (insert the user into the mysql database)</p>
<p>So far, this is what my code is looking like</p>
<pre><code>@app.route('/api/user',methods=['POST'])
def create_user():
_json = request.json
_email = _json['email']
_phone = _json['phone']
_password = _json['password']
fullname = 'NULL'
custID = '123456'
#conn = mysql.connect()
#cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor = mysql.connection.cursor()
checkuser = 'select email from accounts where email = %s' # check if user exists here.
query = "insert into accounts (email,phone,fullname,password,custID) values (%s, %s,%s, %s,%s)"
#query = "update empData set name = %s, email = %s, phone = %s, address = %s, salary = %s"
bindData = (_email, _phone, _password , fullname , custID)
cursor.execute(query,bindData)
mysql.connection.commit()
cursor.close()
output = {'email':_email, 'phone':_phone, 'fullname':fullname, 'custID':custID, 'message':'ok'}
return jsonify({'result':output}),200
</code></pre>
<p>How do I go about something like this, I started out flask a week ago.</p>
<p><strong>Edits</strong></p>
<p>This is what i been working on, but it complains about indentation. Code is looking like so</p>
<pre><code>@app.route('/api/user', methods=['POST'])
def create_user():
_json = request.json
_email = _json['email']
_phone = _json['phone']
_password = _json['password']
fullname = 'NULL'
custID = '123456'
cursor = mysql.connection.cursor()
checkuser = 'select email from accounts where email = %s'
bindData = (_email)
cursor.execute(query,bindData)
acc = cursor.fetchone()
if acc:
return jsonify({'message':'User exists, Please Login'})
elif:
query = "insert into accounts (email,phone,fullname,password,custID) values (%s, %s,%s, %s,%s)"
bindData = (_email, _phone, _password , fullname , custID)
cursor.execute(query,bindData)
mysql.connection.commit()
cursor.close()
output = {'email':_email, 'phone':_phone, 'fullname':fullname, 'custID':custID, 'message':'ok'}
return jsonify({'result':output}),200
</code></pre>
<p><strong>Edits 2</strong></p>
<p>So I made some Edits for the second time, it just fires back Error 500 when i am testing with Postman.</p>
<p>My code is looking Thus</p>
<pre><code>@app.route("/api/user", methods=["POST"])
def create_user():
_json = request.json
_email = _json["email"]
_phone = _json["phone"]
_password = _json["password"]
fullname = "NULL"
custID = "123456"
cursor = mysql.connection.cursor()
cursor.execute('select * from accounts where email = %s', _email)
acc = cursor.fetchone()
if acc:
return jsonify({"message": "User exists, Please Login"})
else:
query = "insert into accounts (email,phone,fullname,password,custID) values (%s, %s,%s, %s,%s)"
bindData = (_email, _phone, _password, fullname, custID)
cursor.execute(query, bindData)
mysql.connection.commit()
cursor.close()
output = {
"email": _email,
"phone": _phone,
"fullname": fullname,
"custID": custID,
"message": "ok",
}
return jsonify({"result": output}), 200
</code></pre>
<p>it says this is where the Error is according to the Log</p>
<p>which is here <code>cursor.execute('select * from accounts where email = %s', _email)</code> Is there something i missed?</p>
| [
{
"answer_id": 74247472,
"author": "Dori Lahav Waisberg",
"author_id": 11360272,
"author_profile": "https://Stackoverflow.com/users/11360272",
"pm_score": 2,
"selected": true,
"text": "if (!data) {\n return <div>Loading...</div>;\n}\n"
},
{
"answer_id": 74247522,
"author": "... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19813264/"
] |
74,247,498 | <p>I have an AKS cluster, as well as a separate VM. AKS cluster and the VM are in the same VNET (as well as subnet).</p>
<p>I deployed a echo server with the following yaml, I'm able to directly curl the pod with vnet ip from the VM. But when trying that with load balancer, nothing returns. Really not sure what I'm missing. Any help is appreciated.</p>
<pre><code>apiVersion: v1
kind: Service
metadata:
name: echo-server
annotations:
service.beta.kubernetes.io/azure-load-balancer-internal: "true"
spec:
type: LoadBalancer
ports:
- port: 80
protocol: TCP
targetPort: 8080
selector:
app: echo-server
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: echo-deployment
spec:
replicas: 1
selector:
matchLabels:
app: echo-server
template:
metadata:
labels:
app: echo-server
spec:
containers:
- name: echo-server
image: ealen/echo-server
ports:
- name: http
containerPort: 8080
</code></pre>
<p>The following pictures demonstrate the situation
<a href="https://i.stack.imgur.com/b9KFj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b9KFj.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/oG4dF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oG4dF.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/kQEUM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kQEUM.png" alt="enter image description here" /></a></p>
<p>I'm expecting that when curl the vnet ip from load balancer, to receive the same response as I did directly curling the pod ip</p>
| [
{
"answer_id": 74247472,
"author": "Dori Lahav Waisberg",
"author_id": 11360272,
"author_profile": "https://Stackoverflow.com/users/11360272",
"pm_score": 2,
"selected": true,
"text": "if (!data) {\n return <div>Loading...</div>;\n}\n"
},
{
"answer_id": 74247522,
"author": "... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18660166/"
] |
74,247,505 | <p>I am having difficulties making my footer background colour span the whole viewport. Hope someone can point me to the right direction! Thanks!</p>
<p>[](<a href="https://i.stack.imgur.com/EhWF4.png" rel="nofollow noreferrer">https://i.stack.imgur.com/EhWF4.png</a>)</p>
<pre><code><footer>
<div id="top-footer">
Hong Kong
</div>
<div id="bottom-footer">
<a href="https://support.google.com/websearch/?p=ws_results_help&hl=en-HK&fg=1">Help</a>
<a href="https://policies.google.com/privacy?hl=en-HK&fg=1">Privacy</a>
<a href="https://policies.google.com/terms?hl=en-HK&fg=1">Terms</a>
</div>
</footer>
</code></pre>
<pre><code> #top-footer, #bottom-footer {
margin: 0;
padding: 1rem 2rem;
height: 1rem;
font-size: medium;
}
#bottom-footer > a {
display: inline;
padding-right: 2rem;
margin: 0;
font-size: medium;
}
footer {
margin-top: 2rem;
background-color: grey;
width: 100%;
}
</code></pre>
| [
{
"answer_id": 74247536,
"author": "Franco Agustín Torres",
"author_id": 20318366,
"author_profile": "https://Stackoverflow.com/users/20318366",
"pm_score": 2,
"selected": true,
"text": "body"
},
{
"answer_id": 74247622,
"author": "DCR",
"author_id": 4398966,
"author_... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19064004/"
] |
74,247,537 | <p>I would like to put a media size that is centered in regular size, when I changed it max-width of 480 the caption is on the left.</p>
<p>but it is stuck to the left. How can I change the code so the caption is in the middle when in media size?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>caption {
font-family: "Rock Salt", cursive;
padding: 20px;
font-style: italic;
caption-side: Top;
color: #666;
text-align: center;
letter-spacing: 1px;
}
@media only screen and (max-width: 480px) {
caption {
caption-side: Top;
text-align: center;
letter-spacing: 1px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="right">
<table>
<caption>Books everyone will enjoy!</caption>
<thead>
<th colspan="4">Recommended childrens books!</th>
<th colspan="2" style="display: none">Recommended childrens books!</th>
<tr>
<th colspan="1">Front of the book</th>
<th colspan="1">Title of the book</th>
<th colspan="1">Authors</th>
<th colspan="1">Book Summary</th>
</tr>
</thead></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74247536,
"author": "Franco Agustín Torres",
"author_id": 20318366,
"author_profile": "https://Stackoverflow.com/users/20318366",
"pm_score": 2,
"selected": true,
"text": "body"
},
{
"answer_id": 74247622,
"author": "DCR",
"author_id": 4398966,
"author_... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20366792/"
] |
74,247,559 | <p>Lets say we have two strings</p>
<pre><code> str1 = "021A,775U,000A,021A,1U2,206B,240,249,255B,260,263B,280,294,2U1,306B,336B,345,427,440,442,474,477,4U4,500,508,523,543L,580,584,772,802,P55,VB" ;
str2 = "772+240+802+P55+263B+1U2+VB";
</code></pre>
<p>and want to know if every substring of str2 splitted by "+" is in str1.</p>
<p>Is there something "better" than doing this</p>
<pre><code> string[] str1Arr = str1.Split(',');
foreach (var s in str2.Split('+'))
{
if (!str1Arr.Contains(s))
{
return false;
}
}
return true;
</code></pre>
<p>str2 would return true, while</p>
<pre><code> str3 ="772+240+802+P55+263B+1U2+V";
</code></pre>
<p>would return false.</p>
<p><strong>Edit</strong>:</p>
<p>Max length of str1 is ~1000 with all delimited strings being unique and sorted.
Max lenght of str2 is ~700 (average 200) with substrings being unique but not sorted.</p>
<p>Here are some more strings:</p>
<pre><code>"200B+201B+202+202B+203B+204B+205+205B+206+206B+207+207B+208+208B+209+209B+210+210B+211B+214B+216B+460+494+498+830+379"//false
"612+637+638+646+649+655+664+678+688+693+694+754+756+758+774+778+780+781+787+99R+B58+RQW+RRG+RTJ+RVI+RVJ+RVU+RVV"//false
"255B+2U1+775U+336B+P55+802"//true
"220+223+224+229+230+233+234+402+537+550+811+863+872+881+889+965+512L+516L+520L+521L+524L+526L+528L+581L+810L+812L+814L+816L+818L+830"//false
"255B"//true
</code></pre>
| [
{
"answer_id": 74247536,
"author": "Franco Agustín Torres",
"author_id": 20318366,
"author_profile": "https://Stackoverflow.com/users/20318366",
"pm_score": 2,
"selected": true,
"text": "body"
},
{
"answer_id": 74247622,
"author": "DCR",
"author_id": 4398966,
"author_... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8024622/"
] |
74,247,569 | <p>A different program I am using (Raven Pro) results in hundreds of .txt files that include nine variables with headers. I also need the file name that each line is being pulled from.</p>
<p>I am using <code>stringr::str_extract(names</code> in order to get a file name thrown into a dataframe with rbindlist. My problem is that I only want a portion of the file name included.</p>
<p>Here's an example of one of my file names -</p>
<pre><code>BIOL10_20201206_180000.wav.Table01.txt
</code></pre>
<p>so if I do <code>("\\d+"))</code> to try and get numbers it only picks up the 10 before the underscore, but the portion of the file name I need is <code>20201206_180000</code></p>
<p>Any help to get around this is appreciated :)</p>
<pre><code>library(plyr)
myfiles <- list.files(path=folder, pattern="*.txt", full.names = FALSE)
dat_tab <- sapply(myfiles, read.table, header= TRUE, sep = "\t", simplify = FALSE, USE.NAMES = TRUE)
names(dat_tab) <- stringr::str_extract(names(dat_tab), ("\\d+"))
binded1 = rbindlist(dat_tab, idcol = "files", fill = TRUE)
</code></pre>
<p>ended up with file name coming in as "10" from the file name "BIOL10_20201206_180000.wav.Table01.txt"</p>
| [
{
"answer_id": 74247664,
"author": "sindri_baldur",
"author_id": 4552295,
"author_profile": "https://Stackoverflow.com/users/4552295",
"pm_score": 0,
"selected": false,
"text": "library(stringr)\nstr_extract(x, \"\\\\d{8}_\\\\d{6}\")\n# \"20201206_180000\"\n"
},
{
"answer_id": 74... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20354424/"
] |
74,247,581 | <p>Hello guys I'm writing a Message Application with Node.js and Mongoose. I keep datas in mongodb like that:</p>
<p><a href="https://i.stack.imgur.com/AvaqI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AvaqI.png" alt="enter image description here" /></a></p>
<p>I want to list users who messaged before so I need to filter my 'Messages' collection but I can't do what exactly I want. If he sent a message to a person I need to take persons name but, if he take a message from a person I need to take persons name however in first situation person name in reciever, in second situation person name in sender. I made a table for explain more easily. I have left table and I need 3 name like second table.(Need to eliminate one John's name)</p>
<p><a href="https://i.stack.imgur.com/PlpBg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PlpBg.png" alt="enter image description here" /></a></p>
<p>Sorry, if this problem asked before but I don't know how can I search this problem.</p>
<p>I tried this but it take user name who logged in and duplicate some names.</p>
<pre><code>Message.find({$or: [{sender: req.user.username}, {reciever: req.user.username}]})
</code></pre>
| [
{
"answer_id": 74247664,
"author": "sindri_baldur",
"author_id": 4552295,
"author_profile": "https://Stackoverflow.com/users/4552295",
"pm_score": 0,
"selected": false,
"text": "library(stringr)\nstr_extract(x, \"\\\\d{8}_\\\\d{6}\")\n# \"20201206_180000\"\n"
},
{
"answer_id": 74... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11739742/"
] |
74,247,588 | <p>When my web page loads it plays this bottom border animation, then afterwords it will display a static bottom border. The issue is, you can see from this snippet that the animated border is shorter than the static border.. How can I center this so both borders are identical at the end result? I would ideally like both borders to look like the second, longer one shown in the snippet.</p>
<p>I have played around with the width but can't seem to figure out what parameter needs a change.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<style>
.border-bottom-animate:after {
content: "";
display: block;
border-bottom: 5px dotted black;
width: 100%;
animation-duration: 3s;
animation-name: border-animation;
}
@keyframes border-animation {
from {
width: 0%;
}
to {
width: 100%;
}
}
.border-bottom-noanimate {
content: "";
display: block;
border-bottom: 5px dotted black;
width: 100%;
}
</style>
</head>
<body>
<div class="container border-bottom-animate">
<p style="font-size: xx-large">
border animation
</p>
</div>
<div class="container border-bottom-noanimate">
<p style="font-size: xx-large">
border no animation
</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.min.js" integrity="sha384-IDwe1+LCz02ROU9k972gdyvl+AESN10+x7tBKgc9I5HFtuNz0wWnPclzo6p9vxnk" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74247664,
"author": "sindri_baldur",
"author_id": 4552295,
"author_profile": "https://Stackoverflow.com/users/4552295",
"pm_score": 0,
"selected": false,
"text": "library(stringr)\nstr_extract(x, \"\\\\d{8}_\\\\d{6}\")\n# \"20201206_180000\"\n"
},
{
"answer_id": 74... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13189532/"
] |
74,247,605 | <pre><code># Common imports:
import sys
from os import path, listdir
from org.apache.lucene.document import Document, Field, StringField, TextField
from org.apache.lucene.util import Version
from org.apache.lucene.store import RAMDirectory
from datetime import datetime
# Indexer imports:
from org.apache.lucene.analysis.miscellaneous import LimitTokenCountAnalyzer
from org.apache.lucene.analysis.standard import StandardAnalyzer
from org.apache.lucene.index import IndexWriter, IndexWriterConfig
# from org.apache.lucene.store import SimpleFSDirectory
# Retriever imports:
from org.apache.lucene.search import IndexSearcher
from org.apache.lucene.index import DirectoryReader
from org.apache.lucene.queryparser.classic import QueryParser
# ---------------------------- global constants ----------------------------- #
BASE_DIR = path.dirname(path.abspath(sys.argv[0]))
INPUT_DIR = BASE_DIR + "/input/"
INDEX_DIR = BASE_DIR + "/lucene_index/"
</code></pre>
<p>I'm trying test pylucene library. I have written this code only for import test. It doesn't work. I get</p>
<pre><code>bigissue@vmi995554:~/myluceneproj$ cd /home/bigissue/myluceneproj ; /usr/bin/env /usr/bin/python3.10 /home/bigissue/.vscode/extensions/ms-python.python-2022.16.1/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher 36991 -- /home/bigissue/myluceneproj/hello_lucene.py
Traceback (most recent call last):
File "/home/bigissue/myluceneproj/hello_lucene.py", line 29, in <module>
from org.apache.lucene.document import Document, Field, StringField, TextField
ModuleNotFoundError: No module named 'org'
bigissue@vmi995554:~/myluceneproj$
</code></pre>
<p>I have run <code>python3.10 -m pip list</code> and there is "lucene" module. if I import lucene work well but python doesn't recognize org module. Why?</p>
<p><strong>UPDATE</strong></p>
<p>I downloaded lucene 9.1 and set environment variable (<code>/etc/environment</code>):</p>
<p><code>CLASSPATH=".:/usr/lib/jvm/temurin-17-jdk-amd64/lib:/home/bigissue/all_lucene/lucene-9.4.1/modules:/home/bigissue/all_lucene/lucene-9.1.0/modules" export CLASSPATH</code></p>
<p>I downloaded pylucene-9.1.0 and I have installed it
first jcc</p>
<pre><code>bigissue@vmi995554:~/all_lucene/pylucene-9.1.0$ pwd
/home/bigissue/all_lucene/pylucene-9.1.0/jcc
bigissue@vmi995554:~/all_lucene/pylucene-9.1.0$python3.10 setup.py build
bigissue@vmi995554:~/all_lucene/pylucene-9.1.0$python3.10 setup.py install
</code></pre>
<p>I downloaded also ant apache.</p>
<p>then pylucene 9.1
<code>cd ..</code>
I have edit Makefile
<code>vim /home/bigissue/all_lucene/pylucene-9.1.0/Makefile</code></p>
<pre><code>PREFIX_PYTHON=/usr/bin
ANT=/home/bigissue/all_lucene/apache-ant-1.10.12
PYTHON=$(PREFIX_PYTHON)/python3.10
JCC=$(PYTHON) -m jcc --shared
NUM_FILES=10
</code></pre>
<pre><code>bigissue@vmi995554:~/all_lucene/pylucene-9.1.0: make
bigissue@vmi995554:~/all_lucene/pylucene-9.1.0: make install
</code></pre>
<p>if I run python3.10 -m pip install | grep -i "lucene" I see it.</p>
<pre><code>bigissue@vmi995554:~/all_lucene/pylucene-9.1.0$ python3.10 -m pip list | grep -i "lucene"
lucene 9.1.0
</code></pre>
<p>Now I have imported lucene</p>
<pre><code>import sys
from os import path, listdir
from lucene import *
directory = RAMDirectory()
</code></pre>
<p>But I get</p>
<pre><code>ImportError: cannot import name 'RAMDirectory' from 'lucene' (/usr/local/lib/python3.10/dist-packages/lucene-9.1.0-py3.10-linux-x86_64.egg/lucene/__init__.py)
</code></pre>
| [
{
"answer_id": 74247664,
"author": "sindri_baldur",
"author_id": 4552295,
"author_profile": "https://Stackoverflow.com/users/4552295",
"pm_score": 0,
"selected": false,
"text": "library(stringr)\nstr_extract(x, \"\\\\d{8}_\\\\d{6}\")\n# \"20201206_180000\"\n"
},
{
"answer_id": 74... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19049340/"
] |
74,247,617 | <p>In my program, I want to have a list of my inputs to be under each other. However, if the input of the foods field is shorter/longer (let's say it's apple) than the one above it (cabbage), the inputs of datefield shift themselves.</p>
<p>This is what it looks like:</p>
<p><a href="https://i.stack.imgur.com/GSKYI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GSKYI.png" alt="" /></a></p>
<p>This program is for a school project and I am stuck with this problem since 2 weeks.</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>function addFoodsAndDate(event) {
foodsdate.innerHTML += `
<li class="mdl-list__item">
<span class="mdl-list__item-primary-content">
${foodsfield.value}
</span>
<span class="mdl-list__item-primary-content">
${datefield.value}
</span>
</li>
`;
foodsfield.value += ``;
datefield.value += ``;
return false;
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.demo-list-item {
width: 320px;
}
.page-content {
padding: 20px 100px;
float: left
}
body {
background: #3d3d3d
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<div class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
<header class="mdl-layout__header">
<div class="mdl-layout__header-row">
<!-- Title -->
<span class="mdl-layout-title">Kühlflex Web-App</span>
<!-- Add spacer, to align navigation to the right -->
<div class="mdl-layout-spacer"></div>
<!-- Navigation. We hide it in small screens. -->
</div>
</header>
<main class="mdl-layout__content">
<div class="page-content">
<!-- Your content goes here -->
<form onsubmit="return addFoodsAndDate()">
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" id="foodsfield">
<label class="mdl-textfield__label" for="foodsfield">Deine Lebensmittel...</label>
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" pattern="-?[0-9+.]*(\.[0-9+.]+)?" id="datefield">
<label class="mdl-textfield__label" for="datefields">Datum...</label>
<span class="mdl-textfield__error">Datum eingeben!</span>
</div>
<button type="submit" class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored">
Hinzufügen
</button>
</form>
<ul class="demo-list-icon mdl-list" id="foodsdate">
</ul>
</div>
</main>
</div></code></pre>
</div>
</div>
</p>
<p>I already tried the <code>float: left</code> method but I'm unsure if I used it correctly.</p>
<p>Thanks in advance</p>
| [
{
"answer_id": 74277723,
"author": "Rounin - Standing with Ukraine",
"author_id": 3897775,
"author_profile": "https://Stackoverflow.com/users/3897775",
"pm_score": 0,
"selected": false,
"text": "<table>"
},
{
"answer_id": 74279376,
"author": "Bqardi",
"author_id": 1464781... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20219637/"
] |
74,247,630 | <p><a href="https://i.stack.imgur.com/uX80x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uX80x.png" alt="enter image description here" /></a></p>
<p>I am able to import other packages like java.io to eclipse but, I am unable to import java.sql to my project in eclipse. What could be the reason?</p>
<p>I don't know how to proceed. I have tried a couple of things, but none of them worked out for me.</p>
| [
{
"answer_id": 74248346,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 0,
"selected": false,
"text": "java.sql"
}
] | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20367323/"
] |
74,247,639 | <p>everyone I was trying to count the number of Yes answered in a column depending on the answer from another previous column to generate pie charts so I'm having problems with this because is giving me counts in boolean like in image below, (This is my codeline):</p>
<pre><code>answers = ['Yes']
hello = (df['Are you okay?']== 'No') &(df['Are yu sad?'].isin(answers))
</code></pre>
<p><a href="https://i.stack.imgur.com/WFAWU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WFAWU.png" alt="enter image description here" /></a></p>
<p>Actually I just want that the result will be something like this:</p>
<pre><code>Yes
110
</code></pre>
<p>EDIT:</p>
<p>This is my result and in red the thing that I want</p>
<p><a href="https://i.stack.imgur.com/UDxDQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UDxDQ.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74248346,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 0,
"selected": false,
"text": "java.sql"
}
] | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16239103/"
] |
74,247,647 | <p>I have (N,2) numpy array :</p>
<pre><code> [3,5]
[4,2]
[1,6]
[5,4]
.....
</code></pre>
<p>I want to swap the values on every row so that the bigger value is FIRST</p>
<pre><code> [5,3]
[4,2]
[6,1]
[5,4]
.....
</code></pre>
| [
{
"answer_id": 74247723,
"author": "Rodrigo Guzman",
"author_id": 13315525,
"author_profile": "https://Stackoverflow.com/users/13315525",
"pm_score": 3,
"selected": true,
"text": "array.sort()\narray = array[:, ::-1]\n"
},
{
"answer_id": 74247786,
"author": "Chen Lin",
"a... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1019129/"
] |
74,247,675 | <p>I am trying to compile the following code
<a href="https://i.stack.imgur.com/eoZ9y.png" rel="nofollow noreferrer">My smart contract</a></p>
<pre><code>pragma solidity 0.5.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
contract GToken is ERC20, Ownable {
constructor() ERC20("GToken", "GT") public {
_mint(msg.sender, 50 * (10**18));
}
}
</code></pre>
<p>I am getting the following error:</p>
<p><a href="https://i.stack.imgur.com/REqHy.png" rel="nofollow noreferrer">Error</a></p>
<pre><code>contracts/GToken.sol:10:19: TypeError: Wrong argument count for modifier invocation: 2 arguments given but expected 0.
constructor() ERC20("GToken", "GT") public {
^-------------------^
Error HH600: Compilation failed
</code></pre>
| [
{
"answer_id": 74247723,
"author": "Rodrigo Guzman",
"author_id": 13315525,
"author_profile": "https://Stackoverflow.com/users/13315525",
"pm_score": 3,
"selected": true,
"text": "array.sort()\narray = array[:, ::-1]\n"
},
{
"answer_id": 74247786,
"author": "Chen Lin",
"a... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13555775/"
] |
74,247,680 | <p>I want to change the value of the progress bar when each tap is clicked.</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 taps = document.getElementsByClassName('et_pb_tab');
for (var i = 0; i < taps.length; i++) {
taps[i].addEventListener('click', () => {
var v1 = document.getElementById('p1').value;
v1.value = v1 + 20;
});
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>li.et_pb_tab_active {
background-color: rgba(255, 211, 14, 0.29);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><progress value="0" max="100" id="p1"></progress>
<ul class="et_pb_tabs_controls">
<li class="et_pb_tab et_pb_tab_active"><a href="#">Clase N° 1</a></li>
<li class="et_pb_tab" style="height: 64.8px;"><a href="#">Clase N° 2</a></li>
<li class="et_pb_tab" style="height: 64.8px;"><a href="#">Clase N° 3</a></li>
<li class="et_pb_tab" style="height: 64.8px;"><a href="#">Clase N° 4</a></li>
<li class="et_pb_tab" style="height: 64.8px;"><a href="#">Clase N° 5</a></li>
</ul></code></pre>
</div>
</div>
</p>
<p>I was trying to get the element "et_pb_tab" that is each tap and with a for add the listener, then click on the tap, the progress bar adds 20 to the value, but it's not working.</p>
| [
{
"answer_id": 74247723,
"author": "Rodrigo Guzman",
"author_id": 13315525,
"author_profile": "https://Stackoverflow.com/users/13315525",
"pm_score": 3,
"selected": true,
"text": "array.sort()\narray = array[:, ::-1]\n"
},
{
"answer_id": 74247786,
"author": "Chen Lin",
"a... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20301118/"
] |
74,247,685 | <p>after the user enters the wrong data, I would like enter the data again again.</p>
<pre><code>a=int(input("enter the value: "))
b=int(input("enter the value: "))
def d(a,b):
if(b == 0):
return "back to menu"
else:
return a / b
print(d(a,b))
</code></pre>
| [
{
"answer_id": 74247723,
"author": "Rodrigo Guzman",
"author_id": 13315525,
"author_profile": "https://Stackoverflow.com/users/13315525",
"pm_score": 3,
"selected": true,
"text": "array.sort()\narray = array[:, ::-1]\n"
},
{
"answer_id": 74247786,
"author": "Chen Lin",
"a... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15030535/"
] |
74,247,686 | <p>I'm using the <code>refreshable</code> modifier on List
<a href="https://developer.apple.com/documentation/SwiftUI/View/refreshable(action:)" rel="nofollow noreferrer">https://developer.apple.com/documentation/SwiftUI/View/refreshable(action:)</a></p>
<p>The List is contained in a view (TestChildView) that has a parameter. When the parameter changes, TestChildView is reinstantiated with the new value. The list has a refreshable action. However, when pulling down to refresh the list, the refresh action is run against the original view instance, so it doesn't see the current value of the parameter.</p>
<p>To reproduce with the following code: If you click the increment button a few times, you can see the updated value propagating to the list item labels. However, if you pull down the list to refresh, it prints the <em>original</em> value of the parameter.</p>
<p>I assume this is happening because of how refreshable works .. it sets the <code>refresh</code> environment value, and I guess it doesn't get updated as new instances of the view are created.</p>
<p>It seems like a bug, but I'm looking for a way to work around -- how can the refreshable action see the current variable/state values?</p>
<pre><code>import SwiftUI
struct TestParentView: View {
@State var myVar = 0
var body: some View {
VStack {
Text("increment")
.onTapGesture {
myVar += 1
}
TestChildView(myVar: myVar)
}
}
}
struct TestChildView: View {
let myVar: Int
struct Item: Identifiable {
var id: String {
return val
}
let val: String
}
var list: [Item] {
return [Item(val: "a \(myVar)"), Item(val: "b \(myVar)"), Item(val: "c \(myVar)")]
}
var body: some View {
VStack {
List(list) { elem in
Text(elem.val)
}.refreshable {
print("myVar: \(myVar)")
}
}
}
}
</code></pre>
| [
{
"answer_id": 74306362,
"author": "Roland Lariotte",
"author_id": 10408494,
"author_profile": "https://Stackoverflow.com/users/10408494",
"pm_score": 2,
"selected": true,
"text": "myVar"
},
{
"answer_id": 74377954,
"author": "Cheezzhead",
"author_id": 2542661,
"autho... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/342647/"
] |
74,247,691 | <p>I am developing a Flutter application with go_router and riverpod for navigation and state management respectively. The app has a widget which displays a live camera feed, and I'd like to "switch it off" and free the camera when other pages are stacked on top of it.</p>
<p>Here's a sample of the GoRouter code <strong>WITHOUT</strong> such logic.</p>
<pre><code>GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => CameraWidget(),
routes: [
GoRoute(
path: 'page1',
builder: (context, state) => Page1Screen(),
),
],
),
],
)
</code></pre>
<p>My first attempt has been to put some logic in the GoRoute builder:</p>
<pre><code>GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) {
if (state.location == "/") {
return CameraWidget();
}
return Center(child: Text("Camera not visible");
},
routes: [
GoRoute(
path: 'page1',
builder: (context, state) => Page1Screen(),
),
],
),
],
)
</code></pre>
<p>But this apparently <strong>does not work</strong> as the builder is not called again when going from "/" to "/page1".</p>
<p>I then thought of using a riverpod StateProvider to hold a camera "on/off" state, to be manipulated by GoRouter. This is what I tried:</p>
<pre><code>GoRouter(
routes: [
GoRoute(
path: '/',
redirect: (context, state) {
final cameraStateNotifier = ref.read(cameraStateNotifierProvider.notifier);
if (state.location == "/") {
cameraStateNotifier.state = true;
} else {
cameraStateNotifier.state = false;
}
return null;
},
builder: (context, state) => CameraWidget(),
routes: [
GoRoute(
path: 'page1',
builder: (context, state) => Page1Screen(),
),
],
),
],
)
</code></pre>
<p>But this also <strong>does not work</strong> as apparently <code>redirect</code> gets called while rebuilding the widget tree, and it is forbidden to change a provider state while that happens.</p>
<p>Has anyone encountered the same issue before? How can I have a provider listen to GoRouter's location changes?</p>
| [
{
"answer_id": 74248251,
"author": "Michele",
"author_id": 8965508,
"author_profile": "https://Stackoverflow.com/users/8965508",
"pm_score": 1,
"selected": false,
"text": "Navigator.pop()"
},
{
"answer_id": 74288650,
"author": "Michele",
"author_id": 8965508,
"author_... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8965508/"
] |
74,247,710 | <p>Since I have upgraded to Chrome 106 (and now to 107) the driver manages to open the URL at the first time but after some timeout (?) or other criteria, the driver.refresh() does not return (i.e. no resposne).
The way it looks to me, if the Refresh occurs within seconds since the initial open, then the refresh succeeds.
Yet, if longer interval has elapsed since the initial open, then the refresh() does not complete.
Code is in Python.</p>
<p>Before version 106 this seemed to work well</p>
<p>Does anyone experience similar behaviour? Any idea how to fix that?</p>
<pre><code>#Code to create the driver:
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--disable-blink-features")
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Chrome(r'... \chromedriver', options=chrome_options)`
#Then, the attempt to refresh:
driver.refresh()
</code></pre>
<p>Expecting the webpage to refresh</p>
| [
{
"answer_id": 74259382,
"author": "Rony",
"author_id": 12977647,
"author_profile": "https://Stackoverflow.com/users/12977647",
"pm_score": 0,
"selected": false,
"text": "import sys sys.path.insert(0,'/usr/lib/chromium-browser/chromedriver')\nfrom selenium import webdriver \nchrome_optio... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19698097/"
] |
74,247,722 | <p>I have a <code>MainStruct</code> which owns an instance of <code>HelperStruct</code>. I want to make a method that calls <code>helper</code>'s method. But the <code>helper</code>'s method really needs (immutable) access to <code>MainStruct</code></p>
<pre class="lang-rust prettyprint-override"><code>struct MainStruct {
helper: HelperStruct,
}
impl MainStruct {
pub fn call_helper(&mut self, args) {
// &mut self because the_method changes inner state of HelperStruct
self.helper.the_method(self, args)
}
}
impl HelperStruct {
pub fn the_method(&mut self, owner: &MainStruct, args) {
owner.other_method();
}
}
</code></pre>
<p>With this setup, I'm getting</p>
<pre><code>error[E0502]: cannot borrow `self.helper` as mutable because it is also borrowed as immutable
214 | self.helper.the_method(self, args)
| ^^^^^^^^^^^^----------^----^^^^^^^^^^^^^^^^^^^^^^
| | | |
| | | immutable borrow occurs here
| | immutable borrow later used by call
| mutable borrow occurs here
</code></pre>
<p>It is crucial that the <code>MainStruct</code> remains the primary interface for interaction with the functionality (so having Helper own Main isn't an option).</p>
<p>How should I restructure my code (or maybe use smart pointers?) so that I can interact with the owner from the inside of Helper?
Also, it is guaranteed that <code>the_method()</code> will only be called inside an instance of <code>MainStruct</code>.</p>
<h3>Actual context:</h3>
<p>The <code>MainStruct</code> is the <code>Field</code> of my game. The <code>HelperStruct</code> is the class that takes care of pathing, A* mostly. A* has a number of large arrays that store its state. After an A* pass only some of them <em>need</em> to be reinitialized (or otherwise cleaned).</p>
<p>I end up calling A* a lot of times, so I want to avoid fully reinitializing it for every pass. So I store it in <code>Field</code>, and only call <code>reset()</code> after a pass.</p>
<p>To path plan properly, A* needs to look at the <code>Field</code> (obstacles, etc). While the A* is going, it of course changes some of its own fields, so <code>the_method</code>, being actually</p>
<pre class="lang-rust prettyprint-override"><code>pub fn full_pathing(&mut self, field: &Field, source: (i32, i32), destination: (i32, i32))
</code></pre>
<p>needs to have a <code>&mut self</code></p>
| [
{
"answer_id": 74248033,
"author": "mdm",
"author_id": 25318,
"author_profile": "https://Stackoverflow.com/users/25318",
"pm_score": 0,
"selected": false,
"text": "self"
},
{
"answer_id": 74248364,
"author": "Silvio Mayolo",
"author_id": 2288659,
"author_profile": "ht... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10919379/"
] |
74,247,758 | <p>My new problem is identical to my previous question asked and kindly answered by @player0 and @TheMaster here:</p>
<p><a href="https://stackoverflow.com/questions/74234209/how-to-concatenate-multiple-non-blank-cells-contents-into-adjacent-column-skippi">How To Concatenate multiple non blank cells contents into adjacent column skipping intermediary blank cells in a GoogleSheets Formula?</a></p>
<p>It is identical in all but the size/length of the non blank cells groups to output.
Previously I asked to omit single cells groups as they wouldn't have any subordinate cells content to concatenate with. But that was a mistake as they'd still require laborious manual extraction one-by-one if omitted.</p>
<p>So the new problem is as follow:</p>
<p>In Column C I need to:</p>
<ul>
<li>concatenate each vertical non-blank cells groups from Column A (ignoring the blank cells groups in between) AND,</li>
<li>only concatenate them once (no duplicate smaller groups in-between) AND,</li>
<li><em>Any or from 1 to 13 at least groups sizes</em> (that's the only difference needed).</li>
</ul>
<p><strong>Single Cell Groups remaining issue:</strong></p>
<p>I've looked at new Functions <a href="https://support.google.com/docs/answer/12568597" rel="nofollow noreferrer">REDUCE</a> and <a href="https://support.google.com/docs/answer/12508718?hl=en" rel="nofollow noreferrer">LAMBDA</a> but still need to work on grasping them.
@TheMaster thanks for your suggestion, I've tested it but it's not returning any value for the single cell groups (please see the screenshot row 20, E20 doesn't return A20 value.
What would be the fix you had in mind (I'm not sure what's the controlling element for the number of row/cells to modify) Thanks again!</p>
<p><strong>Your Formula Tested:</strong></p>
<p><a href="https://i.stack.imgur.com/H9U3w.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H9U3w.png" alt="Your Formula Tested" /></a></p>
<p>@player0, thanks too for the reply and narrowing down of the formula, though the 2nd shared screenshot appears to be same as 1st one, can't see the change).
I reproduced a simplified version of my dataset with the issue in next screenshots and below Text Table:</p>
<p><strong>Your Formula In New Test:</strong></p>
<p><a href="https://i.stack.imgur.com/99gWZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/99gWZ.png" alt="Your Formula In New Test" /></a></p>
<p><strong>My Regex Formula (To Output Only the Cells With 1s Word followed by 2 whitespaces):</strong></p>
<p><code>=Arrayformula(if(regexmatch(A1:A,"^(\w+)(\s\s)"),A1:A,""))</code></p>
<p><a href="https://i.stack.imgur.com/t7NX5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t7NX5.png" alt="My Regex Formula" /></a></p>
<p><strong>My Regex Formula Reversed (To Output the other Cells):</strong></p>
<p><code>=Arrayformula(if(regexmatch(A1:A,"^(\w+)(\s\s)")=FALSE,A1:A,""))</code></p>
<p><a href="https://i.stack.imgur.com/2NWXG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2NWXG.png" alt="My Regex Formula Reversed" /></a>
How To Concatenate multiple non blank cells contents into adjacent column skipping intermediary blank cells in a GoogleSheets Formula?</p>
<p>Text Table Simplified Dataset:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Column A</th>
<th style="text-align: left;">Column B</th>
<th style="text-align: left;">Column C</th>
<th style="text-align: left;">Column D</th>
<th style="text-align: left;">Column E</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">A</td>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
<td style="text-align: left;">A</td>
<td style="text-align: left;"></td>
</tr>
<tr>
<td style="text-align: left;">ONE 1, 2, 3, 4, 5, 6, 7, 8,</td>
<td style="text-align: left;"></td>
<td style="text-align: left;">ONE 1, 2, 3, 4, 5, 6, 7, 8,</td>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
</tr>
<tr>
<td style="text-align: left;">&1, 2, 3, 4, 5, 6</td>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
<td style="text-align: left;">&1, 2, 3, 4, 5, 6</td>
<td style="text-align: left;"></td>
</tr>
<tr>
<td style="text-align: left;">TWO 1, 2, 3, 4, 5, 6, 7, 8,</td>
<td style="text-align: left;"></td>
<td style="text-align: left;">TWO 1, 2, 3, 4, 5, 6, 7, 8,</td>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
</tr>
<tr>
<td style="text-align: left;">&1, 2, 3, 4, 5</td>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
<td style="text-align: left;">&1, 2, 3, 4, 5</td>
<td style="text-align: left;"></td>
</tr>
<tr>
<td style="text-align: left;">THREE 1, 2, 3, 4, 5, 6, 7,</td>
<td style="text-align: left;"></td>
<td style="text-align: left;">THREE 1, 2, 3, 4, 5, 6, 7,</td>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
</tr>
<tr>
<td style="text-align: left;">&1, 2, 3, 4, 5, 6, 7,</td>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
<td style="text-align: left;">&1, 2, 3, 4, 5, 6, 7, "</td>
<td style="text-align: left;">&1, 2, 3, 4, 5, 6, 7,&&1, 2, 3, 4, 5, 6, 7, 8&&&1, 2, 3"</td>
</tr>
<tr>
<td style="text-align: left;">&&1, 2, 3, 4, 5, 6, 7, 8</td>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
<td style="text-align: left;">&&1, 2, 3, 4, 5, 6, 7, 8</td>
<td style="text-align: left;"></td>
</tr>
<tr>
<td style="text-align: left;">&&&1, 2, 3</td>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
<td style="text-align: left;">&&&1, 2, 3</td>
<td style="text-align: left;"></td>
</tr>
<tr>
<td style="text-align: left;">FOUR 1, 2, 3, 4, 5, 6, 7,</td>
<td style="text-align: left;"></td>
<td style="text-align: left;">FOUR 1, 2, 3, 4, 5, 6, 7,</td>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
</tr>
<tr>
<td style="text-align: left;">One, Two, Three, For, Five</td>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
<td style="text-align: left;">One, Two, Three, For, Five</td>
<td style="text-align: left;"></td>
</tr>
<tr>
<td style="text-align: left;">FIVE 1, 2, 3, 4, 5, 6, 7,</td>
<td style="text-align: left;"></td>
<td style="text-align: left;">FIVE 1, 2, 3, 4, 5, 6, 7,</td>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
</tr>
<tr>
<td style="text-align: left;">&1, 2, 3, 4, 5,</td>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
<td style="text-align: left;">&1, 2, 3, 4, 5, "</td>
<td style="text-align: left;">&1, 2, 3, 4, 5,&&1, 2, 3, 4, 5, 6, 7,&&&1, 2, 3, 4, 5, 6,&&&&1, 2, 3"</td>
</tr>
<tr>
<td style="text-align: left;">&&1, 2, 3, 4, 5, 6, 7,</td>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
<td style="text-align: left;">&&1, 2, 3, 4, 5, 6, 7,</td>
<td style="text-align: left;"></td>
</tr>
<tr>
<td style="text-align: left;">&&&1, 2, 3, 4, 5, 6,</td>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
<td style="text-align: left;">&&&1, 2, 3, 4, 5, 6,</td>
<td style="text-align: left;"></td>
</tr>
<tr>
<td style="text-align: left;">&&&&1, 2, 3</td>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
<td style="text-align: left;">&&&&1, 2, 3</td>
<td style="text-align: left;"></td>
</tr>
<tr>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
<td style="text-align: left;"></td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74247790,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 3,
"selected": true,
"text": "=INDEX(LAMBDA(z, IFNA(VLOOKUP(z, LAMBDA(x, {INDEX(SPLIT(x, \" \"),,1), \n SUBSTITUTE(x, \" \", )})\n (FLATTEN(SPLIT(Q... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10789707/"
] |
74,247,763 | <p>In my <code>DbContext</code>, I am setting all strings to <code>varchar(250)</code>, but I have some strings marked as <code>varchar(max)"</code>. After creating my migrations, I see the tables marked as max are still being created with a max length of 250.</p>
<p>How can I have my data annotations override the config builder command?</p>
<p>Config builder:</p>
<pre><code>protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
configurationBuilder.Properties<string>()
.HaveColumnType("varchar(250)")
.AreUnicode(false);
}
</code></pre>
<p>Entity:</p>
<pre><code> [Column(TypeName = "varchar(max)")]
public string? AffectedColumns { get; set; }
</code></pre>
<p>What is generated in the migration:</p>
<pre><code>AffectedColumns = table.Column<string>(type: "varchar(250)", unicode: false, nullable: true)
</code></pre>
| [
{
"answer_id": 74268231,
"author": "Gert Arnold",
"author_id": 861716,
"author_profile": "https://Stackoverflow.com/users/861716",
"pm_score": 0,
"selected": false,
"text": "OnModelCreating"
},
{
"answer_id": 74281828,
"author": "Wes H",
"author_id": 7127182,
"author_... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2911737/"
] |
74,247,772 | <p>I am trying to build a userscript to auto print PDFs using print node. The files can not be accessed without a session based login which printnode can not support. So the other option is to base64 encode the file in the browser and POST it to the API endpoint.</p>
<p><code>https://example.com/InternalReport.php?id=417660</code> is the page I am running this on, which just returns a PDF file that the browser displays by default.</p>
<p>I was able to manually convert the file, and send it like this, im trying to figure out how to get the file which is the page, but not end up encoding the entire display html, just the PDF itself.</p>
<pre><code>fetch(https://api.printnode.com/printjobs, {
method:"POST",
body: JSON.stringify({
printerId: "71635092",
contentType: "pdf_base64",
content: "JVBERi0xLjUNJeLjz9MNCjQgMCBvYmoNPDwvTGluZWFyaXplZ...g0KMTE2DQolJUVPRg0K"
})
}).then(result => {
// do something with the result
console.log("Completed with result:", result);
}).catch(err => {
// if any error occured, then catch it here
console.error(err);
});
</code></pre>
<p>I tried (I think, I deleted my first attempts by accident) <code>base64.encode(Document.body)</code> in the content but print node did not understand the content. I think that actually sent all the HTML of the displayed page including chromes built in viewer. Any help is appreciated.</p>
<p>edit: I am using tamper monkey to embed this in the resulting page, I dont have control over the source otherwise I would obviously do this from the server.</p>
| [
{
"answer_id": 74248653,
"author": "wOxxOm",
"author_id": 3959875,
"author_profile": "https://Stackoverflow.com/users/3959875",
"pm_score": 1,
"selected": false,
"text": "(async () => {\n const blob = await (await fetch(location)).blob();\n const fr = new FileReader();\n const dataUrl... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2005444/"
] |
74,247,784 | <p>I'm writing my results (both text and tables) and the process is quite time-consuming...
I was wondering if a function in R could help me paste my results into the text so I could copy it into WORD?</p>
<p>For example:
R square = <em>put number here</em>, B = <em>put number here</em>... The difference between the models was significant/nonsignificant with p < <em>put number here</em></p>
<p>Then I would love to paste it into WORD.</p>
<p>Best regards,</p>
<p>Daniel</p>
<p>Couldn't find any function that would help me... Tried Flextable...</p>
| [
{
"answer_id": 74248653,
"author": "wOxxOm",
"author_id": 3959875,
"author_profile": "https://Stackoverflow.com/users/3959875",
"pm_score": 1,
"selected": false,
"text": "(async () => {\n const blob = await (await fetch(location)).blob();\n const fr = new FileReader();\n const dataUrl... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15139481/"
] |
74,247,840 | <p>I am aware of q&a on how to check if file exists <em>by name</em> (using <code>hasnext()</code>). I need to check however <em>by file ID</em>, preferably without the advanced Drive API.</p>
<p>Disclosure: I wrote a solution based on error handling:</p>
<pre><code>function ifFileExists(id){
try {DriveApp.getFileById(id);return true;}
catch(e) {return false}
}
</code></pre>
<p>But this feels like clumsy. Anyone knows a better solution?</p>
| [
{
"answer_id": 74249592,
"author": "Tanaike",
"author_id": 7108653,
"author_profile": "https://Stackoverflow.com/users/7108653",
"pm_score": 2,
"selected": false,
"text": "DriveApp.getFileById(id)"
},
{
"answer_id": 74250399,
"author": "Rubén",
"author_id": 1595451,
"... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4015014/"
] |
74,247,849 | <p>I'm trying to splice all matching items of <code>parcel</code> in an array inside an object.</p>
<p>Example of array of objects called <code>documents</code>:</p>
<pre><code>[
{name: "first", content: ["1", "2", "1", "3"]},
{name: "second", content: ["2", "1", "1", "1"]},
{name: "third", content: ["4", "1", "3", "2"]},
]
</code></pre>
<p><code>parcel = 1</code> and I'm trying to splice all instances of <code>1</code>.</p>
<p>Here's what I have at the moment:</p>
<pre><code>console.log(parcel);
const parcel = 1;
console.log("doc start", documents);
for (i of documents) {
// get index by count
let count = -1;
for (j of i.content) {
count = count + 1;
console.log(j);
if (j == parcel) {
i.content.splice(count, 1);
}
}
}
console.log("doc end", documents);
</code></pre>
<p>Here's what the console logs with different array example:</p>
<pre><code>parcel 1
doc start [
{
title: '1',
content: [
'1', '2', '2',
'3', '1', '1',
'2', '3'
]
}
]
1
2
3
1
2
3
doc end [ { title: '1', content: [ '2', '2', '3', '1', '2', '3' ] } ]
</code></pre>
<p>You can see that <code>j</code> doesn't seem to be looping through the whole of <code>i.content</code>, which means that the <code>if</code> statement is not running to splice all the correct items.</p>
<p>The end result of the console log should be:</p>
<pre><code>doc start [{title: '1', content: [ '2', '2', '3', '2', '3' ]}]
</code></pre>
<p>I'm not sure why this is happening...</p>
| [
{
"answer_id": 74247991,
"author": "Andy",
"author_id": 1377002,
"author_profile": "https://Stackoverflow.com/users/1377002",
"pm_score": 1,
"selected": false,
"text": "map"
},
{
"answer_id": 74247997,
"author": "Miguel Hidalgo",
"author_id": 16480445,
"author_profile... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18472704/"
] |
74,247,852 | <p>I'm currently trying to write a function that takes as arguments an Int and an array of Ints and for every even value in the array, it concatenates the Int to the final array.
So, something like this:
f 3 [1,2,3,4,5,6] = [1,2,3,3,4,3,5,6,3]</p>
<p>This is the code I imagined would work (I'm just beginning so sorry if it's bad):</p>
<pre><code>f :: Int -> [Int] -> [Int]
f(x,[]) = []
f(x,y)
|even head(y) = (head(y) ++ [x] ++ f(x,drop 1 y)
|otherwise = head(y) ++ f(x,(drop 1 y))
</code></pre>
<p>The error I'm getting is "Couldn't match expected type of 'Int' with actual type (a3, [[a3]])'. I understand the parameters types are mismatched, but I'm not sure how a proper syntax would look like here</p>
| [
{
"answer_id": 74247861,
"author": "Willem Van Onsem",
"author_id": 67579,
"author_profile": "https://Stackoverflow.com/users/67579",
"pm_score": 3,
"selected": true,
"text": "(x, [])"
},
{
"answer_id": 74249367,
"author": "Chris",
"author_id": 15261315,
"author_profi... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17360903/"
] |
74,247,854 | <p>Can I save values in textview that appear again after restarting the application?</p>
<p>is there a possibility?</p>
<p>namespace App11
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{</p>
<pre><code> EditText edt;
TextView res;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.activity_main);
edt = FindViewById<EditText>(Resource.Id.appCompatEditText1);
Button btn = FindViewById<Button>(Resource.Id.button1);
res = FindViewById<TextView>(Resource.Id.textView10);
btn.Click += Btn_Click;
}
private void Btn_Click(object sender, System.EventArgs e)
{
string s = edt.Text.ToString();
res.Text = s;
}
</code></pre>
<pre><code></code></pre>
| [
{
"answer_id": 74247861,
"author": "Willem Van Onsem",
"author_id": 67579,
"author_profile": "https://Stackoverflow.com/users/67579",
"pm_score": 3,
"selected": true,
"text": "(x, [])"
},
{
"answer_id": 74249367,
"author": "Chris",
"author_id": 15261315,
"author_profi... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17006648/"
] |
74,247,855 | <p>I have problem with removing elements from array by value of elements.
I create a function which remove elements from array by index, now i want to use this function to remove element of array by value.</p>
<p>Here is my code:</p>
<pre><code>bool Array::RemoveAt(int index)
{
if (index < 0 || index >= number_of_elements)
return false;
for (int i = index; i < this->number_of_elements-1; i++)
{
this->arr[i] = this->arr[i + 1];
}
this->number_of_elements--;
return true;
}
bool Array::RemoveByValue(int value)
{
for (int i = 0; i < this->number_of_elements-1; i++)
{
if (this->arr[i] == value) {
this->RemoveAt(i);
return true;
}
else
return false;
}
}
</code></pre>
| [
{
"answer_id": 74247861,
"author": "Willem Van Onsem",
"author_id": 67579,
"author_profile": "https://Stackoverflow.com/users/67579",
"pm_score": 3,
"selected": true,
"text": "(x, [])"
},
{
"answer_id": 74249367,
"author": "Chris",
"author_id": 15261315,
"author_profi... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20367556/"
] |
74,247,875 | <p>Let's assume I have four fields A,B,C,D
I need SQL query to show results only when two or more fields are not null</p>
| [
{
"answer_id": 74248148,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 2,
"selected": false,
"text": "select *\nfrom the_table\nwhere num_nonnulls(a,b,c,d) >= 2;\n"
},
{
"answer_id": 74249922,
"a... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7693745/"
] |
74,247,890 | <p>I'm trying to create a DTO that has another DTO as array, but when sending the body, nestjs/swagger not detecting the body content.
My DTOs are:</p>
<pre><code>export class CreatePageDto {
@ApiHideProperty()
createAt: Date;
@ApiHideProperty()
updateAt: Date;
@ApiProperty({
type: CreatePageTranslateDto,
isArray: true,
})
translations: CreatePageTranslateDto[];
}
export class CreatePageTranslateDto {
@ApiProperty()
slug: string;
@ApiProperty()
title: string;
@ApiProperty({
enum: AvailableLanguages,
})
lang: AvailableLanguages;
}
</code></pre>
<p>When a post a body like this:</p>
<pre><code>
curl --location --request POST 'http://localhost:3000/pages' \
--header 'Content-Type: application/json' \
--data-raw '{
"translations": [
{
"slug": "nombre-de-ejemplo",
"title": "Nombre de ejemplo",
"lang": "es"
}
]
}'
</code></pre>
<p>I get an empty body.</p>
| [
{
"answer_id": 74248148,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 2,
"selected": false,
"text": "select *\nfrom the_table\nwhere num_nonnulls(a,b,c,d) >= 2;\n"
},
{
"answer_id": 74249922,
"a... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74247890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5955927/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.