qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,528,095
|
<p>I will be injecting this repository class into each of my viewModels that require it. The following is the init block for the repository.</p>
<pre><code>init {
GlobalScope.launch {
while(true) {
when (val response = getData()) {
is ApiResponse.Success -> {
response.data?.let {
data = it
}
}
else -> {}
}
delay(5000)
}
}
}
</code></pre>
|
[
{
"answer_id": 74528305,
"author": "Kushal Prajapati",
"author_id": 14070467,
"author_profile": "https://Stackoverflow.com/users/14070467",
"pm_score": 2,
"selected": false,
"text": " RequestOptions myOptions = new RequestOptions()\n .centerCrop() // or centerCrop\n .override(800, 500);//your imageview frame size\n\n Glide.with(activity)\n .applyDefaultRequestOptions(myOptions)\n .load(list.get(position).appthumbnail)\n .error(R.drawable.no_image_available)\n .into(holder.ivImage);\n\n"
},
{
"answer_id": 74541015,
"author": "Android Newbie A",
"author_id": 20125791,
"author_profile": "https://Stackoverflow.com/users/20125791",
"pm_score": 2,
"selected": true,
"text": "relative layout linear layout constraint layout <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"5dp\"\n android:theme=\"@style/Theme.Music.Font\">\n\n <com.google.android.material.imageview.ShapeableImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"50dp\"\n android:layout_height=\"50dp\"\n android:layout_alignParentStart=\"true\"\n android:layout_margin=\"5dp\"\n\n android:contentDescription=\"@string/cover\"\n android:src=\"@drawable/image_as_cover\"\n app:shapeAppearance=\"@style/roundedImageView\"\n \n app:layout_constraintTop_toTopOf=\"parent\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\" />\n\n\n <View\n android:id=\"@+id/linearLayout\"\n android:layout_width=\"0dp\"\n android:layout_height=\"0dp\"\n\n app:layout_constraintTop_toTopOf=\"parent\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintStart_toEndOf=\"@id/imageView\"\n app:layout_constraintEnd_toEndOf=\"parent\" />\n\n <TextView\n android:id=\"@+id/titleView\"\n android:layout_width=\"0dp\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"5dp\"\n\n android:maxLines=\"1\"\n android:singleLine=\"true\"\n android:fontFamily=\"@font/medium\"\n android:text=\"@string/love_is_gone_by_slander_forever_on_love\"\n android:textSize=\"15sp\"\n android:text=\"123\"\n app:layout_constraintTop_toTopOf=\"@id/linearLayout\"\n app:layout_constraintBottom_toTopOf=\"@id/albumName\"\n app:layout_constraintStart_toStartOf=\"@id/linearLayout\"\n app:layout_constraintEnd_toEndOf=\"@id/linearLayout\" />\n \n <TextView\n android:id=\"@+id/albumName\"\n android:layout_width=\"0dp\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"5dp\"\n android:fontFamily=\"@font/medium\"\n android:maxLines=\"1\"\n android:singleLine=\"true\"\n android:text=\"@string/love_is_gone_by_slander_forever_on_love\"\n android:textSize=\"15sp\"\n\n app:layout_constraintTop_toBottomOf=\"@id/titleView\"\n app:layout_constraintBottom_toTopOf=\"@id/duration\"\n app:layout_constraintStart_toStartOf=\"@id/linearLayout\"\n app:layout_constraintEnd_toEndOf=\"@id/linearLayout\" />\n\n <TextView\n android:id=\"@+id/duration\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentEnd=\"true\"\n android:layout_centerVertical=\"true\"\n android:layout_margin=\"10dp\"\n android:fontFamily=\"@font/medium\"\n android:maxLines=\"1\"\n android:text=\"@string/duration\"\n android:textSize=\"11sp\"\n\n app:layout_constraintTop_toBottomOf=\"@id/albumName\"\n app:layout_constraintBottom_toBottomOf=\"@id/linearLayout\"\n app:layout_constraintStart_toStartOf=\"@id/linearLayout\"\n app:layout_constraintEnd_toEndOf=\"@id/linearLayout\" />\n \n</androidx.constraintlayout.widget.ConstraintLayout>\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19361136/"
] |
74,528,129
|
<p>I have a problem thats been stumping me for days. I wanted to run this GAIN program on my local system though command line (<a href="https://github.com/jsyoon0823/GAIN" rel="nofollow noreferrer">https://github.com/jsyoon0823/GAIN</a>) so I downloaded it, installed Python for the first time because</p>
<pre><code>Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
</code></pre>
<p>then created a virtual environment. I ran <code>pip install -r requirements.txt</code> (<a href="https://pastebin.com/FMqagzx5" rel="nofollow noreferrer">logs</a>) When I ran the program it said</p>
<pre><code>(GAINenv) C:\Users\Admin\Downloads\GAIN-master\GAIN-master>python3 main_letter_spam.py --data_name spam --miss_rate: 0.2 --batch_size 128 --hint_rate 0.9 --alpha 100 --iterations 10000
Traceback (most recent call last):
File "C:\Users\Admin\Downloads\GAIN-master\GAIN-master\main_letter_spam.py", line 24, in <module>
import numpy as np
ModuleNotFoundError: No module named 'numpy'
</code></pre>
<p>I was confused because they said in the logs numpy was installed. So I did the following:</p>
<ol>
<li>checked GAINenv\Lib\site-packages for numpy. It was already there written as <code>numpy</code>. In the import, it was also written as <code>import numpy as np</code></li>
<li>checked if there are multiple Python installations. There aren't</li>
<li>ran <code>pip install numpy</code>. It said <code>Requirement already satisfied: numpy in c:\users\admin\downloads\gain-master\gain-master\gainenv\lib\site-packages (1.23.5)</code></li>
<li>forced install <code>pip install -I numpy</code>. Ran the command and got the same no module error</li>
<li>Added the path in virtual env then reset the command prompt window. Same error</li>
<li>did pip3 and pip2 install. Still no module error</li>
<li>downloaded numpy directly from sourceforge then installed it in virtualenv directory. Doesn't work</li>
</ol>
<p>Here is the list of similar questions I read but didn't work:</p>
<ol>
<li><a href="https://stackoverflow.com/questions/58278978/no-module-named-numpy-but-requirement-already-satisfied-numpy">No module named 'numpy' but Requirement already satisfied: numpy</a></li>
<li><a href="https://stackoverflow.com/questions/7818811/error-import-error-no-module-named-numpy-on-windows">Error "Import Error: No module named numpy" on Windows</a></li>
<li><a href="https://stackoverflow.com/questions/66408996/python-not-found-despite-having-been-installed">'Python not found' despite having been installed</a></li>
<li><a href="https://unix.stackexchange.com/questions/93097/numpy-module-not-found-despite-being-in-path">https://unix.stackexchange.com/questions/93097/numpy-module-not-found-despite-being-in-path</a></li>
<li><a href="https://stackoverflow.com/questions/48667739/numpy-module-not-found-after-install">NumPy module not found after install</a></li>
<li><a href="https://stackoverflow.com/questions/69737385/python-module-not-found-despite-being-installed">Python Module not found despite being installed</a></li>
<li><a href="https://stackoverflow.com/questions/48818277/no-module-named-numpy-despite-numpy-being-already-installed">no module named numpy despite numpy being already installed</a></li>
<li><a href="https://stackoverflow.com/questions/53360524/pyaudio-module-not-found-despite-being-installed">Pyaudio module not found despite being installed</a></li>
</ol>
<p>This is what happens when I run <code>python -m site</code></p>
<pre><code>(GAINenv) C:\Users\Admin\Downloads\GAIN-master\GAIN-master>python -m site
sys.path = [
'C:\\Users\\Admin\\Downloads\\GAIN-master\\GAIN-master',
'C:\\Program Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\\python310.zip',
'C:\\Program Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\\DLLs',
'C:\\Program Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\\lib',
'C:\\Users\\Admin\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0',
'C:\\Users\\Admin\\Downloads\\GAIN-master\\GAIN-master\\GAINenv',
'C:\\Users\\Admin\\Downloads\\GAIN-master\\GAIN-master\\GAINenv\\lib\\site-packages',
]
USER_BASE: 'C:\\Users\\Admin\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\\LocalCache\\local-packages' (exists)
USER_SITE: 'C:\\Users\\Admin\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python310\\site-packages' (exists)
ENABLE_USER_SITE: False
</code></pre>
<p>I don't care about Anaconda and PyCharm because I simply want to run a python script locally through command line.</p>
<p>I'm using Windows 10 and Python 3.10 from Microsoft Store. Thanks in advance!</p>
|
[
{
"answer_id": 74528305,
"author": "Kushal Prajapati",
"author_id": 14070467,
"author_profile": "https://Stackoverflow.com/users/14070467",
"pm_score": 2,
"selected": false,
"text": " RequestOptions myOptions = new RequestOptions()\n .centerCrop() // or centerCrop\n .override(800, 500);//your imageview frame size\n\n Glide.with(activity)\n .applyDefaultRequestOptions(myOptions)\n .load(list.get(position).appthumbnail)\n .error(R.drawable.no_image_available)\n .into(holder.ivImage);\n\n"
},
{
"answer_id": 74541015,
"author": "Android Newbie A",
"author_id": 20125791,
"author_profile": "https://Stackoverflow.com/users/20125791",
"pm_score": 2,
"selected": true,
"text": "relative layout linear layout constraint layout <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"5dp\"\n android:theme=\"@style/Theme.Music.Font\">\n\n <com.google.android.material.imageview.ShapeableImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"50dp\"\n android:layout_height=\"50dp\"\n android:layout_alignParentStart=\"true\"\n android:layout_margin=\"5dp\"\n\n android:contentDescription=\"@string/cover\"\n android:src=\"@drawable/image_as_cover\"\n app:shapeAppearance=\"@style/roundedImageView\"\n \n app:layout_constraintTop_toTopOf=\"parent\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\" />\n\n\n <View\n android:id=\"@+id/linearLayout\"\n android:layout_width=\"0dp\"\n android:layout_height=\"0dp\"\n\n app:layout_constraintTop_toTopOf=\"parent\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintStart_toEndOf=\"@id/imageView\"\n app:layout_constraintEnd_toEndOf=\"parent\" />\n\n <TextView\n android:id=\"@+id/titleView\"\n android:layout_width=\"0dp\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"5dp\"\n\n android:maxLines=\"1\"\n android:singleLine=\"true\"\n android:fontFamily=\"@font/medium\"\n android:text=\"@string/love_is_gone_by_slander_forever_on_love\"\n android:textSize=\"15sp\"\n android:text=\"123\"\n app:layout_constraintTop_toTopOf=\"@id/linearLayout\"\n app:layout_constraintBottom_toTopOf=\"@id/albumName\"\n app:layout_constraintStart_toStartOf=\"@id/linearLayout\"\n app:layout_constraintEnd_toEndOf=\"@id/linearLayout\" />\n \n <TextView\n android:id=\"@+id/albumName\"\n android:layout_width=\"0dp\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"5dp\"\n android:fontFamily=\"@font/medium\"\n android:maxLines=\"1\"\n android:singleLine=\"true\"\n android:text=\"@string/love_is_gone_by_slander_forever_on_love\"\n android:textSize=\"15sp\"\n\n app:layout_constraintTop_toBottomOf=\"@id/titleView\"\n app:layout_constraintBottom_toTopOf=\"@id/duration\"\n app:layout_constraintStart_toStartOf=\"@id/linearLayout\"\n app:layout_constraintEnd_toEndOf=\"@id/linearLayout\" />\n\n <TextView\n android:id=\"@+id/duration\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentEnd=\"true\"\n android:layout_centerVertical=\"true\"\n android:layout_margin=\"10dp\"\n android:fontFamily=\"@font/medium\"\n android:maxLines=\"1\"\n android:text=\"@string/duration\"\n android:textSize=\"11sp\"\n\n app:layout_constraintTop_toBottomOf=\"@id/albumName\"\n app:layout_constraintBottom_toBottomOf=\"@id/linearLayout\"\n app:layout_constraintStart_toStartOf=\"@id/linearLayout\"\n app:layout_constraintEnd_toEndOf=\"@id/linearLayout\" />\n \n</androidx.constraintlayout.widget.ConstraintLayout>\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10618936/"
] |
74,528,139
|
<p><strong>Some people said that forEach inside this function is not good and that i should use maps. So, im wodering how do i use maps for this</strong></p>
<p>Some people said that forEach inside this function is not good and that i should use maps. So, im wodering how do i use maps for this:
<em>I also want this to be a reusable function so i could just call it anywhere</em></p>
<p><strong>How do i make this code much cleaner. Without Jquery</strong></p>
<p>JS:</p>
<pre><code>const about = document.getElementById('about');
const numbers = document.querySelectorAll('.number');
const svgEl = document.querySelectorAll('svg circle');
const counters = Array(numbers.length);
const intervals = Array(counters.length);
counters.fill(0);
function moveprogressbar() { numbers.forEach((number, index) => {
intervals[index] = setInterval(() => {
if(counters[index] === parseInt(number.dataset.num)){
clearInterval(counters[index]);
} else{
counters[index] += 1;
number.textContent = counters[index] + "%";
svgEl[index].style.strokeDashoffset = Math.floor(472 - 440 * parseFloat(number.dataset.num / 100));
}
}, 20);
});
}
</code></pre>
|
[
{
"answer_id": 74528175,
"author": "kuuhak-u",
"author_id": 20458458,
"author_profile": "https://Stackoverflow.com/users/20458458",
"pm_score": 0,
"selected": false,
"text": "const about = document.getElementById('about');\nconst numbers = document.querySelectorAll('.number');\nconst svgEl = document.querySelectorAll('svg circle');\nconst counters = Array(numbers.length); \nconst intervals = Array(counters.length);\ncounters.fill(0);\nlet numberArray =[]\nnumberberArray.push[numbers]\nfunction moveprogressbar() { numberArray.map((number, index) => {\nintervals[index] = setInterval(() => {\n if(counters[index] === parseInt(number.dataset.num)){\n clearInterval(counters[index]);\n } else{\n counters[index] += 1;\n number.textContent = counters[index] + \"%\";\n svgEl[index].style.strokeDashoffset = Math.floor(472 - 440 \n* parseFloat(number.dataset.num / 100));\n }\n }, 20);\n });\n}\n"
},
{
"answer_id": 74528186,
"author": "Nahom Ersom",
"author_id": 9700487,
"author_profile": "https://Stackoverflow.com/users/9700487",
"pm_score": -1,
"selected": false,
"text": "function moveprogressbar() { numbers.map((number, index) => {\n intervals[index] = setInterval(() => {\n if(counters[index] === parseInt(number.dataset.num)){\n clearInterval(counters[index]);\n } else{\n counters[index] += 1;\n number.textContent = counters[index] + \"%\";\n svgEl[index].style.strokeDashoffset = Math.floor(472 - 440 * parseFloat(number.dataset.num / 100));\n }\n }, 20);\n });\n }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17333654/"
] |
74,528,155
|
<p>Here in my code <strong>mapResponse</strong> is a variable which can be null, so I want to check and if the mapResponse is null I want the page to navigate to different page in bottom navigation, below given is the code, but it throws the error saying <strong>"The instance member 'mapResponse' can't be accessed in an initializer."</strong></p>
<pre><code>Map? mapResponse
final screens = [
const LandingPage(),
const ComingSoon(),
const ComingSoon(),
mapResponse==null?const ProfileDashBoard():const Home()
];
</code></pre>
|
[
{
"answer_id": 74528175,
"author": "kuuhak-u",
"author_id": 20458458,
"author_profile": "https://Stackoverflow.com/users/20458458",
"pm_score": 0,
"selected": false,
"text": "const about = document.getElementById('about');\nconst numbers = document.querySelectorAll('.number');\nconst svgEl = document.querySelectorAll('svg circle');\nconst counters = Array(numbers.length); \nconst intervals = Array(counters.length);\ncounters.fill(0);\nlet numberArray =[]\nnumberberArray.push[numbers]\nfunction moveprogressbar() { numberArray.map((number, index) => {\nintervals[index] = setInterval(() => {\n if(counters[index] === parseInt(number.dataset.num)){\n clearInterval(counters[index]);\n } else{\n counters[index] += 1;\n number.textContent = counters[index] + \"%\";\n svgEl[index].style.strokeDashoffset = Math.floor(472 - 440 \n* parseFloat(number.dataset.num / 100));\n }\n }, 20);\n });\n}\n"
},
{
"answer_id": 74528186,
"author": "Nahom Ersom",
"author_id": 9700487,
"author_profile": "https://Stackoverflow.com/users/9700487",
"pm_score": -1,
"selected": false,
"text": "function moveprogressbar() { numbers.map((number, index) => {\n intervals[index] = setInterval(() => {\n if(counters[index] === parseInt(number.dataset.num)){\n clearInterval(counters[index]);\n } else{\n counters[index] += 1;\n number.textContent = counters[index] + \"%\";\n svgEl[index].style.strokeDashoffset = Math.floor(472 - 440 * parseFloat(number.dataset.num / 100));\n }\n }, 20);\n });\n }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19717967/"
] |
74,528,160
|
<p>May I ask if the preset minute interval of the TimePicker in element UI is every minute, how to change it to every 10 minutes as an interval? I hope to get your help, it is quite distressing. thanks</p>
<pre><code>[element UI][1]
https://element.eleme.io/#/zh-CN/component/time-picker
[myCode][2]
https://codepen.io/hong-wei/pen/abKqpZY
[1]: https://element.eleme.io/#/zh-CN/component/time-picker
[2]: https://codepen.io/hong-wei/pen/abKqpZY
</code></pre>
|
[
{
"answer_id": 74528175,
"author": "kuuhak-u",
"author_id": 20458458,
"author_profile": "https://Stackoverflow.com/users/20458458",
"pm_score": 0,
"selected": false,
"text": "const about = document.getElementById('about');\nconst numbers = document.querySelectorAll('.number');\nconst svgEl = document.querySelectorAll('svg circle');\nconst counters = Array(numbers.length); \nconst intervals = Array(counters.length);\ncounters.fill(0);\nlet numberArray =[]\nnumberberArray.push[numbers]\nfunction moveprogressbar() { numberArray.map((number, index) => {\nintervals[index] = setInterval(() => {\n if(counters[index] === parseInt(number.dataset.num)){\n clearInterval(counters[index]);\n } else{\n counters[index] += 1;\n number.textContent = counters[index] + \"%\";\n svgEl[index].style.strokeDashoffset = Math.floor(472 - 440 \n* parseFloat(number.dataset.num / 100));\n }\n }, 20);\n });\n}\n"
},
{
"answer_id": 74528186,
"author": "Nahom Ersom",
"author_id": 9700487,
"author_profile": "https://Stackoverflow.com/users/9700487",
"pm_score": -1,
"selected": false,
"text": "function moveprogressbar() { numbers.map((number, index) => {\n intervals[index] = setInterval(() => {\n if(counters[index] === parseInt(number.dataset.num)){\n clearInterval(counters[index]);\n } else{\n counters[index] += 1;\n number.textContent = counters[index] + \"%\";\n svgEl[index].style.strokeDashoffset = Math.floor(472 - 440 * parseFloat(number.dataset.num / 100));\n }\n }, 20);\n });\n }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11241725/"
] |
74,528,166
|
<p>Hi I am trying to implement a treeview. I have a component for it which is hierarchical. The problem I am facing is that emit is not working inside tree component. Please help me out. here is my code...</p>
<p><strong>TreeItem.vue</strong></p>
<pre><code><template>
<div class="node" :style="{ marginLeft: depth * 20 + 'px' }">
<span class="menu-item" v-if="type == 'country'">
<button class="menu-button menu-button--orange" @click="addState()">
Add State
</button>
</span>
<TreeItem
v-if="expanded"
v-for="child in node.children"
:key="child.name"
:node="child"
:depth="depth + 1"
/>
</div></template>
<script>
export default {
name: "TreeItem",
props: {
node: Object,
depth: {
type: Number,
default: 0,
},
emits: ["add-state"],
},
data() {
return {
expanded: false,
};
},
methods: {
addState() {
console.log("Adding State"); //Prints this message to console
this.$emit("add-state");
},
},
};
</script>
</code></pre>
<p><strong>AddressManager.vue</strong>
<br>
Inside template:</p>
<pre><code> <div>
<tree-item :node="treedata" @add-state="addState"></tree-item>
</div>
</code></pre>
<p>Inside Methods:</p>
<pre><code>addState() {
console.log("State will be added"); //Never prints this message
},
</code></pre>
<p>We need to emit on button click. But the emit is not working.</p>
|
[
{
"answer_id": 74528175,
"author": "kuuhak-u",
"author_id": 20458458,
"author_profile": "https://Stackoverflow.com/users/20458458",
"pm_score": 0,
"selected": false,
"text": "const about = document.getElementById('about');\nconst numbers = document.querySelectorAll('.number');\nconst svgEl = document.querySelectorAll('svg circle');\nconst counters = Array(numbers.length); \nconst intervals = Array(counters.length);\ncounters.fill(0);\nlet numberArray =[]\nnumberberArray.push[numbers]\nfunction moveprogressbar() { numberArray.map((number, index) => {\nintervals[index] = setInterval(() => {\n if(counters[index] === parseInt(number.dataset.num)){\n clearInterval(counters[index]);\n } else{\n counters[index] += 1;\n number.textContent = counters[index] + \"%\";\n svgEl[index].style.strokeDashoffset = Math.floor(472 - 440 \n* parseFloat(number.dataset.num / 100));\n }\n }, 20);\n });\n}\n"
},
{
"answer_id": 74528186,
"author": "Nahom Ersom",
"author_id": 9700487,
"author_profile": "https://Stackoverflow.com/users/9700487",
"pm_score": -1,
"selected": false,
"text": "function moveprogressbar() { numbers.map((number, index) => {\n intervals[index] = setInterval(() => {\n if(counters[index] === parseInt(number.dataset.num)){\n clearInterval(counters[index]);\n } else{\n counters[index] += 1;\n number.textContent = counters[index] + \"%\";\n svgEl[index].style.strokeDashoffset = Math.floor(472 - 440 * parseFloat(number.dataset.num / 100));\n }\n }, 20);\n });\n }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11821885/"
] |
74,528,215
|
<p>We would like know if we using Databricks jobs instead ADF for orchestration, we might have to check if databricks jobs support file based trigger. kindly advise.</p>
<p>ultimately goal is, we have different ADF environment and subscription, we know that the subscription and environment does not a issues to stop our goal.</p>
<p>Kindly help.</p>
|
[
{
"answer_id": 74528175,
"author": "kuuhak-u",
"author_id": 20458458,
"author_profile": "https://Stackoverflow.com/users/20458458",
"pm_score": 0,
"selected": false,
"text": "const about = document.getElementById('about');\nconst numbers = document.querySelectorAll('.number');\nconst svgEl = document.querySelectorAll('svg circle');\nconst counters = Array(numbers.length); \nconst intervals = Array(counters.length);\ncounters.fill(0);\nlet numberArray =[]\nnumberberArray.push[numbers]\nfunction moveprogressbar() { numberArray.map((number, index) => {\nintervals[index] = setInterval(() => {\n if(counters[index] === parseInt(number.dataset.num)){\n clearInterval(counters[index]);\n } else{\n counters[index] += 1;\n number.textContent = counters[index] + \"%\";\n svgEl[index].style.strokeDashoffset = Math.floor(472 - 440 \n* parseFloat(number.dataset.num / 100));\n }\n }, 20);\n });\n}\n"
},
{
"answer_id": 74528186,
"author": "Nahom Ersom",
"author_id": 9700487,
"author_profile": "https://Stackoverflow.com/users/9700487",
"pm_score": -1,
"selected": false,
"text": "function moveprogressbar() { numbers.map((number, index) => {\n intervals[index] = setInterval(() => {\n if(counters[index] === parseInt(number.dataset.num)){\n clearInterval(counters[index]);\n } else{\n counters[index] += 1;\n number.textContent = counters[index] + \"%\";\n svgEl[index].style.strokeDashoffset = Math.floor(472 - 440 * parseFloat(number.dataset.num / 100));\n }\n }, 20);\n });\n }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2878290/"
] |
74,528,225
|
<p>So I have to make a CRUD application and when run on postman, the error being shown is 405, Method not allowed. Upon trying "spring.mvc.hiddenmethod.filter.enabled: true" in the application.properties file, the code still showed the same error when tested using postman.</p>
<p>This is the controller</p>
<pre><code>@RestController
@RequestMapping("/employees")
public class EmpController {
@Autowired
private EmpService empService;
@Autowired
private EmpRepository empRepo;
@GetMapping("")
public List<Employee> getAllEmployees()
{
return empService.getAllEmployees();
}
@PostMapping("")
public void addEmployee(@RequestBody Employee emp)
{
empService.addEmployee(emp);
}
@PutMapping("/{id}")
public void updateEmployee(@PathVariable String id,@RequestBody Employee emp)
{
empService.updateEmployee(id,emp);
}
@DeleteMapping(path="/{id}")
public void deleteEmployee(@PathVariable String id) {
System.out.println("Delete function");
empService.deleteEmployee(id);
}
}
</code></pre>
<p>This is the service</p>
<pre><code>@org.springframework.stereotype.Service
public class EmpService {
@Autowired
public EmpRepository empRepo;
public List<Employee> getAllEmployees(){
List<Employee> employees = new ArrayList<>();
empRepo.findAll().forEach(employees::add);
return employees;
}
public void addEmployee(Employee emp) {
empRepo.save(emp);
}
public void updateEmployee(String id, Employee emp) {
empRepo.save(emp);
}
public void deleteEmployee(String id) {
empRepo.deleteById(id);
}
}
</code></pre>
<p>on trying the the other put post and get methods the code was working perfectly fine. But this is the only place where I found the 405 error.</p>
|
[
{
"answer_id": 74528175,
"author": "kuuhak-u",
"author_id": 20458458,
"author_profile": "https://Stackoverflow.com/users/20458458",
"pm_score": 0,
"selected": false,
"text": "const about = document.getElementById('about');\nconst numbers = document.querySelectorAll('.number');\nconst svgEl = document.querySelectorAll('svg circle');\nconst counters = Array(numbers.length); \nconst intervals = Array(counters.length);\ncounters.fill(0);\nlet numberArray =[]\nnumberberArray.push[numbers]\nfunction moveprogressbar() { numberArray.map((number, index) => {\nintervals[index] = setInterval(() => {\n if(counters[index] === parseInt(number.dataset.num)){\n clearInterval(counters[index]);\n } else{\n counters[index] += 1;\n number.textContent = counters[index] + \"%\";\n svgEl[index].style.strokeDashoffset = Math.floor(472 - 440 \n* parseFloat(number.dataset.num / 100));\n }\n }, 20);\n });\n}\n"
},
{
"answer_id": 74528186,
"author": "Nahom Ersom",
"author_id": 9700487,
"author_profile": "https://Stackoverflow.com/users/9700487",
"pm_score": -1,
"selected": false,
"text": "function moveprogressbar() { numbers.map((number, index) => {\n intervals[index] = setInterval(() => {\n if(counters[index] === parseInt(number.dataset.num)){\n clearInterval(counters[index]);\n } else{\n counters[index] += 1;\n number.textContent = counters[index] + \"%\";\n svgEl[index].style.strokeDashoffset = Math.floor(472 - 440 * parseFloat(number.dataset.num / 100));\n }\n }, 20);\n });\n }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20569294/"
] |
74,528,239
|
<p>I wanted to know how to remove punctuation marks at the end and at the beginning of one or more words.
If there are punctuation marks between the word, we don't remove.</p>
<p>for example</p>
<p>input:</p>
<p><code>word = "!.test-one,-"</code></p>
<p>output:</p>
<p><code>word = "test-one"</code></p>
|
[
{
"answer_id": 74528309,
"author": "Epsi95",
"author_id": 6660638,
"author_profile": "https://Stackoverflow.com/users/6660638",
"pm_score": 4,
"selected": true,
"text": "strip >>> import string\n>>> word = \"!.test-one,-\"\n>>> word.strip(string.punctuation)\n'test-one'\n"
},
{
"answer_id": 74528346,
"author": "Bhargav",
"author_id": 15358800,
"author_profile": "https://Stackoverflow.com/users/15358800",
"pm_score": 1,
"selected": false,
"text": "re.sub import re\nword = \"!.test-one,-\"\nout = re.sub(r\"(^[^\\w]+)|([^\\w]+$)\", \"\", word)\nprint(out)\n test-one\n"
},
{
"answer_id": 74528348,
"author": "Oghli",
"author_id": 5169186,
"author_profile": "https://Stackoverflow.com/users/5169186",
"pm_score": 1,
"selected": false,
"text": "slice import string\nsentence = \"_blogs that are consistently updated by people that know about the trends, and market, and care about giving quality content to their readers.\" \nif sentence[0] in string.punctuation:\n sentence = sentence[1:]\nif sentence[-1] in string.punctuation:\n sentence = sentence[:-1]\nprint(sentence)\n blogs that are consistently updated by people that know about the trends, and market, and care about giving quality content to their readers\n"
},
{
"answer_id": 74528869,
"author": "Claudio",
"author_id": 7711283,
"author_profile": "https://Stackoverflow.com/users/7711283",
"pm_score": 2,
"selected": false,
"text": ".strip(chars) str strip() strip() \nchars = '''!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~'''\n\ndef cstm_strip_1(word, chars):\n # Approach using recursion: \n w = word[1 if word[0] in chars else 0: -1 if word[-1] in chars else None]\n if w == word:\n return w\n else: \n return cstm_strip_1(w, chars)\n\ndef cstm_strip_2(word, chars):\n # Approach using a while loop: \n i , j = 0, -1\n while word[i] in chars:\n i += 1\n while word[j] in chars:\n j -= 1\n return word[i:j+1]\n\nimport re, string\n\nchars = string.punctuation\nword = \"~!.test-one^&test-one--two???\"\n\nwsc = word.strip(chars)\nassert wsc == cstm_strip_1(word, chars)\nassert wsc == cstm_strip_2(word, chars)\nassert wsc == re.sub(r\"(^[^\\w]+)|([^\\w]+$)\", \"\", word)\n\nword = \"__~!.test-one^&test-one--two??__\"\n\nwsc = word.strip(chars)\nassert wsc == cstm_strip_1(word, chars)\nassert wsc == cstm_strip_2(word, chars)\n# assert wsc == re.sub(r\"(^[^\\w]+)|([^\\w]+$)\", \"\", word)\nassert re.sub(r\"(^[^\\w]+)|([^\\w]+$)\", \"\", word) == word\n\nprint(re.sub(r\"(^[^\\w]+)|([^\\w]+$)\", \"\", word), '!=', wsc )\nprint('\"',re.sub(r\"(^[^\\w]+)|([^\\w]+$)\", \"\", \"\\tword\\t\"), '\" != \"', \"\\tword\\t\".strip(chars), '\"', sep='' )\n [^\\w] string.punctuation (^[^\\w]+)|([^\\w]+$)\n The '|' character means 'or' providing two alternatives for the \n sub-string (called match) which is to find in the provided string. \n\n'(^[^\\w]+)' is the first of the two alternatives for a match\n\n '(' ')' enclose what is called a \"capturing group\" (^[^\\w]+)\n\n The first of the two '^' asserts position at start of a line\n\n '\\w' : with \\ escaped 'w' means: \"word character\" \n (i.e. letters a-z, A-Z, digits 0-9 and the underscore '_').\n\n The second of the two '^' means: logical \"not\" \n (here not a \"word character\")\n i.e. all characters except a-zA-z0-9 and '_'\n (for example '~' or 'ö')\n Notice that the meaning of '^' depends on context: \n '^' outside of [ ] it means start of line/string\n '^' inside of [ ] as first char means logical not \n and not as first means itself \n\n '[', ']' enclose specification of a set of characters \n and mean the occurrence of exactly one of them\n\n '+' means occurrence between one and unlimited times\n of what was defined in preceding token\n\n '([^\\w]+$)' is the second alternative for a match \n differing from the first by stating that the match\n should be found at the end of the string\n '$' means: \"end of the line\" (or \"end of string\")\n re.sub(r\"(^[^\\w]+)|([^\\w]+$)\", \"\", word)"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072541/"
] |
74,528,257
|
<p>I Create a New Website in Windows IIS , It has been working for several months</p>
<p>but i get this error today.</p>
<pre><code>“The connection has timed out.”
the server 192.168.1.7 at is taking too long to respond
</code></pre>
<p>i set binding</p>
<p><a href="https://i.stack.imgur.com/d6z8I.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d6z8I.jpg" alt="enter image description here" /></a></p>
<p>and get this error</p>
<p><a href="https://i.stack.imgur.com/zkIRA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zkIRA.jpg" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74528309,
"author": "Epsi95",
"author_id": 6660638,
"author_profile": "https://Stackoverflow.com/users/6660638",
"pm_score": 4,
"selected": true,
"text": "strip >>> import string\n>>> word = \"!.test-one,-\"\n>>> word.strip(string.punctuation)\n'test-one'\n"
},
{
"answer_id": 74528346,
"author": "Bhargav",
"author_id": 15358800,
"author_profile": "https://Stackoverflow.com/users/15358800",
"pm_score": 1,
"selected": false,
"text": "re.sub import re\nword = \"!.test-one,-\"\nout = re.sub(r\"(^[^\\w]+)|([^\\w]+$)\", \"\", word)\nprint(out)\n test-one\n"
},
{
"answer_id": 74528348,
"author": "Oghli",
"author_id": 5169186,
"author_profile": "https://Stackoverflow.com/users/5169186",
"pm_score": 1,
"selected": false,
"text": "slice import string\nsentence = \"_blogs that are consistently updated by people that know about the trends, and market, and care about giving quality content to their readers.\" \nif sentence[0] in string.punctuation:\n sentence = sentence[1:]\nif sentence[-1] in string.punctuation:\n sentence = sentence[:-1]\nprint(sentence)\n blogs that are consistently updated by people that know about the trends, and market, and care about giving quality content to their readers\n"
},
{
"answer_id": 74528869,
"author": "Claudio",
"author_id": 7711283,
"author_profile": "https://Stackoverflow.com/users/7711283",
"pm_score": 2,
"selected": false,
"text": ".strip(chars) str strip() strip() \nchars = '''!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~'''\n\ndef cstm_strip_1(word, chars):\n # Approach using recursion: \n w = word[1 if word[0] in chars else 0: -1 if word[-1] in chars else None]\n if w == word:\n return w\n else: \n return cstm_strip_1(w, chars)\n\ndef cstm_strip_2(word, chars):\n # Approach using a while loop: \n i , j = 0, -1\n while word[i] in chars:\n i += 1\n while word[j] in chars:\n j -= 1\n return word[i:j+1]\n\nimport re, string\n\nchars = string.punctuation\nword = \"~!.test-one^&test-one--two???\"\n\nwsc = word.strip(chars)\nassert wsc == cstm_strip_1(word, chars)\nassert wsc == cstm_strip_2(word, chars)\nassert wsc == re.sub(r\"(^[^\\w]+)|([^\\w]+$)\", \"\", word)\n\nword = \"__~!.test-one^&test-one--two??__\"\n\nwsc = word.strip(chars)\nassert wsc == cstm_strip_1(word, chars)\nassert wsc == cstm_strip_2(word, chars)\n# assert wsc == re.sub(r\"(^[^\\w]+)|([^\\w]+$)\", \"\", word)\nassert re.sub(r\"(^[^\\w]+)|([^\\w]+$)\", \"\", word) == word\n\nprint(re.sub(r\"(^[^\\w]+)|([^\\w]+$)\", \"\", word), '!=', wsc )\nprint('\"',re.sub(r\"(^[^\\w]+)|([^\\w]+$)\", \"\", \"\\tword\\t\"), '\" != \"', \"\\tword\\t\".strip(chars), '\"', sep='' )\n [^\\w] string.punctuation (^[^\\w]+)|([^\\w]+$)\n The '|' character means 'or' providing two alternatives for the \n sub-string (called match) which is to find in the provided string. \n\n'(^[^\\w]+)' is the first of the two alternatives for a match\n\n '(' ')' enclose what is called a \"capturing group\" (^[^\\w]+)\n\n The first of the two '^' asserts position at start of a line\n\n '\\w' : with \\ escaped 'w' means: \"word character\" \n (i.e. letters a-z, A-Z, digits 0-9 and the underscore '_').\n\n The second of the two '^' means: logical \"not\" \n (here not a \"word character\")\n i.e. all characters except a-zA-z0-9 and '_'\n (for example '~' or 'ö')\n Notice that the meaning of '^' depends on context: \n '^' outside of [ ] it means start of line/string\n '^' inside of [ ] as first char means logical not \n and not as first means itself \n\n '[', ']' enclose specification of a set of characters \n and mean the occurrence of exactly one of them\n\n '+' means occurrence between one and unlimited times\n of what was defined in preceding token\n\n '([^\\w]+$)' is the second alternative for a match \n differing from the first by stating that the match\n should be found at the end of the string\n '$' means: \"end of the line\" (or \"end of string\")\n re.sub(r\"(^[^\\w]+)|([^\\w]+$)\", \"\", word)"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/970404/"
] |
74,528,274
|
<p>I want to use three functions at the same time asynchronously. I'm not sure that this is how I want it.</p>
<p>The only purpose of using inputPaymentData is that I want to use three different functions simultaneously, so I can get the result as fast as I can. I thought it would take more time if I don't use async and just use it synchronously way. Also, do I need to use await? I don't think I need to wait to get any data. Thanks.</p>
<pre><code>void inputPaymentData(
{required String user,
required bool type,
required String merchantUid,
required String lessonUid,
required num amount,
required bool agree,
required String lesson,
required bool lessonCard,
required String? review,
required String coach}) async {
inputRecordData(
user: user,
type: type,
merchantUid: merchantUid,
lessonUid: lessonUid,
amount: amount);
inputReservationData(
user: user,
agree: agree,
lesson: lesson,
lessonCard: lessonCard,
review: review,
coach: coach);
increaseLessonNum(user);
}
void inputRecordData(
{required String user,
required bool type,
required String merchantUid,
required String lessonUid,
required num amount}) =>
paymentUseCase.inputRecordData(
user: user,
type: type,
merchantUid: merchantUid,
lessonUid: lessonUid,
amount: amount);
void inputReservationData(
{required String user,
required bool agree,
required String lesson,
required bool lessonCard,
required String? review,
required String coach}) =>
paymentUseCase.inputReservationData(
user: user,
agree: agree,
lesson: lesson,
lessonCard: lessonCard,
review: review,
coach: coach);
void increaseLessonNum(String user) =>
paymentUseCase.increaseLessonNum(user);
</code></pre>
|
[
{
"answer_id": 74528316,
"author": "Aashish Shrestha",
"author_id": 19329843,
"author_profile": "https://Stackoverflow.com/users/19329843",
"pm_score": 1,
"selected": false,
"text": "Future<return_type> functionName() async {\n ...\n await callAPI(); //task that would take some time for execution like API calls \n ...\n return <something of return_type>;\n};\n"
},
{
"answer_id": 74529129,
"author": "Sabahat Hussain Qureshi",
"author_id": 17901132,
"author_profile": "https://Stackoverflow.com/users/17901132",
"pm_score": 0,
"selected": false,
"text": "getApiData() async {\n\n response = await HttpServices.getCustomer();\n \n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15193435/"
] |
74,528,283
|
<p>I'd like to add autoplay to my slider, but I don't know how to do it (slider works fine). I understand that it can be done using an interval but I don't handle it very well... If you can give me a hand I would be very grateful</p>
<pre><code>const ImageSlider = ({ slides }) => {
const [current, setCurrent] = useState(0);
const length = slides.length;
const nextSlide = () => {
setCurrent(current === length - 1 ? 0 : current + 1);
};
const prevSlide = () => {
setCurrent(current === 0 ? length - 1 : current - 1);
};
const moveDot = (index) => {
setCurrent(index);
};
if (!Array.isArray(slides) || slides.length <= 0) {
return null;
}
return (
<div className="container-slider">
Code...
</div>
);
};
export default ImageSlider;
</code></pre>
|
[
{
"answer_id": 74528469,
"author": "WestMountain",
"author_id": 9331978,
"author_profile": "https://Stackoverflow.com/users/9331978",
"pm_score": -1,
"selected": false,
"text": "useEffect(() => {\n const i = setInterval(() => {\n nextSlide();\n }, 5000);\n return () => {\n clearInterval(i);\n };\n}, [current]);\n"
},
{
"answer_id": 74528494,
"author": "Thaiyalnayaki",
"author_id": 15431167,
"author_profile": "https://Stackoverflow.com/users/15431167",
"pm_score": 0,
"selected": false,
"text": "**Use \"react-bootstrap/Carousel\"** \n\nimport Carousel from \"react-bootstrap/Carousel\";\nimport \"bootstrap/dist/css/bootstrap.css\";\nfunction CarouselIntervalsExample() {\n return (\n <div style={{ display: \"block\", width: 700, padding: 30 }}>\n <Carousel>\n <Carousel.Item interval={1500}>\n <img className=\"d-block w-100\" src=\"image1.png\" />\n <Carousel.Caption>\n <h3>first slide</h3>\n <p>Image One</p>\n </Carousel.Caption>\n </Carousel.Item>\n <Carousel.Item interval={500}>\n <img className=\"d-block w-100\" src=\"image2.png\" />\n <Carousel.Caption>\n <h3>Label for second slide</h3>\n <p>Image Two</p>\n </Carousel.Caption>\n </Carousel.Item>\n </Carousel>\n </div>\n );\n}\n\nexport default CarouselIntervalsExample;\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19545573/"
] |
74,528,301
|
<p>Base on <a href="https://stackoverflow.com/questions/61627857/c-style-arrays-vs-stdvector-using-stdvectorat-stdvectoroperator-an">C-style Arrays vs std::vector using std::vector::at, std::vector::operator[], and iterators</a>
I run the following benchmarks.</p>
<ul>
<li><p>no optimization
<a href="https://quick-bench.com/q/LjybujMGImpATTjbWePzcb6xyck" rel="nofollow noreferrer">https://quick-bench.com/q/LjybujMGImpATTjbWePzcb6xyck</a></p>
</li>
<li><p>O3
<a href="https://quick-bench.com/q/u5hnSy90ZRgJ-CQ75b1c1a_3BuY" rel="nofollow noreferrer">https://quick-bench.com/q/u5hnSy90ZRgJ-CQ75b1c1a_3BuY</a></p>
</li>
</ul>
<p>From here, vectors definitely perform better in O3.</p>
<p><strong>However, C-style Array is slower with -O3 than -O0</strong></p>
<ul>
<li><p>C-style (no opt) : about 2500</p>
</li>
<li><p>C-style (O3) : about 3000</p>
</li>
</ul>
<p>I don't know what factors lead to this result. Maybe it's because the compiler is c++14?</p>
<p>(I'm not asking about <code>std::vector</code> relative to plain arrays, I'm just asking about plain arrays with/without optimization.)</p>
|
[
{
"answer_id": 74528997,
"author": "Peter Cordes",
"author_id": 224132,
"author_profile": "https://Stackoverflow.com/users/224132",
"pm_score": 3,
"selected": true,
"text": "-O0 for (auto _ : state) {} %rbx # outer loop of your -O3 version\n sub $0x1,%rbx\n jne 407f57 <BM_map_c_array(benchmark::State&)+0x37>\n 0x10(%rdi) benchmark::State& state # part of the outer loop of your -O0 version\n12.50% mov -0x8060(%rbp),%rax\n25.00% sub $0x1,%rax\n12.50% mov %rax,-0x8060(%rbp)\n call map_c_array nop looptop: dec %ebx jnz looptop dec"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20182123/"
] |
74,528,302
|
<p>How to turn such a string into an emoji? 1F600 => or 1F600 => \U0001F600 or 1F600 => 0x1F600</p>
<p>I spent a few days but I still didn't understand how to translate a string like 1F600 into emoji</p>
|
[
{
"answer_id": 74528471,
"author": "Klaus Gütter",
"author_id": 2142950,
"author_profile": "https://Stackoverflow.com/users/2142950",
"pm_score": 1,
"selected": false,
"text": "var utf32Char = uint.Parse(\"1F600\", NumberStyles.AllowHexSpecifier); var utf32Bytes = BitConverter.GetBytes(utf32Char);\nif (!BitConverter.IsLittleEndian)\n Array.Reverse(utf32Bytes);\n var str = Encoding.UTF32.GetString(utf32Bytes);\nConsole.WriteLine(str);\n"
},
{
"answer_id": 74528549,
"author": "phuclv",
"author_id": 995714,
"author_profile": "https://Stackoverflow.com/users/995714",
"pm_score": 3,
"selected": true,
"text": "var emoji = Char.ConvertFromUtf32(Convert.ToInt32(\"1F600\", 16));\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12461370/"
] |
74,528,303
|
<ol>
<li>Firstly this is my api data data.</li>
</ol>
<pre><code>{
"code": 200,
"message": "Request fulfilled, document follows",
"data": [
{
"sn": "ACC-LEW-1JY1-J4X2",
"created_on": "2022-11-12T07:42:26.531786Z",
"owner": "devtest01",
"toy_user_type": 1,
"shared_status": "Owned",
"product_data": {
"id": 179,
"product_skuid": "any-name",
"variant_id": "any-id",
"product_name": "any-product-name",
"product_type_val": "car-toy",
"product_category_slug": "stunt-car",
"desc": null,
},
"attribute_data": {
"toy_distance_travelled": "0",
"toy_time_played": "0",
"toy_last_updated": "0",
"toy_donuts": "0",
"toy_rash_drives": "0",
"toy_smooth_drives": "0",
"toy_top_boost": "0",
"toy_tank_size": "0",
"toy_draft_collector": "0",
"toy_acceleration": "0",
"toy_braking": "0",
"toy_name": "",
"toy_last_played": "",
"toy_experience": "0",
"toy_drifts": "0",
"toy_top_speed": "0",
"drifts": "0",
"toy_last_maintainence_distance": "0"
},
"game_attribute_data": [
{
"attr_key": "td_distance_travelled",
"value": 21,
"sync_version": 3
},
{
"attr_key": "td_time_played",
"value": 8,
"sync_version": 3
},
{
"attr_key": "td_drifts_completed",
"value": 3,
"sync_version": 3
}
]
},
],
"error": null,
"server_time": "2022-11-21T12:57:44.319Z"
}
</code></pre>
<ol start="2">
<li><p>I want to access the data of game_attribute_data. I tam trying to use map function but I am unable to get the data.</p>
</li>
<li><p>This is my api call using fetch method in React.js</p>
</li>
</ol>
<pre><code>const allToysData = async () => {
await fetch(
`URL`,
{
method: "GET",
headers: {
Authorization: "token"
},
redirect: "follow"
}
)
.then(response => response.json())
.then(data => {
const toysdata = data.data;
const updatedToysData = toysdata.map(
(x: {
created_on: any;
owner: any;
shared_status: any;
sn: any;
attribute_data: any;
product_data: any;
game_attribute_data: any;
}) => ({
created_on: x.created_on,
owner: x.owner,
shared_status: x.shared_status,
sn: x.sn,
toy_drifts: x.attribute_data.toy_drifts,
toy_time_played: x.attribute_data.toy_time_played,
toy_last_played: x.attribute_data.toy_last_played,
toy_last_maintainence_distance: x.attribute_data.toy_last_maintainence_distance,
product_skuid: x.product_data.product_skuid,
product_image_1x: x.product_data.data.product_image_1x,
game_attribute_data: x.game_attribute_data.map(x => x),
})
);
const result = updatedToysData.map(x => x.game_attribute_data);
setToyAttribute(updatedToysData);
setArrToys(updatedToysData);
})
// eslint-disable-next-line no-console
.catch(error => console.log(`Error: ${error}`));
};
</code></pre>
<ol start="3">
<li>I want to show the data of game_attribute_data in a table. How should I access the data in React.js.</li>
</ol>
<p>I already tried to get the data using map function but the data is not rendering in table so Please show me where my mistake might be.</p>
|
[
{
"answer_id": 74528471,
"author": "Klaus Gütter",
"author_id": 2142950,
"author_profile": "https://Stackoverflow.com/users/2142950",
"pm_score": 1,
"selected": false,
"text": "var utf32Char = uint.Parse(\"1F600\", NumberStyles.AllowHexSpecifier); var utf32Bytes = BitConverter.GetBytes(utf32Char);\nif (!BitConverter.IsLittleEndian)\n Array.Reverse(utf32Bytes);\n var str = Encoding.UTF32.GetString(utf32Bytes);\nConsole.WriteLine(str);\n"
},
{
"answer_id": 74528549,
"author": "phuclv",
"author_id": 995714,
"author_profile": "https://Stackoverflow.com/users/995714",
"pm_score": 3,
"selected": true,
"text": "var emoji = Char.ConvertFromUtf32(Convert.ToInt32(\"1F600\", 16));\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20569350/"
] |
74,528,314
|
<p>I am doing a post call to the Api,</p>
<pre><code>axios
.post(authUrl+'/user/login', body)
.then((response) => {
console.log("axios header response",response.headers);
return(response);
})
</code></pre>
<p>I get this message in console</p>
<pre><code>axios header response { "content-length": "1129", "content-type": "application/json; charset=utf-8" }
</code></pre>
<p>When I go on the Network tab on Inspect Menu, I get all the headers of the response.</p>
<pre><code>Access-Control-Allow-Origin
*
Connection
keep-alive
Content-Length
1129
Content-Type
application/json; charset=utf-8
Date
Tue, 22 Nov 2022 06:18:49 GMT
ETag
W/"469-zAeRmNfvDmioaHmzPG+XynZaSYo"
Keep-Alive
timeout=5
x-access-token
eyJhbG......
X-Powered-By
Express
x-refresh-token
eyJhb......
</code></pre>
<p>How can I get all of this data on React?</p>
|
[
{
"answer_id": 74528471,
"author": "Klaus Gütter",
"author_id": 2142950,
"author_profile": "https://Stackoverflow.com/users/2142950",
"pm_score": 1,
"selected": false,
"text": "var utf32Char = uint.Parse(\"1F600\", NumberStyles.AllowHexSpecifier); var utf32Bytes = BitConverter.GetBytes(utf32Char);\nif (!BitConverter.IsLittleEndian)\n Array.Reverse(utf32Bytes);\n var str = Encoding.UTF32.GetString(utf32Bytes);\nConsole.WriteLine(str);\n"
},
{
"answer_id": 74528549,
"author": "phuclv",
"author_id": 995714,
"author_profile": "https://Stackoverflow.com/users/995714",
"pm_score": 3,
"selected": true,
"text": "var emoji = Char.ConvertFromUtf32(Convert.ToInt32(\"1F600\", 16));\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19545651/"
] |
74,528,319
|
<p>I'm using <code>v-list-item-group</code> and I want to show data in another component when the <code>list item</code> is selected. clear data when I <code>unSelect</code> item, and change data when I click on another <code>list item</code></p>
<p>how can I possibly do it in vue?
the list item which I select:
Here I want to clear curr step data if the <code>list.eid</code> changed or when index changed</p>
<pre><code> <v-list-item-group v-model="wfs">
<v-list-item v-for="(list,index) in workflowStepsList" :key="index"
@click="getWorkflowStep(list.eid)">
<v-list-item-action-text class="pe-4"> {{ index+1 }}</v-list-item-action-text>
<v-list-item-content v-if="!list.title">
{{ list.stepTitle }}
</v-list-item-content>
<v-list-item-content v-if="!list.stepTitle">
{{ list.title }}
</v-list-item-content>
<v-list-item-icon>
<v-icon small color="red">mdi-delete</v-icon>
</v-list-item-icon>
</v-list-item>
<v-list-item v-if="!workflowStepsList.length">
مرحله ای وجود ندارد
</v-list-item>
</v-list-item-group>
</code></pre>
<p>and the list I render data based on what I selected:</p>
<pre><code> <v-card>
<v-card-title class="bg-success text-white d-flex justify-space-between">
مرحله فعلی
<add-curr :getSteps="getSteps"/>
</v-card-title>
<v-card-text>
<v-list>
<v-list-item-group class="v-list-item-group" v-model="stepId">
<v-list-item
v-if="!currStep.length"
class="text-muted"
>
یک مرحله انتخاب کنید
</v-list-item>
<v-list-item
v-for="(element) in currStep"
:key="element.eid"
v-show="element.eid !== null"
>
{{ element.title }}
</v-list-item>
</v-list-item-group>
</v-list>
</v-card-text>
</v-card>
</code></pre>
<p>the function:</p>
<pre><code>async getWorkflowStep(weid) {
await this.$store.dispatch("axiosGet",
{url: `folder/api/workflow-steps/${weid}`, params: {workflowId: this.id}}).then(response => {
if (response.status === 'error') return
this.workflowStepsObj = response.data.data
const x = response.data.data
const curr = {
title: x.stepTitle,
eid: x.stepEid
}
this.currStep.push(curr)
})
},
</code></pre>
|
[
{
"answer_id": 74528471,
"author": "Klaus Gütter",
"author_id": 2142950,
"author_profile": "https://Stackoverflow.com/users/2142950",
"pm_score": 1,
"selected": false,
"text": "var utf32Char = uint.Parse(\"1F600\", NumberStyles.AllowHexSpecifier); var utf32Bytes = BitConverter.GetBytes(utf32Char);\nif (!BitConverter.IsLittleEndian)\n Array.Reverse(utf32Bytes);\n var str = Encoding.UTF32.GetString(utf32Bytes);\nConsole.WriteLine(str);\n"
},
{
"answer_id": 74528549,
"author": "phuclv",
"author_id": 995714,
"author_profile": "https://Stackoverflow.com/users/995714",
"pm_score": 3,
"selected": true,
"text": "var emoji = Char.ConvertFromUtf32(Convert.ToInt32(\"1F600\", 16));\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20108474/"
] |
74,528,335
|
<p>I'm making a screen with creating a pin code to enter the application. But unfortunately my code doesn't work.</p>
<p>I'm trying to implement this through local storage. Here's the logic - as soon as the user goes to the create screen, I check if there is a pin code in the local storage.
Here is the function -</p>
<pre><code>Future<int?> sharedPrefsGet() async {
final prefs = await SharedPreferences.getInstance();
print(await prefs.getInt('pinCode'));
return await prefs.getInt('pinCode');
}
late final Future<int?> future = sharedPrefsGet();
void initState() {
super.initState();
sharedPrefsGet();
}
</code></pre>
<p>Further, when entering the pin code, I check if there is a pin code and what will happen -</p>
<pre><code>onCompleted: (value) async {
pinCode = int parse(value);
sharedPrefsSet(pinCode);
if(sharedPrefsGet() == value) {
context.go('/home');
} else {
context.go('/createPinCode');
}
context.go('/createPinCode');
},
</code></pre>
<p>and of course, there I try to save the pin code to the local storage. Here is the function -</p>
<pre><code>var pinCode;
sharedPrefsSet(int pin) async {
final prefs = await SharedPreferences.getInstance();
return await prefs.setInt('pinCode', pin);
}
</code></pre>
<p>but my code doesn't work, I don't get any errors.</p>
<p>The user enters the password, this screen opens again, he enters the code again, but navigation to the home page no longer occurs. Why?</p>
<p>full code -</p>
<pre><code>class CreatePinCode extends StatefulWidget {
@override
_CreatePinCodeState createState() => _CreatePinCodeState();
}
class _CreatePinCodeState extends State<CreatePinCode> {
final TextEditingController _controller = TextEditingController();
var pinCode;
sharedPrefsSet(int pin) async {
final prefs = await SharedPreferences.getInstance();
return await prefs.setInt('pinCode', pin);
}
Future<int?> sharedPrefsGet() async {
final prefs = await SharedPreferences.getInstance();
print(await prefs.getInt('pinCode'));
return await prefs.getInt('pinCode');
}
late final Future<int?> future = sharedPrefsGet();
@override
void initState() {
super.initState();
sharedPrefsGet();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: ConfigColor.background,
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FutureBuilder(
future: future,
builder: (context, snapshot) =>
snapshot.hasData? Text('123123123123123') : Text('ababababab')
),
Padding(
padding: const EdgeInsets.all(100),
child: SizedBox(
height: 70,
child: Center(
child: PinCodeTextField(
controller: _controller,
mainAxisAlignment: MainAxisAlignment.spaceAround,
obscuringWidget: Container(
width: 15,
height: 15,
decoration: BoxDecoration(
color: ConfigColor.green,
shape: BoxShape.circle
),
),
appContext: context,
length: 4,
onChanged: (value) {
print(value);
},
pinTheme: PinTheme(
shape: PinCodeFieldShape.box,
borderRadius: BorderRadius.circular(50),
fieldHeight: 15,
fieldWidth: 15,
activeColor: ConfigColor.green,
inactiveColor: Colors.white.withOpacity(0.3),
disabledColor: Colors.white.withOpacity(0.3),
),
onCompleted: (values) async {
final prefs = await SharedPreferences.getInstance();
final pinCod = await prefs.setInt('pinCod', int.parse(values));
if(!pinCod) {// either true or false
if(pinCod == int.parse(values)) {
log('Все хорошо');
} else {
log('Код не совпадает!');
}
}
pinCode = int.parse(values);
final int? value = await sharedPrefsGet() ;
if(value== null) {
context.go('/createPinCode');
} else if (value == pinCode){
await sharedPrefsSet(pinCode);
context.go('/home');
} else {
}
},
)
),
),
),
// implement the custom NumPad
NumPad(
buttonSize: 65,
buttonColor: ConfigColor.background,
iconColor: Colors.deepOrange,
controller: _controller,
delete: () {
_controller.text = _controller.text
.substring(0, _controller.text.length - 1);
},
// do something with the input numbers
onSubmit: () {
debugPrint('Your code: ${_controller.text}');
showDialog(
context: context,
builder: (_) => AlertDialog(
content: Text(
"You code is ${_controller.text}",
style: const TextStyle(fontSize: 30),
),
));
},
),
],
)
);
}
}
</code></pre>
|
[
{
"answer_id": 74528471,
"author": "Klaus Gütter",
"author_id": 2142950,
"author_profile": "https://Stackoverflow.com/users/2142950",
"pm_score": 1,
"selected": false,
"text": "var utf32Char = uint.Parse(\"1F600\", NumberStyles.AllowHexSpecifier); var utf32Bytes = BitConverter.GetBytes(utf32Char);\nif (!BitConverter.IsLittleEndian)\n Array.Reverse(utf32Bytes);\n var str = Encoding.UTF32.GetString(utf32Bytes);\nConsole.WriteLine(str);\n"
},
{
"answer_id": 74528549,
"author": "phuclv",
"author_id": 995714,
"author_profile": "https://Stackoverflow.com/users/995714",
"pm_score": 3,
"selected": true,
"text": "var emoji = Char.ConvertFromUtf32(Convert.ToInt32(\"1F600\", 16));\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18540229/"
] |
74,528,345
|
<p>We have one table A in database. We are loading that table into flink using Flink SQL JdbcCatalog.</p>
<p>Here is how we are loading the data</p>
<p><code>val catalog = new JdbcCatalog("my_catalog", "database_name", username, password, url)</code></p>
<p><code>streamTableEnvironment.registerCatalog("my_catalog", catalog)</code>
<code>streamTableEnvironment.useCatalog("my_catalog")</code></p>
<p><code>val query = "select timestamp, count from A"</code></p>
<p><code>val sourceTable = streamTableEnvironment.sqlQuery(query) streamTableEnvironment.createTemporaryView("innerTable", sourceTable)</code></p>
<p><code>val aggregationQuery = select window_end, sum(count) from TABLE(TUMBLE(TABLE innerTable, DESCRIPTOR(timestamp), INTERVAL '10' minutes)) group by window_end</code></p>
<p>It throws following error
<code>Exception in thread "main" org.apache.flink.table.api.ValidationException: SQL validation failed. The window function TUMBLE(TABLE table_name, DESCRIPTOR(timecol), datetime interval[, datetime interval]) requires the timecol is a time attribute type, but is TIMESTAMP(6).</code></p>
<p>In short we want to apply windowing aggregation on an already existing column. How can we do that
Note - This is a batch processing</p>
|
[
{
"answer_id": 74528471,
"author": "Klaus Gütter",
"author_id": 2142950,
"author_profile": "https://Stackoverflow.com/users/2142950",
"pm_score": 1,
"selected": false,
"text": "var utf32Char = uint.Parse(\"1F600\", NumberStyles.AllowHexSpecifier); var utf32Bytes = BitConverter.GetBytes(utf32Char);\nif (!BitConverter.IsLittleEndian)\n Array.Reverse(utf32Bytes);\n var str = Encoding.UTF32.GetString(utf32Bytes);\nConsole.WriteLine(str);\n"
},
{
"answer_id": 74528549,
"author": "phuclv",
"author_id": 995714,
"author_profile": "https://Stackoverflow.com/users/995714",
"pm_score": 3,
"selected": true,
"text": "var emoji = Char.ConvertFromUtf32(Convert.ToInt32(\"1F600\", 16));\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14817486/"
] |
74,528,347
|
<p>I've been playing around my code editor and accidentally made this. This compiles fine, and works as intended. For additional context, I'm using GCC on Debian 11. As for how I knew the prototypes, VS Code's IntelliSense told me.</p>
<p>Why does it work, and how? Neither <code><stdio.h></code> nor <code><math.h></code> is included.</p>
<pre><code>double pow(double _x, double _y);
int printf(const char *__restrict__ __format, ...);
int main(void)
{
printf("%f\n", pow(2, -1));
}
</code></pre>
<p>Output: <code>0.500000</code></p>
|
[
{
"answer_id": 74528373,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 2,
"selected": false,
"text": "-nolibc"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20404210/"
] |
74,528,366
|
<p>Unable to find the replacement for DBMS_JOB.Broken command to make the job broken. Please assist me for the same.
Command used in my code is</p>
<pre><code>dbms_job.broken(oracle_job_num, true);
</code></pre>
<p>Have done the changes for the below commands which was used in our code.</p>
<pre><code>DBMS_JOB.SUBMIT -> DBMS_SCHEDULER.CREATE_JOB
DBMS_JOB.REMOVE -> DBMS_SCHEDULER.DROP_JOB
</code></pre>
|
[
{
"answer_id": 74528373,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 2,
"selected": false,
"text": "-nolibc"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5444290/"
] |
74,528,412
|
<pre><code>import os ,fnmatch
import os.path
import os
file_dir= '/home/deeghayu/Desktop/mec_sim/up_folder'
file_type = ['*.py']
for root, dirs,files in os.walk( file_dir ):
for extension in ( tuple(file_type) ):
for filename in fnmatch.filter(files, extension):
filepath = os.path.join(root, filename)
if os.path.isfile( filepath ):
print(filename , 'executing...');
exec(open('/home/deeghayu/Desktop/mec_sim/up_folder/{}'.format(filename)).read())
else:
print('Execution failure!!!')
</code></pre>
<p>Hello everyone I am working on this code which execute a python file using a python code. I need to save my output of the code as a text file. Here I have shown my code. Can any one give me a solution how do I save my output into a text file?</p>
|
[
{
"answer_id": 74528437,
"author": "Ajay K",
"author_id": 10782096,
"author_profile": "https://Stackoverflow.com/users/10782096",
"pm_score": 0,
"selected": false,
"text": "f= open(\"file.txt\",\"w+\")\n for i in range(10):\n f.write(\"This is line %d\\r\\n\" % (i+1))\n f.close()\n"
},
{
"answer_id": 74528560,
"author": "Mike L",
"author_id": 10008247,
"author_profile": "https://Stackoverflow.com/users/10008247",
"pm_score": 2,
"selected": true,
"text": "f = open() \nwith open(\"file.txt\",\"w+\") as f:\n for i in range(10):\n f.write(\"This is line %d\\r\\n\" % (i+1))\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10348267/"
] |
74,528,441
|
<p>Using the Python package <a href="https://spacy.io/" rel="nofollow noreferrer">spaCy</a>, how can one detect whether a sentence uses a passive or active voice? For example, the following sentences should be detected as using a passive and active voice respectively:</p>
<pre class="lang-none prettyprint-override"><code>passive_sentence = "John was accused of committing crimes by David"
# passive voice "John was accused"
active_sentence = "David accused John of committing crimes"
# active voice "David accused John"
</code></pre>
|
[
{
"answer_id": 74528437,
"author": "Ajay K",
"author_id": 10782096,
"author_profile": "https://Stackoverflow.com/users/10782096",
"pm_score": 0,
"selected": false,
"text": "f= open(\"file.txt\",\"w+\")\n for i in range(10):\n f.write(\"This is line %d\\r\\n\" % (i+1))\n f.close()\n"
},
{
"answer_id": 74528560,
"author": "Mike L",
"author_id": 10008247,
"author_profile": "https://Stackoverflow.com/users/10008247",
"pm_score": 2,
"selected": true,
"text": "f = open() \nwith open(\"file.txt\",\"w+\") as f:\n for i in range(10):\n f.write(\"This is line %d\\r\\n\" % (i+1))\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14953200/"
] |
74,528,442
|
<p>I want to generate select and options for my project dynamically with array data
here I attached what I want and what is the data I have this is data</p>
<p><img src="https://i.stack.imgur.com/l4PE1.png" alt="" />
This is the options I want</p>
<p><img src="https://i.stack.imgur.com/n8exi.png" alt="" />]</p>
<p>please help to get solution</p>
|
[
{
"answer_id": 74528437,
"author": "Ajay K",
"author_id": 10782096,
"author_profile": "https://Stackoverflow.com/users/10782096",
"pm_score": 0,
"selected": false,
"text": "f= open(\"file.txt\",\"w+\")\n for i in range(10):\n f.write(\"This is line %d\\r\\n\" % (i+1))\n f.close()\n"
},
{
"answer_id": 74528560,
"author": "Mike L",
"author_id": 10008247,
"author_profile": "https://Stackoverflow.com/users/10008247",
"pm_score": 2,
"selected": true,
"text": "f = open() \nwith open(\"file.txt\",\"w+\") as f:\n for i in range(10):\n f.write(\"This is line %d\\r\\n\" % (i+1))\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20569511/"
] |
74,528,457
|
<pre><code><?php
//These came from my database
$_SESSION['dateOfMembershipEnds'] = $row['dateOfMembershipEnds'];
if(empty($email)){
echo '<script>alert("Email is required!")</script>';
}else if(empty($password)){
echo '<script>alert("Password is required!")</script>';
}else if(strtotime($_SESSION['dateOfMembershipEnds']) >= date("Y-m-d")){
echo '<script>alert("Your Subscription Mr/Ms: '.$_SESSION['username'].' is already expired") </script>';
?>
</code></pre>
<p>I am expecting in my code that if the membership date is already expired the statement in my else if statement should be run.</p>
|
[
{
"answer_id": 74528437,
"author": "Ajay K",
"author_id": 10782096,
"author_profile": "https://Stackoverflow.com/users/10782096",
"pm_score": 0,
"selected": false,
"text": "f= open(\"file.txt\",\"w+\")\n for i in range(10):\n f.write(\"This is line %d\\r\\n\" % (i+1))\n f.close()\n"
},
{
"answer_id": 74528560,
"author": "Mike L",
"author_id": 10008247,
"author_profile": "https://Stackoverflow.com/users/10008247",
"pm_score": 2,
"selected": true,
"text": "f = open() \nwith open(\"file.txt\",\"w+\") as f:\n for i in range(10):\n f.write(\"This is line %d\\r\\n\" % (i+1))\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20413612/"
] |
74,528,459
|
<p>I'm trying to make autofill record from bank.account.account to account.journal but it seems it didn't work. I wonder where is the mistake in this code</p>
<pre><code>class BankAccounAccount(models.Model):
_name = 'bank.account.account'
_description = "Bank Account Account"
_rec_name = 'acc_number'
acc_number = fields.Char(string="Account Number", required=True)
bank_id = fields.Many2one('res.bank', string="Bank")
bank_bic = fields.Char(string="Bank Identifier Code")
company_id = fields.Many2one('res.company', string="Company", default=lambda self: self.env.user.company_id.id)
branch_id = fields.Many2one('res.branch', string="Branch")
@api.model
def create(self, values):
res = super(BankAccounAccount, self).create(values)
for rec in self:
values = {
'acc_number': rec.acc_number.id,
'bank_id': rec.bank_id.id,
'bank_bic': rec.bank_bic.id,
'company_id': rec.company_id.id,
'branch_id': rec.branch_id.id,
}
self.env['account.journal'].create(values)
return res
class AccountJournal(models.Model):
_inherit = "account.journal"
name = fields.Char(string='Journal Name', required=True,
tracking=True)
code = fields.Char(string='Short Code', size=5, required=True, help="Shorter name used for display. The journal entries of this journal will also be named using this prefix by default.",
tracking=True)
active = fields.Boolean(default=True, help="Set active to false to hide the Journal without removing it.",
tracking=True)
type = fields.Selection([
('sale', 'Sales'),
('purchase', 'Purchase'),
('cash', 'Cash'),
('bank', 'Bank'),
('general', 'Miscellaneous'),
], required=True,
help="Select 'Sale' for customer invoices journals.\n"\
"Select 'Purchase' for vendor bills journals.\n"\
"Select 'Cash' or 'Bank' for journals that are used in customer or vendor payments.\n"\
"Select 'General' for miscellaneous operations journals.",
tracking=True)
type_control_ids = fields.Many2many('account.account.type', 'journal_account_type_control_rel', 'journal_id', 'type_id', string='Allowed account types',
tracking=True)
account_control_ids = fields.Many2many('account.account', 'journal_account_control_rel', 'journal_id', 'account_id', string='Allowed accounts',
check_company=True,
domain="[('deprecated', '=', False), ('company_id', '=', company_id), ('is_off_balance', '=', False)]",
tracking=True)
default_account_type = fields.Many2one('account.account.type', compute="_compute_default_account_type",
tracking=True)
default_account_id = fields.Many2one(
comodel_name='account.account', check_company=True, copy=False, ondelete='restrict',
string='Default Account',
domain="[('deprecated', '=', False), ('company_id', '=', company_id),"
"'|', ('user_type_id', '=', default_account_type), ('user_type_id', 'in', type_control_ids),"
"('user_type_id.type', 'not in', ('receivable', 'payable'))]",
tracking=True)
payment_debit_account_id = fields.Many2one(
comodel_name='account.account', check_company=True, copy=False, ondelete='restrict',
help="Incoming payments entries triggered by invoices/refunds will be posted on the Outstanding Receipts Account "
"and displayed as blue lines in the bank reconciliation widget. During the reconciliation process, concerned "
"transactions will be reconciled with entries on the Outstanding Receipts Account instead of the "
"receivable account.", string='Outstanding Receipts Account',
domain=lambda self: "[('deprecated', '=', False), ('company_id', '=', company_id), \
('user_type_id.type', 'not in', ('receivable', 'payable')), \
'|', ('user_type_id', '=', %s), ('id', '=', default_account_id)]" % self.env.ref('account.data_account_type_current_assets').id,
tracking=True)
payment_credit_account_id = fields.Many2one(
comodel_name='account.account', check_company=True, copy=False, ondelete='restrict',
help="Outgoing payments entries triggered by bills/credit notes will be posted on the Outstanding Payments Account "
"and displayed as blue lines in the bank reconciliation widget. During the reconciliation process, concerned "
"transactions will be reconciled with entries on the Outstanding Payments Account instead of the "
"payable account.", string='Outstanding Payments Account',
domain=lambda self: "[('deprecated', '=', False), ('company_id', '=', company_id), \
('user_type_id.type', 'not in', ('receivable', 'payable')), \
'|', ('user_type_id', '=', %s), ('id', '=', default_account_id)]" % self.env.ref('account.data_account_type_current_assets').id,
tracking=True)
suspense_account_id = fields.Many2one(
comodel_name='account.account', check_company=True, ondelete='restrict', readonly=False, store=True,
compute='_compute_suspense_account_id',
help="Bank statements transactions will be posted on the suspense account until the final reconciliation "
"allowing finding the right account.", string='Suspense Account',
domain=lambda self: "[('deprecated', '=', False), ('company_id', '=', company_id), \
('user_type_id.type', 'not in', ('receivable', 'payable')), \
('user_type_id', '=', %s)]" % self.env.ref('account.data_account_type_current_liabilities').id,
tracking=True)
restrict_mode_hash_table = fields.Boolean(string="Lock Posted Entries with Hash",
help="If ticked, the accounting entry or invoice receives a hash as soon as it is posted and cannot be modified anymore.",
tracking=True)
sequence = fields.Integer(help='Used to order Journals in the dashboard view', default=10,
tracking=True)
invoice_reference_type = fields.Selection(string='Communication Type', required=True, selection=[('none', 'Free'), ('partner', 'Based on Customer'), ('invoice', 'Based on Invoice')], default='invoice', help='You can set here the default communication that will appear on customer invoices, once validated, to help the customer to refer to that particular invoice when making the payment.',
tracking=True)
invoice_reference_model = fields.Selection(string='Communication Standard', required=True, selection=[('odoo', 'Odoo'),('euro', 'European')], default=_default_invoice_reference_model, help="You can choose different models for each type of reference. The default one is the Odoo reference.",
tracking=True)
#groups_id = fields.Many2many('res.groups', 'account_journal_group_rel', 'journal_id', 'group_id', string='Groups')
currency_id = fields.Many2one('res.currency', help='The currency used to enter statement', string="Currency",
tracking=True)
company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True, index=True, default=lambda self: self.env.company,
help="Company related to this journal",
tracking=True)
country_code = fields.Char(related='company_id.country_id.code', readonly=True,
tracking=True)
refund_sequence = fields.Boolean(string='Dedicated Credit Note Sequence', help="Check this box if you don't want to share the same sequence for invoices and credit notes made from this journal", default=False,
tracking=True)
sequence_override_regex = fields.Text(help="Technical field used to enforce complex sequence composition that the system would normally misunderstand.\n"\
"This is a regex that can include all the following capture groups: prefix1, year, prefix2, month, prefix3, seq, suffix.\n"\
"The prefix* groups are the separators between the year, month and the actual increasing sequence number (seq).\n"\
"e.g: ^(?P<prefix1>.*?)(?P<year>\d{4})(?P<prefix2>\D*?)(?P<month>\d{2})(?P<prefix3>\D+?)(?P<seq>\d+)(?P<suffix>\D*?)$",
tracking=True)
inbound_payment_method_ids = fields.Many2many(
comodel_name='account.payment.method',
relation='account_journal_inbound_payment_method_rel',
column1='journal_id',
column2='inbound_payment_method',
domain=[('payment_type', '=', 'inbound')],
string='Inbound Payment Methods',
compute='_compute_inbound_payment_method_ids',
store=True,
readonly=False,
help="Manual: Get paid by cash, check or any other method outside of Odoo.\n"
"Electronic: Get paid automatically through a payment acquirer by requesting a transaction"
" on a card saved by the customer when buying or subscribing online (payment token).\n"
"Batch Deposit: Encase several customer checks at once by generating a batch deposit to"
" submit to your bank. When encoding the bank statement in Odoo, you are suggested to"
" reconcile the transaction with the batch deposit. Enable this option from the settings.",
tracking=True
)
outbound_payment_method_ids = fields.Many2many(
comodel_name='account.payment.method',
relation='account_journal_outbound_payment_method_rel',
column1='journal_id',
column2='outbound_payment_method',
domain=[('payment_type', '=', 'outbound')],
string='Outbound Payment Methods',
compute='_compute_outbound_payment_method_ids',
store=True,
readonly=False,
help="Manual: Pay bill by cash or any other method outside of Odoo.\n"
"Check: Pay bill by check and print it from Odoo.\n"
"SEPA Credit Transfer: Pay bill from a SEPA Credit Transfer file you submit to your"
" bank. Enable this option from the settings.",
tracking=True
)
at_least_one_inbound = fields.Boolean(compute='_methods_compute', store=True,
tracking=True)
at_least_one_outbound = fields.Boolean(compute='_methods_compute', store=True,
tracking=True)
profit_account_id = fields.Many2one(
comodel_name='account.account', check_company=True,
help="Used to register a profit when the ending balance of a cash register differs from what the system computes",
string='Profit Account',
domain=lambda self: "[('deprecated', '=', False), ('company_id', '=', company_id), \
('user_type_id.type', 'not in', ('receivable', 'payable')), \
('user_type_id', 'in', %s)]" % [self.env.ref('account.data_account_type_revenue').id,
self.env.ref('account.data_account_type_other_income').id],
tracking=True)
loss_account_id = fields.Many2one(
comodel_name='account.account', check_company=True,
help="Used to register a loss when the ending balance of a cash register differs from what the system computes",
string='Loss Account',
domain=lambda self: "[('deprecated', '=', False), ('company_id', '=', company_id), \
('user_type_id.type', 'not in', ('receivable', 'payable')), \
('user_type_id', '=', %s)]" % self.env.ref('account.data_account_type_expenses').id,
tracking=True)
# Bank journals fields
company_partner_id = fields.Many2one('res.partner', related='company_id.partner_id', string='Account Holder', readonly=True, store=False)
bank_account_id = fields.Many2one('res.partner.bank',
string="Bank Account",
ondelete='restrict', copy=False,
check_company=True,
domain="[('partner_id','=', company_partner_id), '|', ('company_id', '=', False), ('company_id', '=', company_id)]",
tracking=True)
bank_statements_source = fields.Selection(selection=_get_bank_statements_available_sources, string='Bank Feeds', default='undefined', help="Defines how the bank statements will be registered",
tracking=True)
bank_acc_number = fields.Char(related='bank_account_id.acc_number', readonly=False,
tracking=True)
bank_id = fields.Many2one('res.bank', related='bank_account_id.bank_id', readonly=False,
tracking=True)
# Sale journals fields
sale_activity_type_id = fields.Many2one('mail.activity.type', string='Schedule Activity', default=False, help="Activity will be automatically scheduled on payment due date, improving collection process.",
tracking=True)
sale_activity_user_id = fields.Many2one('res.users', string="Activity User", help="Leave empty to assign the Salesperson of the invoice.",
tracking=True)
sale_activity_note = fields.Text('Activity Summary',
tracking=True)
# alias configuration for journals
alias_id = fields.Many2one('mail.alias', string='Email Alias', help="Send one separate email for each invoice.\n\n"
"Any file extension will be accepted.\n\n"
"Only PDF and XML files will be interpreted by Odoo", copy=False,
tracking=True)
alias_domain = fields.Char('Alias domain', compute='_compute_alias_domain', default=_default_alias_domain, compute_sudo=True,
tracking=True)
alias_name = fields.Char('Alias Name', copy=False, related='alias_id.alias_name', help="It creates draft invoices and bills by sending an email.", readonly=False,
tracking=True)
journal_group_ids = fields.Many2many('account.journal.group',
domain="[('company_id', '=', company_id)]",
check_company=True,
string="Journal Groups",
tracking=True)
secure_sequence_id = fields.Many2one('ir.sequence',
help='Sequence to use to ensure the securisation of data',
check_company=True,
readonly=True, copy=False,
tracking=True)
</code></pre>
<p>Thanks</p>
<p>I've been stuck for weeks and already tried manipulating but none of them are working</p>
|
[
{
"answer_id": 74539681,
"author": "Gas",
"author_id": 20576453,
"author_profile": "https://Stackoverflow.com/users/20576453",
"pm_score": 0,
"selected": false,
"text": "for rec in self: vals = {'acc_number': self.acc_number, 'bank_id': self.bank_id.id, e.t.c} \nself.env['account.journal'].create(vals)\n values account.journal"
},
{
"answer_id": 74543209,
"author": "Waleed Mohsen",
"author_id": 1656236,
"author_profile": "https://Stackoverflow.com/users/1656236",
"pm_score": -1,
"selected": true,
"text": "account.journal (name, code, type, company_id) code class BankAccounAccount(models.Model):\n _name = 'bank.account.account'\n _description = \"Bank Account Account\"\n _rec_name = 'acc_number'\n\n acc_number = fields.Char(string=\"Account Number\", required=True)\n bank_id = fields.Many2one('res.bank', string=\"Bank\")\n bank_bic = fields.Char(string=\"Bank Identifier Code\")\n company_id = fields.Many2one('res.company', string=\"Company\", default=lambda self: self.env.user.company_id.id)\n branch_id = fields.Many2one('res.branch', string=\"Branch\")\n code = fields.Char(string='Short Code', size=5, required=True); # You need to make sure that the entered code not already used by another journal\n \n @api.model\n def create(self, values):\n res = super(BankAccounAccount, self).create(values)\n for rec in res:\n values = {\n 'company_id': rec.company_id.id,\n 'name': rec.acc_number,\n 'type':'bank',\n 'code': rec.code,\n #'acc_number': rec.acc_number.id, # the acc_number field is not exists in 'account.journal' so you canot use it\n #'bank_id': rec.bank_id.id, # this bank_id field is related to bank_account_id.bank_id and bank_account_id is Many2One from 'res.partner.bank' \n #'bank_bic': rec.bank_bic.id, # the bank_bic field is not exists in 'account.journal' so you canot use it\n #'branch_id': rec.branch_id.id, # the branch_id field is not exists in 'account.journal' unless \n }\n self.env['account.journal'].create(values) # make sure that the user you are using has access to account.journal unless use the below commented code\n self.env['account.journal'].sudo().create(values)\n return res\n\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20516023/"
] |
74,528,499
|
<p>As you can see in below code, the TS compiler <strong>infers</strong> the type as :</p>
<pre class="lang-js prettyprint-override"><code>const message = Math.random() > 0.5 ? "hello, can you here me" : null;
</code></pre>
<p>So <strong>message</strong> variable is inferred as <code>"hello, can you here me" | null</code>, which makes sense, as there are two absolute possible values, however in this example bellow the return value is still an absolute value, but the getName type is <code>string</code> primitive type not <code>John Gump</code></p>
<pre class="lang-js prettyprint-override"><code>const getName = () => "John Gump";
</code></pre>
|
[
{
"answer_id": 74529981,
"author": "Tobias S.",
"author_id": 8613630,
"author_profile": "https://Stackoverflow.com/users/8613630",
"pm_score": 3,
"selected": true,
"text": "const message = Math.random() > 0.5 ? \"hello, can you here me\" : null;\n message const \"hello, can you here me\" | null let let message = Math.random() > 0.5 ? \"hello, can you here me\" : null;\n// ^? message: string | null\n const getName = () => \"John Gump\";\n \"John Gump\" string"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1254256/"
] |
74,528,504
|
<p>I am using Material UI in my project. I want to know the best way to override the CSS in react components without using MUI theme.</p>
|
[
{
"answer_id": 74529981,
"author": "Tobias S.",
"author_id": 8613630,
"author_profile": "https://Stackoverflow.com/users/8613630",
"pm_score": 3,
"selected": true,
"text": "const message = Math.random() > 0.5 ? \"hello, can you here me\" : null;\n message const \"hello, can you here me\" | null let let message = Math.random() > 0.5 ? \"hello, can you here me\" : null;\n// ^? message: string | null\n const getName = () => \"John Gump\";\n \"John Gump\" string"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19290397/"
] |
74,528,507
|
<p>So suppose I have a big spark dataframe .I dont know how many columns.</p>
<p>(the solution has to be in pyspark using pandas udf. Not a different approach)</p>
<p>I want to perform an action on all columns. So it's ok to loop inside on all columns
But I dont want to loop through rows. I want it to act on the column at once.</p>
<p>I didnt find on the internet how this could be done.</p>
<p>Suppose I have this datafrme</p>
<pre><code>A B C
5 3 2
1 7 0
</code></pre>
<p>Now I want to send to pandas udf to get sum of each row.</p>
<pre><code>Sum
10
8
</code></pre>
<p>Number of columns not known.</p>
<p>I can do it inside the udf by looping row at a time. But I dont want. I want it to act on all rows without looping. And I allow looping through columns if needed.</p>
<p>One option I tried is combining all colmns to array column</p>
<pre><code>ARR
[5,3,2]
[1,7,0]
</code></pre>
<p>But even here it doesnt work for me without looping.
I send this column to the udf and then inside I need to loop through its rows and sum each value of the list-row.</p>
<p>It would be nice if I could seperate each column as a one and act on the whole column at once</p>
<p>How do I act on the column at once? Without looping through the rows?</p>
<p>If I loop through the rows I guess it's no better than a regular python udf</p>
|
[
{
"answer_id": 74529115,
"author": "wwnde",
"author_id": 8986975,
"author_profile": "https://Stackoverflow.com/users/8986975",
"pm_score": 1,
"selected": false,
"text": "df = spark.read.load('/databricks-datasets/asa/small/small.csv', header=True,format='csv')\n\nsf = df.select(df.colRegex(\"`.*rrDelay$|.*pDelay$`\"))\n\n#sf.show()\n\ncolumns = [\"id\",\"ArrDelay\",\"DepDelay\"]\ndata = [(\"a\", 81.0,3),\n (\"b\", 36.2,5),\n (\"c\", 12.0,5),\n (\"d\", 81.0,5),\n (\"e\", 36.3,5),\n (\"f\", 12.0,5),\n (\"g\", 111.7,5)]\n\nsf = spark.createDataFrame(data=data,schema=columns)\n\nsf.show()\n\n# Use aggregate function\nnew = (sf.withColumn('sums', array(*[x for x in ['ArrDelay','DepDelay'] ]))#Create an array of values per row on desired columns\n .withColumn('sums', expr(\"aggregate(sums,cast(0 as double), (c,i)-> c+i)\"))# USE aggregate to sum\n ).show()\n\n\n#use pandas udf\nsch= sf.withColumn('v', lit(90.087654623)).schema\ndef sum_s(iterator: Iterator[pd.DataFrame]) -> Iterator[pd.DataFrame]:\n for pdf in iterator:\n \n yield pdf.assign(v=pdf.sum(1))\n\nsf.mapInPandas(sum_s, schema=sch).show()\n"
},
{
"answer_id": 74529141,
"author": "iambdot",
"author_id": 1415826,
"author_profile": "https://Stackoverflow.com/users/1415826",
"pm_score": 0,
"selected": false,
"text": "from pyspark.sql import functions as F\nfrom pyspark.sql.types import *\nfrom pyspark.sql import Window\nfrom functools import reduce\n\ndf = spark.createDataFrame(\n [\n (5,3,2),\n (1,7,0), \n ],\n [\"A\", \"B\", \"C\"],\n)\n\ncols = df.columns\ncalculate_sum = reduce(lambda a, x: a+x, map(col, cols))\n\ndf = (\n df\n .withColumn(\n \"sum\",calculate_sum\n )\n)\n\ndf.show()\n +---+---+---+---+\n| A| B| C|sum|\n+---+---+---+---+\n| 5| 3| 2| 10|\n| 1| 7| 0| 8|\n+---+---+---+---+\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11531487/"
] |
74,528,514
|
<p>I have this code where the user has to input the name of a file which includes a message and the name of a file where the message must be written after its encrypted via Caesar-Cipher.</p>
<p>I would like to validate the inputs, so that if there's a wrong input, the code won't crash but ask the user for a valid file path until the user inputs it.
I have some familiarity with validation using the while loop, however I couldn't apply it here without ruining other parts of the code.</p>
<p>Any suggestions are appreciated.</p>
<pre><code> def open_file(source_path: str, dest_path: str):
with open(source_path, mode='r') as fd:
while line := fd.readline():
return line
def write_to_file(dest_path: str, line: str):
with open(dest_path, mode='a') as fd:
fd.write(line)
source_path = input("Enter the name of the file including the message: ")
dest_path = input("Enter the name of the file where the encrypted message will be written: ")
MODE_ENCRYPT = 1
def caesar(source: str, dest: str, steps, mode):
alphabet = "abcdefghijklmnopqrstuvwxyzabcABCDEFGHIJKLMNOPQRSTUVWXYZABC"
alpha_len: int = len(alphabet)
new_data = ""
file = open_file(source_path, dest_path)
for char in file:
index = alphabet.find(char)
if index == -1:
new_data += char
else:
# compute first parth
changed = index + steps if mode == MODE_ENCRYPT else index - steps
# make an offset
changed %= alpha_len
new_data += alphabet[changed:changed + 1]
write_to_file(dest_path, new_data)
return new_data
while True:
# Validating input key
key = input("Enter the key: ")
try:
key = int(key)
except ValueError:
print("Please enter a valid key: ")
continue
break
ciphered = caesar(source_path, dest_path, key, MODE_ENCRYPT)
</code></pre>
|
[
{
"answer_id": 74529115,
"author": "wwnde",
"author_id": 8986975,
"author_profile": "https://Stackoverflow.com/users/8986975",
"pm_score": 1,
"selected": false,
"text": "df = spark.read.load('/databricks-datasets/asa/small/small.csv', header=True,format='csv')\n\nsf = df.select(df.colRegex(\"`.*rrDelay$|.*pDelay$`\"))\n\n#sf.show()\n\ncolumns = [\"id\",\"ArrDelay\",\"DepDelay\"]\ndata = [(\"a\", 81.0,3),\n (\"b\", 36.2,5),\n (\"c\", 12.0,5),\n (\"d\", 81.0,5),\n (\"e\", 36.3,5),\n (\"f\", 12.0,5),\n (\"g\", 111.7,5)]\n\nsf = spark.createDataFrame(data=data,schema=columns)\n\nsf.show()\n\n# Use aggregate function\nnew = (sf.withColumn('sums', array(*[x for x in ['ArrDelay','DepDelay'] ]))#Create an array of values per row on desired columns\n .withColumn('sums', expr(\"aggregate(sums,cast(0 as double), (c,i)-> c+i)\"))# USE aggregate to sum\n ).show()\n\n\n#use pandas udf\nsch= sf.withColumn('v', lit(90.087654623)).schema\ndef sum_s(iterator: Iterator[pd.DataFrame]) -> Iterator[pd.DataFrame]:\n for pdf in iterator:\n \n yield pdf.assign(v=pdf.sum(1))\n\nsf.mapInPandas(sum_s, schema=sch).show()\n"
},
{
"answer_id": 74529141,
"author": "iambdot",
"author_id": 1415826,
"author_profile": "https://Stackoverflow.com/users/1415826",
"pm_score": 0,
"selected": false,
"text": "from pyspark.sql import functions as F\nfrom pyspark.sql.types import *\nfrom pyspark.sql import Window\nfrom functools import reduce\n\ndf = spark.createDataFrame(\n [\n (5,3,2),\n (1,7,0), \n ],\n [\"A\", \"B\", \"C\"],\n)\n\ncols = df.columns\ncalculate_sum = reduce(lambda a, x: a+x, map(col, cols))\n\ndf = (\n df\n .withColumn(\n \"sum\",calculate_sum\n )\n)\n\ndf.show()\n +---+---+---+---+\n| A| B| C|sum|\n+---+---+---+---+\n| 5| 3| 2| 10|\n| 1| 7| 0| 8|\n+---+---+---+---+\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20111366/"
] |
74,528,531
|
<p>It works if I hardcode my string when passing it to String.replace(/3):</p>
<pre><code>String.replace("username", "", ".")
=> ".u.s.e.r.n.a.m.e.
</code></pre>
<p>But I´d like to run String.replace(/3) on the content that I have in my variable:</p>
<pre><code> username = 'marcel_huber'
new_username = String.replace(username, "", ".")
** (FunctionClauseError) no function clause matching in String.replace/4
The following arguments were given to String.replace/4:
# 1
'marcel_huber'
# 2
""
# 3
"."
# 4
[]
Attempted function clauses (showing 1 out of 1):
def replace(subject, pattern, replacement, options) when is_binary(subject) and is_binary(replacement) or is_function(replacement, 1) and is_list(options)
(elixir 1.14.0) lib/string.ex:1521: String.replace/4
iex:7: (file)
</code></pre>
<p>How can I make this work?</p>
|
[
{
"answer_id": 74530703,
"author": "zwippie",
"author_id": 409792,
"author_profile": "https://Stackoverflow.com/users/409792",
"pm_score": 2,
"selected": false,
"text": "username = 'marcel_huber'\n username = \"marcel_huber\"\n"
},
{
"answer_id": 74541274,
"author": "Adam Millerchip",
"author_id": 1225617,
"author_profile": "https://Stackoverflow.com/users/1225617",
"pm_score": 1,
"selected": false,
"text": "iex(1)> String.replace(\"double-quotes\", \"-\", \" \")\n\"double quotes\"\niex(2)> string = \"double-quotes\"\n\"double-quotes\"\niex(3)> String.replace(string, \"-\", \" \")\n\"double quotes\"\n iex(4)> String.replace('single-quotes', \"-\", \" \")\n** (FunctionClauseError) no function clause matching in String.replace/4\niex(4)> charlist = 'single-quotes'\n[115, 105, 110, 103, 108, 101, 45, 113, 117, 111, 116, 101, 115]\niex(5)> String.replace(charlist, \"-\", \" \")\n** (FunctionClauseError) no function clause matching in String.replace/4\n String IEx.configure(inspect: [charlists: :as_lists]) iex(4)"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/375721/"
] |
74,528,540
|
<p>As the title states, when I register multiple instances of <code>IHostedService</code>, it calls <code>StartAsync</code> twice on the first instance, but not the second, but it does call both constructors.</p>
<p><strong>Program.cs</strong></p>
<pre><code>services.AddSingleton<IHostedService, ProductService>(provider => (ProductService)provider.GetService<IProductService>()!);
services.AddSingleton<IProductService, ProductService>();
services.AddSingleton<IHostedService, ProductService>(provider => (ProductService)provider.GetService<IProductService>()!);
services.AddSingleton<IProductService, ProductService>();
</code></pre>
<p><strong>ProductService.cs</strong></p>
<pre><code>public class ProductService : IProductService, IHostedService
{
public async Task StartAsync(CancellationToken cancellationToken) { }
public async Task StopAsync(CancellationToken cancellationToken) { }
}
</code></pre>
<p>How can I solve this? I need multiple instances of <code>ProductService</code> (name changed for simplicity).</p>
|
[
{
"answer_id": 74529255,
"author": "Avinash Reddy",
"author_id": 7765929,
"author_profile": "https://Stackoverflow.com/users/7765929",
"pm_score": -1,
"selected": false,
"text": "class ProductFactory : IProductFactory\n{\n private readonly Dictionary<string, ProductService> _productService ;\n\n public void Register(string name, ProductService productService)\n {\n _productService[name] = productService;\n }\n\n public HttpClient Resolve(string name)\n {\n return _productService[name];\n }\n}\n\n\nvar factory = new ProductFactory();\nfactory.Register(\"p1\", new ProductService());\nfactory.Register(\"p2\", new ProductService());\nservices.AddSingleton<IProductFactory>(factory);\n\n\npublic ProductController(IProductFactory factory)\n{\n _productFactory = factory.Resolve(\"p1\");\n}\n"
},
{
"answer_id": 74627630,
"author": "user2250152",
"author_id": 2250152,
"author_profile": "https://Stackoverflow.com/users/2250152",
"pm_score": 0,
"selected": false,
"text": "StartAsync StartAsync StartAsync StartAsync public Task StartAsync(CancellationToken cancellationToken)\n{\n Task.Run(() => SomeWork(cancellationToken));\n return Task.CompletedTask;\n}\n"
},
{
"answer_id": 74648015,
"author": "pfx",
"author_id": 9200675,
"author_profile": "https://Stackoverflow.com/users/9200675",
"pm_score": 0,
"selected": false,
"text": "StartAsync Guid ProductService services.AddTransient<IHostedService, ProductService>();\nservices.AddTransient<IHostedService, ProductService>();\n public class ProductService : IHostedService\n{\n private readonly Guid _id = Guid.NewGuid();\n\n public ProductService( /* Any dependencies */ )\n { }\n\n public Task StartAsync(CancellationToken cancellationToken)\n => Task.CompletedTask;\n\n public Task StopAsync(CancellationToken cancellationToken)\n => Task.CompletedTask;\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3973081/"
] |
74,528,551
|
<p>I have a Python expression that looks like the following:</p>
<pre><code>var1 = 'GOOGLE'
var2 = '5'
expr = 'df[df[var1]>=var2]'
</code></pre>
<p>In my workspace var1 and var2 are well defined so I can evaluate expr as follows:</p>
<pre><code>eval(expr)
</code></pre>
<p>However, I want to pass this expr (as string) to another function with values of var1 and var2 substituted in it. I do not want to pass the variables var1 and var2, as I can have any number of variables, not just two. How do I accomplish this?</p>
|
[
{
"answer_id": 74528677,
"author": "Maxwell D. Dorliea",
"author_id": 12906648,
"author_profile": "https://Stackoverflow.com/users/12906648",
"pm_score": 1,
"selected": false,
"text": "expr = f'df[df[{var1}] >= {var2}]'\n\n"
},
{
"answer_id": 74528854,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 1,
"selected": true,
"text": "ast.parse ast.NodeTransformer Name Constant ast.unparse import ast\n\nvar1 = 'GOOGLE'\nvar2 = '5'\nexpr = 'df[df[var1]>=var2]'\n\nclass NamesToConstants(ast.NodeTransformer):\n def visit_Name(self, node):\n if node.id in globals(): # feel free to use your own dict instead of globals()\n value = globals()[node.id]\n try: # convert value to integer if viable\n value = int(value)\n except:\n pass\n return ast.Constant(value=value)\n return node\n\ntree = ast.parse(expr)\nNamesToConstants().visit(tree)\nprint(ast.unparse(tree))\n df[df['GOOGLE'] >= 5]\n ast.unparse astunparse.unparse"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10151520/"
] |
74,528,578
|
<p>Is there a standard function, or family of functions, for sequencing tuples of applicatives, as a generalization of <code>sequenceA</code>? Like the following, except for all reasonable tuple lengths:</p>
<pre class="lang-hs prettyprint-override"><code>sequence3TupleA :: Applicative f => (f a1, f a2, f a3) -> f (a1, a2, a3)
</code></pre>
<p>I believe this should be possible to implement (it is for the applicatives I'm working with anyway).</p>
<p>I found <a href="https://hackage.haskell.org/package/tuple-0.3.0.2/docs/Data-Tuple-Sequence.html" rel="nofollow noreferrer"><code>SequenceT</code></a> from <code>Data.Tuple.Sequence</code>, but it appears to require a monad and also it doesn't seem to actually contain the sequence function (I am probably misreading the documentation somehow).</p>
|
[
{
"answer_id": 74535059,
"author": "Ari Fordsham",
"author_id": 12153248,
"author_profile": "https://Stackoverflow.com/users/12153248",
"pm_score": 3,
"selected": true,
"text": "SequenceT sequenceT tuple Applicative Monad sequence3TupleA (a, b, c) = (,,) <$> a <*> b <*> c\n"
},
{
"answer_id": 74582774,
"author": "Willem Van Onsem",
"author_id": 67579,
"author_profile": "https://Stackoverflow.com/users/67579",
"pm_score": 1,
"selected": false,
"text": "(a, b, c) (a, (b, c)) HList tuple-append SequenceTuple sequenceTupleA sequenceTupleA_"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1505451/"
] |
74,528,585
|
<p>I trying to make a password generator using python. Currently, I just want the program to print random characters from the ascii table. I will later introduce numbers and symbols. I used a for loop to print random character from a range that the user inputs. It works however, when I use the end='' to print the characters on the same line a % shows up. I think it is there to show that it printed a no character. I would like the program to not print the % because later I will add other numbers and symbols.</p>
<p>I tried subtracting 1 from the range of number. What resulted was the same string with a % but 1 less than intended. I also tried creating a while loop that would print while the variable was less than the password number. It also printed the %.</p>
<p>Here is the code:</p>
<pre><code>import random
import string
letters=string.ascii_letters
passwordnumber=int(input("How many characters do you want your password to be? "))
for i in range(passwordnumber):
print(random.choice(letters), end='')
</code></pre>
|
[
{
"answer_id": 74528631,
"author": "veekxt",
"author_id": 5417267,
"author_profile": "https://Stackoverflow.com/users/5417267",
"pm_score": 2,
"selected": true,
"text": "% \"\\n\" print() \"\\n\" %"
},
{
"answer_id": 74528671,
"author": "Nitin Ashutosh",
"author_id": 6736690,
"author_profile": "https://Stackoverflow.com/users/6736690",
"pm_score": 0,
"selected": false,
"text": "characters = list(string.ascii_letters + string.digits + \"!@#$%^&*()\")\ndef generate_random_password():\n ## length of password from the user\n length = 8\n\n ## shuffling the characters\n random.shuffle(characters)\n\n ## picking random characters from the list\n password = []\n for i in range(length):\n password.append(random.choice(characters))\n\n ## shuffling the resultant password\n random.shuffle(password)\n\n ## converting the list to string\n ## printing the list\n return \"\".join(password)\n"
},
{
"answer_id": 74528686,
"author": "Bhargav",
"author_id": 15358800,
"author_profile": "https://Stackoverflow.com/users/15358800",
"pm_score": 0,
"selected": false,
"text": "end import random\nimport string\nletters=string.ascii_letters\npas =''\npasswordnumber=int(input(\"How many characters do you want your password to be? \"))\nfor i in range(passwordnumber):\n pas += random.choice(letters)\n \nprint(pas)\n How many characters do you want your password to be? 5\nAvfYm\n"
},
{
"answer_id": 74528878,
"author": "lroth",
"author_id": 11032782,
"author_profile": "https://Stackoverflow.com/users/11032782",
"pm_score": 0,
"selected": false,
"text": "- iterable of elements to use - number of elements to take import random\nimport string\nletters=string.ascii_letters\npasswordnumber=int(input(\"How many characters do you want your password to be? \"))\npas = ''.join(random.sample(letters, k=passwordnumber))\nprint(pas)\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20569481/"
] |
74,528,590
|
<p>I have to update ads in an app (which somebody else made). I need to enable Test Ads, without using Test IDs. (the IDs must be the same as the other developer put it).
Also, I want test ads, just because google threatens to disable the account if we test on real ads. (see screenshot)</p>
<p>Please dont refer to "Admob shows Test ads but not real ads". What I want is completely opposite scenario.</p>
<p><a href="https://i.stack.imgur.com/xvqWt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xvqWt.png" alt="google's threat" /></a></p>
|
[
{
"answer_id": 74542132,
"author": "Saad Mansoor",
"author_id": 11565523,
"author_profile": "https://Stackoverflow.com/users/11565523",
"pm_score": 0,
"selected": false,
"text": " MobileAds.instance.updateRequestConfiguration(\n RequestConfiguration(\n testDeviceIds: [\n/* These are `IDs` of different mobile phones on which I have installed and tested my app. */\n \n\n '140A01B86DF7D67991BF3A31AEEE9041', \n \"85BB5D148620523D06692E2F45ED4A30\",\n \"2F4C6DEC28A5611835CA2C3EE14EF31C\",\n ],\n ),\n );\n ID Check the console or logcat output for a message that looks like this:\n\n I/Ads: Use\n RequestConfiguration.Builder\n .setTestDeviceIds(Arrays.asList(\"33BE2250B43518CCDA7DE426D04EE231\"))\n to get test ads on this device.\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11565523/"
] |
74,528,610
|
<p>trying to create a Python program to guess a number between 1 to 9 entered by the user and count the number of attempts taken by the computer to guess the correct number.</p>
<p>this is what I have so far, need to add on a counter that tells me how many attempts have been made, any advice?
thank you</p>
<pre><code>import random #Python import random module in Python defines a series of functions for generating or manipulating random integers
target_num, guess_num = random.randint(1, 10), 0
while target_num != guess_num:
guess_num = int(input('Guess a number between 1 and 10 until you get it right : '))
print('Well guessed!')
</code></pre>
|
[
{
"answer_id": 74542132,
"author": "Saad Mansoor",
"author_id": 11565523,
"author_profile": "https://Stackoverflow.com/users/11565523",
"pm_score": 0,
"selected": false,
"text": " MobileAds.instance.updateRequestConfiguration(\n RequestConfiguration(\n testDeviceIds: [\n/* These are `IDs` of different mobile phones on which I have installed and tested my app. */\n \n\n '140A01B86DF7D67991BF3A31AEEE9041', \n \"85BB5D148620523D06692E2F45ED4A30\",\n \"2F4C6DEC28A5611835CA2C3EE14EF31C\",\n ],\n ),\n );\n ID Check the console or logcat output for a message that looks like this:\n\n I/Ads: Use\n RequestConfiguration.Builder\n .setTestDeviceIds(Arrays.asList(\"33BE2250B43518CCDA7DE426D04EE231\"))\n to get test ads on this device.\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19638154/"
] |
74,528,624
|
<p>I am new at flutter ant trying to use bloc/cubit</p>
<p>I have a state inside cubit file and when I try to emit state... state is not changing and I don't understand why</p>
<p>This is my cubit file:</p>
<p>//auth_cubit.dart</p>
<pre><code>import 'package:flutter_bloc/flutter_bloc.dart';
part of 'auth_state.dart'; // here ide returns an error: The part-of directive must be the only directive in a part.
class AuthCubit extends Cubit<AuthState> { // The name 'AuthState' isn't a type so it can't be used as a type argument.
AuthCubit() : super(AuthState(
email: "Log in",
password: null,
firstName: "",
lastName: "",
genderId: 0,
ageGroupId: 0,
countryUuid: 0
));
void setCountryUuid(int countryUuid) => emit(AuthState(countryUuid: countryUuid));
}
</code></pre>
<p>//auth_state.dart</p>
<pre><code>part of 'auth_cubit.dart';
class AuthState {
final email;
final password;
final firstName;
final lastName;
final genderId;
final ageGroupId;
final countryUuid;
const AuthState({
this.email, //string
this.password, //string
this.firstName, //string
this.lastName, //string
this.genderId, //int
this.ageGroupId, //int
this.countryUuid //int
});
}
</code></pre>
<p>Why does state cannot connect to cubit?</p>
|
[
{
"answer_id": 74542132,
"author": "Saad Mansoor",
"author_id": 11565523,
"author_profile": "https://Stackoverflow.com/users/11565523",
"pm_score": 0,
"selected": false,
"text": " MobileAds.instance.updateRequestConfiguration(\n RequestConfiguration(\n testDeviceIds: [\n/* These are `IDs` of different mobile phones on which I have installed and tested my app. */\n \n\n '140A01B86DF7D67991BF3A31AEEE9041', \n \"85BB5D148620523D06692E2F45ED4A30\",\n \"2F4C6DEC28A5611835CA2C3EE14EF31C\",\n ],\n ),\n );\n ID Check the console or logcat output for a message that looks like this:\n\n I/Ads: Use\n RequestConfiguration.Builder\n .setTestDeviceIds(Arrays.asList(\"33BE2250B43518CCDA7DE426D04EE231\"))\n to get test ads on this device.\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20478292/"
] |
74,528,637
|
<p>I have this line of code</p>
<pre><code> bool containsInt = "Sanjay 400".Any(char.IsDigit)
</code></pre>
<p>What I am trying to do is extract the 400 from the string but</p>
<pre><code>Any(char.IsDigit)
</code></pre>
<p>only returns a true value. I am very new to coding and c# especially.</p>
|
[
{
"answer_id": 74528679,
"author": "Mong Zhu",
"author_id": 5174469,
"author_profile": "https://Stackoverflow.com/users/5174469",
"pm_score": 2,
"selected": false,
"text": "List<char> allInts = \"Sanjay 400\".Where(char.IsDigit).ToList();\n char[] allIntCharsArray = \"Sanjay 400\".Where(char.IsDigit).ToArray();\nint theValue = Convert.ToInt32(new string(allIntCharsArray));\n int.TryParse(allIntCharsArray, out int theValue);\n"
},
{
"answer_id": 74528698,
"author": "eloiz",
"author_id": 16756296,
"author_profile": "https://Stackoverflow.com/users/16756296",
"pm_score": -1,
"selected": false,
"text": "var containsInt = Convert.ToInt32(Regex.Replace(@\"Sanjay 400\", @\"\\D\", \"\"));\n"
},
{
"answer_id": 74528816,
"author": "fubo",
"author_id": 1315444,
"author_profile": "https://Stackoverflow.com/users/1315444",
"pm_score": 3,
"selected": true,
"text": "int result = int.Parse(string.Concat(\"Sanjay 400\".Where(char.IsDigit)));\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20495971/"
] |
74,528,672
|
<p>According to <a href="https://stackoverflow.com/questions/39385391/rs-order-equivalent-in-python">this post</a> <code>np.argsort()</code> would be the function I am looking for. <br/></p>
<p>However, this is not giving me my desire result. <br/></p>
<p>Below is the R code that I am trying to convert to Python and my current Python code. <br/></p>
<h3>R Code</h3>
<p><code>data.frame %>% select(order(colnames(.)))</code></p>
<h3>Python Code</h3>
<p><code>dataframe.iloc[numpy.array(dataframe.columns).argsort()]</code></p>
<p>The dataframe I am working with is 1,000,000+ rows and 42 columns, so I can not exactly re-create the output. <br/></p>
<p>But I believe I can re-create the <code>order()</code> outputs. <br/>
From my understanding each number represents the original position in the columns list <br/></p>
<p><code>order(colnames(data.frame))</code> returns <br/>
3,2,5,6,8,4,7,10,9,11,12,13,14,15,16,17,18,19,23,20,21,22,1,25,26,28,24,27,38,29,34,33,36,30,31,32,35,41,42,39,40,37 <br/></p>
<p><code>numpy.array(dataframe.columns).argsort()</code> returns <br/>
2,4,5,7,3,6,9,8,10,11,12,13,14,15,16,17,18,22,19,20,21,0,24,25,27,23,26,37,28,33,32,35,29,30,31,34,40,41,38,39,36,1</p>
<p>I know R does not have 0 index like python, so I know the first two numbers 3 and 2 are the same. <br/></p>
<p>I am looking for python code that could potentially return the same ordering at the R code.</p>
|
[
{
"answer_id": 74528959,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 1,
"selected": false,
"text": "np.argsort > x=c(1,2,3,10,20,30,5,15,25,35)\n> x\n [1] 1 2 3 10 20 30 5 15 25 35\n> order(x)\n [1] 1 2 3 7 4 8 5 9 6 10\n >>> x=np.array([1,2,3,10,20,30,5,15,25,35])\n>>> x\narray([ 1, 2, 3, 10, 20, 30, 5, 15, 25, 35])\n>>> x.argsort()+1\narray([ 1, 2, 3, 7, 4, 8, 5, 9, 6, 10])\n +1 argsort np.argsort"
},
{
"answer_id": 74529038,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "order(c('a', 'b', 'B', 'A', 'c'))\n# [1] 1 4 2 3 5\n\nx <- c('a', 'b', 'B', 'A', 'c')\nx[order(c('a', 'b', 'B', 'A', 'c'))]\n# [1] \"a\" \"A\" \"b\" \"B\" \"c\"\n np.argsort(['a', 'b', 'B', 'A', 'c'])+1\n# array([4, 3, 1, 2, 5])\n\nx = np.array(['a', 'b', 'B', 'A', 'c'])\nx[np.argsort(x)]\n# array(['A', 'B', 'a', 'b', 'c'], dtype='<U1')\n numpy.lexsort x = np.array(['a', 'b', 'B', 'A', 'c'])\nx[np.lexsort([np.char.swapcase(x), np.char.lower(x)])]\n# array(['a', 'A', 'b', 'B', 'c'], dtype='<U1')\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15773858/"
] |
74,528,690
|
<p>I am trying to have two identically sized frames inside a grid, like this:
<a href="https://i.stack.imgur.com/jpasE.png" rel="nofollow noreferrer">enter image description here</a>
i have control over the frame's size when nothing is in it but when i add something into the frame, i lose control over the size itself and it adapts to the size of stuff placed in it. Any way to control the size of a frame when something is inside it?
<a href="https://i.stack.imgur.com/DjTh6.png" rel="nofollow noreferrer">size of frame when something is inside:</a>
<a href="https://i.stack.imgur.com/DR0rM.png" rel="nofollow noreferrer">when nothing is in the frame</a></p>
<pre class="lang-py prettyprint-override"><code>from tkinter import *
import random as rn
def value_change(choice):
global user_choice
user_choice=choice
return(user_choice)
user_choice=4
hlavni=Tk()
jmeno=Label(hlavni,text='Kámen, nůžky,papír',font=("arial","20","bold"),justify='center')
jmeno.grid(row=0,column=0,columnspan=2)
hrac_name=Label(hlavni,text='Hráč',justify="left")
hrac_name.grid(row=1,column=0)
pc_name=Label(hlavni,text="Počítač")
pc_name.grid(row=1,column=1)
hrac_f=Frame(hlavni,relief="ridge",borderwidth=4,width=400,height=400,padx=10,pady=10)
hrac_f.grid(row=2,column=0,padx=10,pady=10)
""" stuff inside the frame
Volba=Label(hrac_f,text="Zadej svou volbu",font=("arial",10,"bold")).grid(row=0,column=0)
values=Label(hrac_f,text="Vyber: Kámen, Nůžky, Papír",font=("arial",10)).grid(row=1,column=0)
choice_f=Frame(hrac_f)
choice_f.grid(row=3,column=0)
stone=Button(choice_f,text="kámen",relief="ridge",command=lambda: value_change(0))
stone.grid(row=0,column=0)
scissors=Button(choice_f,text="nůžky",relief="ridge",command=lambda: value_change(1))
scissors.grid(row=0,column=1)
paper=Button(choice_f,text="papír",relief="ridge",command=lambda: value_change(2))
paper.grid(row=0,column=2) """
hlavni.mainloop()
</code></pre>
|
[
{
"answer_id": 74528959,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 1,
"selected": false,
"text": "np.argsort > x=c(1,2,3,10,20,30,5,15,25,35)\n> x\n [1] 1 2 3 10 20 30 5 15 25 35\n> order(x)\n [1] 1 2 3 7 4 8 5 9 6 10\n >>> x=np.array([1,2,3,10,20,30,5,15,25,35])\n>>> x\narray([ 1, 2, 3, 10, 20, 30, 5, 15, 25, 35])\n>>> x.argsort()+1\narray([ 1, 2, 3, 7, 4, 8, 5, 9, 6, 10])\n +1 argsort np.argsort"
},
{
"answer_id": 74529038,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "order(c('a', 'b', 'B', 'A', 'c'))\n# [1] 1 4 2 3 5\n\nx <- c('a', 'b', 'B', 'A', 'c')\nx[order(c('a', 'b', 'B', 'A', 'c'))]\n# [1] \"a\" \"A\" \"b\" \"B\" \"c\"\n np.argsort(['a', 'b', 'B', 'A', 'c'])+1\n# array([4, 3, 1, 2, 5])\n\nx = np.array(['a', 'b', 'B', 'A', 'c'])\nx[np.argsort(x)]\n# array(['A', 'B', 'a', 'b', 'c'], dtype='<U1')\n numpy.lexsort x = np.array(['a', 'b', 'B', 'A', 'c'])\nx[np.lexsort([np.char.swapcase(x), np.char.lower(x)])]\n# array(['a', 'A', 'b', 'B', 'c'], dtype='<U1')\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20513079/"
] |
74,528,752
|
<p>HI I am trying to create a storage blob container in which the source uri = the SAS key key generated referring to the other storage account. It is working fine but i have to pass the SAS key as secret ( in azure portal)</p>
<p>I tried giving the SAS key directly, it is working but i need to pass the SAS key as secret</p>
|
[
{
"answer_id": 74528959,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 1,
"selected": false,
"text": "np.argsort > x=c(1,2,3,10,20,30,5,15,25,35)\n> x\n [1] 1 2 3 10 20 30 5 15 25 35\n> order(x)\n [1] 1 2 3 7 4 8 5 9 6 10\n >>> x=np.array([1,2,3,10,20,30,5,15,25,35])\n>>> x\narray([ 1, 2, 3, 10, 20, 30, 5, 15, 25, 35])\n>>> x.argsort()+1\narray([ 1, 2, 3, 7, 4, 8, 5, 9, 6, 10])\n +1 argsort np.argsort"
},
{
"answer_id": 74529038,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "order(c('a', 'b', 'B', 'A', 'c'))\n# [1] 1 4 2 3 5\n\nx <- c('a', 'b', 'B', 'A', 'c')\nx[order(c('a', 'b', 'B', 'A', 'c'))]\n# [1] \"a\" \"A\" \"b\" \"B\" \"c\"\n np.argsort(['a', 'b', 'B', 'A', 'c'])+1\n# array([4, 3, 1, 2, 5])\n\nx = np.array(['a', 'b', 'B', 'A', 'c'])\nx[np.argsort(x)]\n# array(['A', 'B', 'a', 'b', 'c'], dtype='<U1')\n numpy.lexsort x = np.array(['a', 'b', 'B', 'A', 'c'])\nx[np.lexsort([np.char.swapcase(x), np.char.lower(x)])]\n# array(['a', 'A', 'b', 'B', 'c'], dtype='<U1')\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19871649/"
] |
74,528,764
|
<p>I have started learning Regex recently and I was given a string as follows:</p>
<pre><code>T10BestFruits_Mango_7-Slices_Thick_Daily_noshare_BD5567#Aware#SeasonalFruits#NA#NA|FreshMangoes-6x5-NPM-5300000-Nov22
</code></pre>
<p>I want to extract <code>6x5</code> using <code>REGEXEXTRACT</code> function but I cannot find the right Regex pattern that will do it perfectly. Is there any regex pattern that will give me "6x5" directly without any delimiters or words attached?</p>
<p>I first tried using <code>([|.*?]\w*[-.*?]\w*[-.*?]\w*[-.*?]\w*[-.*?]\w*)</code> to extract the substring but the result came out as <code>|FreshMangoes-6x5-NPM-5300000-Nov22</code>.</p>
<p>Then I tried <code>[|](.*)[-]</code> which gave me <code>FreshMangoes-6x5-NPM-5300000</code> and <code>-[\w*]+-</code> which gave me <code>-6x5-</code>.</p>
<p>What I needed was <code>6x5</code> exactly. There should be no delimiters in this substring.</p>
|
[
{
"answer_id": 74530606,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 1,
"selected": false,
"text": "=REGEXEXTRACT(col, \".*\\|.*?-(\\w+)\")\n .* \\| | .*? - (\\w+)"
},
{
"answer_id": 74532991,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 0,
"selected": false,
"text": "=REGEXEXTRACT(A1; \"-(\\d+x\\d+)-\")\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20562352/"
] |
74,528,785
|
<p><strong>Error: node_modules/@firebase/auth-compat/dist/auth-compat/index.d.ts:53:10 - error TS2300: Duplicate identifier 'type'.</strong></p>
<p>Try to <strong>build angular code</strong>, i am getting below <strong>error in cmd</strong>.</p>
<pre><code> import { type User, type Unsubscribe, type ActionCodeInfo, type UserCredential, type Auth, type IdTokenResult, type MultiFactorError, type MultiFactorResolver, type PopupRedirectResolver, type Dependencies, type AuthCredential, type ApplicationVerifier, type ConfirmationResult, type AuthProvider, type MultiFactorUser, type NextOrObserver, type ErrorFn, type CompleteFn, type ActionCodeSettings, type Persistence, type PhoneAuthCredential } from "@firebase/auth";
~~~~
Error: node_modules/@firebase/auth-compat/dist/auth-compat/index.d.ts:53:10 - error TS2300: Duplicate identifier 'type'.
</code></pre>
<p>Some times i get error in <strong>all firebase compat</strong> file like <strong>database-compat, storage-compat, etc</strong>.</p>
<p>This is my <strong>package.json</strong> file</p>
<pre><code>"dependencies": {
"@angular/animations": "^11.2.9",
"@angular/cdk": "^13.0.2",
"@angular/common": "~12.2.0",
"@angular/compiler": "~12.2.0",
"@angular/core": "~12.2.0",
"@angular/fire": "^7.2.0",
"@angular/forms": "~12.2.0",
"@angular/material": "^11.2.12",
"@angular/platform-browser": "~12.2.0",
"@angular/platform-browser-dynamic": "~12.2.0",
"@angular/router": "~12.2.0",
"@ng-bootstrap/ng-bootstrap": "^10.0.0",
"angularfire2": "^5.4.2",
"aws-sdk": "^2.1081.0",
"bootstrap": "^5.1.3",
"concurrently": "^6.2.1",
"cors": "^2.8.5",
"file-saver": "^2.0.5",
"firebase": "^9.4.1",
"http": "0.0.1-security",
"http-client": "^4.3.1",
"http-server": "^13.0.2",
"karma-chai": "^0.1.0",
"karma-mocha": "^2.0.1",
"karma-spec-reporter": "0.0.32",
"karma-viewport": "^1.0.8",
"mocha": "^9.1.1",
"ngx-toastr": "^14.1.4",
"rxjs": "~6.6.0",
"tslib": "^2.3.0",
"util": "^0.12.4",
"uuid-generator-ts": "^1.1.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "~12.2.6",
"@angular/cli": "~12.2.6",
"@angular/compiler-cli": "~12.2.0",
"@types/file-saver": "^2.0.5",
"@types/jasmine": "~3.8.0",
"@types/node": "^12.20.46",
"@types/uuid": "^8.3.4",
"jasmine-core": "~3.8.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "~1.7.0",
"typescript": "~4.3.5"
}
</code></pre>
<p>This is my <strong>tsconfig.json</strong> file</p>
<pre><code>{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true,
"target": "es2017",
"module": "es2020",
"lib": [
"es2018",
"dom"
]
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": false
}
}
</code></pre>
<p>I try to reduce <strong>firebase and @angular/fire version in 9.0.0 and ^7.0.0</strong> based on <strong>Angular version</strong>. But this is not working.</p>
<p>I <strong>ref this link</strong> to change version. <a href="https://www.stackoverflow.com/">https://www.npmjs.com/package/@angular/fire</a></p>
<p>Help to solve this problem.</p>
<p>I try to solve that problem in many ways, but i can't solve this.</p>
<p>I expecting to solve the problem as soon as possible.</p>
<p>When install all dependencies in <strong>my angular application using npm install</strong>, after that automatically <strong>type</strong> can add infornt of all <strong>firebase modules</strong> like <strong>Unsubscribe, User, ActionCodeInfo, etc</strong>. Below i add the <strong>firebase node modules index.d.ts</strong> code.</p>
<p><code>import { type User, type Unsubscribe, type ActionCodeInfo, type UserCredential, type Auth, type IdTokenResult, type MultiFactorError, type MultiFactorResolver, type PopupRedirectResolver, type Dependencies, type AuthCredential, type ApplicationVerifier, type ConfirmationResult, type AuthProvider, type MultiFactorUser, type NextOrObserver, type ErrorFn, type CompleteFn, type ActionCodeSettings, type Persistence, type PhoneAuthCredential } from "@firebase/auth";</code></p>
<p>After install all dependencies, try to build the application. i get the above mentioned error (<strong>node_modules/@firebase/auth-compat/dist/auth-compat/index.d.ts:53:10 - error TS2300: Duplicate identifier 'type'.</strong>).</p>
<p>My question is how to solve the error in my application?.</p>
<p>One month ago above mentioned <strong>firebase and @angular/fire version is working</strong>. But <strong>last one month</strong> it through the <strong>error</strong>.</p>
|
[
{
"answer_id": 74530606,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 1,
"selected": false,
"text": "=REGEXEXTRACT(col, \".*\\|.*?-(\\w+)\")\n .* \\| | .*? - (\\w+)"
},
{
"answer_id": 74532991,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 0,
"selected": false,
"text": "=REGEXEXTRACT(A1; \"-(\\d+x\\d+)-\")\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15145333/"
] |
74,528,808
|
<p>I am writing a stored procedure with DB name as input parameter. I am creating some physical tables dynamically. If a table already exists then I need to delete the Table.</p>
<pre><code>DECLARE @TargetDBName NVARCHAR(100) = 'PRD_Inventory'
DECLARE @TargetSchema NVARCHAR(100) = 'usr'
</code></pre>
<p><strong>Current Query</strong></p>
<pre><code>IF OBJECT_ID('TempUserData') IS NOT NULL DROP TABLE TempUserData
</code></pre>
<p><strong>Expected format:</strong></p>
<pre><code>IF OBJECT_ID('@TargetDBName.@TargetSchema.TempUserData') IS NOT NULL DROP TABLE @TargetDBName.@TargetSchema.TempUserData
</code></pre>
|
[
{
"answer_id": 74529073,
"author": "masoud rafiee",
"author_id": 4256602,
"author_profile": "https://Stackoverflow.com/users/4256602",
"pm_score": -1,
"selected": false,
"text": "DECLARE @TargetDBName NVARCHAR(100) = 'PRD_Inventory'\nDECLARE @TargetSchema NVARCHAR(100) = 'usr'\nDECLARE @TableName NVARCHAR(100) = 'tablename'\nDECLARE @TableNameWithShema NVARCHAR(250) = @TargetDBName +'.'+@TargetSchema+'.'+@TableName ;\n\nIF OBJECT_ID(@TableNameWithShema) IS NOT NULL DROP TABLE @TableNameWithShema\n"
},
{
"answer_id": 74530195,
"author": "Stu",
"author_id": 15332650,
"author_profile": "https://Stackoverflow.com/users/15332650",
"pm_score": 1,
"selected": false,
"text": "declare @TargetDBName sysname = 'PRD_Inventory',\n @TargetSchema sysname = 'usr', \n @sql nvarchar(max);\n\nset @sql = 'if exists (\n select * from ' + QuoteName(@TargetDBName) + '.sys.objects o\n join ' + QuoteName(@TargetDBName) + '.sys.schemas s on s.schema_id = o.schema_id\n where o.name = ''TempUserData'' and s.name = ''' + @TargetSchema + '''\n) drop table '+ QuoteName(@TargetDBName) + '.' + QuoteName(@TargetSchema) + '.TempUserData;'\n\nexec (@sql);\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3881070/"
] |
74,528,832
|
<p>I have an excel question.</p>
<p>I have some products in A,B,C warehouses. How Can I compare the numbers in these warehouses and show the warehouse with the highest number?</p>
<p><a href="https://i.stack.imgur.com/BH4d2.png" rel="nofollow noreferrer">Here's the Excel example</a></p>
<p>I tried If function but it didn't work.</p>
|
[
{
"answer_id": 74528887,
"author": "steve stephen",
"author_id": 7961978,
"author_profile": "https://Stackoverflow.com/users/7961978",
"pm_score": 0,
"selected": false,
"text": "=MAX(B2:D2)\n"
},
{
"answer_id": 74528911,
"author": "Yossi Benagou",
"author_id": 18366972,
"author_profile": "https://Stackoverflow.com/users/18366972",
"pm_score": 1,
"selected": false,
"text": "=INDEX($B$1:$D$1,MATCH(MAX(B2:D2),B2:D2,0))"
},
{
"answer_id": 74528927,
"author": "Aaryan Vijayraj",
"author_id": 12916850,
"author_profile": "https://Stackoverflow.com/users/12916850",
"pm_score": 0,
"selected": false,
"text": "=MAX(B2:D2) \n=MAX(B3:D3)\n=MAX(B4:D4)\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16791874/"
] |
74,528,862
|
<p>I am making an API call to firebase from useEffect and the data returned is empty when the page loads for the first time but gets populated if I make any changes to the code and save it. I want the data to be present when the page loads for the first time.</p>
<pre><code>import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { motion } from "framer-motion";
import { getDatabase, ref, onValue } from "firebase/database";
import Helmet from "../components/Helmet/Helmet";
import "../styles/home.css";
import { Container, Row, Col } from "reactstrap";
import heroImg from "../assets/images/hero-img.png";
import Services from "../services/Services";
import ProductsList from "../components/UI/ProductsList";
import Clock from "../components/UI/Clock";
import counterImg from "../assets/images/counter-timer-img.png";
const Home = () => {
const [isLoading, setIsLoading] = useState(true);
const [products, setProducts] = useState([]);
const [trendingProducts, setTrendingProducts] = useState([]);
const [bestSalesProducts, setBestSalesProducts] = useState([]);
const [mobileProducts, setMobileProducts] = useState([]);
const [wirelessProducts, setWirelessProducts] = useState([]);
const [popularProducts, setPopularProducts] = useState([]);
const year = new Date().getFullYear();
useEffect(() => {
const fetchProducts = () => {
const db = getDatabase();
const thumbnailRef = ref(db, "Contents/");
onValue(thumbnailRef, (snapshot) => {
const data = snapshot.val();
if (data !== null) {
Object.values(data).map((product) => {
return setProducts((oldArray) => [...oldArray, product]);
});
console.log(products);
}
});
};
const filteredTrendingProducts = products.filter(
(item) => item.category === "Kids"
);
const filteredBestSalesProducts = products.filter(
(item) => item.category === "Entertainment"
);
const filteredMobileProducts = products.filter(
(item) => item.category === "LifeStyle"
);
const filteredWirelessProducts = products.filter(
(item) => item.category === "wireless"
);
const filteredPopularProducts = products.filter(
(item) => item.category === "watch"
);
setTrendingProducts(filteredTrendingProducts);
setBestSalesProducts(filteredBestSalesProducts);
setMobileProducts(filteredMobileProducts);
setWirelessProducts(filteredWirelessProducts);
setPopularProducts(filteredPopularProducts);
setIsLoading(false);
fetchProducts();
}, []);
if (isLoading) {
return <div> Loading ... </div>;
}
return (
whileTap={{ scale: 1.2 }}
className="buy__btn store__btn"
>
<Link to="/shop">Visit Store</Link>
</motion.button>
</Col>
<Col lg="6" md="12" className="text-end counter__img">
<img src={counterImg} alt="" />
</Col>
</Row>
</Container>
</section>
<section className="new__arrivals">
<Container>
<Row>
<Col lg="12" className="text-center mb-5">
<h2 className="section__title">New Arrivals</h2>
</Col>
<ProductsList data={mobileProducts} />
<ProductsList data={wirelessProducts} />
</Row>
</Container>
</section>
<section className="popular_category">
<Container>
<Row>
<Col lg="12" className="text-center mb-5">
<h2 className="section__title">Popular in Category</h2>
</Col>
<ProductsList data={popularProducts} />
</Row>
</Container>
</section>
</Helmet>
);
};
export default Home;
</code></pre>
<p>I have tried adding products as the useEffect depencies but it creates an infinite loop fetching.</p>
<p>What do I have to do for the data to be fetched on the first page load?</p>
|
[
{
"answer_id": 74529030,
"author": "John Li",
"author_id": 20436957,
"author_profile": "https://Stackoverflow.com/users/20436957",
"pm_score": 3,
"selected": true,
"text": "console.log(products) setProducts() undefined setProducts() products products useEffect products useEffect products products useEffect(() => {\n const fetchProducts = () => {\n const db = getDatabase();\n const thumbnailRef = ref(db, \"Contents/\");\n\n onValue(thumbnailRef, (snapshot) => {\n const data = snapshot.val();\n if (data !== null) {\n Object.values(data).map((product) => {\n return setProducts((oldArray) => [...oldArray, product]);\n });\n console.log(products);\n }\n });\n };\n setIsLoading(false);\n fetchProducts();\n}, []);\n useEffect(() => {\n const filteredTrendingProducts = products.filter(\n (item) => item.category === \"Kids\"\n );\n const filteredBestSalesProducts = products.filter(\n (item) => item.category === \"Entertainment\"\n );\n const filteredMobileProducts = products.filter(\n (item) => item.category === \"LifeStyle\"\n );\n\n const filteredWirelessProducts = products.filter(\n (item) => item.category === \"wireless\"\n );\n\n const filteredPopularProducts = products.filter(\n (item) => item.category === \"watch\"\n );\n\n setTrendingProducts(filteredTrendingProducts);\n setBestSalesProducts(filteredBestSalesProducts);\n setMobileProducts(filteredMobileProducts);\n setWirelessProducts(filteredWirelessProducts);\n setPopularProducts(filteredPopularProducts);\n}, [products]);\n"
},
{
"answer_id": 74529135,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 1,
"selected": false,
"text": "useEffect(() => {\n const fetchProducts = () => {\n const db = getDatabase();\n const thumbnailRef = ref(db, \"Contents/\");\n\n onValue(thumbnailRef, (snapshot) => {\n const data = snapshot.val();\n if (data !== null) {\n Object.values(data).map((product) => {\n return setProducts((oldArray) => [...oldArray, product]);\n });\n console.log(products);\n }\n });\n };\n fetchProducts();\n }, []);\n\nuseEffect(() => {\nconst filteredTrendingProducts = products.filter(\n (item) => item.category === \"Kids\"\n );\n const filteredBestSalesProducts = products.filter(\n (item) => item.category === \"Entertainment\"\n );\n const filteredMobileProducts = products.filter(\n (item) => item.category === \"LifeStyle\"\n );\n\n const filteredWirelessProducts = products.filter(\n (item) => item.category === \"wireless\"\n );\n\n const filteredPopularProducts = products.filter(\n (item) => item.category === \"watch\"\n );\n\n setTrendingProducts(filteredTrendingProducts);\n setBestSalesProducts(filteredBestSalesProducts);\n setMobileProducts(filteredMobileProducts);\n setWirelessProducts(filteredWirelessProducts);\n setPopularProducts(filteredPopularProducts);\n setIsLoading(false);\n}, [procuts]);\n useEffect(async () => {\n let tempProducts = [];\n const fetchProducts = async () => {\n const db = await getDatabase();\n const thumbnailRef = await ref(db, \"Contents/\");\n\n await onValue(thumbnailRef, (snapshot) => {\n const data = snapshot.val();\n if (data !== null) {\n Object.values(data).map((product) => {\n tempProducts = [...products, product]\n return setProducts(tempProducts);\n });\n console.log(tempProducts);\n }\n });\n };\n\n const filteredTrendingProducts = tempProducts.filter(\n (item) => item.category === \"Kids\"\n );\n const filteredBestSalesProducts = tempProducts.filter(\n (item) => item.category === \"Entertainment\"\n );\n const filteredMobileProducts = tempProducts.filter(\n (item) => item.category === \"LifeStyle\"\n );\n\n const filteredWirelessProducts = tempProducts.filter(\n (item) => item.category === \"wireless\"\n );\n\n const filteredPopularProducts = tempProducts.filter(\n (item) => item.category === \"watch\"\n );\n\n setTrendingProducts(filteredTrendingProducts);\n setBestSalesProducts(filteredBestSalesProducts);\n setMobileProducts(filteredMobileProducts);\n setWirelessProducts(filteredWirelessProducts);\n setPopularProducts(filteredPopularProducts);\n setIsLoading(false);\n await fetchProducts();\n }, []);\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13541483/"
] |
74,528,867
|
<p><a href="https://i.stack.imgur.com/jbd0R.png" rel="nofollow noreferrer">enter image description here</a> I have these five input fields and below are their previews BUT only the last upload image is being displayed I want to display all five images</p>
<p>` this is what my current code looks like</p>
<pre><code> const [preview, setFilepre] = useState();
function fileSelectedHandler(e) {
let file = e.target.files[0];
console.log(e.target.name);
setFilepre(URL.createObjectURL(e.target.files[0]));
setMemberData({
...memberData,
[e.target.name]: {
data: e.target.files[0],
contentType: e.target.files[0].type,
},
});
}
</code></pre>
<p>`</p>
<pre><code>CContainer className="form-image-cont " >
<CFormText>Images</CFormText>
<img src={preview} className="image-input"/>
<img src={preview} className="image-input"/>
<img src={preview} className="image-input"/>
<img src={preview} className="image-input"/>
<img src={preview} className="image-input"/>
</CContainer>
</code></pre>
|
[
{
"answer_id": 74528942,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 1,
"selected": true,
"text": "const [previewImages, setPreviewImages] = useState(Array(5).fill(null));\nfunction fileSelectedHandler(e, index) {\n let file = e.target.files[0];\n const newPreviewImages = [...previewImages];\n const imageSrc = URL.createObjectURL(e.target.files[0]);\n /* insert image at the index of the array */\n newPreviewImages.splice(index, 0, imageSrc);\n setPreviewImages(newPreviewImages);\n setMemberData({\n ...memberData,\n [e.target.name]: {\n data: e.target.files[0],\n contentType: e.target.files[0].type,\n },\n });\n}\n CContainer className=\"form-image-cont \" >\n <CFormText>Images</CFormText>\n {previewImages.map((previewImage) => previewImage ? <img src={previewImage} className=\"image-input\"/> : null)}\n</CContainer>\n function fileSelectedHandler(e, index) {\n let file = e.target.files[0];\n const newPreviewImages = [...previewImages];\n const imageSrc = URL.createObjectURL(e.target.files[0]);\n if(newPreviewImages[index] === null) {\n /* insert image at the index of the array */\n newPreviewImages.splice(index, 0, imageSrc);\n } else {\n /* replace the previous image at index */\n newPreviewImages[index] = imageSrc;\n }\n setPreviewImages(newPreviewImages);\n setMemberData({\n ...memberData,\n [e.target.name]: {\n data: e.target.files[0],\n contentType: e.target.files[0].type,\n },\n });\n}\n"
},
{
"answer_id": 74529060,
"author": "Charles Kasasira",
"author_id": 13582824,
"author_profile": "https://Stackoverflow.com/users/13582824",
"pm_score": -1,
"selected": false,
"text": "setFilepre(URL.createObjectURL(e.target.files[0]));\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15468689/"
] |
74,528,879
|
<p>When I using query to select values to temp table like this:</p>
<pre><code>drop table if exists tTemp;
select tt.id, tt.name
into tTemp
from test.TestTable tt
</code></pre>
<p>It's work great. But when I using this construction in function I have this error:</p>
<blockquote>
<p>[42601] ERROR: "tTemp" is not a known variableq</p>
</blockquote>
<p>Why this construction don't work in function?</p>
|
[
{
"answer_id": 74528978,
"author": "masoud rafiee",
"author_id": 4256602,
"author_profile": "https://Stackoverflow.com/users/4256602",
"pm_score": 0,
"selected": false,
"text": "INSERT INTO tTemp\nselect tt.id, tt.name\nfrom test.TestTable tt\n"
},
{
"answer_id": 74529219,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 1,
"selected": false,
"text": "drop table if exists tTemp;\n\ncreate table ttemp \nas\nselect tt.id, tt.name\nfrom test.TestTable tt\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4675431/"
] |
74,528,908
|
<p>The title on the 16th line is strike through. How is that done?</p>
<p><a href="https://i.stack.imgur.com/uDp6C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uDp6C.png" alt="enter image description here" /></a></p>
<p>I am trying to follow a tutorial in a youtube video and I cannot find a way to do this or replace it with an other code.</p>
|
[
{
"answer_id": 74528978,
"author": "masoud rafiee",
"author_id": 4256602,
"author_profile": "https://Stackoverflow.com/users/4256602",
"pm_score": 0,
"selected": false,
"text": "INSERT INTO tTemp\nselect tt.id, tt.name\nfrom test.TestTable tt\n"
},
{
"answer_id": 74529219,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 1,
"selected": false,
"text": "drop table if exists tTemp;\n\ncreate table ttemp \nas\nselect tt.id, tt.name\nfrom test.TestTable tt\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20569777/"
] |
74,528,949
|
<p>In my Data Repository I created a function:</p>
<pre><code> public function myData(){
$data = $this->createQueryBuilder('data')
->leftJoin('data.fields', 'f')
->andWhere('f.name = :field')
->setParameter('field', 'company');
$result = $data->getQuery()->execute();
return $result;
}
</code></pre>
<p>In my Controller I want to use this function:</p>
<pre><code>class PagesController extends AbstractController
{
public function __construct(EntityManagerInterface $em) {
$this->em = $em;
}
/**
* @Route("/page", name="page", methods={"POST", "GET"})
*/
public function page(Request $request)
{
$data = $this->em->getRepository('App\\Entity\\Data')->myData();
</code></pre>
<p>But I get the error message:</p>
<blockquote>
<p>Undefined method 'myData'. The method name must start with either
findBy, findOneBy or countBy!</p>
</blockquote>
|
[
{
"answer_id": 74528978,
"author": "masoud rafiee",
"author_id": 4256602,
"author_profile": "https://Stackoverflow.com/users/4256602",
"pm_score": 0,
"selected": false,
"text": "INSERT INTO tTemp\nselect tt.id, tt.name\nfrom test.TestTable tt\n"
},
{
"answer_id": 74529219,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 1,
"selected": false,
"text": "drop table if exists tTemp;\n\ncreate table ttemp \nas\nselect tt.id, tt.name\nfrom test.TestTable tt\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5024157/"
] |
74,528,954
|
<p><a href="http://68.178.166.65:3080/AgADcw48" rel="nofollow noreferrer">http://68.178.166.65:3080/AgADcw48</a> This is the link of the video. I generated it by the bot made with linux vps. The link is working fine but why it's not playing in html? Please can anyone help me?</p>
<pre><code><!DOCTYPE html>
<html>
<body>
<video width="400" controls>
<source src="http://68.178.166.65:3080/AgADcw48" type="video/mp4">
Your browser does not support HTML video.
</video>
<p>
Video courtesy of
<a href="" target="_blank"></a>.
</p>
</body>
</html>
</code></pre>
<p>The result of this code is here.- <a href="https://gdplaydora.blogspot.com/p/your-browser-does-not-support-html-video_21.html" rel="nofollow noreferrer">https://gdplaydora.blogspot.com/p/your-browser-does-not-support-html-video_21.html</a></p>
<p>The reason of this error and I want the solution</p>
|
[
{
"answer_id": 74528978,
"author": "masoud rafiee",
"author_id": 4256602,
"author_profile": "https://Stackoverflow.com/users/4256602",
"pm_score": 0,
"selected": false,
"text": "INSERT INTO tTemp\nselect tt.id, tt.name\nfrom test.TestTable tt\n"
},
{
"answer_id": 74529219,
"author": "a_horse_with_no_name",
"author_id": 330315,
"author_profile": "https://Stackoverflow.com/users/330315",
"pm_score": 1,
"selected": false,
"text": "drop table if exists tTemp;\n\ncreate table ttemp \nas\nselect tt.id, tt.name\nfrom test.TestTable tt\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20569852/"
] |
74,528,996
|
<p>I have a string in an array:</p>
<pre><code>string_array = ["firstname@domain.com.au", "lastname@domaintwo.com.au"]
domains = ["@domain.com.au", "firstname"]
</code></pre>
<p>and I need to remove any matches where the strings in the above array contains a substring from another array.</p>
<p>I've tried the below:</p>
<pre><code>test = string_array.reject { |item| domains.include?(item) }
#=> ["firstname@domain.com.au", "lastname@domaintwo.com.au"]
</code></pre>
<p>It should be the other way around, right? something like</p>
<pre><code>test = string_array.reject { |item| item.include?(domains) }
</code></pre>
<p>But that raises <code>TypeError: no implicit conversion of Array into String</code></p>
|
[
{
"answer_id": 74529048,
"author": "spickermann",
"author_id": 2483313,
"author_profile": "https://Stackoverflow.com/users/2483313",
"pm_score": 3,
"selected": true,
"text": "string_array = [\"firstname@domain.com.au\", \"lastname@domaintwo.com.au\"]\ndomains = [\"@domain.com.au\", \"firstname\"]\n\nstring_array.reject { |email| domains.any? { |domain| email.include?(domain) } }\n#=> [\"lastname@domaintwo.com.au\"]\n"
},
{
"answer_id": 74529523,
"author": "Stefan",
"author_id": 477037,
"author_profile": "https://Stackoverflow.com/users/477037",
"pm_score": 2,
"selected": false,
"text": "Regexp.union grep_v string_array = [\"firstname@domain.com.au\", \"lastname@domaintwo.com.au\"]\ndomains = [\"@domain.com.au\", \"firstname\"]\n\nstring_array.grep_v(Regexp.union(domains))\n#=> [\"lastname@domaintwo.com.au\"]\n Regexp.union /@domain\\.com\\.au\\z/ \\z"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74528996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6752183/"
] |
74,529,005
|
<p>I have a file with multiple content such as :</p>
<pre><code>Create initial parsimony tree by phylogenetic likelihood library (PLL)... 0.022 seconds
Perform fast likelihood tree search using LG+I+G model...
Estimate model parameters (epsilon = 5.000)
Perform nearest neighbor interchange...
Estimate model parameters (epsilon = 1.000)
1. Initial log-likelihood: -30833.549
Optimal log-likelihood: -30833.420
Proportion of invariable sites: 0.016
Gamma shape alpha: 2.035
Parameters optimization took 1 rounds (0.226 sec)
Time for fast ML tree search: 2.912 seconds
NOTE: ModelFinder requires 64 MB RAM!
ModelFinder will test up to 546 protein models (sample size: 1544) ...
No. Model -LnL df AIC AICc BIC
1 LG 31317.712 31 62697.424 62698.736 62863.030
2 LG+I 31170.012 32 62404.024 62405.422 62574.972
3 LG+G4 30870.402 32 61804.803 61806.201 61975.751
4 LG+I+G4 30833.404 33 61732.808 61734.294 61909.098
5 LG+R2 30881.301 33 61828.602 61830.088 62004.892
6 LG+R3 30831.187 35 61732.374 61734.045 61919.349
Akaike Information Criterion: VT+F+R4
Corrected Akaike Information Criterion: VT+F+R4
Bayesian Information Criterion: VT+F+R4
Best-fit model: VT+F+R4 chosen according to BIC
other content....
</code></pre>
<p>And I would like to store using bash command the element after the part :</p>
<pre><code>Bayesian Information Criterion:
</code></pre>
<p>within a variable called : The_variable.</p>
<p>So far I tried :</p>
<pre><code>The_variable="$(grep 'Bayesian Information Criterion:' the_file.txt)"
</code></pre>
<p>which gives me all the grep line</p>
<pre><code>echo $The_variable
Bayesian Information Criterion: VT+F+R4
</code></pre>
<p>but I would like it to store only the <code>VT+F+R4</code> part.</p>
<p>To isolate that part I tried :</p>
<pre><code>sed 's@.*: @@g' $VAR
</code></pre>
<p>Any idea ?</p>
|
[
{
"answer_id": 74529041,
"author": "Chen A.",
"author_id": 840582,
"author_profile": "https://Stackoverflow.com/users/840582",
"pm_score": 1,
"selected": false,
"text": "awk awk '{ print $4 }' ➜ echo 'Bayesian Information Criterion: VT+F+R4' | awk '{ print $4 }'\nVT+F+R4\n"
},
{
"answer_id": 74529044,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 3,
"selected": true,
"text": "awk awk -F ' *: *' '$1 == \"Bayesian Information Criterion\" {print $2}' file\n\nVT+F+R4\n\n# to save this in a variable:\nmyvar=$(awk -F ' *: *' '$1 == \"Bayesian Information Criterion\" {print $2}' file)\n gnu-grep \\K grep -oP 'Bayesian Information Criterion:\\h*\\K.+' file\n\nVT+F+R4\n sed sed -n 's/Bayesian Information Criterion: *//p' file\n\nVT+F+R4\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12559770/"
] |
74,529,013
|
<p>So I can get url with</p>
<pre><code>driver.get('https://www.w3.org/')
</code></pre>
<p>But what I want to test is, if I give a fault link, I should get something like</p>
<pre><code>This page does not exist.
</code></pre>
<p>But when I try to capture this, I can't get the result</p>
<p>This is failed, can't report the fault link</p>
<pre><code>link = "https://www.w3.org/fault_link"
if driver.find_elements_by_xpath("//*[contains(text(), 'This page does not exist')]"):
logger.info("Found fault link %s", link)
</code></pre>
<p>this is failed as well, can't capture it.</p>
<pre><code>element = driver.find_element(
By.XPATH, '//*[@id="__next"]/div[1]/main')
# when I print out the element text, I can see the output
# 404 ERROR
# This page does not exist.
# The page you are looking for could not be found.
# Go back home →
logger.info(element.text)
if e.text=='This page does not exist.':
logger.info("Found fault link %s", link)
</code></pre>
<p>this is failed as well</p>
<pre><code>if search("This page does not exist.", element.text):
logger.info("Found fault link %s", link)
</code></pre>
<p>Any suggestions?</p>
|
[
{
"answer_id": 74529041,
"author": "Chen A.",
"author_id": 840582,
"author_profile": "https://Stackoverflow.com/users/840582",
"pm_score": 1,
"selected": false,
"text": "awk awk '{ print $4 }' ➜ echo 'Bayesian Information Criterion: VT+F+R4' | awk '{ print $4 }'\nVT+F+R4\n"
},
{
"answer_id": 74529044,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 3,
"selected": true,
"text": "awk awk -F ' *: *' '$1 == \"Bayesian Information Criterion\" {print $2}' file\n\nVT+F+R4\n\n# to save this in a variable:\nmyvar=$(awk -F ' *: *' '$1 == \"Bayesian Information Criterion\" {print $2}' file)\n gnu-grep \\K grep -oP 'Bayesian Information Criterion:\\h*\\K.+' file\n\nVT+F+R4\n sed sed -n 's/Bayesian Information Criterion: *//p' file\n\nVT+F+R4\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3671801/"
] |
74,529,035
|
<p>I have a list of players and on selecting a player name , I'm displaying the respective player details by introducing a boolean flag (<em><strong>isPlayerSelected</strong></em>) in each formGroup . One disadvantage with this approach is that the page response is slow (when there are more number of items) as it has to update the boolean flag in each formGroup by using patchValue . Is there a better way to do instead of introducing boolean flag?</p>
<p>Please help . I have attached the <a href="https://stackblitz.com/edit/angular-ivy-qdlkok?file=src/app/components/players-list/players-list.component.html" rel="nofollow noreferrer">StackBlitz</a> link as well</p>
<pre><code>selectPlayer(player: any) {
player.isPlayerSelected = !player.isPlayerSelected;
const selectedPlayer = this.playerDetailsControls.find(
(item) => player?.id === item.get('id')?.value
);
const otherPlayers = this.playerDetailsControls.filter(
(item) => player.id !== item.get('id')?.value
);
selectedPlayer?.patchValue({
isPlayerSelected: true,
});
otherPlayers.map((item) => {
item?.patchValue({
isPlayerSelected: false,
});
});
}
</code></pre>
<p>HTML</p>
<pre><code><form [formGroup]="form">
<div formArrayName="playerDetails">
<div *ngFor="let control of playerDetailsControls; let i = index">
<div [formGroupName]="i">
<div *ngIf="control.get('isPlayerSelected')?.value">
Player Name : <input formControlName="playerName" /><br /><br />
Role: <input formControlName="role" /><br /><br />
Country: <input formControlName="country" /><br /><br />
<hr />
</div>
</div>
</div>
</div>
</form>
</code></pre>
<p><a href="https://i.stack.imgur.com/Vbp9D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vbp9D.png" alt="enter image description here" /></a></p>
<p><a href="https://stackblitz.com/edit/angular-ivy-qdlkok?file=src/app/components/players-list/players-list.component.html" rel="nofollow noreferrer">Stackblitz</a></p>
|
[
{
"answer_id": 74529041,
"author": "Chen A.",
"author_id": 840582,
"author_profile": "https://Stackoverflow.com/users/840582",
"pm_score": 1,
"selected": false,
"text": "awk awk '{ print $4 }' ➜ echo 'Bayesian Information Criterion: VT+F+R4' | awk '{ print $4 }'\nVT+F+R4\n"
},
{
"answer_id": 74529044,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 3,
"selected": true,
"text": "awk awk -F ' *: *' '$1 == \"Bayesian Information Criterion\" {print $2}' file\n\nVT+F+R4\n\n# to save this in a variable:\nmyvar=$(awk -F ' *: *' '$1 == \"Bayesian Information Criterion\" {print $2}' file)\n gnu-grep \\K grep -oP 'Bayesian Information Criterion:\\h*\\K.+' file\n\nVT+F+R4\n sed sed -n 's/Bayesian Information Criterion: *//p' file\n\nVT+F+R4\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12306627/"
] |
74,529,042
|
<p>Create list with all possible combinations from another list in R</p>
<p>Ive seen people ask this question but only found threads with answers for other software and not I R</p>
<p>Basically I just want to create a list with all unique combinations possible</p>
<p>Desired input</p>
<pre><code>a, b, c
</code></pre>
<p>desired output</p>
<pre><code>a, ab, ac, b, bc, c, abc
</code></pre>
|
[
{
"answer_id": 74529041,
"author": "Chen A.",
"author_id": 840582,
"author_profile": "https://Stackoverflow.com/users/840582",
"pm_score": 1,
"selected": false,
"text": "awk awk '{ print $4 }' ➜ echo 'Bayesian Information Criterion: VT+F+R4' | awk '{ print $4 }'\nVT+F+R4\n"
},
{
"answer_id": 74529044,
"author": "anubhava",
"author_id": 548225,
"author_profile": "https://Stackoverflow.com/users/548225",
"pm_score": 3,
"selected": true,
"text": "awk awk -F ' *: *' '$1 == \"Bayesian Information Criterion\" {print $2}' file\n\nVT+F+R4\n\n# to save this in a variable:\nmyvar=$(awk -F ' *: *' '$1 == \"Bayesian Information Criterion\" {print $2}' file)\n gnu-grep \\K grep -oP 'Bayesian Information Criterion:\\h*\\K.+' file\n\nVT+F+R4\n sed sed -n 's/Bayesian Information Criterion: *//p' file\n\nVT+F+R4\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18564314/"
] |
74,529,108
|
<h2>Background</h2>
<p>I have a piece of cdk code that runs in a function. Each time through it creates a cloud front distribution. I want one instance to have a different value of behavior. This seems like a very simple thing, but I always get the error below that I do not understand.</p>
<h2>Code</h2>
<pre class="lang-js prettyprint-override"><code> // 1. Default:
let behavior: cloudfront.Behavior = {isDefaultBehavior: true};
// Lambda Edge / Cloudfront Function Authentication...
if (subDomain == "monkey-ops") {
// 2. Cloudfront Function.
const cfFunct = new cloudfront.Function(this, 'id', {
functionName: 'http-auth-ops',
comment: 'http-auth for monkey-ops.monkeytronics.co.nz static site',
code: cloudfront.FunctionCode.fromFile({filePath: __dirname + '\\http-auth-ops-cf.js'})
});
behavior = {
isDefaultBehavior: false,
functionAssociations: [{
eventType: cloudfront.FunctionEventType.VIEWER_REQUEST,
function: cfFunct
}]
};
// behavior = {isDefaultBehavior: true};
} else {
behavior = {isDefaultBehavior: true};
}
let cloudFrontDistribution = new cloudfront.CloudFrontWebDistribution(this, subDomain + 'Distribution', {
originConfigs: [
{
customOriginSource: {
domainName: s3Bucket.bucketWebsiteDomainName,
originProtocolPolicy: cloudfront.OriginProtocolPolicy.HTTP_ONLY,
},
// behaviors : [ {isDefaultBehavior: true} ],
behaviors : [ behavior ],
}
],
viewerCertificate: cloudfront.ViewerCertificate.fromAcmCertificate(
tslCert,
{
aliases: [ subDomain + '.monkeytronics.co.nz' ],
// securityPolicy: cloudfront.SecurityPolicyProtocol.SSL_V3, // default
securityPolicy: cloudfront.SecurityPolicyProtocol.TLS_V1_2_2021,
sslMethod: cloudfront.SSLMethod.SNI, // default
},
),
});
</code></pre>
<h2>Error</h2>
<p>Gives the following error, which I can't unpick...</p>
<pre><code> Error: There can only be one default behavior across all sources. [ One default behavior per distribution ].
at new CloudFrontWebDistribution (D:\MonkeySource\2-Cloud\cdk_stacks\node_modules\aws-cdk-lib\aws-cloudfront\lib\web-distribution.js:1:6631)
at new StaticSite (D:\MonkeySource\2-Cloud\cdk_stacks\lib\factory\static-site\static-site-factory.ts:120:42)
at new SnWebStack (D:\MonkeySource\2-Cloud\cdk_stacks\lib\sn-web-stack.ts:57:7)
at Object.<anonymous> (D:\MonkeySource\2-Cloud\cdk_stacks\bin\cdk.ts:19:1)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Module.m._compile (D:\MonkeySource\2-Cloud\cdk_stacks\node_modules\ts-node\src\index.ts:1056:23)
at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Object.require.extensions.<computed> [as .ts] (D:\MonkeySource\2-Cloud\cdk_stacks\node_modules\ts-node\src\index.ts:1059:12)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
Subprocess exited with error 1
</code></pre>
|
[
{
"answer_id": 74547977,
"author": "Andrew Gillis",
"author_id": 7211548,
"author_profile": "https://Stackoverflow.com/users/7211548",
"pm_score": 2,
"selected": true,
"text": "{\n isDefaultBehavior: true, // <-- This needs to be true for one behavior\n functionAssociations: [{\n eventType: cloudfront.FunctionEventType.VIEWER_REQUEST,\n function: cfFunct\n }] \n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9115897/"
] |
74,529,159
|
<p>the question is exactly same as <a href="https://stackoverflow.com/questions/73247684/row-have-title-centered-but-other-widget-on-the-right">this post</a></p>
<p>but I did not find an answer from the post.</p>
<p>my goal is to set the title widget in the center <br>
<a href="https://i.stack.imgur.com/EudcL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EudcL.png" alt="enter image description here" /></a></p>
<p>and other two buttons on the right side.
the solutions in the link all put the title widget slightly on the left side.</p>
<p>does anyone know how to do this without using Stack? I'm afraid of the title widget being over the button widgets when the title gets too long.</p>
<p>the code:</p>
<pre><code>SizedBox(
height: 40,
width: MediaQuery.of(context).size.width,
child: Row(
children: [
const SizedBox(width: 17),
Text(
'TITLE',
style: const TextStyle(
color: Colors.white, fontSize: 30, fontWeight: FontWeight.w500),
),
Spacer(),
Row(
children: [
GestureDetector(
onTap: (){null;},
child: SizedBox(
child: Icon(Icons.wallet_membership, color: Colors.white),
),
),
const SizedBox(width: 17),
GestureDetector(
onTap: (){Get.toNamed('/wallet_setting');},
child: const SizedBox(
child: Icon(Icons.settings, color: Colors.white),
),
),
]
)
]
),
)
</code></pre>
|
[
{
"answer_id": 74547977,
"author": "Andrew Gillis",
"author_id": 7211548,
"author_profile": "https://Stackoverflow.com/users/7211548",
"pm_score": 2,
"selected": true,
"text": "{\n isDefaultBehavior: true, // <-- This needs to be true for one behavior\n functionAssociations: [{\n eventType: cloudfront.FunctionEventType.VIEWER_REQUEST,\n function: cfFunct\n }] \n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15661607/"
] |
74,529,223
|
<p>What I am looking for is to put for each ID the most current description (as long as it is not an empty cell, and if it’s is empty, it should be the first non-empty description). I have sorted the DF by ID and by Date, so for each ID "group", the first description is the most current.</p>
<p>The problem comes when I have to take that description and replace it in the rest of the rows of the same ID. The process with a FOR loop takes me more than 30 minutes, so I need a much more efficient solution.</p>
<p>So far, my procedure has been:</p>
<ul>
<li>list unique IDs</li>
<li>Iterate with a loop for those IDs, and with a '.loc' take out the description field:</li>
<li>If the most recent description is null, I put an <code>if</code> to catch the second description field</li>
</ul>
<pre class="lang-py prettyprint-override"><code>for id in list(df.columnaid.unique()):
if df.loc[(df.columnaid == id).description.unique()[0] != "":
description = df.loc[(df.columnaid == id).description.unique()[0]
elif df.loc[(df.columnaid == id).description.unique()[0] == "" and len(df.loc[(df.columnaid == id).description.unique()) >1:
description = df.loc[(df.columnaid == id).description.unique()[1]
</code></pre>
<ul>
<li>Save the ID product and the description in a dictionary:</li>
</ul>
<pre><code>dicc[id] = dicc.get(id, description)
</code></pre>
<p>Then, with a<code>.loc</code>, an <code>.isin</code> and a <code>map</code> I replace the values obtained in the description column
This procedure Works, but it’s not optimal at all, and I need to know how could it be done a better way without taking more than 30 min.</p>
<pre><code>df.loc[df['columnaid'].isin(dicc.keys()), 'description'] = df['columnaid'].map(dicc)
</code></pre>
<p>An example of the DataFrame (it would be the same but with millions of rows) is:</p>
<pre><code>df = pd.DataFrame({"columnaid": ["2321fdsf", "2321fdsf", "3gsdfer3", "4gdsfg44", "4gdsfg44", "4gdsfg44", "7fg45d"],
"date": ["2022-11-16","2022-10-07","2022-09-02","2021-12-04","2021-09-23","2021-03-06","2021-03-15"],
"description": ["aaa", "bbb", "abc", "eee", "", "aqwert", "yuiop"],
})
columnaid date description
0 2321fdsf 2022-11-16 aaa
1 2321fdsf 2022-10-07 bbb
2 3gsdfer3 2022-09-02 abc
3 4gdsfg44 2021-12-04 eee
4 4gdsfg44 2021-09-23
5 4gdsfg44 2021-03-06 aqwert
6 7fg45d 2021-03-15 yuiop
</code></pre>
<p>The outcome should be:</p>
<pre><code> columnaid date description
0 2321fdsf 2022-11-16 aaa
1 2321fdsf 2022-10-07 aaa
2 3gsdfer3 2022-09-02 abc
3 4gdsfg44 2021-12-04 eee
4 4gdsfg44 2021-09-23 eee
5 4gdsfg44 2021-03-15 eee
6 7fg45d 2021-03-06 yuiop
</code></pre>
<p>Thank you</p>
<pre><code></code></pre>
|
[
{
"answer_id": 74529296,
"author": "AKX",
"author_id": 51685,
"author_profile": "https://Stackoverflow.com/users/51685",
"pm_score": 1,
"selected": false,
"text": "groupby import pandas as pd\n\ndf = pd.DataFrame(\n {\n \"columnaid\": [\"2321fdsf\", \"2321fdsf\", \"3gsdfer3\", \"4gdsfg44\", \"4gdsfg44\", \"4gdsfg44\", \"7fg45d\"],\n \"date\": [\"2022-11-16\", \"2022-10-07\", \"2022-09-02\", \"2021-12-04\", \"2021-09-23\", \"2021-03-06\", \"2021-03-15\"],\n \"description\": [\"aaa\", \"bbb\", \"abc\", \"eee\", \"\", \"aqwert\", \"yuiop\"],\n }\n)\n\n# Convert date so we can `idxmax` it\ndf[\"date\"] = pd.to_datetime(df[\"date\"])\n\n# Find newest descriptions per columnaid into an indexed series\nnewest_descriptions = df.groupby(\"columnaid\").apply(lambda x: x.loc[x[\"date\"].idxmax(), \"description\"])\n# (Print for debugging)\nprint(newest_descriptions)\n\n# Map the descriptions back into the original df\ndf[\"description\"] = df[\"columnaid\"].map(newest_descriptions)\n\nprint(df)\n columnaid\n2321fdsf aaa\n3gsdfer3 abc\n4gdsfg44 eee\n7fg45d yuiop\ndtype: object\n\n columnaid date description\n0 2321fdsf 2022-11-16 aaa\n1 2321fdsf 2022-10-07 aaa\n2 3gsdfer3 2022-09-02 abc\n3 4gdsfg44 2021-12-04 eee\n4 4gdsfg44 2021-09-23 eee\n5 4gdsfg44 2021-03-06 eee\n6 7fg45d 2021-03-15 yuiop\n"
},
{
"answer_id": 74529540,
"author": "PTQuoc",
"author_id": 11850322,
"author_profile": "https://Stackoverflow.com/users/11850322",
"pm_score": 1,
"selected": false,
"text": "#drop n/a\ndfn = df.dropna(subset=['description']).copy()\n\n#now you have a clean `dfn` simply sort then pickup the 1st observation in each group\nuniq = dfn.groupby('colummaid')['description'].first().reset_index('first_obs')\n\n#now you can merge uniq back to df\ndf = pd.merge(df, uniq, how='left', on='columnaid')\n first_obs"
},
{
"answer_id": 74537495,
"author": "Esteban",
"author_id": 20567414,
"author_profile": "https://Stackoverflow.com/users/20567414",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({\"columnid\": [\"2321fdsf\", \"2321fdsf\", \"3gsdfer3\", \"4gdsfg44\", \"4gdsfg44\", \"4gdsfg44\", \"7fg45d\", \"7fg45d\"],\n \"date\": [\"2022-11-16\",\"2022-10-07\",\"2022-09-02\",\"2021-12-04\",\"2021-09-23\",\"2021-03-06\", \"2022-05-13\",\"2021-03-15\"],\n \"description\": [\"aaa\", \"bbb\", \"abc\", \"eee\", \"\", \"aqwert\", \"\", \"yuiop\"],\n })\n\ndf[\"description\"] = df[\"description\"].replace(\"\", np.nan)\n\ndf[\"description\"] = df.groupby(by = \"columnid\")['description'].transform('first')\ndf\n columnid date description\n0 2321fdsf 2022-11-16 aaa\n1 2321fdsf 2022-10-07 aaa\n2 3gsdfer3 2022-09-02 abc\n3 4gdsfg44 2021-12-04 eee\n4 4gdsfg44 2021-09-23 eee\n5 4gdsfg44 2021-03-06 eee\n6 7fg45d 2022-05-13 yuiop\n7 7fg45d 2021-03-15 yuiop\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20567414/"
] |
74,529,236
|
<p>hello I want have to run two functions(Function1() and Function2()) and store value of these returns and run third function. But some time according to condition Function1() or Function2() or both not be run.</p>
<pre><code>if(condition1){
await Function1();
}
if(condition2){
await Function2();
}
await Functon3();
</code></pre>
<p>I try as above but Function3() run simultaneously with Function1() or with Function2().</p>
<p>My Function1() code looks like following...</p>
<pre><code> Future Function1() async {
apiService
.apiFileUpload()
.then((value) async {
///codes goes here
}).catchError((error) {
print('EEEE: ' + error.toString());
});
}
</code></pre>
<p>If anything not clear please let me know in the comment section.</p>
|
[
{
"answer_id": 74529296,
"author": "AKX",
"author_id": 51685,
"author_profile": "https://Stackoverflow.com/users/51685",
"pm_score": 1,
"selected": false,
"text": "groupby import pandas as pd\n\ndf = pd.DataFrame(\n {\n \"columnaid\": [\"2321fdsf\", \"2321fdsf\", \"3gsdfer3\", \"4gdsfg44\", \"4gdsfg44\", \"4gdsfg44\", \"7fg45d\"],\n \"date\": [\"2022-11-16\", \"2022-10-07\", \"2022-09-02\", \"2021-12-04\", \"2021-09-23\", \"2021-03-06\", \"2021-03-15\"],\n \"description\": [\"aaa\", \"bbb\", \"abc\", \"eee\", \"\", \"aqwert\", \"yuiop\"],\n }\n)\n\n# Convert date so we can `idxmax` it\ndf[\"date\"] = pd.to_datetime(df[\"date\"])\n\n# Find newest descriptions per columnaid into an indexed series\nnewest_descriptions = df.groupby(\"columnaid\").apply(lambda x: x.loc[x[\"date\"].idxmax(), \"description\"])\n# (Print for debugging)\nprint(newest_descriptions)\n\n# Map the descriptions back into the original df\ndf[\"description\"] = df[\"columnaid\"].map(newest_descriptions)\n\nprint(df)\n columnaid\n2321fdsf aaa\n3gsdfer3 abc\n4gdsfg44 eee\n7fg45d yuiop\ndtype: object\n\n columnaid date description\n0 2321fdsf 2022-11-16 aaa\n1 2321fdsf 2022-10-07 aaa\n2 3gsdfer3 2022-09-02 abc\n3 4gdsfg44 2021-12-04 eee\n4 4gdsfg44 2021-09-23 eee\n5 4gdsfg44 2021-03-06 eee\n6 7fg45d 2021-03-15 yuiop\n"
},
{
"answer_id": 74529540,
"author": "PTQuoc",
"author_id": 11850322,
"author_profile": "https://Stackoverflow.com/users/11850322",
"pm_score": 1,
"selected": false,
"text": "#drop n/a\ndfn = df.dropna(subset=['description']).copy()\n\n#now you have a clean `dfn` simply sort then pickup the 1st observation in each group\nuniq = dfn.groupby('colummaid')['description'].first().reset_index('first_obs')\n\n#now you can merge uniq back to df\ndf = pd.merge(df, uniq, how='left', on='columnaid')\n first_obs"
},
{
"answer_id": 74537495,
"author": "Esteban",
"author_id": 20567414,
"author_profile": "https://Stackoverflow.com/users/20567414",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({\"columnid\": [\"2321fdsf\", \"2321fdsf\", \"3gsdfer3\", \"4gdsfg44\", \"4gdsfg44\", \"4gdsfg44\", \"7fg45d\", \"7fg45d\"],\n \"date\": [\"2022-11-16\",\"2022-10-07\",\"2022-09-02\",\"2021-12-04\",\"2021-09-23\",\"2021-03-06\", \"2022-05-13\",\"2021-03-15\"],\n \"description\": [\"aaa\", \"bbb\", \"abc\", \"eee\", \"\", \"aqwert\", \"\", \"yuiop\"],\n })\n\ndf[\"description\"] = df[\"description\"].replace(\"\", np.nan)\n\ndf[\"description\"] = df.groupby(by = \"columnid\")['description'].transform('first')\ndf\n columnid date description\n0 2321fdsf 2022-11-16 aaa\n1 2321fdsf 2022-10-07 aaa\n2 3gsdfer3 2022-09-02 abc\n3 4gdsfg44 2021-12-04 eee\n4 4gdsfg44 2021-09-23 eee\n5 4gdsfg44 2021-03-06 eee\n6 7fg45d 2022-05-13 yuiop\n7 7fg45d 2021-03-15 yuiop\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11168442/"
] |
74,529,269
|
<p>I have this table:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>RANK</th>
</tr>
</thead>
<tbody>
<tr>
<td>111</td>
<td>1</td>
</tr>
<tr>
<td>111</td>
<td>2</td>
</tr>
<tr>
<td>111</td>
<td>3</td>
</tr>
<tr>
<td>222</td>
<td>1</td>
</tr>
<tr>
<td>222</td>
<td>2</td>
</tr>
</tbody>
</table>
</div>
<p>I want to add two colums that will show if this is the first/last row for each id</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>first</th>
<th>last</th>
</tr>
</thead>
<tbody>
<tr>
<td>111</td>
<td>YES</td>
<td>NO</td>
</tr>
<tr>
<td>111</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>111</td>
<td>NO</td>
<td>YES</td>
</tr>
<tr>
<td>222</td>
<td>YES</td>
<td>NO</td>
</tr>
<tr>
<td>222</td>
<td>NO</td>
<td>YES</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74529900,
"author": "Littlefoot",
"author_id": 9097906,
"author_profile": "https://Stackoverflow.com/users/9097906",
"pm_score": 0,
"selected": false,
"text": "SQL> with\n 2 test (id, rank) as\n 3 (select 111, 1 from dual union all\n 4 select 111, 2 from dual union all\n 5 select 111, 3 from dual union all\n 6 select 222, 1 from dual union all\n 7 select 222, 2 from dual\n 8 ),\n 9 temp as\n 10 (select id,\n 11 rank,\n 12 first_value(rank) over (partition by id) rnk_min,\n 13 last_value(rank) over (partition by id ) rnk_max\n 14 from test\n 15 )\n 16 select id,\n 17 case when rank = rnk_min then 'Yes' else 'No' end first,\n 18 case when rank = rnk_max then 'Yes' else 'No' end last\n 19 from temp\n 20 order by id, rank;\n\n ID FIRST LAST\n---------- ------- -------\n 111 Yes No\n 111 No No\n 111 No Yes\n 222 Yes No\n 222 No Yes\n\nSQL>\n"
},
{
"answer_id": 74529905,
"author": "Jonas Metzler",
"author_id": 18794826,
"author_profile": "https://Stackoverflow.com/users/18794826",
"pm_score": 1,
"selected": false,
"text": "SELECT id,\nCASE WHEN rn = 1 THEN 'YES' ELSE 'NO' END AS first,\nCASE WHEN rn = COUNT(*) OVER (PARTITION BY id) \nTHEN 'YES' ELSE 'NO' END AS last \nFROM \n(\n SELECT\n id,\n ROW_NUMBER() OVER (PARTITION BY id ORDER BY id) rn\n FROM yourtable\n);\n SELECT id,\nCASE WHEN rn1 = 1 THEN 'YES' ELSE 'NO' END AS first,\nCASE WHEN rn2 = 1 THEN 'YES' ELSE 'NO' END AS last\nFROM \n(\n SELECT\n id,\n ROW_NUMBER() OVER (PARTITION BY id ORDER BY rank) rn1,\n ROW_NUMBER() OVER (PARTITION BY id ORDER BY rank DESC) rn2\n FROM yourtable\n);\n"
},
{
"answer_id": 74530418,
"author": "astentx",
"author_id": 2778710,
"author_profile": "https://Stackoverflow.com/users/2778710",
"pm_score": 0,
"selected": false,
"text": "lag/lead default with sample_tab (id, rank) as (\n select 111, 1 from dual union all\n select 111, 2 from dual union all\n select 111, 3 from dual union all\n select 222, 1 from dual union all\n select 222, 2 from dual\n)\nselect\n id\n , lag('No', 1, 'Yes') over(partition by id order by rank asc) as last\n , lead('No', 1, 'Yes') over(partition by id order by rank asc) as last\nfrom sample_tab\n coalesce with sample_tab (id, rank) as (\n select 111, 1 from dual union all\n select 111, 2 from dual union all\n select 111, 2 from dual union all\n select 222, 1 from dual union all\n select 222, 2 from dual\n)\nselect\n id\n , coalesce(max('No') over(\n partition by id order by rank asc\n /*RANGE for logical offset,\n setting the same flag for a group of first/last rows*/\n range between 1 preceding and 1 preceding\n ), 'Yes') as first\n , coalesce(max('No') over(\n partition by id order by rank asc\n range between 1 following and 1 following\n ), 'Yes') as last\nfrom sample_tab\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13942179/"
] |
74,529,272
|
<p>I have several items listed on a page that can be added to a shopping cart. A Product component is being rendered for each product, and there is a form select as part of each component.</p>
<pre><code> const [qty, setQty] = useState(1);
...
<Form.Control
className="w-100"
as="select"
value={qty}
onChange={(e) => {
setQty(e.target.value);
}}
>
</code></pre>
<p>If I useState this way, every product on the page has its Select Value changed when a change is made to the select because it is derived from the <code>qty</code> variable. Since I don't know how many products will be rendered on each page, how can I write a function that will only update the value of the product within the component being changed?</p>
|
[
{
"answer_id": 74529417,
"author": "Unclebigay",
"author_id": 7953084,
"author_profile": "https://Stackoverflow.com/users/7953084",
"pm_score": -1,
"selected": false,
"text": "useState useState map Product \nimport React, { useState } from \"react\";\n\nconst productFromServer = [\n { id: 1, name: \"Bread\", qty: 0 },\n { id: 2, name: \"Sugar\", qty: 0 },\n { id: 3, name: \"Butter\", qty: 0 },\n { id: 4, name: \"Tea\", qty: 0 },\n];\n\nexport const Product = () => {\n const [products, setProducts] = useState(productFromServer); // or useEffect\n\n const handleQuantityChange = (id, qty) => {\n const updatedProducts = products.map((product) => {\n if (product.id === id) {\n product.qty = qty; // update the quantity of the product\n return product;\n }\n return product;\n });\n setProducts(updatedProducts); // update the product state\n };\n\n console.log(products);\n\n return (\n <>\n <h1>Product Page</h1>\n <div className='product-container'>\n {products?.map(({ id, name, qty }) => {\n return (\n <div key={id} className='product-card'>\n <h2>{name}</h2>\n <p>Quantity: {qty}</p>\n <QtySelect\n id={id}\n qty={qty}\n handleQuantityChange={handleQuantityChange}\n />\n </div>\n );\n })}\n </div>\n </>\n );\n};\n QtySelect const QtySelect = ({ id, qty, handleQuantityChange }) => {\n return (\n <select\n className='w-100'\n value={qty}\n onChange={(e) => {\n handleQuantityChange(id, Number(e.target.value));\n }}\n >\n <option value={1}>1</option>\n <option value={2}>2</option>\n </select>\n );\n};\n"
},
{
"answer_id": 74529999,
"author": "rastawolf",
"author_id": 3085213,
"author_profile": "https://Stackoverflow.com/users/3085213",
"pm_score": 0,
"selected": false,
"text": "setState const [qty, setQty] = useState({ int: 1 })...\n\n <Form.Control\n className=\"w-100\"\n as=\"select\"\n value={item._id in qty ? qty[item.id] : qty.int}\n onChange={(e) => {\n setQty({ ...qty, [item._id]: e.target.value });\n }}\n >\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3085213/"
] |
74,529,284
|
<p>I want to pass in ARRAYFORMULA into the QUERY so that I can get the sum without splitting the two functions apart.</p>
<p>I want to do this but getting an error ("unable to parse query string for function query parameter"):</p>
<pre><code>=QUERY(ARRAYFORMULA(SPLIT(O5:O7, " to ")),"select sum(O),sum(P)")
</code></pre>
<p><strong>Example:</strong></p>
<p>This is the input:</p>
<pre><code>1.080 to 3.240
0.771 to 2.312
0.721 to 2.164
</code></pre>
<p>Above input is pass in as <strong>O5:O7</strong>. Using this function, it will split into 2 columns and extract the number:</p>
<pre><code>=ARRAYFORMULA(SPLIT(O5:O7, " to ")
</code></pre>
<p>As result, shown as following:</p>
<pre><code>1.08 3.24
0.771 2.312
0.721 2.164
</code></pre>
<p>The above result will be pass into as <strong>O18:P20</strong>. This function will give the sum of each columns:</p>
<pre><code>=QUERY(O18:P20,"select sum(O),sum(P)")
</code></pre>
<p>Result as the following:</p>
<pre><code>sum sum
2.572 7.716
</code></pre>
<p>Could I pass in the arrayformula's result into the query?</p>
|
[
{
"answer_id": 74530244,
"author": "Harun24hr",
"author_id": 5514747,
"author_profile": "https://Stackoverflow.com/users/5514747",
"pm_score": 2,
"selected": true,
"text": "BYCOL() =BYCOL(INDEX(SPLIT(P5:P7,\" to \")),LAMBDA(x,SUM(x)))\n QUERY() =QUERY(INDEX(SPLIT(P5:P7,\" to \")),\"select sum(Col1),sum(Col2)\")\n"
},
{
"answer_id": 74533036,
"author": "player0",
"author_id": 5632629,
"author_profile": "https://Stackoverflow.com/users/5632629",
"pm_score": 0,
"selected": false,
"text": "=ARRAYFORMULA(QUERY(SPLIT(O5:O7, \" to \"), \"select sum(Col1),sum(Col2)\"))\n =INDEX(QUERY(SPLIT(O5:O7, \" to \"), \"select sum(Col1),sum(Col2)\"), 2)\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7362037/"
] |
74,529,319
|
<p>I'm a couple days into learning Flutter, and I keep running into a situation where I want to scale a collection of widgets (aka a <code>Row</code>, <code>Column</code>, <code>Stack</code>, etc) down when the screen shrinks, akin to what <code>Flexible()</code> does. Except unlike <code>Flexible()</code>, I want <em>all</em> children to scale down when the container shrinks, not just the largest elements. Consider this example of a <code>Column()</code> (green) with two children: a red child matching its parent's width, and a blue child with half the parent's width:</p>
<p><a href="https://i.stack.imgur.com/mhpwK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mhpwK.png" alt="enter image description here" /></a></p>
<p>In the above case, if the green <code>Column()</code> were to be constrained such that its width was less, you would end up with something like such:</p>
<p><a href="https://i.stack.imgur.com/lU2Gj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lU2Gj.png" alt="enter image description here" /></a></p>
<p>However, what I am wanting is for each of the child elements (red/blue) to scale their width/height relative to each other, like this:</p>
<p><a href="https://i.stack.imgur.com/8W0TO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8W0TO.png" alt="enter image description here" /></a></p>
<p>How can I accomplish this?</p>
<p>In the specific <code>Column()</code> case I illustrated above, my workaround was to add a <code>Row()</code> containing the blue widget as well as a <code>Padding()</code>, both with equal flex properties, so that when the <code>Column()</code> shrunk the blue element scaled correctly. I feel like this is a hack though, and wouldn't be as feasible if I had many elements with differing widths/alignments. It would be a nightmare to add one <code>Padding()</code> for left/right aligned elements and two for centered ones. Is there a better way?</p>
<p>I'd also like to know of a similar solution for using <code>Stack()</code>s. Using the <code>Positional()</code> element seems to set the width/height in a way that the <code>Stack()</code> crops any overflow. It'd be nice to have a <code>Stack()</code> that scales all its children the same, just like if it was a single image, and similar to my <code>Column()</code> example above.</p>
|
[
{
"answer_id": 74529720,
"author": "baek",
"author_id": 1049200,
"author_profile": "https://Stackoverflow.com/users/1049200",
"pm_score": 1,
"selected": false,
"text": " Flexible(\n child: FractionallySizedBox(\n widthFactor: 0.5,\n heightFactor: 0.5,\n alignment: FractionalOffset.centerLeft,\n child: Container(\n color: Colors.blue),\n ),\n ),\n"
},
{
"answer_id": 74529765,
"author": "Tasnuva Tavasum oshin",
"author_id": 8480069,
"author_profile": "https://Stackoverflow.com/users/8480069",
"pm_score": 3,
"selected": true,
"text": "import 'package:flutter/material.dart';\n\nvoid main() => runApp(const MyApp());\n\nclass MyApp extends StatelessWidget {\n const MyApp({super.key});\n\n static const String _title = 'Flutter Code Sample';\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n title: _title,\n home: Scaffold(\n appBar: AppBar(title: const Text(_title)),\n body: const MyStatelessWidget(),\n ),\n );\n }\n}\n\nclass MyStatelessWidget extends StatelessWidget {\n const MyStatelessWidget({super.key});\n\n @override\n Widget build(BuildContext context) {\n return SizedBox.expand(\n child: FractionallySizedBox(\n widthFactor: 0.5,\n heightFactor: 0.5,\n alignment: FractionalOffset.center,\n child: DecoratedBox(\n decoration: BoxDecoration(\n border: Border.all(\n color: Colors.blue,\n width: 4,\n ),\n ),\n ),\n ),\n );\n }\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20027466/"
] |
74,529,345
|
<p>How can I test in Cypress that the background image I get is working and the image is loaded properly in the preview?
<a href="https://i.stack.imgur.com/E0C6k.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E0C6k.jpg" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74529720,
"author": "baek",
"author_id": 1049200,
"author_profile": "https://Stackoverflow.com/users/1049200",
"pm_score": 1,
"selected": false,
"text": " Flexible(\n child: FractionallySizedBox(\n widthFactor: 0.5,\n heightFactor: 0.5,\n alignment: FractionalOffset.centerLeft,\n child: Container(\n color: Colors.blue),\n ),\n ),\n"
},
{
"answer_id": 74529765,
"author": "Tasnuva Tavasum oshin",
"author_id": 8480069,
"author_profile": "https://Stackoverflow.com/users/8480069",
"pm_score": 3,
"selected": true,
"text": "import 'package:flutter/material.dart';\n\nvoid main() => runApp(const MyApp());\n\nclass MyApp extends StatelessWidget {\n const MyApp({super.key});\n\n static const String _title = 'Flutter Code Sample';\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n title: _title,\n home: Scaffold(\n appBar: AppBar(title: const Text(_title)),\n body: const MyStatelessWidget(),\n ),\n );\n }\n}\n\nclass MyStatelessWidget extends StatelessWidget {\n const MyStatelessWidget({super.key});\n\n @override\n Widget build(BuildContext context) {\n return SizedBox.expand(\n child: FractionallySizedBox(\n widthFactor: 0.5,\n heightFactor: 0.5,\n alignment: FractionalOffset.center,\n child: DecoratedBox(\n decoration: BoxDecoration(\n border: Border.all(\n color: Colors.blue,\n width: 4,\n ),\n ),\n ),\n ),\n );\n }\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12024752/"
] |
74,529,367
|
<p>I'm quite new to SQL and i have issues with a query i find quite complex.</p>
<p>So i'm trying to create a query that shows a 17 month date interval.
In that interval it has to show the what the current month and current date is.
Then it has to compare that date with the months before current date.</p>
<p>I'll then use the data i get in a Highcharts chart.</p>
<p>This is what my current query and table looks like.</p>
<pre><code>SELECT
MONTH(s_order_main.added_date) AS iMonth,
s_order_main.channel AS strChannel,
COUNT(DISTINCT s_order_styles.s_order_style_id) AS iOrderCount,
SUM(DISTINCT s_order_styles.sales_price) AS fTurnover
FROM
s_order_main
INNER JOIN
s_order_styles ON
s_order_styles.s_order_main_id = s_order_main.id
WHERE
s_order_main.channel
&& s_order_main.order_type = 'pre'
&& YEAR(s_order_main.added_date) = YEAR(CURDATE() - INTERVAL 17 MONTH)
GROUP BY
MONTH(s_order_main.added_date)
;
</code></pre>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>iMonth</th>
<th>strChannel</th>
<th>iOrderCount</th>
<th>fTurnover</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>normal</td>
<td>2234</td>
<td>33048.66</td>
</tr>
<tr>
<td>2</td>
<td>normal</td>
<td>6638</td>
<td>66711.96</td>
</tr>
<tr>
<td>3</td>
<td>normal</td>
<td>4266</td>
<td>30742.70</td>
</tr>
<tr>
<td>4</td>
<td>normal</td>
<td>171</td>
<td>766.10</td>
</tr>
<tr>
<td>5</td>
<td>normal</td>
<td>90</td>
<td>926.55</td>
</tr>
<tr>
<td>6</td>
<td>normal</td>
<td>1254</td>
<td>12334.04</td>
</tr>
<tr>
<td>7</td>
<td>normal</td>
<td>921</td>
<td>2990.35</td>
</tr>
<tr>
<td>8</td>
<td>normal</td>
<td>9469</td>
<td>46407.63</td>
</tr>
<tr>
<td>9</td>
<td>normal</td>
<td>5837</td>
<td>31623.17</td>
</tr>
<tr>
<td>10</td>
<td>normal</td>
<td>70</td>
<td>305.03</td>
</tr>
<tr>
<td>11</td>
<td>normal</td>
<td>323</td>
<td>2726.99</td>
</tr>
<tr>
<td>12</td>
<td>normal</td>
<td>370</td>
<td>6693.94</td>
</tr>
</tbody>
</table>
</div>
<p>This is what i want my table to look like - Not sure if current month is supposed to look like that though.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>iMonth</th>
<th>strChannel</th>
<th>iOrderCount</th>
<th>fTurnover</th>
<th>iCurrentMonth</th>
<th>strCurrentDate</th>
</tr>
</thead>
<tbody>
<tr>
<td>12</td>
<td>normal</td>
<td>2234</td>
<td>33048.66</td>
<td>0</td>
<td>2021-12-22 13:54:09</td>
</tr>
<tr>
<td>1</td>
<td>normal</td>
<td>2234</td>
<td>33048.66</td>
<td>0</td>
<td>2022-01-22 13:54:09</td>
</tr>
<tr>
<td>2</td>
<td>normal</td>
<td>6638</td>
<td>66711.96</td>
<td>0</td>
<td>2022-02-22 13:54:09</td>
</tr>
<tr>
<td>3</td>
<td>normal</td>
<td>4266</td>
<td>30742.70</td>
<td>0</td>
<td>2022-03-22 13:54:09</td>
</tr>
<tr>
<td>4</td>
<td>normal</td>
<td>171</td>
<td>766.10</td>
<td>0</td>
<td>2022-04-22 13:54:09</td>
</tr>
<tr>
<td>5</td>
<td>normal</td>
<td>90</td>
<td>926.55</td>
<td>0</td>
<td>2022-05-22 13:54:09</td>
</tr>
<tr>
<td>6</td>
<td>normal</td>
<td>1254</td>
<td>12334.04</td>
<td>0</td>
<td>2022-06-22 13:54:09</td>
</tr>
<tr>
<td>7</td>
<td>normal</td>
<td>921</td>
<td>2990.35</td>
<td>0</td>
<td>2022-07-22 13:54:09</td>
</tr>
<tr>
<td>8</td>
<td>normal</td>
<td>9469</td>
<td>46407.63</td>
<td>0</td>
<td>2022-08-22 13:54:09</td>
</tr>
<tr>
<td>9</td>
<td>normal</td>
<td>5837</td>
<td>31623.17</td>
<td>0</td>
<td>2022-09-22 13:54:09</td>
</tr>
<tr>
<td>10</td>
<td>normal</td>
<td>70</td>
<td>305.03</td>
<td>0</td>
<td>2022-10-22 13:54:09</td>
</tr>
<tr>
<td>11</td>
<td>normal</td>
<td>323</td>
<td>2726.99</td>
<td>1</td>
<td>2022-10-22 13:54:09</td>
</tr>
<tr>
<td>12</td>
<td>normal</td>
<td>370</td>
<td>6693.94</td>
<td>0</td>
<td>2022-12-22 13:54:09</td>
</tr>
<tr>
<td>1</td>
<td>b2b</td>
<td>370</td>
<td>6693.94</td>
<td>0</td>
<td>2023-01-22 13:54:09</td>
</tr>
<tr>
<td>2</td>
<td>normal</td>
<td>370</td>
<td>6693.94</td>
<td>0</td>
<td>2023-02-22 13:54:09</td>
</tr>
<tr>
<td>3</td>
<td>b2b</td>
<td>370</td>
<td>6693.94</td>
<td>0</td>
<td>2023-03-22 13:54:09</td>
</tr>
<tr>
<td>4</td>
<td>normal</td>
<td>370</td>
<td>6693.94</td>
<td>0</td>
<td>2023-04-22 13:54:09</td>
</tr>
</tbody>
</table>
</div>
<p>Hope it makes sense, but if i need to elaborate something then please ask :)</p>
|
[
{
"answer_id": 74529720,
"author": "baek",
"author_id": 1049200,
"author_profile": "https://Stackoverflow.com/users/1049200",
"pm_score": 1,
"selected": false,
"text": " Flexible(\n child: FractionallySizedBox(\n widthFactor: 0.5,\n heightFactor: 0.5,\n alignment: FractionalOffset.centerLeft,\n child: Container(\n color: Colors.blue),\n ),\n ),\n"
},
{
"answer_id": 74529765,
"author": "Tasnuva Tavasum oshin",
"author_id": 8480069,
"author_profile": "https://Stackoverflow.com/users/8480069",
"pm_score": 3,
"selected": true,
"text": "import 'package:flutter/material.dart';\n\nvoid main() => runApp(const MyApp());\n\nclass MyApp extends StatelessWidget {\n const MyApp({super.key});\n\n static const String _title = 'Flutter Code Sample';\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n title: _title,\n home: Scaffold(\n appBar: AppBar(title: const Text(_title)),\n body: const MyStatelessWidget(),\n ),\n );\n }\n}\n\nclass MyStatelessWidget extends StatelessWidget {\n const MyStatelessWidget({super.key});\n\n @override\n Widget build(BuildContext context) {\n return SizedBox.expand(\n child: FractionallySizedBox(\n widthFactor: 0.5,\n heightFactor: 0.5,\n alignment: FractionalOffset.center,\n child: DecoratedBox(\n decoration: BoxDecoration(\n border: Border.all(\n color: Colors.blue,\n width: 4,\n ),\n ),\n ),\n ),\n );\n }\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20569918/"
] |
74,529,378
|
<p>I've updated antd to 5.0.0. I've these imports which are giving error now.</p>
<pre><code>@import '~antd/es/style/themes/default.less';
@import '~antd/dist/antd.less';
</code></pre>
<p>what should I replace with in new versions?</p>
|
[
{
"answer_id": 74529419,
"author": "Mohammed Shahed",
"author_id": 19067773,
"author_profile": "https://Stackoverflow.com/users/19067773",
"pm_score": 0,
"selected": false,
"text": "App.js import 'antd/dist/reset.css';"
},
{
"answer_id": 74529656,
"author": "Michael An",
"author_id": 14245047,
"author_profile": "https://Stackoverflow.com/users/14245047",
"pm_score": 3,
"selected": true,
"text": "antd/dist/antd.css import antd/dist/reset.css"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2067264/"
] |
74,529,412
|
<p>I need to get the current working week from our current day.
Example:</p>
<p>22.11.2022(Tuesday) should return me the dates
from 21.11.2022(Monday) - 26.11.2022(Saturday)</p>
<p>27.11.2022(Sunday) should return me the next week:
28.11.2022(Monday) - 03.12.2022(Saturday).</p>
<p>I found this stack overflow question, but in Java(Don't really understand, how to translate it to c#): <a href="https://stackoverflow.com/questions/8321537/how-to-find-nearest-week-day-for-an-arbitrary-date">How to find nearest week day for an arbitrary date?</a></p>
|
[
{
"answer_id": 74529419,
"author": "Mohammed Shahed",
"author_id": 19067773,
"author_profile": "https://Stackoverflow.com/users/19067773",
"pm_score": 0,
"selected": false,
"text": "App.js import 'antd/dist/reset.css';"
},
{
"answer_id": 74529656,
"author": "Michael An",
"author_id": 14245047,
"author_profile": "https://Stackoverflow.com/users/14245047",
"pm_score": 3,
"selected": true,
"text": "antd/dist/antd.css import antd/dist/reset.css"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15951473/"
] |
74,529,436
|
<p>I am using Mui v5 components in my project and currently I am using sx props for styling all the MUI components but putting sx in every line for each components is not looking good. So, I wanted to know is there any other way of styling or applying custom classes to each and every component like we do in styled-components library. I also know about styled from MUI but that is used for making reusable components but i want to use something which will help me in preparing styles which i can apply to any components.</p>
<p>Below is my code example.</p>
<pre><code> const theme = useTheme();
return (
<Box sx={{ border: '1px solid red', flex: 'auto', paddingLeft: '8px' }}>
<Box
sx={{
width: '100%',
height: '46px',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
background: theme.palette['P-10'],
padding: '8px 24px'
}}
>
</Box>
<Box sx={{ border: '1px solid green' }}>{AreaChartComp}</Box>
</Box>
);
};
If you see there i had to use sx 3 times, which do not want, instead am looking of other way where i can pass classes.
</code></pre>
|
[
{
"answer_id": 74530788,
"author": "Carl",
"author_id": 10295430,
"author_profile": "https://Stackoverflow.com/users/10295430",
"pm_score": 1,
"selected": false,
"text": "const styles = {\n title: {\n color: 'blue',\n },\n description: {\n color: 'red',\n },\n content: {\n fontStyle: 'italic',\n textDecoration: 'underline',\n },\n button: {\n '&:hover': {\n fontWeight: 'bold',\n },\n}\n};\n return (\n <div className=\"App\">\n <Paper>\n <Typography sx={styles.title} variant=\"h3\">Hello World</Typography>\n <Typography sx={styles.description} variant=\"h5\">This is a description</Typography>\n <Typography sx={{...styles.content, color: 'green'}} variant=\"body1\">\n Lorem ipsum dolor sit amet\n </Typography>\n <Button sx={styles.button} variant=\"contained\">The Button</Button>\n </Paper>\n </div>\n);\n"
},
{
"answer_id": 74531402,
"author": "Serwa_srp",
"author_id": 20241546,
"author_profile": "https://Stackoverflow.com/users/20241546",
"pm_score": 0,
"selected": false,
"text": "import { makeStyles } from '@material-ui/core'\n\nexport default makeStyles((theme) => ({\n Box: {\n width: '100%',\n height: '46px',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'space-between',\n background: theme.palette['P-10'],\n padding: '8px 24px'\n\n }\n }\n )\n ) import useStyle from './index.styles'\n\n const classes = useStyle()\n\n return (\n <Box className={classes.Box} >\n );\n };"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19068559/"
] |
74,529,438
|
<p>dataframe 'df' has the following data -</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
</tr>
</thead>
<tbody>
<tr>
<td>Item_ID1</td>
<td>Information - information for item that has ID as 1\nPrice - $7.99\nPlace - Albany, NY</td>
</tr>
<tr>
<td>Item_ID2</td>
<td>Information - item's information with ID as 2\nPrice - $5.99\nPlace - Ottawa, ON</td>
</tr>
</tbody>
</table>
</div>
<p>How to segregate the values from column B using 'Information', 'Price', and 'Place' into different columns like -</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
<th>Information</th>
<th>Price</th>
<th>Place</th>
</tr>
</thead>
<tbody>
<tr>
<td>Item_ID1</td>
<td>information for item that has ID as 1</td>
<td>$7.99</td>
<td>Albany, NY</td>
</tr>
<tr>
<td>Item_ID2</td>
<td>item's information with ID as 2</td>
<td>$5.99</td>
<td>Ottawa, ON</td>
</tr>
</tbody>
</table>
</div>
<p>I tried splitting the column B based on string values like 'Information - ', 'Price - ', 'Place - ' but that is becoming more complicated and the very first slice has information on Price and Place which is not required in it.</p>
|
[
{
"answer_id": 74529650,
"author": "abokey",
"author_id": 16120011,
"author_profile": "https://Stackoverflow.com/users/16120011",
"pm_score": 2,
"selected": false,
"text": "pandas.Series.split df[[\"Information\", \"Price\", \"Place\"]]= df.pop(\"Column B\").str.split(r\"\\\\n\", expand=True)\n\ndf= df.astype(str).apply(lambda x: x.replace(x.name, \"\", regex=True).str.strip(\" - \"))\n print(df.to_string())\n\n Column A Information Price Place\n0 Item_ID1 information for item that has ID as 1 $7.99 Albany, NY\n1 Item_ID2 item's information with ID as 2 $5.99 Ottawa, ON\n"
},
{
"answer_id": 74529700,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": false,
"text": "str.extractall pivot out = df.drop(columns='Column B').join(\n df['Column B']\n .str.extractall(r'([^-]+) - ([^\\n]+)\\n?')\n .droplevel('match')\n .pivot(columns=0, values=1)\n)\n \\ n df['Column B'] = df['Column B'].str.replace(r'\\\\n', '\\n') Column A Information Place Price\n0 Item_ID1 information for item that has ID as 1 Albany, NY $7.99\n1 Item_ID2 item's information with ID as 2 Ottawa, ON $5.99\n"
},
{
"answer_id": 74531264,
"author": "PaulS",
"author_id": 11564487,
"author_profile": "https://Stackoverflow.com/users/11564487",
"pm_score": 1,
"selected": false,
"text": "Column B \\s-\\s|\\\\n pandas.Series.str.split numpy.reshape pandas.pivot_table (pd.concat([df['Column A'], pd.DataFrame(\n df['Column B'].str.split(r'\\s-\\s|\\\\n', expand=True, regex=True).values\n .reshape((-1,2)))\n .pivot_table(columns=0, values=1, aggfunc=list)\n .pipe(lambda d: d.explode(d.columns.tolist(), ignore_index=True))], axis=1))\n Column A Information Place Price\n0 Item_ID1 information for item that has ID as 1 Albany, NY $7.99\n1 Item_ID2 item's information with ID as 2 Ottawa, ON $5.99\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20262950/"
] |
74,529,477
|
<p>I am using react-hook-form validation for my project. I have a select option, when it change I set the value of selected one to another input which is customer but when I submit the form , customer value show empty, How to fix this issue ?</p>
<p>This is my code</p>
<pre><code>function App() {
const [inputs, setInputs] = useState();
const [inputs1, setInputs1] = useState();
const {
register,
formState: { errors },
trigger,
handleSubmit
} = useForm({
defaultValues: {
searchby: "searchby",
customers: "",
firstName: ""
}
});
const onSubmit = (data) => {
alert(JSON.stringify(data));
};
const handleInputChanges = (event) => {
const name = event.target.name;
const value = event.target.value;
setInputs(value);
setInputs1(value);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<select
name="searchby"
{...register("searchby", {
required: "password is required."
})}
value={inputs}
onChange={handleInputChanges}
>
<option selected value="searchby">
Search By
</option>
<option value="customerID">Custimer ID </option>
<option value="teleco">Teleco</option>
</select>
{errors.searchby && <p>This field is Required</p>}
<label>Customer: </label>
<input
name="customers"
{...register("customers")}
value={inputs1}
onChange={handleInputChanges}
/>
{errors.customers && <p>This field is Required</p>}
<label>First name: </label>
<input {...register("firstName", { required: true })} />
{errors.firstName && <p>This field is Required</p>}
<input type="submit" />
<button
type="button"
>
Validate All
</button>
</form>
);
}
</code></pre>
<p>This is what I am getting when I submit the form</p>
<p><a href="https://i.stack.imgur.com/33Cr7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/33Cr7.png" alt="enter image description here" /></a></p>
<p>Code link : <a href="https://codesandbox.io/s/react-hook-form-7gcizr?file=/src/index.js:0-1865" rel="nofollow noreferrer">codesandbox.io</a></p>
|
[
{
"answer_id": 74529610,
"author": "yermartee",
"author_id": 20567042,
"author_profile": "https://Stackoverflow.com/users/20567042",
"pm_score": 2,
"selected": false,
"text": " <input\n name=\"customers\"\n {...register(\"customers\")} \n/>\n useController register register"
},
{
"answer_id": 74529862,
"author": "marius florescu",
"author_id": 16233425,
"author_profile": "https://Stackoverflow.com/users/16233425",
"pm_score": 2,
"selected": false,
"text": "react-hook-form react-hook-form onChange useForm() const {\n register,\n formState: { errors },\n setValue,\n handleSubmit\n } = useForm({\n defaultValues: {\n searchby: \"searchby\",\n customers: \"\",\n firstName: \"\"\n }\n });\n register() onChange const {onChange, ...rest} = register('searchby', {required: 'Password is required'})\n onSelectChange const handleSelectChange = (e) => {\n onChange(e);\n //change this to any value / logic you want\n setValue('customers', 'SomeValue')\n }\n <select/> <select\n {...rest}\n onChange={handleSelectChange}\n >\n <option selected value=\"searchby\">\n Search By\n </option>\n <option value=\"customerID\">Custimer ID </option>\n <option value=\"teleco\">Teleco</option>\n </select>\n function App() {\n const {\n register,\n formState: { errors },\n setValue,\n handleSubmit\n } = useForm({\n defaultValues: {\n searchby: \"searchby\",\n customers: \"\",\n firstName: \"\"\n }\n });\n\n const {onChange, ...rest} = register('searchby', {required: 'Password is required'})\n\n const handleSelectChange = (e) => {\n onChange(e);\n //change this to any value / logic you want\n setValue('customers', 'SomeValue')\n }\n\n const onSubmit = (data) => {\n alert(JSON.stringify(data));\n };\n\n return (\n <form onSubmit={handleSubmit(onSubmit)}>\n <select\n {...rest}\n onChange={handleSelectChange}\n >\n <option selected value=\"searchby\">\n Search By\n </option>\n <option value=\"customerID\">Custimer ID </option>\n <option value=\"teleco\">Teleco</option>\n </select>\n {errors.searchby && <p>This field is Required</p>}\n <label>Customer: </label>\n <input\n name=\"customers\"\n {...register(\"customers\")}\n />\n\n {errors.customers && <p>This field is Required</p>}\n\n <label>First name: </label>\n <input {...register(\"firstName\", { required: true })} />\n {errors.firstName && <p>This field is Required</p>}\n\n <input type=\"submit\" />\n <button type=\"button\">Validate All</button>\n </form>\n );\n}\n"
},
{
"answer_id": 74529955,
"author": "Fraction",
"author_id": 11129751,
"author_profile": "https://Stackoverflow.com/users/11129751",
"pm_score": 2,
"selected": true,
"text": "register ref value onChange onBlur onChange setValue customers const {\n register,\n formState: { errors },\n trigger,\n handleSubmit,\n setValue\n } = useForm({\n defaultValues: {\n searchby: \"searchby\",\n customers: \"\",\n firstName: \"\"\n }\n });\n\n...\n\n\nconst handleInputChanges = (event) => {\n const value = event.target.value;\n setValue(\"customers\", value);\n};\n\n...\n\n<select\n name=\"searchby\"\n {...register(\"searchby\", {\n onChange: handleInputChanges,\n required: \"password is required.\"\n })}\n>\n <option selected value=\"searchby\">\n Search By\n </option>\n <option value=\"customerID\">Custimer ID </option>\n <option value=\"teleco\">Teleco</option>\n</select>\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19629701/"
] |
74,529,555
|
<p>I am trying to use a list comprehension to extract specific elements from a list, using conditionals on the list indices.<br />
When the list indices differ, specific operations need to happen.<br />
When the list indices are the same, no element should be added.<br />
The latter is what I do not know how to do, except by adding <code>''</code> and removing it afterwards.</p>
<p>Example (simpler than my actual case, but conceptually the same):</p>
<pre><code>x = [0, 1, 2, 3, 4]
i = 2
x2 = [2 * x[j] - x[i] if j > i else 2 * x[i] - x[j] if j < i else '' for j in x]
x2.remove('')
x2
# [4, 3, 4, 6]
</code></pre>
<p>How would you exclude the case where <code>i == j</code> a priori?</p>
<p>I would have thought that just not having <code>else ''</code> at the end would work, but then I get an <code>invalid_syntax</code> error.</p>
<p>I suppose in essence I am looking for a neutral element for the list comprehension.</p>
|
[
{
"answer_id": 74529610,
"author": "yermartee",
"author_id": 20567042,
"author_profile": "https://Stackoverflow.com/users/20567042",
"pm_score": 2,
"selected": false,
"text": " <input\n name=\"customers\"\n {...register(\"customers\")} \n/>\n useController register register"
},
{
"answer_id": 74529862,
"author": "marius florescu",
"author_id": 16233425,
"author_profile": "https://Stackoverflow.com/users/16233425",
"pm_score": 2,
"selected": false,
"text": "react-hook-form react-hook-form onChange useForm() const {\n register,\n formState: { errors },\n setValue,\n handleSubmit\n } = useForm({\n defaultValues: {\n searchby: \"searchby\",\n customers: \"\",\n firstName: \"\"\n }\n });\n register() onChange const {onChange, ...rest} = register('searchby', {required: 'Password is required'})\n onSelectChange const handleSelectChange = (e) => {\n onChange(e);\n //change this to any value / logic you want\n setValue('customers', 'SomeValue')\n }\n <select/> <select\n {...rest}\n onChange={handleSelectChange}\n >\n <option selected value=\"searchby\">\n Search By\n </option>\n <option value=\"customerID\">Custimer ID </option>\n <option value=\"teleco\">Teleco</option>\n </select>\n function App() {\n const {\n register,\n formState: { errors },\n setValue,\n handleSubmit\n } = useForm({\n defaultValues: {\n searchby: \"searchby\",\n customers: \"\",\n firstName: \"\"\n }\n });\n\n const {onChange, ...rest} = register('searchby', {required: 'Password is required'})\n\n const handleSelectChange = (e) => {\n onChange(e);\n //change this to any value / logic you want\n setValue('customers', 'SomeValue')\n }\n\n const onSubmit = (data) => {\n alert(JSON.stringify(data));\n };\n\n return (\n <form onSubmit={handleSubmit(onSubmit)}>\n <select\n {...rest}\n onChange={handleSelectChange}\n >\n <option selected value=\"searchby\">\n Search By\n </option>\n <option value=\"customerID\">Custimer ID </option>\n <option value=\"teleco\">Teleco</option>\n </select>\n {errors.searchby && <p>This field is Required</p>}\n <label>Customer: </label>\n <input\n name=\"customers\"\n {...register(\"customers\")}\n />\n\n {errors.customers && <p>This field is Required</p>}\n\n <label>First name: </label>\n <input {...register(\"firstName\", { required: true })} />\n {errors.firstName && <p>This field is Required</p>}\n\n <input type=\"submit\" />\n <button type=\"button\">Validate All</button>\n </form>\n );\n}\n"
},
{
"answer_id": 74529955,
"author": "Fraction",
"author_id": 11129751,
"author_profile": "https://Stackoverflow.com/users/11129751",
"pm_score": 2,
"selected": true,
"text": "register ref value onChange onBlur onChange setValue customers const {\n register,\n formState: { errors },\n trigger,\n handleSubmit,\n setValue\n } = useForm({\n defaultValues: {\n searchby: \"searchby\",\n customers: \"\",\n firstName: \"\"\n }\n });\n\n...\n\n\nconst handleInputChanges = (event) => {\n const value = event.target.value;\n setValue(\"customers\", value);\n};\n\n...\n\n<select\n name=\"searchby\"\n {...register(\"searchby\", {\n onChange: handleInputChanges,\n required: \"password is required.\"\n })}\n>\n <option selected value=\"searchby\">\n Search By\n </option>\n <option value=\"customerID\">Custimer ID </option>\n <option value=\"teleco\">Teleco</option>\n</select>\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6376297/"
] |
74,529,578
|
<p>I'm trying to print the results of my arrays to the console, but I can't access the functions inside the class. what can we do.</p>
<p><strong>This is the result I want. But arranged according to oop principles</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let arrya = [];
let arryb = [];
for (let i = 0; i <= 9; i++) {
function crad_a(max) {
a = Math.floor(Math.random() * max);
return a;
}
// console.log(crad_a(10));
function crad_b(max) {
b = Math.floor(Math.random() * max);
return b;
}
// console.log(crad_b(10));
i++;
arrya.push(crad_a(10));
arryb.push(crad_b(10));
}
console.log(arrya);
console.log(arryb);
for (let j = 0; j <= arrya.length; j++) {
if (arrya[j] != arryb[j]) {
if (arrya[j] > arryb[j]) {
console.log("a" + " " + "win" + " " + " the game");
} else {
console.log("b" + " " + "win" + " " + "the game");
}
}
}</code></pre>
</div>
</div>
</p>
<h1><strong>This is what I tried and got stuck</strong></h1>
<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>class card_number_one {
constructor() {
this.card_one = [];
this.card_tow = [];
}
crad_a(max) {
for (let d = 0; d <= 9; d++) {
a = Math.floor(Math.random() * max);
return a;
}
d++;
this.card_one.push(crad_a(10));
}
crad_b(max) {
for (let i = 0; i <= 9; i++) {
b = Math.floor(Math.random() * max);
return b;
}
i++;
this.card_tow.push(crad_b(10));
}
}
console.log(this.card_one); /// Not working for me</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74529648,
"author": "Boguz",
"author_id": 5509709,
"author_profile": "https://Stackoverflow.com/users/5509709",
"pm_score": 0,
"selected": false,
"text": "console.log() this class card_number_one {\n constructor() {\n this.card_one = [];\n this.card_tow = [];\n }\n crad_a(max) {\n for (let d = 0; d <= 9; d++) {\n a = Math.floor(Math.random() * max);\n return a;\n }\n d++;\n this.card_one.push(crad_a(10));\n }\n crad_b(max) {\n for (let i = 0; i <= 9; i++) {\n b = Math.floor(Math.random() * max);\n return b;\n }\n i++;\n this.card_tow.push(crad_b(10));\n }\n}\n\n// Create an instance of the class and save it in the \"exampleCard\" variable\nconst exampleCard = new card_number_one();\n\n// Console log the property \"card_one\" of the \"exampleCard\" instance of your class\nconsole.log(exampleCard.card_one);"
},
{
"answer_id": 74530010,
"author": "WizardOfOz",
"author_id": 19668106,
"author_profile": "https://Stackoverflow.com/users/19668106",
"pm_score": 2,
"selected": true,
"text": " // Defining your class\n class Card {\n // stuff\n }\n \n // Constructing your class\n let foo = new Card();\n console.log(foo)\n class Card {\n constructor(array, max) {\n this.array = array;\n this.max = max;\n }\n get maxNumber(){\n for (let i = 0; i <= this.max; i++) {\n return Math.floor(Math.random() * this.max);\n }\n }\n\n}\n\nlet array1 = [1,2,3,4];\nlet array2 = [5,6,7,8];\n\nlet card1 = new Card(array1, 10)\nlet card2 = new Card(array2, 20)\n\nconsole.log(card1.maxNumber); // Returns 7\nconsole.log(card2.maxNumber); // Returns 6\n\nlet difference = card1.maxNumber - card2.maxNumber // Assuming the number doesn't have to be greater than 0.\n\n// Print your message\nconsole.log(`Your game score is ${difference}, good job!`);\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20570230/"
] |
74,529,581
|
<p>I need to use a <code>GestureDetector</code> because it can detect many more types of user interactions than <code>InkWell</code>, but unlike <code>InkWell</code> it doesn't provide any visual response when a user taps or long presses on it.</p>
<p>Is it possible to add a ripple effect for tap/long press while still handling user interactions in the <code>GestureDetector</code>?</p>
|
[
{
"answer_id": 74529695,
"author": "My Car",
"author_id": 16124033,
"author_profile": "https://Stackoverflow.com/users/16124033",
"pm_score": -1,
"selected": false,
"text": "InkWell(\n onLongPress: () {\n // Do what you want to do\n },\n child: child,\n),\n"
},
{
"answer_id": 74529866,
"author": "Anand PS",
"author_id": 19165360,
"author_profile": "https://Stackoverflow.com/users/19165360",
"pm_score": 0,
"selected": false,
"text": "touch_ripple_effect: ^2.2.4\n TouchRippleEffect(\n borderRadius: _helloRadius,\n rippleColor: Colors.white60,\n onTap: (){\n print(\"Anand !\");\n },\n child: Container(\n width: 110, \n height: 50, \n alignment: Alignment.center, \n decoration: BoxDecoration(color: Colors.pink, borderRadius: _helloRadius),\n child: IconButton(\n iconSize: 24.0, \n icon: Icon(Icons.search,color: Colors.white, size: 36,), \n onPressed: null\n ),)\n ),\n TouchFeedback(\n onTap: (){\n print(\" I am Aditya\");\n },\n rippleColor: Colors.blue[200],\n child: Container(\n width: 120,\n height: 40, \n alignment: Alignment.center,\n decoration: BoxDecoration(color: Colors.yellow, borderRadius: BorderRadius.circular(5),), \n child: Text(\n \"Hit me !\", \n style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)\n )\n ),\n )\n"
},
{
"answer_id": 74530327,
"author": "Hassan",
"author_id": 14378940,
"author_profile": "https://Stackoverflow.com/users/14378940",
"pm_score": 0,
"selected": false,
"text": "class Test extends StatelessWidget {\n const Test({\n Key? key,\n this.onTap,\n }) : super(key: key);\n final void Function()? onTap;\n@override\nWidget build(BuildContext context) {\nfinal width = MediaQuery.of(context).size.width;\nreturn Scaffold(\n body: GestureDetector(\n onTap: onTap,\n child: SizedBox(\n width: width * 0.2,\n height: 70,\n child: Card(\n color: Colors.red,\n child: InkWell(\n onTap: () {},\n ),\n ),\n ),\n ),\n );\n }\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/930640/"
] |
74,529,599
|
<p>When I create temp table via python, an error throws
400 Use of CREATE TEMPORARY TABLE requires a script or session
How can I create a session?</p>
<pre><code>from google.colab import auth
from google.cloud import bigquery
from google.colab import data_table
client = bigquery.Client(project=project, location = location)
client.query('''
create temp table t_acquisted_users as
select *
from table_a
limit 10
''').result()
</code></pre>
|
[
{
"answer_id": 74529695,
"author": "My Car",
"author_id": 16124033,
"author_profile": "https://Stackoverflow.com/users/16124033",
"pm_score": -1,
"selected": false,
"text": "InkWell(\n onLongPress: () {\n // Do what you want to do\n },\n child: child,\n),\n"
},
{
"answer_id": 74529866,
"author": "Anand PS",
"author_id": 19165360,
"author_profile": "https://Stackoverflow.com/users/19165360",
"pm_score": 0,
"selected": false,
"text": "touch_ripple_effect: ^2.2.4\n TouchRippleEffect(\n borderRadius: _helloRadius,\n rippleColor: Colors.white60,\n onTap: (){\n print(\"Anand !\");\n },\n child: Container(\n width: 110, \n height: 50, \n alignment: Alignment.center, \n decoration: BoxDecoration(color: Colors.pink, borderRadius: _helloRadius),\n child: IconButton(\n iconSize: 24.0, \n icon: Icon(Icons.search,color: Colors.white, size: 36,), \n onPressed: null\n ),)\n ),\n TouchFeedback(\n onTap: (){\n print(\" I am Aditya\");\n },\n rippleColor: Colors.blue[200],\n child: Container(\n width: 120,\n height: 40, \n alignment: Alignment.center,\n decoration: BoxDecoration(color: Colors.yellow, borderRadius: BorderRadius.circular(5),), \n child: Text(\n \"Hit me !\", \n style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)\n )\n ),\n )\n"
},
{
"answer_id": 74530327,
"author": "Hassan",
"author_id": 14378940,
"author_profile": "https://Stackoverflow.com/users/14378940",
"pm_score": 0,
"selected": false,
"text": "class Test extends StatelessWidget {\n const Test({\n Key? key,\n this.onTap,\n }) : super(key: key);\n final void Function()? onTap;\n@override\nWidget build(BuildContext context) {\nfinal width = MediaQuery.of(context).size.width;\nreturn Scaffold(\n body: GestureDetector(\n onTap: onTap,\n child: SizedBox(\n width: width * 0.2,\n height: 70,\n child: Card(\n color: Colors.red,\n child: InkWell(\n onTap: () {},\n ),\n ),\n ),\n ),\n );\n }\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/762295/"
] |
74,529,606
|
<p>from power bi desktop I created a dashboard with links to Saleforce and with a link to an excel table on my computer.
from "edit query" I deactivated the updating of the excel file in the report (it must not update) and I uploaded the dashboard online so that I can share it.
the computer on which I have the excle file does not always stay on, when I go to create a scheduled update of the dashboard, it fails because it cannot connect to the excel file.</p>
<p>my aim is to keep the excel file because I created some measurements (so as not to redo them) and to update the dashboard
you have to update the dashboard with the saleforce dates but not with the excel file</p>
|
[
{
"answer_id": 74529695,
"author": "My Car",
"author_id": 16124033,
"author_profile": "https://Stackoverflow.com/users/16124033",
"pm_score": -1,
"selected": false,
"text": "InkWell(\n onLongPress: () {\n // Do what you want to do\n },\n child: child,\n),\n"
},
{
"answer_id": 74529866,
"author": "Anand PS",
"author_id": 19165360,
"author_profile": "https://Stackoverflow.com/users/19165360",
"pm_score": 0,
"selected": false,
"text": "touch_ripple_effect: ^2.2.4\n TouchRippleEffect(\n borderRadius: _helloRadius,\n rippleColor: Colors.white60,\n onTap: (){\n print(\"Anand !\");\n },\n child: Container(\n width: 110, \n height: 50, \n alignment: Alignment.center, \n decoration: BoxDecoration(color: Colors.pink, borderRadius: _helloRadius),\n child: IconButton(\n iconSize: 24.0, \n icon: Icon(Icons.search,color: Colors.white, size: 36,), \n onPressed: null\n ),)\n ),\n TouchFeedback(\n onTap: (){\n print(\" I am Aditya\");\n },\n rippleColor: Colors.blue[200],\n child: Container(\n width: 120,\n height: 40, \n alignment: Alignment.center,\n decoration: BoxDecoration(color: Colors.yellow, borderRadius: BorderRadius.circular(5),), \n child: Text(\n \"Hit me !\", \n style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)\n )\n ),\n )\n"
},
{
"answer_id": 74530327,
"author": "Hassan",
"author_id": 14378940,
"author_profile": "https://Stackoverflow.com/users/14378940",
"pm_score": 0,
"selected": false,
"text": "class Test extends StatelessWidget {\n const Test({\n Key? key,\n this.onTap,\n }) : super(key: key);\n final void Function()? onTap;\n@override\nWidget build(BuildContext context) {\nfinal width = MediaQuery.of(context).size.width;\nreturn Scaffold(\n body: GestureDetector(\n onTap: onTap,\n child: SizedBox(\n width: width * 0.2,\n height: 70,\n child: Card(\n color: Colors.red,\n child: InkWell(\n onTap: () {},\n ),\n ),\n ),\n ),\n );\n }\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20570272/"
] |
74,529,609
|
<p>I have <code>List<Result<String>></code> and I would like to convert it to <code>Result<List<String>></code>. I understand that <code>List<Result<String>></code> could have both failure and successful results but I would like to terminate in the first failure.</p>
|
[
{
"answer_id": 74529790,
"author": "Dinamots",
"author_id": 13115358,
"author_profile": "https://Stackoverflow.com/users/13115358",
"pm_score": 2,
"selected": true,
"text": "fun <T> List<Result<T>>.toResult() = if (any { it.isFailure }) {\n Result.failure<List<Result<Any>>>(Throwable(\"A result has errors\"))\n } else {\n Result.success(map { it.getOrNull() })\n }\n fun <T> List<Result<T>>.toResult() = runCatching {\n Result.success(map { it.getOrThrow() })\n}\n\n"
},
{
"answer_id": 74529791,
"author": "A.J.Rouvoet",
"author_id": 1375800,
"author_profile": "https://Stackoverflow.com/users/1375800",
"pm_score": 0,
"selected": false,
"text": "sequence Either Result val xs: List<Result<String>> = ...\nval ys: Result<List<String>> = xs.sequence()\n getOrThrow Throwable Result fun <T> List<Result<T>>.sequence(): Result<List<T>> = try {\n Result.success(this.map { it.getOrThrow() })\n }\n catch (e:Throwable) { Result.failure(e) }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10334333/"
] |
74,529,644
|
<p>I have written a code (excel VBA) to output powerpoint report. Part of the code is to create a table, then supply the data into it from the excel. My problem now is copying a certain data from excel. I do not want to copy any information inside the parenthesis as well as the parenthesis itself. For example, the data is the name of the employee together with their employee ID. I just need the employee's name. Do you know how to do it?</p>
<p>Below is part of the code. It's quite long since im still new in VBA coding. From the code below, the last part .Text = Range("F1") is the code where I will copy the data I will translate to the powerpoint.</p>
<pre><code> Set myShape = myPresentation.Slides(2).Shapes.AddTable(10, 4, 50, 100, 800)
myShape.Table.Rows.Add
myShape.Height = 0
With myShape.Table
.Cell(1, 1).Merge MergeTo:=.Cell(1, 2)
.Cell(1, 2).Merge MergeTo:=.Cell(1, 3)
.Cell(1, 3).Merge MergeTo:=.Cell(1, 4)
With .Cell(1, 4).Shape
With .TextFrame.TextRange
.Text = "General Information"
.Font.Size = 13
.Font.Name = "Arial"
.Font.Color = RGB(0, 0, 0)
End With
End With
With .Cell(2, 1).Shape
With .TextFrame.TextRange
.Text = "FA Site"
.Font.Size = 13
.Font.Name = "Arial"
.Font.Color = RGB(0, 0, 0)
End With
End With
With .Cell(2, 2).Shape
With .TextFrame.TextRange
.Text = "Singapore"
.Font.Size = 13
.Font.Name = "Arial"
.Font.Color = RGB(0, 0, 0)
End With
End With
With .Cell(2, 3).Shape
With .TextFrame.TextRange
.Text = Range("F1")
.Font.Size = 13
.Font.Name = "Arial"
.Font.Color = RGB(0, 0, 0)
End With
End With
</code></pre>
<p>I dont know how to write the VBA code for this problem. I hope someone can help me.</p>
|
[
{
"answer_id": 74529790,
"author": "Dinamots",
"author_id": 13115358,
"author_profile": "https://Stackoverflow.com/users/13115358",
"pm_score": 2,
"selected": true,
"text": "fun <T> List<Result<T>>.toResult() = if (any { it.isFailure }) {\n Result.failure<List<Result<Any>>>(Throwable(\"A result has errors\"))\n } else {\n Result.success(map { it.getOrNull() })\n }\n fun <T> List<Result<T>>.toResult() = runCatching {\n Result.success(map { it.getOrThrow() })\n}\n\n"
},
{
"answer_id": 74529791,
"author": "A.J.Rouvoet",
"author_id": 1375800,
"author_profile": "https://Stackoverflow.com/users/1375800",
"pm_score": 0,
"selected": false,
"text": "sequence Either Result val xs: List<Result<String>> = ...\nval ys: Result<List<String>> = xs.sequence()\n getOrThrow Throwable Result fun <T> List<Result<T>>.sequence(): Result<List<T>> = try {\n Result.success(this.map { it.getOrThrow() })\n }\n catch (e:Throwable) { Result.failure(e) }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20570193/"
] |
74,529,741
|
<p>I have a lot of images on my website and that makes my website load too slowly. should I create a small image with low quality and small size and make a blur effect on it and make the real images load slowly (lazy load) after all page files are downloaded or what should I do</p>
|
[
{
"answer_id": 74666965,
"author": "ymz",
"author_id": 4062197,
"author_profile": "https://Stackoverflow.com/users/4062197",
"pm_score": 2,
"selected": true,
"text": "<style>\n img.loader {\n display: none;\n }\n\n img.loader.active {\n display: block;\n }\n</style>\n\n<script>\n function loadImage(target, url) {\n const imgElement = target.querySelector('img.target')\n const imgLoaderElement = document.createElement('img')\n const loaderElement = target.querySelector('img.loader')\n \n imgLoaderElement.onload = event => {\n // nice to have - the actual size of the requested image\n console.log(imgLoaderElement.width, imgLoaderElement.height) \n \n loaderElement.classList.remove('active')\n imgElement.src = url\n }\n \n imgLoaderElement.src = url\n }\n</script>\n\n<div id=\"image-loader-1\">\n <img class=\"active loader\" src=\"https://cdnjs.cloudflare.com/ajax/libs/galleriffic/2.0.1/css/loader.gif\" alt=\"\" width=\"48\" height=\"48\">\n <img class=\"target\" />\n</div>\n\n<button onclick=\"loadImage(document.querySelector('#image-loader-1'), 'https://picsum.photos/600/400')\">\n Load Image\n</button>\n div element loadImage image-loader-1 vanilla JS"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16260445/"
] |
74,529,747
|
<p>This is the function I'm using</p>
<pre><code>MyModel.aggregate([
{ $match: query },
{ $sort: { 'createdAt': -1 } },
{ $skip: skip },
{ $limit: 10 }
], { allowDiskUse : true });
</code></pre>
<p><code>query</code> is to filter the rows. <code>skip</code> is dynamic value based on pagination (i.e 0, 10, 20 ...). The problem is, the rows for each page in wrong. For instance, I can see a specific row in page 1,2,3,4 at the same time! some rows are missing as well.</p>
<p>Why is it happening?</p>
|
[
{
"answer_id": 74530453,
"author": "Stacks Queue",
"author_id": 14820590,
"author_profile": "https://Stackoverflow.com/users/14820590",
"pm_score": 0,
"selected": false,
"text": "limit skip (page - 1 * limit) const limit = 10;\nconst page = 1;\nconst skip = (page - 1) * limit; // basically is 0\n\nMyModel.aggregate([\n { $match: query },\n { $sort: { 'createdAt': -1 } },\n { $skip: skip },\n { $limit: limit }\n ], { allowDiskUse : true });\n const limit = 10;\nconst page = 2;\nconst skip = (page - 1) * limit; // basically is 10\n\nMyModel.aggregate([\n { $match: query },\n { $sort: { 'createdAt': -1 } },\n { $skip: skip },\n { $limit: limit }\n ], { allowDiskUse : true });\n"
},
{
"answer_id": 74533630,
"author": "user20042973",
"author_id": 20042973,
"author_profile": "https://Stackoverflow.com/users/20042973",
"pm_score": 2,
"selected": true,
"text": "createdAt $sort 123 123 _id _id { $sort: { 'createdAt': -1, _id: 1 } },\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17344899/"
] |
74,529,755
|
<p>We are having issue with a regex validation using Pattern. It is happening in Spring framework and hibernate's validation.</p>
<p>Below snippet shows the request object being validated:</p>
<pre><code>@PostMapping
public ResponseEntity create(@RequestBody RequestObj request) {
validationService.validate(request);
.....
}
</code></pre>
<p>Regex pattern:</p>
<pre><code>public class RequestObj {
@Pattern(regexp = "^([a-zA-Z])+[-.'\\s]?[-a-zA-Z]*$", message = ValidationConstant.ERR_INVALID_FIRST_NAME)
@NotNull(message = ValidationConstant.ERR_FIRST_NAME_EMPTY)
@Size(max = 30, message = ValidationConstant.ERR_INVALID_NAME_SIZE)
private String firstName;
@Pattern(regexp = "^[\\sa-zA-Z0-9]+([ a-zA-Z0-9,'.?!\\-_&]+)*$", message = ValidationConstant.ERR_INVALID_COMMENT)
@Size(max = 200, message = ValidationConstant.ERR_INVALID_COMMENT_SIZE)
private String comment;
}
</code></pre>
<p>When this validation is called, at times the CPU usage of the thread shows 100%.(It works most of the time).
The thread dump shows that thread is stuck in Pattern class.</p>
<pre><code>"http-nio-8080-exec-4" #53 daemon prio=5 os_prio=0 tid=0x00007fce45f0d000 nid=0x44 runnable [0x00007fcdb3af6000]
java.lang.Thread.State: RUNNABLE
at java.util.regex.Pattern$5.isSatisfiedBy(Pattern.java:5265)
at java.util.regex.Pattern$5.isSatisfiedBy(Pattern.java:5265)
at java.util.regex.Pattern$5.isSatisfiedBy(Pattern.java:5265)
at java.util.regex.Pattern$CharProperty.match(Pattern.java:3790)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4274)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4672)
at java.util.regex.Pattern$Loop.match(Pattern.java:4799)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4731)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4286)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4672)
at java.util.regex.Pattern$Loop.match(Pattern.java:4799)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4731)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4286)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4672)
at java.util.regex.Pattern$Loop.match(Pattern.java:4799)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4731)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4286)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4672)
at java.util.regex.Pattern$Loop.match(Pattern.java:4799)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4731)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4286)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4672)
at java.util.regex.Pattern$Loop.match(Pattern.java:4799)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4731)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4286)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4672)
at java.util.regex.Pattern$Loop.match(Pattern.java:4799)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4731)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4286)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4672)
at java.util.regex.Pattern$Loop.match(Pattern.java:4799)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4731)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4286)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4672)
at java.util.regex.Pattern$Loop.match(Pattern.java:4799)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4731)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4286)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4672)
at java.util.regex.Pattern$Loop.match(Pattern.java:4799)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4731)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4286)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4672)
at java.util.regex.Pattern$Loop.match(Pattern.java:4799)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4731)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4286)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4672)
at java.util.regex.Pattern$Loop.match(Pattern.java:4799)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4731)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4286)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4672)
at java.util.regex.Pattern$Loop.match(Pattern.java:4799)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4731)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4286)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4672)
at java.util.regex.Pattern$Loop.match(Pattern.java:4799)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4731)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4286)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4672)
at java.util.regex.Pattern$Loop.match(Pattern.java:4799)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4731)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4286)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4672)
at java.util.regex.Pattern$Loop.match(Pattern.java:4799)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4731)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4286)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4672)
at java.util.regex.Pattern$Loop.match(Pattern.java:4799)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4731)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4286)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4672)
at java.util.regex.Pattern$Loop.match(Pattern.java:4799)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4731)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4286)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4672)
at java.util.regex.Pattern$Loop.match(Pattern.java:4799)
at java.util.regex.Pattern$GroupTail.match(Pattern.java:4731)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4286)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$GroupHead.match(Pattern.java:4672)
at java.util.regex.Pattern$Loop.matchInit(Pattern.java:4818)
at java.util.regex.Pattern$Prolog.match(Pattern.java:4755)
at java.util.regex.Pattern$Curly.match0(Pattern.java:4286)
at java.util.regex.Pattern$Curly.match(Pattern.java:4248)
at java.util.regex.Pattern$Begin.match(Pattern.java:3539)
at java.util.regex.Matcher.match(Matcher.java:1270)
at java.util.regex.Matcher.matches(Matcher.java:604)
at org.hibernate.validator.internal.constraintvalidators.bv.PatternValidator.isValid(PatternValidator.java:60)
at org.hibernate.validator.internal.constraintvalidators.bv.PatternValidator.isValid(PatternValidator.java:24)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:171)
at org.hibernate.validator.internal.engine.constraintvalidation.SimpleConstraintTree.validateConstraints(SimpleConstraintTree.java:68)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:73)
at org.hibernate.validator.internal.metadata.core.MetaConstraint.doValidateConstraint(MetaConstraint.java:127)
at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:120)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:533)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForSingleDefaultGroupElement(ValidatorImpl.java:496)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:465)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:430)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:380)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateCascadedAnnotatedObjectForCurrentGroup(ValidatorImpl.java:605)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateCascadedConstraints(ValidatorImpl.java:568)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:389)
at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:169)
</code></pre>
<p>Is there any issue in my regex?</p>
<p>The regex for first name validation which supports alphabets and few special chars <code>^([a-zA-Z])+[-.'\\s]?[-a-zA-Z]*$</code></p>
<p>Regex for message box text <code>^[\sa-zA-Z0-9]+([ a-zA-Z0-9,'.?!\-_&]+)*$</code></p>
|
[
{
"answer_id": 74529904,
"author": "cyberbrain",
"author_id": 2846138,
"author_profile": "https://Stackoverflow.com/users/2846138",
"pm_score": 1,
"selected": false,
"text": "([a-zA-Z]) + ^([a-zA-Z]+)[-.'\\\\s]?[-a-zA-Z]*$\n ^[a-zA-Z]+[-.'\\\\s]?[-a-zA-Z]*$\n"
},
{
"answer_id": 74530115,
"author": "Joop Eggen",
"author_id": 984823,
"author_profile": "https://Stackoverflow.com/users/984823",
"pm_score": 0,
"selected": false,
"text": "\"^[a-zA-Z]+[-.'\\\\s]?[-a-zA-Z]*$\"\n \"^[a-zA-Z]+([-.'\\\\s][-a-zA-Z]*)?$\"\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20569900/"
] |
74,529,761
|
<p>I'm using the following logic that seems to run in parallel when running locally, but when deployed on azure functions, it's running sequencially:</p>
<pre><code>var allRecordTasks = new List<Task<DataRecord>>();
for (int i = 0; i < 100; i++)
{
allRecordTasks.Add(Task.Run(() => MyTask(cancellationToken)));
}
await Task.WhenAll(allRecordTasks);
</code></pre>
<p>I'm running under S1 plan and I was under the assumption that a single core could run multiple threads.</p>
<p>Is there some setting to make this work, is it possible when running a plan with multiple cores or is it simply not possible without using durable functions?</p>
<pre><code>private async Task<DataRecord> MyTask(CancellationToken cancellationToken)
{
var timeSeriesType = await GetTimeSeriesTypeAsync();
var dataRecord = new DataRecord(timeSeriesType);
return dataRecord;
}
</code></pre>
<p>Update: Simply using</p>
<pre><code>allRecordTasks.Add(MyTask(cancellationToken));
</code></pre>
<p>ran in parallel. Other issues in my code caused the CPU core to be busy, which didn't cost much locally (quad-core), but prevented performance on a single core. Thanks Peter Bons and Stephen Cleary for clearing things up, pointing me in the right direction.</p>
|
[
{
"answer_id": 74532470,
"author": "Simmetric",
"author_id": 1738491,
"author_profile": "https://Stackoverflow.com/users/1738491",
"pm_score": 0,
"selected": false,
"text": "async await Parallel Tasks"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3774527/"
] |
74,529,769
|
<p>I am trying to display the name of a project in a new page, as a string that I had saved in a previous page using Shared Preferences. Below is the section of code where I saved this:</p>
<pre><code> onPressed: () async {
SharedPreferences localStorage =
await SharedPreferences
.getInstance();
localStorage.setString(
'project_id', nDataList.id);
localStorage.setString(
'project_name',
nDataList.title);
localStorage.setString(
'project_desc',
nDataList.description);
localStorage.setString(
'project_due',
nDataList.endDate);
// ignore: use_build_context_synchronously
Navigator.pushNamed(
context, 'activities');
},
)
</code></pre>
<p>In the new page, I am using the get string in a function and then I want to display the result in a text widget. Here is all the code for the second page:</p>
<pre><code>import 'package:flutter/material.dart';
import 'package:mne/Actual%20Tasks/activity_widget.dart';
import 'package:mne/UserTasks/task_widget.dart';
import 'package:shared_preferences/shared_preferences.dart';
class ProjectTask extends StatefulWidget {
const ProjectTask({Key key}) : super(key: key);
@override
State<ProjectTask> createState() => _ProjectTaskState();
}
class _ProjectTaskState extends State<ProjectTask> {
@override
void initState() {
super.initState();
_fetchData();
}
Future<Null> _fetchData() async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences localStorage = await SharedPreferences.getInstance();
var pname = localStorage.getString('project_name');
var pdesc = localStorage.getString('project_desc');
var pdue = localStorage.getString('project_due');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: true,
centerTitle: true,
title: const Text('Project Details')),
body: SingleChildScrollView(
child: Column(children: [
// for image
Container(
child: Image.asset('assets/images/projectbanner.png'),
),
//for project name
Container(
child: Row(children: [
Container(
padding: const EdgeInsets.only(right: 10, top: 8),
child: const Icon(Icons.calendar_month_outlined)),
RichText(
text: TextSpan(children: [
TextSpan(
text: 'Due: ',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Colors.black)),
TextSpan(
text: '$pname',
style: TextStyle(fontSize: 14, color: Colors.black))
])),
])),
// for description title
Container(child: const Text('Description')),
// for actual desc
Container(),
// for task title
Container(),
// for task widget
Container(height: 630, child: const ActivityWidget()),
]),
),
);
}
}
</code></pre>
<p>The error that I am getting says that 'pname' is undefined and that it is of type dynamic. How can I use the information saved in the variable in the text widget? Any help is much appreciated</p>
|
[
{
"answer_id": 74529793,
"author": "manhtuan21",
"author_id": 8921450,
"author_profile": "https://Stackoverflow.com/users/8921450",
"pm_score": 2,
"selected": true,
"text": "class ProjectTask extends StatefulWidget {\n const ProjectTask({Key key}) : super(key: key);\n\n @override\n State<ProjectTask> createState() => _ProjectTaskState();\n}\n\nclass _ProjectTaskState extends State<ProjectTask> {\n\n String pname;\n String pdesc;\n String pdue;\n \n @override\n void initState() {\n super.initState();\n _fetchData();\n }\n\n Future<Null> _fetchData() async {\n WidgetsFlutterBinding.ensureInitialized();\n SharedPreferences localStorage = await SharedPreferences.getInstance();\n setState(() {\n pname = localStorage.getString('project_name');\n pdesc = localStorage.getString('project_desc');\n pdue = localStorage.getString('project_due');\n });\n }\n\n\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n automaticallyImplyLeading: true,\n centerTitle: true,\n title: const Text('Project Details')),\n body: SingleChildScrollView(\n child: Column(children: [\n // for image\n Container(\n child: Image.asset('assets/images/projectbanner.png'),\n ),\n //for project name\n Container(\n child: Row(children: [\n Container(\n padding: const EdgeInsets.only(right: 10, top: 8),\n child: const Icon(Icons.calendar_month_outlined)),\n RichText(\n text: TextSpan(children: [\n TextSpan(\n text: 'Due: ',\n style: TextStyle(\n fontSize: 14,\n fontWeight: FontWeight.bold,\n color: Colors.black)),\n TextSpan(\n text: '$pname',\n style: TextStyle(fontSize: 14, color: Colors.black))\n ])),\n ])),\n // for description title\n Container(child: const Text('Description')),\n // for actual desc\n Container(),\n // for task title\n Container(),\n // for task widget\n Container(height: 630, child: const ActivityWidget()),\n ]),\n ),\n );\n }\n}\n"
},
{
"answer_id": 74529939,
"author": "thanhdang98",
"author_id": 12510844,
"author_profile": "https://Stackoverflow.com/users/12510844",
"pm_score": 0,
"selected": false,
"text": " class ProjectTask extends StatefulWidget {\n const ProjectTask({Key key}) : super(key: key);\n\n @override\n State<ProjectTask> createState() => _ProjectTaskState();\n}\n\nclass _ProjectTaskState extends State<ProjectTask> {\n\n String pname;\n String pdesc;\n String pdue;\n \n @override\n void initState() {\n super.initState();\nWidgetsBinding.instance.addPostFrameCallback((timeStamp) async {\n await _fetchData();\n });\n }\n\n Future<Null> _fetchData() async {\n WidgetsFlutterBinding.ensureInitialized();\n SharedPreferences localStorage = await SharedPreferences.getInstance();\n setState(() {\n pname = localStorage.getString('project_name');\n pdesc = localStorage.getString('project_desc');\n pdue = localStorage.getString('project_due');\n });\n }\n\n\n\n @override\n Widget build(BuildContext context) {\n return Scaffold(\n appBar: AppBar(\n automaticallyImplyLeading: true,\n centerTitle: true,\n title: const Text('Project Details')),\n body: SingleChildScrollView(\n child: Column(children: [\n // for image\n Container(\n child: Image.asset('assets/images/projectbanner.png'),\n ),\n //for project name\n Container(\n child: Row(children: [\n Container(\n padding: const EdgeInsets.only(right: 10, top: 8),\n child: const Icon(Icons.calendar_month_outlined)),\n RichText(\n text: TextSpan(children: [\n TextSpan(\n text: 'Due: ',\n style: TextStyle(\n fontSize: 14,\n fontWeight: FontWeight.bold,\n color: Colors.black)),\n TextSpan(\n text: '${pname??''}',\n style: TextStyle(fontSize: 14, color: Colors.black))\n ])),\n ])),\n // for description title\n Container(child: const Text(pdesc??'')),\n // for actual desc\n Container(),\n // for task title\n Container(),\n // for task widget\n Container(height: 630, child: const ActivityWidget()),\n ]),\n ),\n );\n }\n}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16712104/"
] |
74,529,783
|
<p>I am new to perl scripting. tried following code</p>
<pre class="lang-perl prettyprint-override"><code>#!/usr/bin/perl -w
our $sep = "-";
open my $data, $ARGV[0] or die "Can't open $ARGV[0] for reading: $!";
while( my $line = <$data> )
{
$line =~ s/]:/\n]:/g;
my @spl = split(', ', $line);
$hello = $spl[2].'-'.$spl[1];
print $hello;
print "\n";
}
</code></pre>
<p>My sample input</p>
<pre class="lang-none prettyprint-override"><code>, 1234, task]: 1122
</code></pre>
<p>My current output</p>
<pre class="lang-none prettyprint-override"><code>task
]: 1122
-1234
</code></pre>
<p>My expected sample output</p>
<pre class="lang-none prettyprint-override"><code>task-1234]: 1122
</code></pre>
|
[
{
"answer_id": 74530279,
"author": "Jaff_NL",
"author_id": 12111665,
"author_profile": "https://Stackoverflow.com/users/12111665",
"pm_score": 1,
"selected": false,
"text": "open my $stack, $ARGV[0] or die \"Can't open $ARGV[0] for reading: $!\";\nwhile( my $line = <$stack> )\n{\n my @spl = split(']:', $line);\n my @spl1 = split(', ', $spl[0]);\n $line = $spl1[2].'-'.$spl1[1].\"]:\".$spl[1];\n print $line;\n print \"\\n\";\n}\n task-1234]: 1122\n"
},
{
"answer_id": 74530440,
"author": "Polar Bear",
"author_id": 12313309,
"author_profile": "https://Stackoverflow.com/users/12313309",
"pm_score": 3,
"selected": true,
"text": "use strict;\nuse warnings;\nuse feature 'say';\n\nmy($fname,$regex);\n\n$regex = qr/^, (\\d+), (.+?)]: (\\d+)$/;\n\nwhile( <DATA> )\n{\n next if /^\\s*$/;\n my @data = $_ =~ /$regex/;\n say \"$data[1]-$data[0]\\]: $data[2]\";\n}\n\nexit 0;\n\n__DATA__\n, 1234, task]: 1122\n task-1234]: 1122\n <DATA> use strict;\nuse warnings;\nuse feature 'say';\n\nwhile( <DATA> )\n{\n next if /^\\s*$/;\n my @data = split(/[, \\]:]+/, $_);\n say \"$data[2]-$data[1]\\]: $data[3]\";\n}\n\nexit 0;\n\n__DATA__\n, 1234, task]: 1122\n task-1234]: 1122\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12111665/"
] |
74,529,801
|
<p>I want to alter multiple HTML elements that live inside a singular CSS class.</p>
<p>For example:</p>
<pre><code><div class="main">
<h1>Hello</h1>
<p>Good Morning</p>
</div>
</code></pre>
<p>I know it is possible to do this:</p>
<pre><code>.main h1 { ... }
.main p {...}
</code></pre>
<p>Is it possible to create a single CSS clause that does this in one line? (Like this:)</p>
<pre><code>.main h1,p {...}
</code></pre>
<p>Thanks!</p>
|
[
{
"answer_id": 74529823,
"author": "Fabrizio Calderan",
"author_id": 1098851,
"author_profile": "https://Stackoverflow.com/users/1098851",
"pm_score": 4,
"selected": true,
"text": ".main .main * { ... }\n .main :is :where .main :where(h1, p) { ... }\n MDN"
},
{
"answer_id": 74529841,
"author": "Akasiek",
"author_id": 9027746,
"author_profile": "https://Stackoverflow.com/users/9027746",
"pm_score": 2,
"selected": false,
"text": ".main h1,\n.main p {...}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12750283/"
] |
74,529,806
|
<p>i need to upload <a href="/questions/tagged/laravel" class="post-tag" title="show questions tagged 'laravel'" aria-label="show questions tagged 'laravel'" rel="tag" aria-labelledby="laravel-container">laravel</a> project on sub folder in subdomain because there will be <a href="/questions/tagged/wordpress" class="post-tag" title="show questions tagged 'wordpress'" aria-label="show questions tagged 'wordpress'" rel="tag" aria-labelledby="wordpress-container">wordpress</a> website,
while i am searching i found that i can use <a href="/questions/tagged/.htaccess" class="post-tag" title="show questions tagged '.htaccess'" aria-label="show questions tagged '.htaccess'" rel="tag" aria-labelledby=".htaccess-container">.htaccess</a>, is there another way ? because i am new to laravel and no experience in [tag:.htaccess ]
--- subdmoain.com
--- public_html
--- subfolder
---laravel project</p>
<p>i tried using changing App_Url</p>
|
[
{
"answer_id": 74529823,
"author": "Fabrizio Calderan",
"author_id": 1098851,
"author_profile": "https://Stackoverflow.com/users/1098851",
"pm_score": 4,
"selected": true,
"text": ".main .main * { ... }\n .main :is :where .main :where(h1, p) { ... }\n MDN"
},
{
"answer_id": 74529841,
"author": "Akasiek",
"author_id": 9027746,
"author_profile": "https://Stackoverflow.com/users/9027746",
"pm_score": 2,
"selected": false,
"text": ".main h1,\n.main p {...}\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20570431/"
] |
74,529,830
|
<p>Not sure how to formulate my question so I'll start with an example.
I have a dataset that looks like this (the whole dataset has ~150000 rows) - highlighted some of the values for easier viewing:</p>
<p><a href="https://i.stack.imgur.com/UHyr7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UHyr7.png" alt="enter image description here" /></a></p>
<p>What I want to do is count how many times "Johnson, Jim, 10" and "Gordon, Tom, 15" appear in the same SUBDATA set where the first column cells have the same value.</p>
<p>I counted how many times the respective values appear in the whole data set separately using COUNTIFS:</p>
<p><a href="https://i.stack.imgur.com/nqfY5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nqfY5.png" alt="enter image description here" /></a></p>
<p>But what I want to do is somehow counting how many times both iterations of the given data ("Johnson, Jim, 10" and "Gordon, Tom, 15") appear IF the first column value is the same (the value should be a DATE in the format YYYYMMDD).</p>
<p>I don't want to give the formula a date e.g. 20221005 and see if those 2 instances appear together because I have hundreds of dates. I just want to somehow tell the formula to CHECK when it finds any of those two records if there is an instance where the DATE is the same and count it.</p>
<p>e.g. If "Johnson, Jim, 10" and "Gordon, Tom, 15" have their respective related A cell with the same value (20221010), count it. And see how many times this happens in the whole dataset.</p>
<p>I would like to know if it's possible to do this using only formulas, without using Macros.</p>
<p>PS: Sorry if I didn't make myself clear enough, I will answer every question you have.</p>
|
[
{
"answer_id": 74530169,
"author": "JvdV",
"author_id": 9758194,
"author_profile": "https://Stackoverflow.com/users/9758194",
"pm_score": 1,
"selected": false,
"text": "K2 =LET(x,FILTER(A1:A12,BYROW(B1:D12,LAMBDA(a,SUM(--(MMULT(--(a=H1:J2),{1,1,1})=3))))),COUNT(UNIQUE(FILTER(x,MAP(x,LAMBDA(y,SUM(--(x=y))))=2))))\n"
},
{
"answer_id": 74537650,
"author": "David Leal",
"author_id": 6237093,
"author_profile": "https://Stackoverflow.com/users/6237093",
"pm_score": 1,
"selected": true,
"text": "I3 =LET(dates, A1:A12, values, B1:B12&C1:C12&D1:D12, lkUp, F2:F3&G2:G3&H2:H3,\n REDUCE(0, UNIQUE(dates), LAMBDA(acc,ux, LET(\n set, FILTER(values, dates=ux), match, IF(COUNT(XMATCH(lkUp, set))=2, 1, 0), \n acc + match)))\n)\n dates XMATCH lkUp 1 0 REDUCE"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20570218/"
] |
74,529,837
|
<p>Lets say I am having two collections named CollectionA and CollectionB, Both collection have <strong>different fields</strong>.
CollectionA will have multiple documents with Same field,
CollectionB contain only one document</p>
<p>Example</p>
<pre><code>CollectionA
{
"UniqeId" :1,
"Hobbies" : "Eating"
},
{
"UniqeId" :2,
"Hobbies" : "Sleeping"
},
{
"UniqeId" :3,
"Hobbies" : "Walking"
}
CollectionB
{
"UserName" :"Sukuna",
"UserType" : "Villan"
}
</code></pre>
<p>I want output like this</p>
<pre><code>{
"UniqeId" :1,
"Hobbies" : "Eating",
"UserName" :"Sukuna",
"UserType" : "Villan"
}
</code></pre>
<p>Consider All the documents in a CollectionA will contain same fields
And you can see there is no Unique fields between the two collection, and you can see we need to apply filter in CollectionA
ie) <strong>UniqeId=1</strong></p>
<p>I am using C#, and I can able do two DB request to get those collection details (<em>One req for CollectionA output and another one for CollectionB output</em>) and manage to combine both in API level to get the desired output, but I want to do in DB level itself,</p>
<p>I don't want two DB calls, that is eating the API performance, so is there anyway to achieve this in a <strong>single DB call</strong> or by using any <strong>aggregate pipeline</strong>?.
Thanks in Advance</p>
|
[
{
"answer_id": 74540749,
"author": "YuTing",
"author_id": 16695245,
"author_profile": "https://Stackoverflow.com/users/16695245",
"pm_score": 2,
"selected": true,
"text": "db.a.aggregate([\n {\n $lookup: {\n from: \"b\",\n localField: \"1\",\n foreignField: \"1\",\n as: \"docs\"\n }\n },\n {\n $replaceRoot: {\n newRoot: {\n $mergeObjects: [\n \"$$ROOT\",\n { $first: \"$docs\" }\n ]\n }\n }\n },\n {\n $unset: [ \"docs\", \"_id\" ]\n },\n {\n $group: {\n _id: \"$UserName\",\n doc: { $first: \"$$ROOT\" }\n }\n },\n {\n $replaceWith: \"$doc\"\n }\n])\n"
},
{
"answer_id": 74551853,
"author": "Thiru",
"author_id": 18065912,
"author_profile": "https://Stackoverflow.com/users/18065912",
"pm_score": 0,
"selected": false,
"text": "var pipeline1= new BsonDocument(\"$unionWith\", \n new BsonDocument\n {\n { \"coll\", \"CollectionB\" }, \n { \"pipeline\", \n new BsonArray\n {\n new BsonDocument(\"$match\", \n new BsonDocument(\"UniqeId\", 1))\n } }\n });\n\nvar pipeline2 = new BsonDocument(\"$group\", \n new BsonDocument\n {\n { \"_id\", 0 }, \n { \"merged\", \n new BsonDocument(\"$push\", \"$$ROOT\") }\n });\n\nvar pipeline3 = new BsonDocument(\"$replaceRoot\", \n new BsonDocument(\"newRoot\", \n new BsonDocument(\"$mergeObjects\", \"$merged\")));\n\nvar pipeline4 = new BsonDocument(\"$project\", \n new BsonDocument(\"_id\", 0));\n\n\nBsonDocument[] pipeline = new BsonDocument[] { pipeline1, pipeline2, pipeline3, pipeline4 };\n\nvar dbResponse = await collection.Aggregate<BsonDocument>(pipeline).ToListAsync();\n\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18065912/"
] |
74,529,863
|
<p>Basically i have a dataset with car models and i need a bar graph where the highest review count of 20 car brands should be displayed in the bar graph!</p>
<p>I have tried this below code but i am getting all the brand models from the dataset but i need only top 20 highest review count car brands in bar graph.</p>
<p><a href="https://i.stack.imgur.com/gsTCS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gsTCS.png" alt="[enter image description here](https://i.stack.imgur.com/iHZRz.png)" /></a></p>
<p>Used Dataset : <a href="https://www.kaggle.com/datasets/tr1gg3rtrash/cars-2022-dataset?group=owned" rel="nofollow noreferrer">https://www.kaggle.com/datasets/tr1gg3rtrash/cars-2022-dataset?group=owned</a></p>
|
[
{
"answer_id": 74540749,
"author": "YuTing",
"author_id": 16695245,
"author_profile": "https://Stackoverflow.com/users/16695245",
"pm_score": 2,
"selected": true,
"text": "db.a.aggregate([\n {\n $lookup: {\n from: \"b\",\n localField: \"1\",\n foreignField: \"1\",\n as: \"docs\"\n }\n },\n {\n $replaceRoot: {\n newRoot: {\n $mergeObjects: [\n \"$$ROOT\",\n { $first: \"$docs\" }\n ]\n }\n }\n },\n {\n $unset: [ \"docs\", \"_id\" ]\n },\n {\n $group: {\n _id: \"$UserName\",\n doc: { $first: \"$$ROOT\" }\n }\n },\n {\n $replaceWith: \"$doc\"\n }\n])\n"
},
{
"answer_id": 74551853,
"author": "Thiru",
"author_id": 18065912,
"author_profile": "https://Stackoverflow.com/users/18065912",
"pm_score": 0,
"selected": false,
"text": "var pipeline1= new BsonDocument(\"$unionWith\", \n new BsonDocument\n {\n { \"coll\", \"CollectionB\" }, \n { \"pipeline\", \n new BsonArray\n {\n new BsonDocument(\"$match\", \n new BsonDocument(\"UniqeId\", 1))\n } }\n });\n\nvar pipeline2 = new BsonDocument(\"$group\", \n new BsonDocument\n {\n { \"_id\", 0 }, \n { \"merged\", \n new BsonDocument(\"$push\", \"$$ROOT\") }\n });\n\nvar pipeline3 = new BsonDocument(\"$replaceRoot\", \n new BsonDocument(\"newRoot\", \n new BsonDocument(\"$mergeObjects\", \"$merged\")));\n\nvar pipeline4 = new BsonDocument(\"$project\", \n new BsonDocument(\"_id\", 0));\n\n\nBsonDocument[] pipeline = new BsonDocument[] { pipeline1, pipeline2, pipeline3, pipeline4 };\n\nvar dbResponse = await collection.Aggregate<BsonDocument>(pipeline).ToListAsync();\n\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20570476/"
] |
74,529,877
|
<p>Task policy:</p>
<pre><code>class TaskPolicy
{
use HandlesAuthorization;
public function canSeeTeam()
{
return true;
}
}
</code></pre>
<p>AuthServiceProvider:</p>
<pre><code>class AuthServiceProvider extends ServiceProvider
{
protected $policies = [
'App\Models\Task' => 'App\Policies\TaskPolicy',
];
</code></pre>
<p>Task controller:</p>
<pre><code>public function update(Request $request, Task $task)
{
$this->authorize('canSeeTeam');
dd('Authorized!');
}
</code></pre>
<p>Instead of getting <code>Authorized!</code> I get:</p>
<blockquote>
<p>"message": "This action is unauthorized.",
"exception": "Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException",</p>
</blockquote>
<p>I'm logged in, and have access to the team, not it matters because <code>canSeeTeam</code> always <code>true</code>.</p>
|
[
{
"answer_id": 74530425,
"author": "Huy Dev",
"author_id": 16054374,
"author_profile": "https://Stackoverflow.com/users/16054374",
"pm_score": -1,
"selected": false,
"text": " public function canSeeTeam()\n {\n return true; => return false;\n }\n"
},
{
"answer_id": 74530581,
"author": "stefket",
"author_id": 2499739,
"author_profile": "https://Stackoverflow.com/users/2499739",
"pm_score": 2,
"selected": true,
"text": "$this->authorize('canSeeTeam', $task);\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20178708/"
] |
74,529,906
|
<p>Am trying to create an R dodged geom bar with this data but am not getting a plot that i need</p>
<pre><code> Department Male Female
<chr> <int> <int>
1 "Admin Offices" 3 6
2 "Executive Office" 0 1
3 "IT/IS" 28 22
4 "Production " 83 126
5 "Sales" 16 15
6 "Software Engineering" 5 6
</code></pre>
<p>What i tried seems pretty wrong so anyone can help</p>
|
[
{
"answer_id": 74530425,
"author": "Huy Dev",
"author_id": 16054374,
"author_profile": "https://Stackoverflow.com/users/16054374",
"pm_score": -1,
"selected": false,
"text": " public function canSeeTeam()\n {\n return true; => return false;\n }\n"
},
{
"answer_id": 74530581,
"author": "stefket",
"author_id": 2499739,
"author_profile": "https://Stackoverflow.com/users/2499739",
"pm_score": 2,
"selected": true,
"text": "$this->authorize('canSeeTeam', $task);\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20570523/"
] |
74,529,946
|
<p>I am fetching images from Firebase storage, if there is no image on firebase, I want to show thumbnail,</p>
<p>Thats where I get the error</p>
<pre><code>if let error = error {
Swift.print(error)
}
</code></pre>
<p>Here is my thumbnail</p>
<pre><code>Image("shoePlaceHolder")
.resizable()
.aspectRatio(contentMode: .fit)
</code></pre>
<p>Here is the complete code</p>
<pre><code>func getFullImageURL() {
let storage = Storage.storage()
let storagePath = "gs://on-switch.appspot.com/main/\(season)/"
let storageRef = storage.reference(forURL: storagePath)
let formattedImageURL = imageURL.absoluteString.replacingOccurrences(of: "file:///", with: "")
let ref = storageRef.child(formattedImageURL)
ref.downloadURL { url, error in
DispatchQueue.main.async {
if let error = error {
Swift.print(error)
} else if let url = url {
fullImageURL = url
} else {
Swift.print("No url and no error")
}
}
}
}
@ViewBuilder
var content: some View {
VStack {
VStack {
headerView()
HStack {
AsyncImage(url: $fullImageURL.wrappedValue) { image in
image
.resizable()
.aspectRatio(contentMode: .fit)
} placeholder: {
Image("shoePlaceHolder")
.resizable()
.aspectRatio(contentMode: .fit)
}.frame(width: 260, height: 180)
.onAppear(perform: getFullImageURL)
VStack(alignment: .leading) {
titleView()
subtitleView()
}
Spacer()
}
}
.padding()
OnDivider()
.padding(.horizontal)
SectionView(leadingView: {
Text("\(variants.count) variants")
.secondaryText()
}, trailingView: {
Image(systemName: "rectangle.expand.vertical")
.foregroundColor(Color(.secondaryLabel))
}).padding()
}
</code></pre>
|
[
{
"answer_id": 74587495,
"author": "Owen Zhao",
"author_id": 1606231,
"author_profile": "https://Stackoverflow.com/users/1606231",
"pm_score": 0,
"selected": false,
"text": "if error.localizedDescription == NoImageErrorString { // NoImageErrorString is something you can find in Firebase code\n // show thumbnail here\n} else {\n // your original code\n}\n"
},
{
"answer_id": 74592268,
"author": "cora",
"author_id": 11287363,
"author_profile": "https://Stackoverflow.com/users/11287363",
"pm_score": 0,
"selected": false,
"text": "struct ContentView: View {\n @State private var url: URL?\n \n func getFullImageURL() {\n self.url = URL(string: \"\")\n }\n \n var body: some View {\n VStack {\n AsyncImage(url: url) { image in\n image\n .resizable()\n .aspectRatio(contentMode: .fit)\n } placeholder: {\n Image(systemName: \"star\")\n .resizable()\n .aspectRatio(contentMode: .fit)\n }\n .frame(width: 260, height: 180)\n .onAppear(perform: getFullImageURL)\n }\n .padding()\n }\n}\n\nstruct ContentView_Previews: PreviewProvider {\n static var previews: some View {\n ContentView()\n }\n}\n shoePlaceHolder Assets Image(\"shoePlaceHolder\")\n"
},
{
"answer_id": 74613480,
"author": "aone",
"author_id": 3575747,
"author_profile": "https://Stackoverflow.com/users/3575747",
"pm_score": 0,
"selected": false,
"text": "struct ImageWithErrorPlaceholder {\n var fullImageURL: URL?\n var showErrorPlaceholder: Bool = false\n}\n ref.downloadURL { url, error in\n DispatchQueue.main.async {\n if let error = error {\n imageWithErrorPlaceholder.showErrorPlaceholder = true\n Swift.print(error)\n } else if let url = url {\n imageWithErrorPlaceholder.fullImageURL = url\n } else {\n Swift.print(\"No url and no error\")\n }\n }\n}\n AsyncImage(url: imageWithErrorPlaceholder.fullImageURL) { image in\n image\n .resizable()\n .aspectRatio(contentMode: .fit)\n} placeholder: {\n if imageWithErrorPlaceholder.showErrorPlaceholder {\n Image(\"shoePlaceHolder\")\n .resizable()\n .aspectRatio(contentMode: .fit)\n }\n}\n"
},
{
"answer_id": 74614068,
"author": "Payam Asefi",
"author_id": 1656813,
"author_profile": "https://Stackoverflow.com/users/1656813",
"pm_score": 1,
"selected": false,
"text": "fullImageURL fullImageURL = nil\n func getFullImageURL() {\n let storage = Storage.storage()\n let storagePath = \"gs://on-switch.appspot.com/main/\\(season)/\"\n let storageRef = storage.reference(forURL: storagePath) \n let formattedImageURL = imageURL.absoluteString.replacingOccurrences(of: \"file:///\", with: \"\")\n let ref = storageRef.child(formattedImageURL)\n ref.downloadURL { url, error in\n DispatchQueue.main.async {\n if let error = error {\n Swift.print(error)\n fullImageURL = nil\n } else if let url = url {\n fullImageURL = url\n } else {\n Swift.print(\"No url and no error\")\n fullImageURL = nil\n }\n }\n }\n }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/315594/"
] |
74,529,972
|
<p>I don't understand why it is giving me this error:</p>
<p>Uncaught SyntaxError: Identifier 'html' has already been declared (at obtenerTipos.js:1:1) at obtenerTipos.js:1:</p>
<pre><code>var xmlHttp = new XMLHttpRequest();
xmlHttp.open(
"GET",
"http://localhost:8080/recetarioappmain/sistema/API/tipos.php",
false
); // false for synchronous request
xmlHttp.send(null);
//console.log(xmlHttp.responseText);
//Convertimos en objeto
var resultadoTipos = JSON.parse(xmlHttp.responseText);
//console.log(resultadoTipos);
var html = '<option value="">Seleccione un tipo</option>';
for (var i = 0; i < resultadoTipos.length; i++) {
html +=
'<option value="' +
resultadoTipos[i].id +
'">' +
resultadoTipos[i].nombre +
"</option>";
}
document.getElementById("id_tipos").innerHTML += html;
</code></pre>
<p>Can anybody help me? I can't see what's going on.</p>
<p>Thank you</p>
|
[
{
"answer_id": 74530102,
"author": "jjj",
"author_id": 13365797,
"author_profile": "https://Stackoverflow.com/users/13365797",
"pm_score": -1,
"selected": true,
"text": "// var html = '<option value=\"\">Seleccione un tipo</option>';\nvar my_unique_html = '<option value=\"\">Seleccione un tipo</option>';\n"
},
{
"answer_id": 74530158,
"author": "Dr. Light",
"author_id": 13225518,
"author_profile": "https://Stackoverflow.com/users/13225518",
"pm_score": 0,
"selected": false,
"text": "let const var let let const var var a b if (someCondition) {\n var a = 'someValue'\n let b = 'someOtherValue'\n}\nconsole.log(a)\nconsole.log(b)\n let const var"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18979748/"
] |
74,529,973
|
<p>I'm using the Go client for Bigquery with our setup located (as far as I can tell) entirely in the EU location, but I see some errors stating</p>
<pre><code>Access Denied: Table <table>: User does not have permission to query table <table>, or perhaps it does not exist in location US
</code></pre>
<p>My understanding is that if my dataset and tables are in EU, the jobs will also be run there. However, I can see in the log details that the job is labeled as using the US location:</p>
<pre><code>resource: {
labels: {
location: "US"
project_id: "<project_id>"
}
type: "bigquery_project"
}
</code></pre>
<p>The CloudRun instance this is running from is also in the EU, specifically <code>europe-west6</code>.</p>
<p>Not sure how to fix this.</p>
<p>Per comment from <a href="https://stackoverflow.com/users/11372593/guillaume-blaquiere">guillaume blaquiere</a>, here's a rough approximation of the code:</p>
<pre class="lang-golang prettyprint-override"><code>client, err := bigquery.NewClient(ctx, 'my-project')
if err != nil {
return false, err
}
checkQuery := fmt.Sprintf(`
SELECT COUNT(*) AS Count
FROM %s
WHERE Id = @id`,
'tableName',
)
q := client.Query(checkQuery)
q.Parameters = []bigquery.QueryParameter{
{
Name: "id",
Value: id,
},
})
type check struct {
Count int64
}
var check flightCheck
it, err := q.Read(ctx)
if err != nil {
return false, err
}
if err := it.Next(result); err != nil {
s.log.Error(err, "failed to get query result")
return false, err
}
return check > 0, nil
</code></pre>
|
[
{
"answer_id": 74530102,
"author": "jjj",
"author_id": 13365797,
"author_profile": "https://Stackoverflow.com/users/13365797",
"pm_score": -1,
"selected": true,
"text": "// var html = '<option value=\"\">Seleccione un tipo</option>';\nvar my_unique_html = '<option value=\"\">Seleccione un tipo</option>';\n"
},
{
"answer_id": 74530158,
"author": "Dr. Light",
"author_id": 13225518,
"author_profile": "https://Stackoverflow.com/users/13225518",
"pm_score": 0,
"selected": false,
"text": "let const var let let const var var a b if (someCondition) {\n var a = 'someValue'\n let b = 'someOtherValue'\n}\nconsole.log(a)\nconsole.log(b)\n let const var"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/518191/"
] |
74,529,979
|
<p>I'm here because I can't find a solution to my problem. I have a form in Symfony 6 and one of the value is id_client and reffer to another entity, Client (relation ManyToOne).</p>
<p>I tested few methods to make the field be a select choice of all the clients (I show the name of the client). And every of them works but when I submit the form this value is add as the whole entity and not just the id. This is a problem because I end with this:</p>
<p><code>Expected argument of type "int", "App\\Entity\\Client" given at property path "id_client".</code></p>
<p>In my form it looks like this:</p>
<pre><code><?php
namespace App\Form;
use App\Entity\Client;
use App\Entity\Group;
use App\Repository\ClientRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
class Group1Type extends AbstractType
{
private $clientRepository;
public function __construct(ClientRepository $clientRepository)
{
$this->clientRepository = $clientRepository;
$this->clients = $clientRepository->findAll();
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('name', TextType::class, [
'attr' => [
'class' => 'form-control'
],
'label' => 'Name: '
])
->add('can_display', CheckboxType::class, [
'label' => 'Can display : ',
'attr' => [
'class' => 'my-3 mx-2'
]
])
->add('id_client', EntityType::class, [
'class' => Client::class,
// 'choices' => $this->clientRepository->findAllNameAlphabetical(),
// 'query_builder' => function (ClientRepository $client) {
// return $client->findAllNameAlphabetical();
// },
'choice_label' => 'name',
'expanded' => false,
'multiple' => false,
'attr' => [
'class' => 'form-control'
]
])
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Group::class,
]);
}
}
</code></pre>
<p>The twig:</p>
<pre><code><section class="container my-3">
<div class="row">
<div class="col">
{{ form_start(form) }}
{{ form_row(form.name) }}
{{ form_row(form.can_display) }}
{{ form_row(form.id_client) }}
<button class="btn btn-primary my-3">{{ button_label|default('Save') }}</button>
{{ form_end(form) }}
</div>
</div>
</section>
</code></pre>
<p>The controller (I have the same result if I let it as it was at the beginning):</p>
<pre><code>#[Route('/new', name: 'app_group_new', methods: ['GET', 'POST'])]
public function new(Request $request, GroupRepository $groupRepository): Response
{
$group = new Group();
$form = $this->createForm(Group1Type::class, $group);
$form->handleRequest($request);
// $group->id_client = $group->id_client->id;
if ($form->isSubmitted()) {
// dd('submit');
// if(gettype($group->id_client)=="Client"){
// dd($group);
if($form->isValid()){
dd('valid');
$groupRepository->save($group, true);
$this->addFlash('success', 'The creation went successfully.');
return $this->redirectToRoute('app_group_index', [], Response::HTTP_SEE_OTHER);
// }
}
}
return $this->renderForm('group/new.html.twig', [
'group' => $group,
'form' => $form,
]);
}
</code></pre>
<p>My entity:</p>
<pre><code> #[ORM\Column]
private ?int $id_client = null;
</code></pre>
|
[
{
"answer_id": 74533147,
"author": "Jonathan",
"author_id": 3048505,
"author_profile": "https://Stackoverflow.com/users/3048505",
"pm_score": 2,
"selected": true,
"text": "id_* $client $id_client ->add('client', EntityType::class, [\n 'class' => Client::class,\n // ...\n ])\n class Group\n{\n // ...\n\n #[ORM\\ManyToOne(targetEntity: Client::class, inversedBy: 'groups')]\n #[ORM\\JoinColumn(nullable: false)]\n private $client;\n\n // ...\n}\n $id EntityType OneToMany Group Client DataTransformer"
},
{
"answer_id": 74533430,
"author": "benkov",
"author_id": 2769031,
"author_profile": "https://Stackoverflow.com/users/2769031",
"pm_score": -1,
"selected": false,
"text": "public function buildForm(FormBuilderInterface $builder, array $options): void\n{\n $builder\n ->add('client', ChoiceType::class, [\n 'choices'=> $this->getClients(),\n ])\n}\npublic function getClients(){\n $conn = $this->getEntityManager()->getConnection();\n $query = \"SELECT `name`, `id` FROM `clients` order by `name`\";\n $stmt = $conn->executeQuery($query);\n return $stmt->fetchAllKeyValue(); \n }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20570513/"
] |
74,529,980
|
<p>I have a numpy array like this:</p>
<ul>
<li>26.4812 32.0000 -5.0000 10000.0000 20000.0000 2.0000</li>
<li>26.4812 32.0000 10.0000 10000.0000 20000.0000 2.0000</li>
<li>26.4812 32.0000 0.0000 10000.0000 20000.0000 2.0000...</li>
</ul>
<p>I want to change it so that the 3rd column(z value) has more steps like this:</p>
<ul>
<li>26.4812 32.0000 -5.0000 10000.0000 20000.0000 2.0000</li>
<li>26.4812 32.0000 -4.0000 10000.0000 20000.0000 2.0000</li>
<li>26.4812 32.0000 -3.0000 10000.0000 20000.0000 2.0000</li>
<li>...</li>
<li>26.4812 32.0000 9.0000 10000.0000 20000.0000 2.0000</li>
<li>26.4812 32.0000 10.0000 10000.0000 20000.0000 2.0000...</li>
</ul>
<p>the steps must be defined by a variable step = 1mm at this example.
how can i achive that?</p>
|
[
{
"answer_id": 74533147,
"author": "Jonathan",
"author_id": 3048505,
"author_profile": "https://Stackoverflow.com/users/3048505",
"pm_score": 2,
"selected": true,
"text": "id_* $client $id_client ->add('client', EntityType::class, [\n 'class' => Client::class,\n // ...\n ])\n class Group\n{\n // ...\n\n #[ORM\\ManyToOne(targetEntity: Client::class, inversedBy: 'groups')]\n #[ORM\\JoinColumn(nullable: false)]\n private $client;\n\n // ...\n}\n $id EntityType OneToMany Group Client DataTransformer"
},
{
"answer_id": 74533430,
"author": "benkov",
"author_id": 2769031,
"author_profile": "https://Stackoverflow.com/users/2769031",
"pm_score": -1,
"selected": false,
"text": "public function buildForm(FormBuilderInterface $builder, array $options): void\n{\n $builder\n ->add('client', ChoiceType::class, [\n 'choices'=> $this->getClients(),\n ])\n}\npublic function getClients(){\n $conn = $this->getEntityManager()->getConnection();\n $query = \"SELECT `name`, `id` FROM `clients` order by `name`\";\n $stmt = $conn->executeQuery($query);\n return $stmt->fetchAllKeyValue(); \n }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74529980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14295652/"
] |
74,530,022
|
<p>The deviations of the mean should always sum up to 0.
However, when the mean has a lot of digits, maybe infinitely like this one which is 20/7, R fails to calculate it.</p>
<pre><code>x <- c(1,2,2,3,3,4,5)
sum(x - mean(x))
[1] -4.440892e-16
</code></pre>
<p>I am quite a newbie and have not found any information about this so far, maybe I was not searching for the right terms.
Is it possible to calculate with infinitely long numbers in R?
I am asking this out of theoretical interest.</p>
|
[
{
"answer_id": 74533147,
"author": "Jonathan",
"author_id": 3048505,
"author_profile": "https://Stackoverflow.com/users/3048505",
"pm_score": 2,
"selected": true,
"text": "id_* $client $id_client ->add('client', EntityType::class, [\n 'class' => Client::class,\n // ...\n ])\n class Group\n{\n // ...\n\n #[ORM\\ManyToOne(targetEntity: Client::class, inversedBy: 'groups')]\n #[ORM\\JoinColumn(nullable: false)]\n private $client;\n\n // ...\n}\n $id EntityType OneToMany Group Client DataTransformer"
},
{
"answer_id": 74533430,
"author": "benkov",
"author_id": 2769031,
"author_profile": "https://Stackoverflow.com/users/2769031",
"pm_score": -1,
"selected": false,
"text": "public function buildForm(FormBuilderInterface $builder, array $options): void\n{\n $builder\n ->add('client', ChoiceType::class, [\n 'choices'=> $this->getClients(),\n ])\n}\npublic function getClients(){\n $conn = $this->getEntityManager()->getConnection();\n $query = \"SELECT `name`, `id` FROM `clients` order by `name`\";\n $stmt = $conn->executeQuery($query);\n return $stmt->fetchAllKeyValue(); \n }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74530022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19487551/"
] |
74,530,044
|
<p>I have multiple tabitem's (tab1, tab2, ... etc) in a WPF tabcontrol. When I click a button I want to restart the app and open a specific tabitem, say tab2 (in MVVM friendly way).</p>
<p>To restart the app I use</p>
<pre><code> Process.Start(Application.ResourceAssembly.Location);
Application.Current.Shutdown();
</code></pre>
<p>But how do I specify which tabitem to display after restart?</p>
|
[
{
"answer_id": 74533147,
"author": "Jonathan",
"author_id": 3048505,
"author_profile": "https://Stackoverflow.com/users/3048505",
"pm_score": 2,
"selected": true,
"text": "id_* $client $id_client ->add('client', EntityType::class, [\n 'class' => Client::class,\n // ...\n ])\n class Group\n{\n // ...\n\n #[ORM\\ManyToOne(targetEntity: Client::class, inversedBy: 'groups')]\n #[ORM\\JoinColumn(nullable: false)]\n private $client;\n\n // ...\n}\n $id EntityType OneToMany Group Client DataTransformer"
},
{
"answer_id": 74533430,
"author": "benkov",
"author_id": 2769031,
"author_profile": "https://Stackoverflow.com/users/2769031",
"pm_score": -1,
"selected": false,
"text": "public function buildForm(FormBuilderInterface $builder, array $options): void\n{\n $builder\n ->add('client', ChoiceType::class, [\n 'choices'=> $this->getClients(),\n ])\n}\npublic function getClients(){\n $conn = $this->getEntityManager()->getConnection();\n $query = \"SELECT `name`, `id` FROM `clients` order by `name`\";\n $stmt = $conn->executeQuery($query);\n return $stmt->fetchAllKeyValue(); \n }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74530044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6119995/"
] |
74,530,059
|
<p><a href="https://i.stack.imgur.com/SF9r5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SF9r5.png" alt="enter image description here" /></a></p>
<p>Hello I am select boxes when I click on select all, Right now it's selection all the boxes on the page, But I have to make it section specific, Means when I click on "select all" of A section. It should select all A section's boxes, not of section B or C. How to make my selection section specific. plz check image for better understanding</p>
<h1>css</h1>
<pre><code> .box {
background:red;
padding:10px;
width:200px;
display:none;
}
.toggle-check-group {
margin-top: 10px;
padding: 0px 0px;
margin-bottom: 20px;
}
.switch input {
opacity: 0 !important;
width: 0 !important;
height: 0 !important;
}
.slider {
cursor: url('../img/pest_cursor.svg'), move !important;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #fff;
-webkit-transition: .1s;
transition: .1s;
text-align: center;
margin: auto;
padding: 5px 10px;
border: 1px solid #707070;
border-radius: 5px;
font-size: .8rem;
margin-right: 10px;
transition: top .1s;
}
.slider:hover {
top: -5px;
}
input:checked + .slider {
color: #188a80;
background-color: #daf1ef;
border: 1px solid #188a80;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
.slider::selection {
color: none;
background: none;
}
/* For Mozilla Firefox */
.slider::-moz-selection {
color: none;
background: none;
}
/* For Mozilla Firefox */
.slider::-webkit-selection {
color: none;
background: none;
}
</code></pre>
<h1>html</h1>
<pre><code> <div class="card" style="background:#ff000014; padding:10px;">
<div class="card-header " id="Div1">
<h3>Section A</h3>
<h5 class="mb-0 ">
<a class="btn-link " data-toggle="collapse" data-target="#cp2" aria-expanded="true" aria-controls="collapsecroptwo">Select All
<img src="select_all.png" class="check-all " onclick="Toggle()" />
</a>
</h5>
</div>
<div id="Div2" class="collapse show" aria-labelledby="headingcroptwo" data-parent="#accordion" style="">
<div class="card-body">
<div id="Div3" class="category-list list-style-none">
<ul>
<li>
<div class="toggle-check-group">
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll()"><span class="slider" name="pname" title="PNAME">Option-1</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll();"><span class="slider" name="pname" title="PNAME">Option-2</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll();"><span class="slider" name="pname" title="PNAME">Option-3</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll(); "><span class="slider" name="pname" title="PNAME">Option-4</span></label>
</div>
</li>
<li>
<div class="toggle-check-group">
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll()"><span class="slider" name="pname" title="PNAME">Option-1</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll();"><span class="slider" name="pname" title="PNAME">Option-2</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll();"><span class="slider" name="pname" title="PNAME">Option-3</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll(); "><span class="slider" name="pname" title="PNAME">Option-4</span></label>
</div>
</li>
<li>
<div class="toggle-check-group">
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll()"><span class="slider" name="pname" title="PNAME">Option-1</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll();"><span class="slider" name="pname" title="PNAME">Option-2</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll();"><span class="slider" name="pname" title="PNAME">Option-3</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll(); "><span class="slider" name="pname" title="PNAME">Option-4</span></label>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
<br />
<br />
<div class="card" style="background:#f8f6ef; padding:10px;">
<div class="card-header " id="Div4">
<h3>Section B</h3>
<h5 class="mb-0 ">
<a class="btn-link " data-toggle="collapse" data-target="#cp2" aria-expanded="true" aria-controls="collapsecroptwo">Select All
<img src="select_all.png" class="check-all " onclick="Toggle()" />
</a>
</h5>
</div>
<div id="Div5" class="collapse show" aria-labelledby="headingcroptwo" data-parent="#accordion" style="">
<div class="card-body">
<div id="Div6" class="category-list list-style-none">
<ul>
<li>
<div class="toggle-check-group">
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll()"><span class="slider" name="pname" title="PNAME">Option-1</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll();"><span class="slider" name="pname" title="PNAME">Option-2</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll();"><span class="slider" name="pname" title="PNAME">Option-3</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll(); "><span class="slider" name="pname" title="PNAME">Option-4</span></label>
</div>
</li>
<li>
<div class="toggle-check-group">
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll()"><span class="slider" name="pname" title="PNAME">Option-1</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll();"><span class="slider" name="pname" title="PNAME">Option-2</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll();"><span class="slider" name="pname" title="PNAME">Option-3</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll(); "><span class="slider" name="pname" title="PNAME">Option-4</span></label>
</div>
</li>
<li>
<div class="toggle-check-group">
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll()"><span class="slider" name="pname" title="PNAME">Option-1</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll();"><span class="slider" name="pname" title="PNAME">Option-2</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll();"><span class="slider" name="pname" title="PNAME">Option-3</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll(); "><span class="slider" name="pname" title="PNAME">Option-4</span></label>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
<br />
<br />
<div class="card" style="background:#ebebf1; padding:10px;">
<div class="card-header " id="Div7">
<h3>Section B</h3>
<h5 class="mb-0 ">
<a class="btn-link " data-toggle="collapse" data-target="#cp2" aria-expanded="true" aria-controls="collapsecroptwo">Select All
<img src="select_all.png" class="check-all " onclick="Toggle()" />
</a>
</h5>
</div>
<div id="Div8" class="collapse show" aria-labelledby="headingcroptwo" data-parent="#accordion" style="">
<div class="card-body">
<div id="Div9" class="category-list list-style-none">
<ul>
<li>
<div class="toggle-check-group">
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll()"><span class="slider" name="pname" title="PNAME">Option-1</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll();"><span class="slider" name="pname" title="PNAME">Option-2</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll();"><span class="slider" name="pname" title="PNAME">Option-3</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll(); "><span class="slider" name="pname" title="PNAME">Option-4</span></label>
</div>
</li>
<li>
<div class="toggle-check-group">
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll()"><span class="slider" name="pname" title="PNAME">Option-1</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll();"><span class="slider" name="pname" title="PNAME">Option-2</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll();"><span class="slider" name="pname" title="PNAME">Option-3</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll(); "><span class="slider" name="pname" title="PNAME">Option-4</span></label>
</div>
</li>
<li>
<div class="toggle-check-group">
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll()"><span class="slider" name="pname" title="PNAME">Option-1</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll();"><span class="slider" name="pname" title="PNAME">Option-2</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll();"><span class="slider" name="pname" title="PNAME">Option-3</span></label>
<label class="switch">
<input type="checkbox" name="pestname" title="3" class="myinput" onclick="CheckUnCheckAll(); "><span class="slider" name="pname" title="PNAME">Option-4</span></label>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</code></pre>
<h1>JS</h1>
<pre><code> <script>
//get all elements with tag name input
var checkboxes = document.getElementsByClassName("myinput");
//create toggle function
function Toggle() {
//iterate over all checkboxes and mark check = true
for (i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type === 'checkbox')
checkboxes[i].checked = !checkboxes[i].checked;
}
}
</script>
</code></pre>
|
[
{
"answer_id": 74533147,
"author": "Jonathan",
"author_id": 3048505,
"author_profile": "https://Stackoverflow.com/users/3048505",
"pm_score": 2,
"selected": true,
"text": "id_* $client $id_client ->add('client', EntityType::class, [\n 'class' => Client::class,\n // ...\n ])\n class Group\n{\n // ...\n\n #[ORM\\ManyToOne(targetEntity: Client::class, inversedBy: 'groups')]\n #[ORM\\JoinColumn(nullable: false)]\n private $client;\n\n // ...\n}\n $id EntityType OneToMany Group Client DataTransformer"
},
{
"answer_id": 74533430,
"author": "benkov",
"author_id": 2769031,
"author_profile": "https://Stackoverflow.com/users/2769031",
"pm_score": -1,
"selected": false,
"text": "public function buildForm(FormBuilderInterface $builder, array $options): void\n{\n $builder\n ->add('client', ChoiceType::class, [\n 'choices'=> $this->getClients(),\n ])\n}\npublic function getClients(){\n $conn = $this->getEntityManager()->getConnection();\n $query = \"SELECT `name`, `id` FROM `clients` order by `name`\";\n $stmt = $conn->executeQuery($query);\n return $stmt->fetchAllKeyValue(); \n }\n"
}
] |
2022/11/22
|
[
"https://Stackoverflow.com/questions/74530059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15232179/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.