qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,228,635 | <p>In an endeavor to write cleaner code I'm (likely over-)using <code>enums</code>, like so:</p>
<pre><code>enum class SoundFileCode : char {
PC_STARTUP = '1', // probably never used
LOADING_READY = '2',
VOICE_RECOGNITION_ON = '3',
VOICE_RECOGNITION_OFF = '4',
DISPENSING = '5'
};
</code></pre>
<p>I'd like to be able to pass that value to a function in a nice clean way (preferably without having to cast anything to make it a cleaner API):</p>
<p><code>sendRemoteAudioMessage(SoundFileCode::LOADING_READY);</code></p>
<p>Here's the function signature:
<code>void sendRemoteAudioMessage(char audioCode){ }</code></p>
<p>I see you shaking your head. You already know the error I'm going to get: <code>Compilation error: cannot convert 'SoundFileCode' to 'char' for argument '1' to 'void sendRemoteAudioMessage(char)'</code></p>
<p>My goals are:</p>
<ol>
<li>To make it easy for code completion to suggest these hard-coded constant values</li>
<li>To be able to reuse the same names, but keep them namespaced cleanly within their own enum</li>
<li>To make it easy for a programmer to just select a code and pass it to the function without thinking too hard about it.</li>
</ol>
<p>If enums won't foot the bill here, what's a good approach? Creating a class with some static constants? (this is likely how I'd approach it in PHP / Java)</p>
<p><strong>UPDATE</strong></p>
<p>The following (if somewhat verbose) approach compiles and runs fine. Is there a superior approach?</p>
<pre><code>class SoundFileCode {
public :
static const char PC_STARTUP = '1';
static const char LOADING_READY = '2';
static const char VOICE_RECOGNITION_ON = '3';
static const char VOICE_RECOGNITION_OFF = '4';
static const char DISPENSING = '5';
};
</code></pre>
| [
{
"answer_id": 74228692,
"author": "lorro",
"author_id": 6292621,
"author_profile": "https://Stackoverflow.com/users/6292621",
"pm_score": 3,
"selected": true,
"text": "enum class"
},
{
"answer_id": 74228703,
"author": "eerorika",
"author_id": 2079303,
"author_profile... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/467386/"
] |
74,228,651 | <p>I have been using Github Actions to deploy changes for a data engineering project. I have been getting warnings that set-output command is deprecated and am attempting to use $GITHUB_OUTPUT but I am not able to set the output of the job using this.</p>
<pre><code>if_merged:
runs-on: ubuntu-latest
if: github.event.pull_request.merged == true
name: check diff changed
steps:
- name: Checkout
uses: actions/checkout@v3
with:
# Checkout as many commits as needed for the diff
fetch-depth: 2
- shell: pwsh
id: check_file_changed
run: |
# Diff HEAD with the previous commit
# filters out deleted files
$diff = git diff --name-only --diff-filter=d HEAD^ HEAD
# Check what files were in the diff
echo $diff
# Check if a file Pipfile.lock or Dockerfile has changed (added, modified, deleted)
$BuildDiff = $diff | Where-Object { $_ -match 'Pipfile.lock' -or $_ -match 'Dockerfile'}
$HasBuildDiff = $BuildDiff.Length -gt 0
# Check if k8s job has changed
$K8sDiff = $diff | Where-Object { $_ -match 'kubernetes_job.py'}
$HasK8sDiff = $K8sDiff.Length -gt 0
# Check if sql file has changed
$SqlDiff = $diff | Where-Object { $_ -match '.sql'}
$HasSqlDiff = $SqlDiff.Length -gt 0
# Check if flow file has changed
$FlowDiff = $diff | Where-Object { $_ -match 'flow.py'}
$HasFlowDiff = $FlowDiff.Length -gt 0
# Check value of matched object
echo BuildDiff $BuildDiff ---
echo K8sDiff $K8sDiff ---
# echo DeploymentDiff $DeploymentDiff ---
echo FlowDiff $FlowDiff ---
# Set the outputs
Write-Host "::set-output name=build_changed::$HasBuildDiff"
Write-Host "::set-output name=k8s_changed::$HasK8sDiff"
Write-Host "::set-output name=sql_changed::$HasSqlDiff"
Write-Host "flow_changed=$HasFlowDiff" >> $GITHUB_OUTPUT
# Write-Host "::set-output name=flow_changed::$HasFlowDiff"
outputs:
build_changed: ${{ steps.check_file_changed.outputs.build_changed }}
k8s_changed: ${{ steps.check_file_changed.outputs.k8s_changed }}
sql_changed: ${{ steps.check_file_changed.outputs.sql_changed }}
flow_changed: ${{ steps.check_file_changed.outputs.flow_changed }}
</code></pre>
<p>I commented out one portion of the Set the outputs step and updated it to $GITHUB_OUTPUT. However, when the job runs the flow_changed output is not set. I cant post images, but if I look at the complete job section after the action runs with $GITHUB_OUTPUT flow_changed is not set. It is set when I use the old set-output command.</p>
| [
{
"answer_id": 74231490,
"author": "jwpol",
"author_id": 8734046,
"author_profile": "https://Stackoverflow.com/users/8734046",
"pm_score": 0,
"selected": false,
"text": "echo \"build_changed=$HasBuildDiff\" >> $GITHUB_OUTPUT\necho \"k8s_changed=$HasK8sDiff\" >> $GITHUB_OUTPUT\necho \"sql... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20353029/"
] |
74,228,653 | <p>I'm currently trying to add multiple columns to my dataframe using mutate.</p>
<p>This is what I started with:</p>
<pre><code>new_df <- old_df %>%
mutate(demo = c("audience 1", "audience 2")
</code></pre>
<p>Here's what I wanted to happen</p>
<pre><code>game demo
1 audience 1
1 audience 2
2 audience 1
2 audience 2
</code></pre>
<p>However this just results in an error. I know this is just my bad beginner syntax, can someone help?</p>
| [
{
"answer_id": 74228727,
"author": "zephryl",
"author_id": 17303805,
"author_profile": "https://Stackoverflow.com/users/17303805",
"pm_score": 3,
"selected": true,
"text": "old_df"
},
{
"answer_id": 74228881,
"author": "SpikyClip",
"author_id": 16745699,
"author_profi... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20353096/"
] |
74,228,654 | <p>I'm looking to generate popover highlight tags on data that I've gotten from a query. Currently, I've tried finding substrings wrapped in curly braces within the text, then replacing them with components, but I can't figure out how to get Vue to render & mount the new components</p>
<p>Example text:</p>
<pre class="lang-markdown prettyprint-override"><code>Lorem {ipsum} dolor sit amet, consectetur {adipiscing} elit, sed do eiusmod tempor incididunt
</code></pre>
<p>I've created a fairly simple regex to find and grab text wrapped in curly braces:</p>
<pre><code>\{(.[^{}]*)\}
</code></pre>
<p>And this is the code I've tried so far:</p>
<pre><code><template>
<span v-html="paragraphText"></span>
</template>
<script lang="ts">
import {MyComponent} from '#components';
export default defineComponent({
data () {
return {
paragraphText: '',
}
},
created () {
const re = /\{(.[^{}]*)\}/g;
let newText = `${this.text}`;
let match: RegExpExecArray;
do {
match = re.exec(newText);
if (match) {
newText = newText.replace(
match[0],
`<MyComponent ref='${match[1]}' style='font-weight:bold;'>${match[1]}</MyComponent>`
);
}
} while (match);
this.paragraphText = newText;
},
components: {
MyComponent,
}
})
</script>
</code></pre>
<p>I'm well aware that <code>v-html</code> won't render components to avoid XSS attacks, but this is mostly just to show what I'm trying to achieve.</p>
<p>My reasoning behind having a component behind each one, is that I want the component to make a web request on hover, to grab some additional information about the word being highlighted.</p>
<p>I'm looking for the cleanest and/or most efficient solution possible - it doesn't have to be Options API</p>
| [
{
"answer_id": 74229281,
"author": "Jaromanda X",
"author_id": 5053002,
"author_profile": "https://Stackoverflow.com/users/5053002",
"pm_score": 3,
"selected": true,
"text": "const { createApp, ref, computed } = Vue;\n\ncreateApp({\n setup() {\n const data = ref(\"Lorem {ipsum}... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9709557/"
] |
74,228,659 | <p>I'm working on a project where I have to give a background-image a full width. The image should become larger as I make the screen larger, and smaller as I make the screen smaller.</p>
<p>This is my code at the moment. It's a footer decoration:</p>
<pre><code>.footerDeco {
background-image: url(../resources/image_geometry_2.svg);
background-repeat: no-repeat;
height: 160px;
background-size: cover;
}
</code></pre>
<p>The background-size: cover makes the image adapt to full width, but the height of the image remains 160px no matter what. If I make the height larger, then it's a problem because it doesn't shrink back proportionally as the screen becomes smaller.</p>
<p>I have tried giving it a height auto or a height 100% expecting the height to change proportionally to the width. (I do understand this height is the height of the footer container, but I don't know how to change it otherwise).</p>
<p>I know it would be much easier to use an img tag. But the demands of the project and good practice insist that since this is a decoration, I should use the background-image property. Is it possible? Thanks!</p>
<p>P.S.: There are similar questions that have been answered here, but none of them (as far as I can tell) solve the problem of the image resizing past the constant container height of 16px.</p>
| [
{
"answer_id": 74229281,
"author": "Jaromanda X",
"author_id": 5053002,
"author_profile": "https://Stackoverflow.com/users/5053002",
"pm_score": 3,
"selected": true,
"text": "const { createApp, ref, computed } = Vue;\n\ncreateApp({\n setup() {\n const data = ref(\"Lorem {ipsum}... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12087785/"
] |
74,228,715 | <p>Need help.
I have a json file locally and I want to render a list. So that in the future I can add data to the json file and it will automatically appear on the page.</p>
<pre><code>[
{
country: "England",
cities: [
{
wikiLink: "https://en.wikipedia.org/wiki/London",
citiesName: "London",
citiesDescription: "is the capital and largest city of England and the United Kingdom, with a population of just under 9 million",
},
{
wikiLink: "https://en.wikipedia.org/wiki/Liverpool",
citiesName: "Liverpool",
citiesDescription: "Is a city and metropolitan borough in Merseyside",
},
]
},
{
country: "Island",
cities: [
{
wikiLink: "https://en.wikipedia.org/wiki/Reykjav%C3%ADk",
citiesName: "Reykjavík",
citiesDescription: "It is located in southwestern Iceland, on the southern shore of Faxaflói bay.",
},
]
},
]`
</code></pre>
<p>I want to get the following code after rendering</p>
<pre><code><div class="content">
<div class="section">
<h2 class="title">England</h2>
<ul class="list">
<li class="list__item">
<a class="list__link" href="https://en.wikipedia.org/wiki/London" target="_blank">
<span class="gradient__text">London</span>
- is the capital and largest city of England and the United Kingdom, with a population of just under 9 million
</a>
</li>
<li class="list__item">
<a class="list__link" href="https://en.wikipedia.org/wiki/Liverpool" target="_blank">
<span class="gradient__text">Liverpool</span>
- Is a city and metropolitan borough in Merseyside
</a>
</li>
</ul>
</div>
<div class="section">
<h2 class="title">Island</h2>
<ul class="list">
<li class="list__item">
<a class="list__link" href="https://en.wikipedia.org/wiki/Reykjavik" target="_blank">
<span class="gradient__text">Reykjavík</span>
- It is located in southwestern Iceland, on the southern shore of Faxaflói bay.
</a>
</li>
</ul>
</div>
</div>`
</code></pre>
<p><a href="https://i.stack.imgur.com/mWwFj.png" rel="nofollow noreferrer">This is roughly what I want to get</a></p>
<p>I can't figure out how to get to the values of cities. Right now my code looks like this:</p>
<pre><code>import { englandData } from "./englandData.js";
import { islandData } from "./islandData.js";
function blockTemplate(block) {
return`
<div class="list__block-item">
<h2 class="list__desc">
${block.country}
</h2>
<ul class="list">
<li class="list__item">
<a class="list__link" href="${block.cities.wikiLink}" target="_blank">
<span class="gradient__text">${block.cities.citiesName}</span> - ${block.cities.citiesDescription}.
</a>
</li>
</ul>
</div>
`
}
document.getElementById("en").innerHTML = `
${englandData.map(blockTemplate).join("")}
`;
document.getElementById("is").innerHTML = `
${islandData.map(blockTemplate).join("")}
`;
</code></pre>
| [
{
"answer_id": 74229281,
"author": "Jaromanda X",
"author_id": 5053002,
"author_profile": "https://Stackoverflow.com/users/5053002",
"pm_score": 3,
"selected": true,
"text": "const { createApp, ref, computed } = Vue;\n\ncreateApp({\n setup() {\n const data = ref(\"Lorem {ipsum}... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19416251/"
] |
74,228,720 | <p>when I got an array of pointers and a pointer why sizeof the array of poninters is equal to the sizeof pointer?
for example:</p>
<pre><code>char *matrixp;
char **m;
printf("%llu", sizeof matrixp);
printf("%llu", sizeof m);
</code></pre>
<p>gives back the same output.
is there a way I can get the total size in bytes for example of</p>
<pre><code>char *vet[10]
</code></pre>
<p>? (that should be 80).</p>
| [
{
"answer_id": 74228911,
"author": "John Bode",
"author_id": 134554,
"author_profile": "https://Stackoverflow.com/users/134554",
"pm_score": 2,
"selected": false,
"text": "char *"
},
{
"answer_id": 74229073,
"author": "DrOncogene",
"author_id": 17748128,
"author_profi... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19064064/"
] |
74,228,723 | <p>i am writing a code to check for session and session value and if they do not exists or exists but have empty value or 0, i want them redirected</p>
<p>here is my start</p>
<pre><code><cfset lstofSessionsToCheck = 'EmplyID,Username'>
<cfset st = {}>
<cfloop collection="#session#" item="i">
<cfset SetVariable("st.session.#i#",duplicate(session[i]))>
</cfloop>
<cfparam name="redirection" default="false">
<cfif session.Username eq ''>
<cfset redirection = true>
<cfelseif session.EmplyID eq ''>
<cfset redirection = true>
</cfif>
</code></pre>
<p>it is missing some checks here</p>
<ol>
<li>check if session is <code>defined</code> before it checks its value</li>
<li>if its defined, its value should not be <code>empty</code> or <code>0</code> or <code>-1</code></li>
</ol>
<p>please guide,m i am almost near its end but stuck at that</p>
| [
{
"answer_id": 74228911,
"author": "John Bode",
"author_id": 134554,
"author_profile": "https://Stackoverflow.com/users/134554",
"pm_score": 2,
"selected": false,
"text": "char *"
},
{
"answer_id": 74229073,
"author": "DrOncogene",
"author_id": 17748128,
"author_profi... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19794380/"
] |
74,228,733 | <p>I think dart formatter is not working right. As an example:</p>
<p><code>controller2.animateToPage(frameworksPage, duration: const Duration(milliseconds: 480), curve: Curves.fastOutSlowIn);</code></p>
<p>formats as:</p>
<pre><code>controller2.animateToPage(
frameworksPage,
duration: const Duration(
milliseconds: 480),
curve: Curves.fastOutSlowIn);
</code></pre>
<p>and it gets even worse when it gets to if statements.
Is there a solution for this bs?</p>
| [
{
"answer_id": 74228911,
"author": "John Bode",
"author_id": 134554,
"author_profile": "https://Stackoverflow.com/users/134554",
"pm_score": 2,
"selected": false,
"text": "char *"
},
{
"answer_id": 74229073,
"author": "DrOncogene",
"author_id": 17748128,
"author_profi... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11175814/"
] |
74,228,741 | <p>I'm looking for a way to show some html, csharp, xml or json code within my UWP app in a formatted way. So I thought about using the control <code>MarkdownTextBlock</code> from the Microsoft.Toolkit.Uwp.UI.Controls library to achieve this.</p>
<p>Witch warping the code with the correct Markdown Fence is working great. But now I would like to be able to scroll down the <code>MarkdownTextBlock</code> end highlights some specific part of the code.
But the control doesn’t seem to allow this.</p>
<p>I'm I wrong?</p>
| [
{
"answer_id": 74228911,
"author": "John Bode",
"author_id": 134554,
"author_profile": "https://Stackoverflow.com/users/134554",
"pm_score": 2,
"selected": false,
"text": "char *"
},
{
"answer_id": 74229073,
"author": "DrOncogene",
"author_id": 17748128,
"author_profi... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1186073/"
] |
74,228,763 | <p>I am defining network interface inside the VMSS AZURE Terraform
Well what i want is disable or enable the load balancer backend address pool id if $app != "api"
In other words if app is api then only add that parameter and attach pool id.</p>
<p>Also, How to enable or disable entire resource lets say i want to diable or enable the network interface block in whole.</p>
<p>Thanks in advance for helping.</p>
<pre><code>load_balancer_backend_address_pool_ids = [var.backend_address_pool_id] #enable only when var.app is api.
</code></pre>
<pre><code>network_interface {
name = "${var.app}-vmss-nic"
primary = true
ip_configuration {
name = "internal"
primary = true
subnet_id = var.pvt_subnet_1_id
load_balancer_backend_address_pool_ids = [var.backend_address_pool_id]
}
}
</code></pre>
| [
{
"answer_id": 74228871,
"author": "Chris Doyle",
"author_id": 1212401,
"author_profile": "https://Stackoverflow.com/users/1212401",
"pm_score": 2,
"selected": true,
"text": "load_balancer_backend_address_pool_ids = var.app == \"api\" ? [var.backend_address_pool_id] : null\n"
},
{
... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8515625/"
] |
74,228,829 | <p>I want to know how to remove a specific Rectangle object in Kivy. I create the Rectangle in .py file by pressing a button and I want to the second button could be able to remove that specific Rectangle.
My .py code:</p>
<pre><code>import kivy
kivy.require("1.10.1")
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.app import App
from kivy.graphics import RoundedRectangle
class Screen1(Screen):
def create_on_press(self):
with self.canvas:
RoundedRectangle(pos = (770, 1250), size = (400, 400), size_hint = (None, None), source = "Rectangle.jpeg")
def remove_on_press(self):
pass #I don't know what to write there
class Test(App):
def build(self):
Builder.load_file("Test.kv")
sm = ScreenManager(transition = FadeTransition())
sm.add_widget(Screen1(name = "scr1"))
return sm
Test().run()
</code></pre>
<p>And the .kv file:</p>
<pre><code>#: kivy 1.10.1
<Screen1>:
id: scr1
orientation: "vertical"
canvas.before:
Rectangle:
pos: self.pos
size: self.size
source: "Background.png"
Button:
pos: (root.width - 600) / 2, 800
size: 600, 200
text: "Create rectangle"
on_press: scr1.create_on_press()
pos_hint: {'width': 0.5, 'top': 0.8}
size_hint: None, None
Button:
pos: (root.width - 600) / 2, 200
size: 600, 200
text: "Remove rectangle"
on_press: scr1.remove_on_press
pos_hint: {'width': 0.5, 'top': 0.2}
size_hint: None, None
</code></pre>
<p>Thanks for any help.</p>
<p>I tried to use self.parent.remove_widget, but it removed the whole Screen1. However, I want to remove only this Rectangle.</p>
| [
{
"answer_id": 74231164,
"author": "ApuCoder",
"author_id": 17375573,
"author_profile": "https://Stackoverflow.com/users/17375573",
"pm_score": 2,
"selected": true,
"text": "group"
},
{
"answer_id": 74243375,
"author": "Aturtl3",
"author_id": 20260166,
"author_profile... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20260166/"
] |
74,228,847 | <p>I need to add an in statement, something along the list of <code>list(vs) if type(vs, str)</code></p>
<pre class="lang-py prettyprint-override"><code>d={'int':["unit", "bool"], 'timestamp':"pruct"}
{v: k
for k, vs in d.items()
for v in vs}
</code></pre>
<p>I need this output</p>
<pre><code>{'unit': 'int', 'bool': 'int', 'pruct': 'timestamp'}
</code></pre>
<p>but I'm getting</p>
<pre><code>{'unit': 'int',
'bool': 'int',
'p': 'timestamp',
'r': 'timestamp',
'u': 'timestamp',
'c': 'timestamp',
't': 'timestamp'}
</code></pre>
| [
{
"answer_id": 74228876,
"author": "Teun Van Der Weij",
"author_id": 17436515,
"author_profile": "https://Stackoverflow.com/users/17436515",
"pm_score": 0,
"selected": false,
"text": "new_dict = {}\nfor key, item in d.items():\n if type(item) is list:\n for i in item:\n ... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11221104/"
] |
74,228,852 | <pre><code>def room1(phone_charge):
phone_charge = 5
import random
randNum = random.randint(1,5)
print("An outlet! You quickly plug in your phone, but the wiring in the house is faulty and soon shorts out.\n")
positve = str(phone_charge + randNum)
print("Your phone is now " + positve + " % charged\n")
return(positve)
</code></pre>
<p>I need to add positive to another function</p>
<pre><code>def room5(phone_charge):
import random
randomNUM = random.randint(1,30)
positve2= str(phone_charge + randomNUM)
print("Your phone is now " + positve2 + " % charged\n")
return(positve2)
</code></pre>
<p>I need to add <code>postive</code> to the <code>room5</code> variable <code>postive2</code></p>
<p>I tried returning variables and putting them in the next function but then my code that was written behind where I entered the returning variable it was no longer highlighted</p>
| [
{
"answer_id": 74228876,
"author": "Teun Van Der Weij",
"author_id": 17436515,
"author_profile": "https://Stackoverflow.com/users/17436515",
"pm_score": 0,
"selected": false,
"text": "new_dict = {}\nfor key, item in d.items():\n if type(item) is list:\n for i in item:\n ... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20353163/"
] |
74,228,860 | <p>I want to reshape the flattened channels array of audio to a 4D array(because audio has 4 channels). Reshape example is below:</p>
<p>Input example: [a1,b1,c1,d1,a2,b2,c2,d2,...]</p>
<p>Output 4D array: [[a1,a2,...], [b1,b2,...], [c1,c2,...], [d1,d2,...]]</p>
<p>Each subarray of the 4D array must be one of the channels of audio.
How can I do it in the fastest way?</p>
| [
{
"answer_id": 74228876,
"author": "Teun Van Der Weij",
"author_id": 17436515,
"author_profile": "https://Stackoverflow.com/users/17436515",
"pm_score": 0,
"selected": false,
"text": "new_dict = {}\nfor key, item in d.items():\n if type(item) is list:\n for i in item:\n ... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11321017/"
] |
74,228,901 | <div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Year</th>
<th style="text-align: center;">Price</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">2017</td>
<td style="text-align: center;">200</td>
</tr>
<tr>
<td style="text-align: left;">2018</td>
<td style="text-align: center;">250</td>
</tr>
<tr>
<td style="text-align: left;">2019</td>
<td style="text-align: center;">300</td>
</tr>
</tbody>
</table>
</div>
<p>Given the table above, is there a way to add months to each year ? For eg: 2017 should have months jan to dec and the same price carried forward in all of the 12 months for all the years listed in a data frame in Pandas?</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;">Year</th>
<th style="text-align: center;">Price</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left;">2017/01/01</td>
<td style="text-align: center;">200</td>
</tr>
<tr>
<td style="text-align: left;">2017/02/01</td>
<td style="text-align: center;">200</td>
</tr>
<tr>
<td style="text-align: left;">2017/03/01</td>
<td style="text-align: center;">200</td>
</tr>
<tr>
<td style="text-align: left;">2017/04/01</td>
<td style="text-align: center;">200</td>
</tr>
<tr>
<td style="text-align: left;">2017/05/01</td>
<td style="text-align: center;">200</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74229219,
"author": "BorrajaX",
"author_id": 289011,
"author_profile": "https://Stackoverflow.com/users/289011",
"pm_score": 2,
"selected": true,
"text": "date"
},
{
"answer_id": 74229302,
"author": "Yolao_21",
"author_id": 15283859,
"author_profile": "... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15262691/"
] |
74,228,902 | <p>I have 2 go files:</p>
<pre><code>main.go
otherFile.go
</code></pre>
<p>Inside of 'main.go' I have a 'main' function and I can call it from the command line like this:</p>
<pre><code>go run main.go
</code></pre>
<p>So far so good.</p>
<p>Inside of 'otherFile' I can't have another 'main' function so I have a function called 'otherFunction'.</p>
<p>How can I call this function in 'otherFile.go' from the command line, similarly to how I did 'go run main.go'?</p>
<p>I don't necessarily want main.go to run, or call 'otherFunction' from 'main.go' by importing it, etc.</p>
<p>Is this possible or am I thinking about it in the wrong way? I am new to Go so still trying to figure out some of the basic concepts.</p>
<p>Thanks.</p>
| [
{
"answer_id": 74229208,
"author": "Nicholas Carey",
"author_id": 467473,
"author_profile": "https://Stackoverflow.com/users/467473",
"pm_score": 3,
"selected": true,
"text": "/path/to/project/root/"
},
{
"answer_id": 74232973,
"author": "Nikko Khresna",
"author_id": 1051... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7725013/"
] |
74,228,918 | <p>I have the following dilemma. I am trying to pickle and then unpickle a numpy array that represents an image.</p>
<p>Executing this code:</p>
<pre><code>a1 = np.zeros((1080, 1920, 3), dtype=np.uint8)
print(sys.getsizeof(a1), a1.shape)
a2 = pickle.dumps(a1)
print(sys.getsizeof(a2), type(a2))
a3 = pickle.loads(a2)
print(sys.getsizeof(a3), a3.shape)
</code></pre>
<p>Produces this output:</p>
<pre><code>6220928 (1080, 1920, 3)
6220995 <class 'bytes'>
128 (1080, 1920, 3)
</code></pre>
<p>Now, <code>a1</code> is thus around 6 MB, <code>a2</code> is the pickle representation of <code>a1</code> and is a bit longer but still roughly the same. And then I try to unpickle <code>a2</code> and I get... something obviously not right.</p>
<p><code>a3</code> looks fine, i can call methods, I can assign values to it's cells etc.</p>
<p>The result is the same if I replace pickle calls with <code>a1.dumps</code> and <code>np.loads</code> since these just call pickle.</p>
<p>So what exactly is the deal with the weird size?</p>
| [
{
"answer_id": 74229208,
"author": "Nicholas Carey",
"author_id": 467473,
"author_profile": "https://Stackoverflow.com/users/467473",
"pm_score": 3,
"selected": true,
"text": "/path/to/project/root/"
},
{
"answer_id": 74232973,
"author": "Nikko Khresna",
"author_id": 1051... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7023187/"
] |
74,228,928 | <p>We created Sign Up and Sign In userflow for our B2C application to authenticate users.</p>
<p>To identify the user selected option i.e, sign up or sign in, we added "User is new" application claim to our user flow:</p>
<p><img src="https://i.imgur.com/yXS1mAO.png" alt="enter image description here" /></p>
<p>But when we generate the token, we cannot see "newUser" flag in it's claims.</p>
<p><img src="https://i.imgur.com/Z0vE9LS.png" alt="enter image description here" /></p>
<pre><code>"iss": "https://ourb2ctenant.b2clogin.com/0006565e-bfe8-45ee-a405-cede36487a6d/v2.0/",
"exp": 1666757889,
"nbf": 1666754289,
"aud": "3df6735e-2c7c-436d-a9f2-058d213d125a",
"tfp": "B2C_1_SUSI",
"azpacr": "1",
"sub": "92769eb0-14f3-40f8-bef8-75fef429214c".
"oid": "92769eb0-14f3-40f8-bef8-75fef429214c",
"tid": "0006565e-bfe8-45ee-a405-cede36487a6d",
"ver": "2.0",
"azp": "3df6735e-2c7c-436d-a9f2-058d213d125a".
"iat": 1666754289
</code></pre>
<p>Are we missing something?</p>
| [
{
"answer_id": 74230650,
"author": "jefftrotman",
"author_id": 3786517,
"author_profile": "https://Stackoverflow.com/users/3786517",
"pm_score": 0,
"selected": false,
"text": " \"exp\": 1666934066,\n \"nbf\": 1666930466,\n \"ver\": \"1.0\",\n \"iss\": \"https://circleboxb2c.b2clogin.... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20045410/"
] |
74,228,936 | <p>I want to make responsive vertical menu with icons, that would shrink with transition (fade in to left) when screen width is to small. It would look like this - normal menu:</p>
<ul>
<li>(icon1) Position1</li>
<li>(icon2) Position2</li>
<li>(icon3) Position3</li>
</ul>
<p>and after shrinking window to let's say 800px it should fade into the left and look like this:</p>
<ul>
<li>(icon1)</li>
<li>(icon2)</li>
<li>(icon3)</li>
</ul>
<p>How do I make such thing using only HTML and CSS?</p>
| [
{
"answer_id": 74229109,
"author": "jessica-98",
"author_id": 20261328,
"author_profile": "https://Stackoverflow.com/users/20261328",
"pm_score": 2,
"selected": true,
"text": "@media only screen and (max-width: 800px) {\n .hide-800 {\n left: 100%;\n opacity: 0;\n }\n}\n\n@media o... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20347461/"
] |
74,228,946 | <p>I am trying to create a random point within a sphere, and I am not sure how to do this. I came up with this but I think it is returning a point within a cube I think I have to do something with <code>Math.PI</code> but not sure how.</p>
<pre class="lang-js prettyprint-override"><code> #createParticlePosition() {
const shape = this.options.shape;
// shape.radius = 2;
if (shape.type === 'sphere') {
return new Three.Vector3(
(Math.random() * shape.radius - (shape.radius / 2)) * 1.0,
(Math.random() * shape.radius - (shape.radius / 2)) * 1.0,
(Math.random() * shape.radius - (shape.radius / 2)) * 1.0
);
}
}
</code></pre>
| [
{
"answer_id": 74229105,
"author": "Marquizzo",
"author_id": 2608515,
"author_profile": "https://Stackoverflow.com/users/2608515",
"pm_score": 3,
"selected": true,
"text": "x,y,z"
},
{
"answer_id": 74231714,
"author": "prisoner849",
"author_id": 4045502,
"author_profi... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1778465/"
] |
74,228,995 | <p>I have this JSON/DICT in Python and I need to pass it to a datframe:</p>
<pre><code>{
"filters": [
{
"field": "example1",
"operation": "like",
"values": [
"Completed"
]
},
{
"field": "example2",
"operation": "like",
"values": [
"value1",
"value2",
"value3",
]
}
]
}
</code></pre>
<p>DF that i need:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>example1</th>
<th>example2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Completed</td>
<td>["value1","value2","value3"]</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74229014,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 3,
"selected": true,
"text": "dct = {\n \"filters\": [\n {\"field\": \"example1\", \"operation\": \"like\", \"values\": [\"Comple... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74228995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16499350/"
] |
74,229,004 | <p>I have two array lists, one for employees, another for their availabilities. The arrays are of different size. I don't see the problem with that when I'm using the array of the larger size in <code>getItemCount()</code>:</p>
<pre><code>@Override
public int getItemCount() {
return allEmployees.size();
}
</code></pre>
<p>I set recycler view to get all employee items, however my availability is a shorter list. If I have 6 availability's and 12 employees everything goes smooth on the first page as it only shows the 6 employees. But when I scroll down it will crash as there is a 7th employee but no 7th availability.</p>
<p>Recycler View :</p>
<pre><code>public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.MyViewHolder> {
List<EmployeeModel> allEmployees;
List<AvailabilityModel> allAvailabilitys;
Context context;
public RecycleViewAdapter(List<EmployeeModel> allEmployees, List<AvailabilityModel> allAvailabilitys, Context context) {
this.allAvailabilitys = allAvailabilitys;
this.allEmployees = allEmployees;
this.context = context;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_employee, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
AvailabilityModel available = allAvailabilitys.get(position);
EmployeeModel employee = allEmployees.get(position);
holder.employeeID.setText(String.valueOf(allEmployees.get(position).getEID()));
holder.firstName.setText(allEmployees.get(position).getfName());
holder.lastName.setText(allEmployees.get(position).getlName());
//holder.position = position;
holder.employee = employee;
holder.editButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(context, EditEmployee.class);
intent.putExtra("Editing", employee);
context.startActivity(intent);
}
});
holder.availabilityButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(context, availability_screen_code.class);
intent.putExtra("Available", employee);
intent.putExtra("Days", available);
context.startActivity(intent);
}
});
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(context, ViewEmployee.class);
intent.putExtra("Viewing", employee);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return allEmployees.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView firstName;
TextView lastName;
TextView employeeID;
int position;
ImageButton editButton;
ImageButton availabilityButton;
EmployeeModel employee;
ConstraintLayout parentLayout;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
firstName = itemView.findViewById(R.id.fNameView);
lastName = itemView.findViewById(R.id.lNameView);
employeeID = itemView.findViewById(R.id.eIDView);
editButton = itemView.findViewById(R.id.imageButton2);
availabilityButton = itemView.findViewById(R.id.imageButton4);
parentLayout = itemView.findViewById(R.id.parentLayout);
}
}
}
</code></pre>
<p>Where I'm using the position:</p>
<pre><code>public class availability_screen_code extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private Spinner mondaySpinner, tuesdaySpinner, wednesdaySpinner, thursdaySpinner, fridaySpinner, saturdaySpinner, sundaySpinner;
// private String mondayChoice, tuesdayChoice, wednesdayChoice, thursdayChoice, fridayChoice, saturdayChoice, sundayChoice;
// private static final boolean [] choices = new boolean[6];
private ImageButton confirmation;
EmployeeDBAssist employeeDB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.availability_screen);
mondaySpinner = findViewById(R.id.mondaySpinner);
tuesdaySpinner = findViewById(R.id.tuesdaySpinner);
wednesdaySpinner = findViewById(R.id.wednesdaySpinner);
thursdaySpinner = findViewById(R.id.thursdaySpinner);
fridaySpinner = findViewById(R.id.fridaySpinner);
saturdaySpinner = findViewById(R.id.saturdaySpinner);
sundaySpinner = findViewById(R.id.sundaySpinner);
confirmation = findViewById(R.id.confirm);
//this is linked to the recycler which gets an entire list of availability!
Bundle bundle = getIntent().getExtras();
AvailabilityModel available = (AvailabilityModel) getIntent().getSerializableExtra("Days");
EmployeeModel employee = (EmployeeModel) getIntent().getSerializableExtra("Available"); //this is where im using it
employeeDB = new EmployeeDBAssist(availability_screen_code.this);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.availableTimes, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//monday
mondaySpinner.setAdapter(adapter);
mondaySpinner.setOnItemSelectedListener(this);
String availableString = available.getMonday();
mondaySpinner.setSelection(getIndex(mondaySpinner, availableString));
Toast.makeText(this, availableString, Toast.LENGTH_SHORT).show();
//tuesday
tuesdaySpinner.setAdapter(adapter);
tuesdaySpinner.setOnItemSelectedListener(this);
//wednesday
wednesdaySpinner.setAdapter(adapter);
wednesdaySpinner.setOnItemSelectedListener(this);
//thursday
thursdaySpinner.setAdapter(adapter);
thursdaySpinner.setOnItemSelectedListener(this);
//friday
fridaySpinner.setAdapter(adapter);
fridaySpinner.setOnItemSelectedListener(this);
//saturday
saturdaySpinner.setAdapter(adapter);
saturdaySpinner.setOnItemSelectedListener(this);
//sunday
sundaySpinner.setAdapter(adapter);
sundaySpinner.setOnItemSelectedListener(this);
confirmation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AvailabilityModel availabilityModel;
try{
availabilityModel = new AvailabilityModel(-1, employee.getEID(), mondaySpinner.getSelectedItem().toString(), tuesdaySpinner.getSelectedItem().toString(), wednesdaySpinner.getSelectedItem().toString(), thursdaySpinner.getSelectedItem().toString(), fridaySpinner.getSelectedItem().toString(), saturdaySpinner.getSelectedItem().toString(), sundaySpinner.getSelectedItem().toString());
EmployeeDBAssist employeeDBAssist = new EmployeeDBAssist(availability_screen_code.this);
employeeDBAssist.updateAvailability(employee.getEID(),mondaySpinner.getSelectedItem().toString(), tuesdaySpinner.getSelectedItem().toString(), wednesdaySpinner.getSelectedItem().toString(), thursdaySpinner.getSelectedItem().toString(), fridaySpinner.getSelectedItem().toString(), saturdaySpinner.getSelectedItem().toString(), sundaySpinner.getSelectedItem().toString());
Toast.makeText(availability_screen_code.this, String.valueOf(employee.getEID()) + " " + mondaySpinner.getSelectedItem().toString()+ " " + tuesdaySpinner.getSelectedItem().toString()+ " " + wednesdaySpinner.getSelectedItem().toString()+ " " + thursdaySpinner.getSelectedItem().toString()+ " " + fridaySpinner.getSelectedItem().toString()+ " " + saturdaySpinner.getSelectedItem().toString()+ " " + sundaySpinner.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
boolean success = employeeDBAssist.addAvailability(availabilityModel);
}
catch (Exception e){
Toast.makeText(availability_screen_code.this, "Error Setting Availability", Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(availability_screen_code.this,activity_main_code.class);
startActivity(i);
Toast.makeText(availability_screen_code.this, String.valueOf(employee.getEID()) + " " + mondaySpinner.getSelectedItem().toString()+ " " + tuesdaySpinner.getSelectedItem().toString()+ " " + wednesdaySpinner.getSelectedItem().toString()+ " " + thursdaySpinner.getSelectedItem().toString()+ " " + fridaySpinner.getSelectedItem().toString()+ " " + saturdaySpinner.getSelectedItem().toString()+ " " + sundaySpinner.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
}
});
}
</code></pre>
<p><code>availability</code> table has 2 values and <code>employees</code> 7. In <code>getItemCount</code> I'm using the size of my employee table. However, I need to get the position of my availability so that I can use it in another class. It will only work for the first two entries. Once I scroll down it throws :</p>
<blockquote>
<p>java.lang.IndexOutOfBoundsException: Index: 2, Size: 2</p>
</blockquote>
<p>Adding an availability for every employee would defeat the purpose of my project. How to solve this with the use of two separate arrays of different size?</p>
| [
{
"answer_id": 74229014,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 3,
"selected": true,
"text": "dct = {\n \"filters\": [\n {\"field\": \"example1\", \"operation\": \"like\", \"values\": [\"Comple... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20269261/"
] |
74,229,031 | <pre><code>def split_trajectories(df):
trajectories_list = []
count = 0
for record in range(len(df)):
if record == 0:
continue
if df['time'].iloc[record] - df['time'].iloc[record - 1] > pd.Timedelta('0 days 00:00:30'):
temp_df = reset_index(df[count:record])
if not temp_df.empty:
if len(temp_df) > 50:
trajectories_list.append(temp_df)
count = record
return trajectories_list
</code></pre>
<p>This is a python function that receives a pandas dataframe and divides it into a list of dataframes when their time delta is greater than 30 seconds and if the dataframe contains than 50 records. In my case I need to execute this function thousands of times and I wonder if anyone can help me optimize it. Thanks in advance!</p>
<p>I tried to optimize it as far as I can.</p>
| [
{
"answer_id": 74229014,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 3,
"selected": true,
"text": "dct = {\n \"filters\": [\n {\"field\": \"example1\", \"operation\": \"like\", \"values\": [\"Comple... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20353254/"
] |
74,229,049 | <p>This program is a Domino memory game where you flip dominos until you make a correct guess where the correct dominos are supposed to stay revealed. However the problem is that while the game does work correctly the dominos do not stay revealed nor does the game end.</p>
<p>This is the code for my Domino Class
`</p>
<pre><code>public class Domino {
private int top, bottom;
private boolean revealed;
public Domino(int x, int y) {
if (x > y) {
top = y;
bottom = x;
} else {
top = x;
bottom = y;
}
}
public int getTop() {
return top;
}
public int getBottom() {
return bottom;
}
public boolean isRevealed() {
if (revealed)
return true;
return false;
}
public void setRevealed(boolean revealed) {
this.revealed = revealed;
}
public boolean equals(Domino other) {
if (top == bottom)
return true;
return false;
}
}
</code></pre>
<p>`</p>
<p>Then here is the memory game class (called MemoryLane)</p>
<p>`</p>
<pre><code>import java.util.Arrays;
import java.util.Random;
public class MemoryLane
{
private Domino[] board;
public MemoryLane(int max)
{
board = new Domino[(max * max) + max];
int i = 0;
for(int top = 1; top <= max; top++)
for(int bot = 1; bot <= max; bot++)
{
// make new Domino(2x) +
// save into array
if(top <= bot)
{
board[i] = new Domino(top, bot);
i++;
board[i] = new Domino(top, bot);
i++;
}
}
shuffle();
}
private void shuffle()
{
int index;
Random random = new Random();
for (int i = board.length - 1; i > 0; i--)
{
index = random.nextInt(i + 1);
if (index != i)
{
Domino temp = board[index];
board[index] = board[i];
board[i] = temp;
}
}
}
public boolean guess(int i, int k)
{
if(board[i] == board[k])
{
return true;
}
return false;
}
public String peek(int a, int b)
{
String text = new String();
text += ("[" + board[a].getTop()+ "] [" + board[b].getTop()+ "]\n");
text += ("[" + board[a].getBottom()+ "] [" + board[b].getBottom()+ "]\n");
return text;
}
public boolean gameOver() {
int count = 0;
for(int i=0; i< board.length; i++)
{
if(board[i].isRevealed())
count ++;
}
return (count == board.length);
}
public String toString() {
String text = new String();
for(int i=0; i< board.length; i++)
{
if(board[i].isRevealed())
text += ("[" + board[i].getTop()+ "] ");
else
text += ("[ ] ");
}
text += ('\n');
for(int i=0; i< board.length; i++)
{
if(board[i].isRevealed())
text += ("[" + board[i].getBottom()+ "] ");
else
text += ("[ ] ");
}
return text;
}
}
</code></pre>
<p>`
Then here is the driver (the driver was provided to me by a third party so it must work as it is presented and cannot be changed)</p>
<p>`</p>
<pre><code>import java.util.Scanner;
public class MemoryLaneDriver
{
public static void main(String[] args)
{
String message = "Welcome to Memory Lane!" + "\n" +
"Choose two indexes to reveal the corresponding dominoes." + "\n" +
"If the dominoes match, they stay revealed." + "\n" +
"Reveal all the dominoes to win the game!" + "\n";
System.out.println(message);
Scanner input = new Scanner(System.in);
MemoryLane game = new MemoryLane(2);
long start = System.currentTimeMillis();
while(!game.gameOver())
{
System.out.println(game);
System.out.print("First: ");
int first = input.nextInt();
System.out.print("Second: ");
int second = input.nextInt();
game.guess(first, second);
System.out.println(game.peek(first, second) + "\n");
}
long stop = System.currentTimeMillis();
long elapsed = (stop - start) / 1000;
System.out.println(game);
System.out.println("\nYou win!");
System.out.println("Total time: " + elapsed + "s");
}
}
</code></pre>
<p>`</p>
<p>I have tried using the methods in Domino like setRevealed and isRevealed in the guess method (for example when i try board.setRevealed = true or board.isRevealed = true), but it wont work and turns up red in IntelliJ. I can also not use any Stringbuilder uses (such as append) because it is outside of what has been covered in class.</p>
<p>When I say the game is working correctly, I mean that it outputs my choices like:</p>
<p>`</p>
<pre><code>Welcome to Memory Lane!
Choose two indexes to reveal the corresponding dominoes.
If the dominoes match, they stay revealed.
Reveal all the dominoes to win the game!
[ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ]
First: 1
Second: 3
[2] [2]
[2] [2]
[ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ]
First:
</code></pre>
<p>`</p>
<p>However as you can see it is not revealing the correct guess, and even if I guess all of the Dominos correctly the game does not end.</p>
| [
{
"answer_id": 74229014,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 3,
"selected": true,
"text": "dct = {\n \"filters\": [\n {\"field\": \"example1\", \"operation\": \"like\", \"values\": [\"Comple... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19849098/"
] |
74,229,053 | <p>can you tell me how to have the following code make multiple images that are layered over one another? Like if I wanted to sometimes have this code post an image1.png with image2.png overlayed over it, but with other if statements true it would post image1.png with image3.png overlayed over it?</p>
<pre><code>// create the images:
var container = document.getElementById("container");
for (var i=0;i<3;i++) {
var img = document.createElement("img");
img.src="https://via.placeholder.com/350x150";
img.classList.add("img");
container.appendChild(img);
}
document.querySelectorAll(".img").forEach(function(img,i) {
img.id="image--"+i; // makes more sense to do that in the creation part too
})
document.getElementById('image--1').src = "https://via.placeholder.com/350x150?text=Image1";
<div id="container"></div>
</code></pre>
<p>I tried this code but I couldn't figure out a way to make images that overlay one another, it just posts them one after another.</p>
<p>I want to keep using this code because it always posts directly under the most recently created image, making a column of images on your webpage which is exactly the aesthetic I'm looking for.</p>
| [
{
"answer_id": 74229014,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 3,
"selected": true,
"text": "dct = {\n \"filters\": [\n {\"field\": \"example1\", \"operation\": \"like\", \"values\": [\"Comple... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20344290/"
] |
74,229,062 | <p>When I am requesting data using route params <code>paramMap</code> I'm able to get everything working great when it's a single argument. For example, <code>foo.getThing(id)</code>.</p>
<p>I am struggling how to "observe" multiple arguments though. I need both, my <code>organizationId</code> <em>and</em> my <code>locationId</code> to look up a location.</p>
<p>I've been reading through several tutorials and perhaps ForkJoin may be what I need, but all I have seen so far is getting the initial request from something that doesn't take arguments. For example, <code>foo.getStuff()</code> not <code>foo.getThing(id)</code></p>
<pre><code>// settings.component.ts
private organizationId!: string;
private locationId!: string;
private organizationId$ = this.activatedRoute.paramMap.pipe(
tap((params) => {
this.organizationId = params.get('organizationId')!;
})
);
private locationId$ = this.activatedRoute.paramMap.pipe(
tap((params) => {
this.locationId = params.get('locationId')!;
})
);
public location$: Observable<ILocation> = this.locationId$.pipe(
switchMap(() =>
this.locationService.getLocation(this.organizationId, this.locationId)
)
);
</code></pre>
<p>When I am getting details about my organization, I can just subscribe to the <code>organizationId</code>. If that changes, the response updates accordingly.</p>
<p>I am trying to accomplish the same for my location. If the <code>organizationId</code> <em>or</em> <code>locationId</code> change, I'd like the pipe to re-run and get the correct data.</p>
<p>How can I subscribe to two different observables?</p>
| [
{
"answer_id": 74229187,
"author": "ginalx",
"author_id": 7322763,
"author_profile": "https://Stackoverflow.com/users/7322763",
"pm_score": 1,
"selected": false,
"text": "combineLatest"
},
{
"answer_id": 74229217,
"author": "JSmart523",
"author_id": 7158380,
"author_p... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3357270/"
] |
74,229,063 | <p>Only half of these are actually being applied!</p>
<pre><code>.btn{
background-color: darkorange;
color: white;
text-decoration: none;
border: 2px solid transparent;
font-weight: bold;
padding: 10x 25px;
border-radius: 30px;
</code></pre>
<p>Any Ideas</p>
| [
{
"answer_id": 74229187,
"author": "ginalx",
"author_id": 7322763,
"author_profile": "https://Stackoverflow.com/users/7322763",
"pm_score": 1,
"selected": false,
"text": "combineLatest"
},
{
"answer_id": 74229217,
"author": "JSmart523",
"author_id": 7158380,
"author_p... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20333694/"
] |
74,229,070 | <p>I have a group of checkboxes with different values each. I want to assign their values in php variables which i'm going to send to database. The main problem is that i don't know how to check inside the php code if the values of selected items matching their default values which i setup in the html (apple == apple, samsung == samsung) and so on. This is because someone can just change the input value inside the console and insert whatever he likes in my DB. Any ideas how i can sort this out. Many thanks!</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <form action="" method="POST">
<label for="apple">Apple</label>
<input id="apple" type="checkbox" name="myCheckBoxes[]" value="Apple">
<label for="samsung">Samsung</label>
<input id="samsung" type="checkbox" name="myCheckBoxes[]" value="Samsung">
<label for="lenovo">Lenovo</label>
<input id="lenovo" type="checkbox" name="myCheckBoxes[]" value="Lenovo">
<label for="google">Google Pixel</label>
<input id="google" type="checkbox" name="myCheckBoxes[]" value="Google Pixel">
<button type="submit" name="submit">Send</button>
</form></code></pre>
</div>
</div>
</p>
<p>PHP Code:</p>
<pre><code>if (isset($_POST['submit'])) {
$checkBoxes = $_POST['myCheckBoxes'];
$numberSelected = count($checkBoxes);
if ($numberSelected > 3) {
echo 'Please select only 3 from the options';
} else {
for ($i = 0; $i < $numberSelected; $i++) {
$option1 = $checkBoxes[0];
$option2 = $checkBoxes[1];
$option3 = $checkBoxes[2];
}
echo 'You have selected', ' ', $option1, ' ', $option2, ' ', $option3;
}
}
</code></pre>
| [
{
"answer_id": 74229486,
"author": "Arleigh Hix",
"author_id": 6127393,
"author_profile": "https://Stackoverflow.com/users/6127393",
"pm_score": 3,
"selected": true,
"text": "const ALLOWED_VALUES = [\n \"apple\" => \"Apple\", \n \"samsung\" => \"Samsung\", \n \"len... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19369766/"
] |
74,229,081 | <pre class="lang-cs prettyprint-override"><code>for (int ctr = 1; ctr <= gregorianCalendar.GetMonthsInYear(gregorianCalendar.GetYear(startOfYear)); ctr++) {
Console.Write(" {0,2}", ctr);
Console.WriteLine("{0,12}{1,15:MMMM}",
gregorianCalendar.GetDaysInMonth(gregorianCalendar.GetYear(startOfMonth), gregorianCalendar.GetMonth(startOfMonth)),
startOfMonth);
startOfMonth = gregorianCalendar.AddMonths(startOfMonth, 1);
}
</code></pre>
<p>I was trying to write the same code in F# but I don't know what <code>{0, 2}</code> and <code>{0,12}{1,15:MMMM}</code> is, what they do and what F# equivalent of these are. The main target here is F# equivalent of C# code above. But, I would be glad if you explain formats above shortly.</p>
<p><strong>Notes:</strong></p>
<ul>
<li><code>gregorianCalendar</code> is an instance of <code>System.Globalization.GregorianCalendar</code>.</li>
<li><code>startOfYear</code> is an instance of <code>DateTime</code> which has value of <code>DateTime(2023, 1, 1)</code>.</li>
<li><code>startOfMonth</code> is an instance of <code>DateTime</code> which has value same as value of <code>startOfYear</code> at initialization. It's used to loop through months.</li>
</ul>
| [
{
"answer_id": 74229460,
"author": "ddastrodd",
"author_id": 5656617,
"author_profile": "https://Stackoverflow.com/users/5656617",
"pm_score": 2,
"selected": false,
"text": "{0, 2}"
},
{
"answer_id": 74229574,
"author": "Brian Berns",
"author_id": 344223,
"author_prof... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17682078/"
] |
74,229,102 | <p>I will almost always be computing my memory needs in the unit of bytes. I wouldn't know how large a "page" is, I had to look it up (<a href="https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/Memory" rel="nofollow noreferrer">MDN says</a> it's 64KB). It's not obvious that the size of a page even <em>should</em> be a fixed (documentable) platform-independent constant. I'm unable to source a reason or even an attestation for the page size being that in MDN's spec link.</p>
<p>I can only think of really bad reasons for it to be this way and I want to figure out whether it really is that bad.</p>
| [
{
"answer_id": 74229460,
"author": "ddastrodd",
"author_id": 5656617,
"author_profile": "https://Stackoverflow.com/users/5656617",
"pm_score": 2,
"selected": false,
"text": "{0, 2}"
},
{
"answer_id": 74229574,
"author": "Brian Berns",
"author_id": 344223,
"author_prof... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1085128/"
] |
74,229,119 | <p>I am trying to ingest 2 csv files into a single spark dataframe. However, the schema of these 2 datasets is very different, and when I perform the below operation, I get back only the schema of the second csv, as if the first one doesn't exist. How can I solve this? My final goal is to count the total number of words.</p>
<p>paths = ["abfss://lmne.dfs.core.windows.net/csvs/MachineLearning_reddit.csv", "abfss://test1@lmne.dfs.core.windows.net/csvs/bbc_news.csv"]</p>
<pre><code>df0_spark=spark.read.format("csv").option("header","false").load(paths)
df0_spark.write.mode("overwrite").saveAsTable("ML_reddit2")
df0_spark.show()
</code></pre>
<p>I tried to load both of the files into a single spark dataframe, but it only gives me back one of the tables.</p>
| [
{
"answer_id": 74231971,
"author": "Rakesh Govindula",
"author_id": 18836744,
"author_profile": "https://Stackoverflow.com/users/18836744",
"pm_score": 1,
"selected": false,
"text": "mergeSchema"
},
{
"answer_id": 74248576,
"author": "Bartosz Gajda",
"author_id": 6870955,... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18715406/"
] |
74,229,121 | <pre><code>with Ada.Text_IO; use Ada.Text_IO;
procedure factor is
rate: Integer;
begin
Put("Enter rate: ");
Get(rate);
case rate is
when 1 | 2 =>
Put("Factor =", factor = 2 * rate - 1);
when 3 | 5 =>
Put("Factor =", factor = 3 * rate + 1);
when 4 =>
Put("Factor =", factor = 4 * rate - 1);
when 6 | 7 | 8 =>
Put("Factor =", factor = rate - 2);
when others =>
Put("Factor =", rate);
end case;
end factor;
</code></pre>
<p>I am new to ada and im not able to resolve this error. please help me with this code</p>
<p>this is a simple switch case in ada.. this should return factor and rate is the input from user</p>
| [
{
"answer_id": 74229308,
"author": "Frédéric Praca",
"author_id": 1677089,
"author_profile": "https://Stackoverflow.com/users/1677089",
"pm_score": 2,
"selected": false,
"text": "factor.adb:8:05: no candidate interpretations match the actuals:\nfactor.adb:8:05: missing argument for param... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20352980/"
] |
74,229,129 | <p><strong>Package References</strong></p>
<pre><code> <PackageReference Include="OpenTelemetry.Exporter.Jaeger" Version="1.4.0-beta.2" />
<PackageReference Include="OpenTelemetry.Exporter.Prometheus" Version="1.2.0-rc5"/>
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.0.0-rc9.8" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.0.0-rc9.8" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.0.0-rc9.8" />
</code></pre>
<p><strong>Program.cs</strong></p>
<pre><code>builder.Services.AddOpenTelemetryMetrics(b =>
{
b.AddPrometheusExporter();
b.AddMeter(TelemetryConstants.MyAppSource);
b.SetResourceBuilder(resource);
b.AddHttpClientInstrumentation();
b.AddAspNetCoreInstrumentation();
});
</code></pre>
<p>When I run the application it's giving the following error</p>
<p><code>System.TypeLoadException: 'Could not load type 'System.ServiceProviderExtensions' from assembly 'OpenTelemetry, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7bd6737fe5b67e3c'.' </code></p>
<p>at <code>app.UseOpenTelemetryPrometheusScrapingEndpoint();</code></p>
| [
{
"answer_id": 74482920,
"author": "Sunilkumar Mandati",
"author_id": 2043343,
"author_profile": "https://Stackoverflow.com/users/2043343",
"pm_score": 3,
"selected": true,
"text": "opentelemetry.exporter.prometheus.aspnetcore"
},
{
"answer_id": 74582749,
"author": "Mark",
... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2043343/"
] |
74,229,166 | <p>My target is to store data from the <code>html form</code>. I tried different ways, bellow way is one of them. But data is not stored in the database. What is the problem? Is the way appropriate?</p>
<p><em><strong>views.py:</strong></em></p>
<pre><code>@api_view(['POST'])
def employeeListView(request):
if request.method == 'POST':
jsonData = JSONParser().parse(request)
serializer = EmployeeSerializer(data=jsonData)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, safe=False)
else:
return JsonResponse(serializer.errors, safe=False)
def InsertAndInfo(request):
if request.method == 'POST':
name = request.POST.get('name')
email = request.POST.get('email')
phone = request.POST.get('phone')
data = {
'name':name
}
headers = {'Content-Type': 'application/json'}
read = requests.post('http://127.0.0.1:8000/api/employees/',json=data,headers=headers)
return render(request, 'InsertAndInfo.html')
</code></pre>
<p><em><strong>models.py:</strong></em></p>
<pre><code>class Employee(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField(max_length=30)
phone = models.IntegerField(null=True)
</code></pre>
<p><em><strong>serializer.py:</strong></em></p>
<pre><code>class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = "__all__"
</code></pre>
<p><em><strong>urls.py:</strong></em></p>
<pre><code>path('', views.InsertAndInfo, name="InsertAndInfo"),
path('employees/', views.employeeListView, name="employeeListView")
</code></pre>
<p><em><strong>InsertAndInfo.html:</strong></em></p>
<pre><code><form action="" method="POST">
<input type="text" class="form-control" name="name" id="name">
</form>
</code></pre>
| [
{
"answer_id": 74482920,
"author": "Sunilkumar Mandati",
"author_id": 2043343,
"author_profile": "https://Stackoverflow.com/users/2043343",
"pm_score": 3,
"selected": true,
"text": "opentelemetry.exporter.prometheus.aspnetcore"
},
{
"answer_id": 74582749,
"author": "Mark",
... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18326398/"
] |
74,229,171 | <p>I have the following service to test</p>
<pre><code>const { data: plan } = await firstValueFrom(
this.httpService
.post<CreatePlanPagarmeInterface>(
`${PagarmeConfig.baseUrl}/plans`,
pagarmeBody,
PagarmeConfig.auth,
)
.pipe(
catchError(() => {
throw new BadRequestException(
'Error to create plan.',
);
}),
),
);
</code></pre>
<p>My test</p>
<pre><code> describe('createPlanMonth', () => {
it('shoud be able to create a new plan month', async () => {
jest.spyOn(httpService, 'post').mockReturnValueOnce(
of({
status: 200,
statusText: 'OK',
config: {},
headers: {},
data: resultPagarmeMock,
}),
);
const result = await planService.createPlanMonth(mockPlan);
expect(result).toEqual(resultMockPlan);
});
});
</code></pre>
<p>however I'm getting an error when the test arrives in the .pipe</p>
<p>TypeError: Cannot read properties of undefined (reading 'pipe')</p>
| [
{
"answer_id": 74482920,
"author": "Sunilkumar Mandati",
"author_id": 2043343,
"author_profile": "https://Stackoverflow.com/users/2043343",
"pm_score": 3,
"selected": true,
"text": "opentelemetry.exporter.prometheus.aspnetcore"
},
{
"answer_id": 74582749,
"author": "Mark",
... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8442561/"
] |
74,229,175 | <p>I'm trying to run the main.py module, as the picture bellow shows, the name is correct, both Letra.py (which is importing from widgets.py) and widgets.py are in the same directory. Widgets.py is not importing anything but "pyglet" which is a library I'm using (and probably irrelevant to this problem).</p>
<p>The picture already shows header code from Letra.py. Here is the header code from main.py</p>
<pre><code>from pyglet.gl import *
from partida import Partida
import Widgets.widgets as widgets
import Widgets.Letra as Letra
class Janela(pyglet.window.Window):
#etc...
</code></pre>
<p>Here is the error it is producing when I try to run main.py:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\mecha\sopa\main.py", line 4, in <module>
import Widgets.Letra as Letra
File "C:\Users\mecha\sopa\Widgets\Letra.py", line 2, in <module>
from widgets import Widget
ModuleNotFoundError: No module named 'widgets'
</code></pre>
<p><a href="https://i.stack.imgur.com/HUUHh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HUUHh.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74482920,
"author": "Sunilkumar Mandati",
"author_id": 2043343,
"author_profile": "https://Stackoverflow.com/users/2043343",
"pm_score": 3,
"selected": true,
"text": "opentelemetry.exporter.prometheus.aspnetcore"
},
{
"answer_id": 74582749,
"author": "Mark",
... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15797182/"
] |
74,229,197 | <p>i want to make a program which related to this question:</p>
<blockquote>
<p>An integer that can be expressed as the square of another integer is called a perfect square, such as 4,9,16,25, etc. Write a progran that checks if a number is a perfect square.</p>
</blockquote>
<p>I did built something goes like:</p>
<pre class="lang-java prettyprint-override"><code>import java.util.Scanner;
class Q3{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num = 0;
int a = 0;
System.out.println("Type a number to check if it has square");
num = sc.nextInt();
for(a = 1;a<num;a++){ }
if (a*a == num){
System.out.println("Ok");
break;
}
else if (a*a != num){
System.out.println("Not ok");
}
}
}
</code></pre>
<p>So it doesn’t give what i want when i run it. What should i change or add ?</p>
| [
{
"answer_id": 74229437,
"author": "Skyhigh",
"author_id": 10382742,
"author_profile": "https://Stackoverflow.com/users/10382742",
"pm_score": 2,
"selected": false,
"text": "static void perfectSquare(int number) {\n for (int i = 1; i < i * number; ++i) {\n // 'i' is the divisor... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20353484/"
] |
74,229,198 | <p>I'm writing a subclass that encapsulates multiple objects of the parent class so I can call functions sort-of like a vector, something like this:</p>
<pre class="lang-perl prettyprint-override"><code>package OriginalClass;
sub new { return bless {bar => 123}, 'OriginalClass' }
sub foo { return shift->{bar}; }
1;
package NewClass;
use parent OriginalClass;
# Return a blessed arrayref of "OriginalClass" objects.
# new() would be called NewClass->new(OriginalClass->new(), ...)
sub new {
my $class = shift;
return bless \@_, 'NewClass';
}
# Vectorized foo(), returns a list of SUPER::foo() results:
sub foo
{
my $self = shift;
my @ret;
push @ret, $_->SUPER::foo() foreach @$self;
return @ret;
}
1;
</code></pre>
<p>I don't want to write a new vectorized function in <code>NewClass</code> for each function in <code>OriginalClass</code>, particularly for when <code>OriginalClass</code> adds new functions to be maintained (vectorized) in <code>NewClass</code>.</p>
<p><strong>Question:</strong></p>
<p>As I understand <code>AUTOLOAD</code> is slow, so is there a way to vectorize calls <code>OriginalClass</code> via something like <code>NewClass</code> without <code>AUTOLOAD</code>?</p>
| [
{
"answer_id": 74229589,
"author": "ikegami",
"author_id": 589924,
"author_profile": "https://Stackoverflow.com/users/589924",
"pm_score": 4,
"selected": true,
"text": "AUTOLOAD"
}
] | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14055985/"
] |
74,229,201 | <p>This code gives me the output: <code>The names found are: ['Alba', 'Dawson', 'Oliver']</code></p>
<p>I would need to remove the brackets and quotes, and always print "and" before the last name (the number of names can be variable and for example I could have 3,4,5,6 names), so I would need this output:</p>
<pre><code>The names found are: Alba, Dawson and Oliver
</code></pre>
<p>Code</p>
<pre><code>name = "Alba, Dawson, Oliver"
names = name.split(', ')
print("The names found are: ", names)
</code></pre>
<p>How can I achieve this?</p>
| [
{
"answer_id": 74229589,
"author": "ikegami",
"author_id": 589924,
"author_profile": "https://Stackoverflow.com/users/589924",
"pm_score": 4,
"selected": true,
"text": "AUTOLOAD"
}
] | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18313765/"
] |
74,229,207 | <p>I have successfully implemented the thread pool from <a href="https://stackoverflow.com/a/32593825/12351436">an answer on Stack Overflow</a>, which helped me in speeding up my program. It uses a single <code>std::queue</code> to distribute jobs (<code>std::function<void()></code>) among multiple workers (<code>std::thread</code>s).</p>
<p>I wanted to improve on this. As I only need to run a limited set of functions, I planned to ditch the queue and to use variables instead. In other words, the <code>n</code>-th worker would do the <code>n</code>-th job from the <code>std::vector<std::function<void()>></code>. Unfortunately, my test app crashes with <code>Segmentation fault (core dumped)</code> and I could not realize my mistake so far.</p>
<p>Here is my ~minimal reproducible code, with the job of counting the odd elements in a vector. (Idea taken from <a href="https://youtu.be/WDIkqP4JbkE?t=551" rel="nofollow noreferrer">Scott Meyers: Cpu Caches and Why You Care</a>.)</p>
<pre><code>#include <algorithm>
#include <condition_variable>
#include <functional>
#include <iostream>
#include <mutex>
#include <stdexcept> // std::invalid_argument
#include <thread>
#include <vector>
// Thread pool with a std::function for each worker.
class Pool {
public:
enum class Status {
idle,
working,
terminate
};
const int worker_count;
std::vector<Status> statuses;
std::vector<std::mutex> mutexes;
std::vector<std::condition_variable> conditions;
std::vector<std::thread> threads;
std::vector<std::function<void()>> jobs;
void thread_loop(int thread_id)
{
std::puts("Thread started");
auto &my_status = statuses[thread_id];
auto &my_mutex = mutexes[thread_id];
auto &my_condition = conditions[thread_id];
auto &my_job = jobs[thread_id];
while (true) {
std::unique_lock<std::mutex> lock(my_mutex);
my_condition.wait(lock, [this, &my_status] { return my_status != Status::idle; });
if (my_status == Status::terminate)
return;
my_job();
my_status = Status::idle;
lock.unlock();
my_condition.notify_one(); // Tell the main thread we are done
}
}
public:
Pool(int size) : worker_count(size), statuses(size, Status::idle), mutexes(size), conditions(size), threads(), jobs(size)
{
if (size < 0)
throw std::invalid_argument("Worker count needs to be a positive integer");
};
~Pool()
{
for (int i = 0; i < worker_count; ++i) {
std::unique_lock lock(mutexes[i]);
statuses[i] = Status::terminate;
lock.unlock(); // Unlock before notifying
conditions[i].notify_one();
}
for (auto &thread : threads)
thread.join();
threads.clear();
};
void start_threads()
{
threads.resize(worker_count);
jobs.resize(worker_count);
for (int i = 0; i < worker_count; ++i) {
statuses[i] = Status::idle;
jobs[i] = []() { std::puts("I am running"); };
threads[i] = std::thread(&Pool::thread_loop, this, i);
}
}
void set_and_start_job(const std::function<void(int)> &job)
{
for (int i = 0; i < worker_count; ++i) {
std::unique_lock lock(mutexes[i]);
jobs[i] = [&job, i]() { job(i); };
statuses[i] = Status::working;
lock.unlock();
conditions[i].notify_one();
}
}
void wait()
{
for (int i = 0; i < worker_count; ++i) {
auto &my_status = statuses[i];
std::unique_lock lock(mutexes[i]);
conditions[i].wait(lock, [this, &my_status] { return my_status != Status::working; });
}
}
};
int main()
{
constexpr int worker_count = 1;
constexpr int vector_size = 1 << 10;
std::vector<int> test_vector;
test_vector.reserve(vector_size);
for (int i = 0; i < vector_size; ++i)
test_vector.push_back(i);
std::vector<int> worker_odd_counts(worker_count, 0);
const auto worker_task = [&](int thread_id) {
int chunk_size = vector_size / (worker_count) + 1;
int my_start = thread_id * chunk_size;
int my_end = std::min(my_start + chunk_size, vector_size);
int local_odd_count = 0;
for (int ii = my_start; ii < my_end; ++ii)
if (test_vector[ii] % 2 != 0)
++local_odd_count;
worker_odd_counts[thread_id] = local_odd_count;
};
Pool pool = Pool(worker_count);
pool.start_threads();
pool.set_and_start_job(worker_task);
pool.wait();
int odd_count = 0;
for (auto elem : worker_odd_counts)
odd_count += elem;
std::cout << odd_count << '\n';
}
</code></pre>
| [
{
"answer_id": 74229297,
"author": "Dudly01",
"author_id": 12351436,
"author_profile": "https://Stackoverflow.com/users/12351436",
"pm_score": 0,
"selected": false,
"text": "Pool::set_and_start_job"
},
{
"answer_id": 74229562,
"author": "user4581301",
"author_id": 4581301... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12351436/"
] |
74,229,216 | <p>I have two apps. The first app launches the second app and should stop the second app after a time interval (currently 10 seconds) and then relaunch the app. Here is the code I have so far:</p>
<pre><code>package com.example.launch
import android.content.ActivityNotFoundException
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onResume() {
super.onResume()
val launchIntent = packageManager.getLaunchIntentForPackage("com.example.secondapp")
while (true) {
if (launchIntent != null) {
try {
startActivityForResult(launchIntent, 1)
Log.d("", "Launching com.example.secondapp")
} catch (e: ActivityNotFoundException) {
Log.d("", "Failed to launch com.example.secondapp")
}
} else {
Log.d("", "Intent is null value.")
}
Thread.sleep(10000)
finishActivity(1)
}
}
}
</code></pre>
<p>On my android phone (Galaxy A12) the first app launches the second app but doesn't stop it. Here is some typical output from the first app.</p>
<pre><code>2022-10-28 00:17:58.127 21240-21240/com.example.launch D/: Launching com.example.secondapp
2022-10-28 00:18:08.140 21240-21240/com.example.launch D/: Launching com.example.secondapp
2022-10-28 00:18:18.150 21240-21240/com.example.launch D/: Launching com.example.secondapp
</code></pre>
<p>So it seems from the output that the first app believes it is successfully launching the second app every 10 seconds. This doesn't correspond with what I am seeing on the phone or in the log for the second app which is continuing to run without being stopped or relaunched.</p>
<p>Where am I going wrong? How can I fix this?</p>
| [
{
"answer_id": 74230267,
"author": "user496854",
"author_id": 496854,
"author_profile": "https://Stackoverflow.com/users/496854",
"pm_score": 0,
"selected": false,
"text": "com.my.app.SHUT_DOWN"
},
{
"answer_id": 74232135,
"author": "Android Newbie A",
"author_id": 201257... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9536877/"
] |
74,229,233 | <p>i am trying to filter my list of a family parameters by their Discipline.
But i do not know how to access it. The same goes for the "Type of Parameter" as you see in the image.</p>
<pre class="lang-c prettyprint-override"><code>List<FamilyParameter> famParm_lst = FamMngr.GetParameters().Cast<FamilyParameter>().ToList();
List<FamilyParameter> famParm_PipeSize_lst = famParm_lst.Where(fp => fp.Definition.(Discipline) == (Pipe Size)).Select();
</code></pre>
<p>Any idea on how i can check for a Discipline of a value "Pipe Size" ?</p>
<p><a href="https://i.stack.imgur.com/jA9g6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jA9g6.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74230267,
"author": "user496854",
"author_id": 496854,
"author_profile": "https://Stackoverflow.com/users/496854",
"pm_score": 0,
"selected": false,
"text": "com.my.app.SHUT_DOWN"
},
{
"answer_id": 74232135,
"author": "Android Newbie A",
"author_id": 201257... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6296776/"
] |
74,229,326 | <p>If I use them both the same time (not sure if it's a good habit or not) in following example, what's the actual timeout?</p>
<pre><code>ExecutorService executorService = executorServiceFactory.createThreads(2);
List<Callable<T>> tasksList = new ArrayList<>();
tasksList.add(task1);
tasksList.add(task2);
executorService.invokeAll(taskList);
// get the result object with 5 minutes timeout
final task1 = tasksList.get(0).get(5, TimeUnit.MINUTES);
final task2 = tasksList.get(1).get(5, TimeUnit.MINUTES);
executorService.shutdown();
// set the timeout to 30 seconds for executor service
executorService.awaitTermination(30, TimeUnit.SECONDS);
</code></pre>
<p>In the above example, I want to get the result of the completable future (used in other places), if I place a 5 minutes timeout in the <code>get()</code> method, but I do shutdown the executor service and <code>awaitTermination</code> for 30 seconds, which time will take effect? Is it 30 seconds? Since it's shorter than 5 minutes?</p>
| [
{
"answer_id": 74230267,
"author": "user496854",
"author_id": 496854,
"author_profile": "https://Stackoverflow.com/users/496854",
"pm_score": 0,
"selected": false,
"text": "com.my.app.SHUT_DOWN"
},
{
"answer_id": 74232135,
"author": "Android Newbie A",
"author_id": 201257... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6837671/"
] |
74,229,335 | <p>I am pretty new to python and coding. I am trying to write a code that will print out the total amount of each given wire type from a list of wires. This is a side project for work. I was able to come up with a code to sum up all of the wire for a user defined wire type. Now I would like to make another code that prints out the total of each wire type in the file.</p>
<p>This is the code that I came up with to sum up individual wire type as selected by the user.</p>
<pre><code>wtype = []
w = []
w1 = []
#opens the .TXT file
fhand = input('\nEnter Text File\n')
try:
if (len(fhand) <= 0):
fhand = 'test.txt'
fh = open(fhand)
except:
print('\nNo File Found:', fhand, '\n')
exit()
#prints out the possible wire types
for line in fh:
line = line.rstrip()
wtype.append(line) #needed for later in the code
line2 = line.split(',')[2]
if line2 not in w:
w.append(line2)
else:
continue
d1 = dict(enumerate(w))
print(d1)
#sums up the selected wire types total length from the given .TXT file
wire = int(input('\nEnter the number that is before the wire type you need:\n'))
for key, val in d1.items():
if key == wire:
for x in wtype:
x = x.split(',')
if x[2] == val:
w1.append(x[1])
else:
continue
s = [eval(i) for i in w1]
print('\nYour will need ', sum(s)/12, ' Feet of ', val, '.\n')
</code></pre>
<p>This is the <code>test.txt</code> file, the length is in inches and the converted to feet in the last line of the code <code>sum(s)/12</code>:</p>
<p>the column are WIRE, LENGTH, TYPE, QTY for this file.</p>
<pre><code>WIRE-006A22,72,M22759/16-22-9,1
WIRE-005A22,60,M22759/16-22-9,1
WIRE-004A22,72,M22759/16-22-9,1
WIRE-003A22,72,M22759/16-20-9,1
WIRE-002A22,60,M22759/16-20-9,1
WIRE-001A22,72,M22759/16-22-9,1
WIRE-009A22,72,M22759/16-22-9,1
WIRE-008A22,60,M22759/16-22-9,1
WIRE-007A22,72,M22759/16-20-9,1
WIRE-011A22,72,M22759/16-22-9,1
WIRE-012A22,72,M22759/16-22-9,1
WIRE-014A22,72,M22759/16-20-9,1
WIRE-013A22,60,M22759/16-22-9,1
WIRE-021A22,72,M22759/16-20-9,1
WIRE-031A22,72,M22759/16-22-9,1
WIRE-032A22,72,M22759/16-20-9,1
WIRE-043A22,60,M22759/16-22-9,1
WIRE-054A22,72,M22759/16-20-9,1
WIRE-065A22,72,M22759/16-22-9,1
WIRE-076A22,60,M22759/16-22-9,1
WIRE-087A22,72,M22759/16-22-9,1
WIRE-098A22,72,M22759/16-20-9,1
WIRE-089A22,72,M22759/16-20-9,1
WIRE-078A22,72,M22759/16-20-9,1
WIRE-067A22,60,M22759/16-22-9,1
WIRE-056A22,72,M22759/16-22-9,1
WIRE-045A22,72,M22759/16-20-9,1
WIRE-034A22,60,M22759/16-22-9,1
WIRE-023A22,60,M22759/16-22-9,1
WIRE-012A22,72,M22759/16-20-9,1
</code></pre>
<p>The output I am looking to try and achieve is:</p>
<pre><code>output: {'M22759/16-22-9': 100, 'M22759/16-20-9': 71}
</code></pre>
<p>and have that be expandable to all the different wire types that could be in <code>d1</code></p>
| [
{
"answer_id": 74229439,
"author": "jarmod",
"author_id": 271415,
"author_profile": "https://Stackoverflow.com/users/271415",
"pm_score": 1,
"selected": false,
"text": "import pandas\n\ndf = pandas.read_csv(\"test.csv\")\ndf_out = df.groupby(\"TYPE\")[\"QTY\"].sum()\nprint(\"Output:\", d... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20353316/"
] |
74,229,355 | <p>I am developing an application in Kotlin for Android 11. My app collects a log of sailing data from the boat instruments and internal GPS during a race.</p>
<p>I want to write a .csv file to some location where the User can access this using Windows File Explorer (connecting to the Android device with a USB cable) to copy and analyse the data in Windows.</p>
<p>I have been able to create and write .csv files to a subdirectory of Documents however if the User deletes the file using FileExplorer then Android 11 still reports that the file exists { filename.exists() returns true } when it doesn't, but worse won't delete what it thinks exists using { filename.delete() }, returns false for { filename.CanWrite() }, fails (returns false) to execute { filename.createNewFile()} and crashes if I try and write anything to the file.</p>
<p>How can I reliably provide the logged data to a User ???
Very happy to use any alternative approach that can get the log data to the User and not be damaged by File Explorer actions.</p>
<p>I successfully obtained User permission to write files to a subdirectory under Documents /storage/emulated/0/Documents/layline</p>
<p>The path to the Documents folder was obtained from:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)</p>
<p>The Manifest contains:<br />
<code> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> android:requestLegacyExternalStorage="true"</code></p>
<p>and I successfully verified the permissions with:
checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) retuns 0
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) returns 0</p>
<p>I was able to read and write to a file OK until the file was deleted using Windows File Explorer.
The files are Read Only from Windows perspective and if the file is edited and saved to a separate location and then copied back to overwrite the original, the file system starts presenting [1], [2] etc suffixes and Android 11 can't seem to get back at the file (it thinks that a version exists but can't delete or write to it).</p>
<p>Uninstalling and reinstalling the app does not fix the problem. Android 11 still reports that the file exists, but can't write to it.<br />
filename.SetWritable() does not help (returns false).</p>
<p>Do I need to use All Files Access or Manage External Storage ?</p>
| [
{
"answer_id": 74229439,
"author": "jarmod",
"author_id": 271415,
"author_profile": "https://Stackoverflow.com/users/271415",
"pm_score": 1,
"selected": false,
"text": "import pandas\n\ndf = pandas.read_csv(\"test.csv\")\ndf_out = df.groupby(\"TYPE\")[\"QTY\"].sum()\nprint(\"Output:\", d... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20353520/"
] |
74,229,364 | <p>I have a database of records in Cosmos DB. I want to write something that would allow me to, given a particular record (let's say it has a description), find the top 5 records with the most similar descriptions to that particular record. What would be the best Azure service to accomplish this?</p>
<p>I looked into text analytics, but it didn't seem to have the functionality I'd need. Maybe I'm wrong, open to any suggestions!</p>
| [
{
"answer_id": 74229439,
"author": "jarmod",
"author_id": 271415,
"author_profile": "https://Stackoverflow.com/users/271415",
"pm_score": 1,
"selected": false,
"text": "import pandas\n\ndf = pandas.read_csv(\"test.csv\")\ndf_out = df.groupby(\"TYPE\")[\"QTY\"].sum()\nprint(\"Output:\", d... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20353644/"
] |
74,229,371 | <p>In each new row of dataframe, I need to keep track of min and max values for a previous group of records.</p>
<ol>
<li>Create dataframe with input data:</li>
</ol>
<pre><code>import pandas as pd
columns = ['timestamp','groupid','value']
data = [['2022-10-14 11:47:38',1000,200],
['2022-10-14 11:47:39',1000,210],
['2022-10-14 11:47:40',1000,220],
['2022-10-14 11:47:41',1000,230],
['2022-10-14 11:47:42',1001,240],
['2022-10-14 11:47:43',1001,250],
['2022-10-14 11:47:44',1002,260],
['2022-10-14 11:47:45',1002,270]]
df = pd.DataFrame(data=data,columns=columns)
print(df)
</code></pre>
<ol start="2">
<li>Calculate min and max values for each group:</li>
</ol>
<pre><code>df['min'] = df.groupby('groupid')['value'].transform('min')
df['max'] = df.groupby('groupid')['value'].transform('max')
</code></pre>
<ol start="3">
<li>Create new columns in dataframe:</li>
</ol>
<pre><code>df['pmin'] = 0
df['pmax'] = 0
df['ppmin'] = 0
df['ppmax'] = 0
df['ppmin'] = df.groupby('groupid')['pmin'].transform('first').shift(1)
df['ppmax'] = df.groupby('groupid')['pmax'].transform('first').shift(1)
df['pmin'] = df.groupby('groupid')['min'].transform('first').shift(1)
df['pmax'] = df.groupby('groupid')['max'].transform('first').shift(1)
print(df)
</code></pre>
<p>The code in step 3 fails to return expected result as shown below:</p>
<pre><code>columns2 = ['timestamp','groupid','value','min','max','pmin','pmax','ppmin','ppmax']
data2 = [['2022-10-14 11:47:38',1000,200,200,230,0,0,0,0],
['2022-10-14 11:47:39',1000,210,200,230,0,0,0,0],
['2022-10-14 11:47:40',1000,220,200,230,0,0,0,0],
['2022-10-14 11:47:41',1000,230,200,230,0,0,0,0],
['2022-10-14 11:47:42',1001,240,240,250,200,230,0,0],
['2022-10-14 11:47:43',1001,250,240,250,200,230,0,0],
['2022-10-14 11:47:44',1002,260,260,270,240,250,200,230],
['2022-10-14 11:47:45',1002,270,260,270,240,250,200,230]]
df = pd.DataFrame(data=data2,columns=columns2)
print(df)
</code></pre>
| [
{
"answer_id": 74229494,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": true,
"text": "df[\"tmp\"] = (df[\"groupid\"] != df[\"groupid\"].shift()).cumsum()\ngrps = df.groupby(\"groupid\")[\"value\"... | 2022/10/27 | [
"https://Stackoverflow.com/questions/74229371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20268123/"
] |
74,229,403 | <p>Would really appreciate if someone can weigh in on this :)</p>
<p>What Im trying to achieve is to grab a specific email from outlook with current date and specified subject. After this I want to copy the contents of the email (a table) to the active excel sheet.
Im already looping through a generic object.</p>
<pre><code>Sub Mail3()
Dim Folder As Outlook.MAPIFolder
Dim sFolders As Outlook.MAPIFolder
Dim MailBoxName As String, Pst_Folder_Name As String
Dim oMail As Object
Dim y As Long, x As Long
Dim olInsp As Outlook.Inspector
Dim wdDoc As Word.Document
Dim tb As Word.Table
Dim Myemail As String
Dim Atmt As Attachment
Dim irow As Integer
Dim oItem As Outlook.MailItem
Dim ns As Namespace
irow = 1
'set email date
Set ns = GetNamespace("MAPI")
Myemail = "abcd"
'Mailbox or PST Main Folder Name to set the name of the inbox - I have several mailboxes, needed to specify
MailBoxName = "myinbox"
'Mailbox Folder or PST Folder Name (As how it is displayed in your Outlook Session)
Pst_Folder_Name = "Inbox" 'Sample "Inbox" or "Sent Items"
'To direct to a Folder at a high level
Set Folder = Outlook.Session.Folders(MailBoxName).Folders(Pst_Folder_Name)
'copying the email contents into the refresh file
For Each oMail In Folder.Items
If oMail.Class = 43 Then
Set oMail = oItem
If oMail.Subject = Myemail And (Now() - oMail.ReceivedTime) < 1 Then
'oMail.SentOn = DateSerial(Year(Now), Month(Now), Day(Now)) Then
Application.ThisWorkbook.Worksheets("Sheet1").Range("B9").Value = oItem.HTMLBody
End If
End If
Next oMail
End Sub
</code></pre>
<p>Bare in my mind that Im learning VBA and this code isnt entirely my creation.</p>
<p>Edit:</p>
<p>Ok so ive changed a bunch of things.
This time using oMail as Object</p>
<p>Still getting an object not definined error
here
Application.ThisWorkbook.Worksheets("Sheet1").Range("B9").Value = oItem.HTMLBody</p>
| [
{
"answer_id": 74229494,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": true,
"text": "df[\"tmp\"] = (df[\"groupid\"] != df[\"groupid\"].shift()).cumsum()\ngrps = df.groupby(\"groupid\")[\"value\"... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19992967/"
] |
74,229,421 | <p>My script doesn't work.
I tried to make it change css style on mouse over but its not working</p>
<pre><code>const robert = document.getElementById('robert');
function animationOver() {
robert.style.margin = '0.8rem 2.7rem 1.2rem 0rem';
robert.style.boxShadow = '0 0 0 #f1faee';
robert.style.transition = '0.5s';
}
function animationOut() {
robert.style.margin = '0rem 3.5rem 2rem 0rem';
robert.style.boxShadow = '0.8rem 0.8rem #e63946'
robert.style.transition = '0.5s'
}
robert.onmouseover = animationOver();
robert.onmouseleave = animationOut();
</code></pre>
<p>I'm new to programming so I don't know what else to try.</p>
| [
{
"answer_id": 74229494,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": true,
"text": "df[\"tmp\"] = (df[\"groupid\"] != df[\"groupid\"].shift()).cumsum()\ngrps = df.groupby(\"groupid\")[\"value\"... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20353720/"
] |
74,229,442 | <p>I want to add a <code>strike-through</code> decoration to the <code>#text</code>-node-like children of a particular item we render using <a href="https://meliorence.github.io/react-native-render-html/docs/guides/custom-renderers" rel="nofollow noreferrer">custom rendering</a>.</p>
<p>But I'm not aware of any way to actually target the child <code>#text</code>-like-node and apply styles to it.</p>
<p>For example, we could wrap the <code>TChildrenRenderer</code> like below, but those styles will not be inherited by the <code>Text</code> component that <code>TChildrenRenderer</code> renders. So this works for some styles, like <code>lineDecorationType: 'line-through'</code>, but not for things like <code>color</code>.</p>
<pre class="lang-js prettyprint-override"><code><Text style={{ color: 'red' }}>
<TChildrenRenderer tchildren={tnode.children} />
</Text>
</code></pre>
<p>Is there any approach that would allow us to set <code>color</code> on the inner rendered text?</p>
<hr />
<p><strong>Edit</strong>: The method has to allow for conditional styling, so a top-level prop like <code>defaultTextProps</code> is out.</p>
| [
{
"answer_id": 74229494,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 2,
"selected": true,
"text": "df[\"tmp\"] = (df[\"groupid\"] != df[\"groupid\"].shift()).cumsum()\ngrps = df.groupby(\"groupid\")[\"value\"... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6025788/"
] |
74,229,451 | <p>I created a GIT Remote Repository in localhost.<br>
Then I push my project.<br>
I can clone my project via :</p>
<pre><code>git clone ssh://127.0.0.1/repo-r/haq
</code></pre>
<p>But when I want to use <code>git://</code> or <code>http://</code> I get the following error:</p>
<pre><code>$ git clone git://127.0.0.1/repo-r/haq/haq.git
Cloning into 'haq'...
fatal: unable to connect to 127.0.0.1:
127.0.0.1[0: 127.0.0.1]: errno=Connection refused
</code></pre>
<p>How do I solve it?</p>
| [
{
"answer_id": 74231061,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "git clone /srv/git/project.git\n"
}
] | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1058591/"
] |
74,229,459 | <p>I have a tricky situation.</p>
<p>I have a source dataset; it has data for four employees and their departments based on an effective date.</p>
<p>I need to convert this source dataset to the destination dataset.</p>
<p><a href="https://i.stack.imgur.com/NJsI7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NJsI7.png" alt="enter image description here" /></a></p>
<p>Both datasets are properly sorted by EmployeeName and EffectiveDate (ASC) order.</p>
<p>(Please see T-SQL scripts using temp table.)</p>
<pre><code>CREATE TABLE #source
(
EmployeeName varchar(100),
EffectiveDate date,
CurrentDepartment varchar(100)
);
INSERT INTO #source
VALUES
('Lisa','2017-06-25','Catering'),
('Lisa','2018-08-17',NULL),
('Lisa','2021-12-05','Gardening'),
('Melissa','2015-08-27',NULL),
('Melissa','2017-11-29','Office'),
('Melissa','2020-10-10','Driving'),
('Melissa','2022-07-11',NULL),
('Omar','2019-01-03',NULL),
('Omar','2020-04-07','Retail'),
('Omar','2021-03-29',NULL),
('Pat', '2012-09-12','Laundry'),
('Pat', '2013-10-30',NULL),
('Pat', '2014-11-29',NULL),
('Pat', '2015-08-16',NULL),
('Pat', '2016-11-05',NULL)
CREATE TABLE #destination
(
EmployeeName varchar(100),
EffectiveDate date,
CurrentDepartment varchar(100),
PreviousNonNULLDepartmentIfAvailable varchar(100)
);
INSERT INTO #destination
VALUES
('Lisa','2017-06-25','Catering',NULL),
('Lisa','2018-08-17',NULL,'Catering'),
('Lisa','2021-12-05','Gardening','Catering'),
('Melissa','2015-08-27',NULL,NULL),
('Melissa','2017-11-29','Office',NULL),
('Melissa','2020-10-10','Driving','Office'),
('Melissa','2022-07-11',NULL,'Driving'),
('Omar','2019-01-03',NULL,NULL),
('Omar','2020-04-07','Retail',NULL),
('Omar','2021-03-29',NULL,'Retail'),
('Pat', '2012-09-12','Laundry',NULL),
('Pat', '2013-10-30',NULL,'Laundry'),
('Pat', '2014-11-29',NULL,'Laundry'),
('Pat', '2015-08-16',NULL,'Laundry'),
('Pat', '2016-11-05',NULL,'Laundry')
SELECT *
FROM #source
ORDER BY EmployeeName, EffectiveDate
SELECT *
FROM #destination
ORDER BY EmployeeName, EffectiveDate
</code></pre>
<p>In the destination dataset, I need one new column called [PreviousNonNULLDepartmentIfAvailable].</p>
<p>What is the logic to derive this above new column?</p>
<p>I need to get each individual's most recent (previous) department; it is easy to use a LAG function to get the most recent (previous) department. See T-SQL code below:</p>
<pre><code>PreviousNonNULLDepartmentIfAvailable = LAG(CurrentDepartment) OVER(PARTITION BY EmployeeName ORDER BY EffectiveDate)
</code></pre>
<p>However, I need the most recent (previous) non-NULL department; if there is no such "most recent (previous) non-NULL" department value within the PARTITION of EmployeeName, then I need to show NULL.</p>
<p>I have tried <a href="https://www.mssqltips.com/sqlservertip/7379/last-non-null-value-set-of-sql-server-records/" rel="nofollow noreferrer">options</a> such as LAG, LAST_VALUE, IGNORE NULLS clause, UNBOUNDED PRECEDING clause. These options are close to what I need, but NOT exactly what I need.</p>
<p>Effectively, I need to get what a LAG function would perform; but the offset value for LAG function has to be dynamic, instead of a static value such as 1 or 2 or 3...; the LAG function needs to iterate (backwards) as many rows as needed to catch the most recent (previous) non-NULL department value, within a PARTITION of EmployeeName.</p>
<p>This said, the column [PreviousNonNULLDepartmentIfAvailable] can <strong>still</strong> have NULL values, if there is <strong>no</strong> such "most recent (previous) non-NULL" department value available within a PARTITION of EmployeeName.</p>
<p>Also, the first row based on ascending order of Effective Date of each partition of EmployeeName will always have NULL as its [PreviousNonNULLDepartmentIfAvailable] value (obviously). This is natural in the way LAG function works.</p>
<p>Any idea on how to convert the source dataset to destination dataset ?</p>
| [
{
"answer_id": 74231061,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "git clone /srv/git/project.git\n"
}
] | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3812887/"
] |
74,229,463 | <p>I got this HTML page that has as a toolbar some buttons and a search filter.</p>
<pre><code><div class="topnav">
<button>Add</button>
<button>Delete</button>
<button>Advanced Filters</button>
<select id="select-items">
<option value="uid">Uid</option>
<option value="name">Name</option>
<option value="email">Email</option>
<option value="user_type">User type</option>
<option value="last_login">Last login</option>
</select>
<select id="select-filter">
<option>=</option>
<option>></option>
<option>>=</option>
<option><</option>
<option><=</option>
<option>Starts with</option>
<option>Contains</option>
<option>Ends with</option>
</select>
<div class>
<form onsubmit="search()" class="search-bar">
<input id="searchBar" class="input searchbar" type="text"
aria-autocomplete="list"
aria-expanded="false"
style="height: 28.5px"
>
<button><i class="fa fa-search"></i>
</button>
</form>
</div>
</div>
</code></pre>
<p>The way it looks right now:</p>
<p><img src="https://i.stack.imgur.com/VprYv.png" alt="enter image description here" /></p>
<p>I would like the search bar to be placed on the same row as the buttons, but it is placed below the first row for some reason. I tried using <code>float: right</code> and it still did not work. What is wrong here?</p>
| [
{
"answer_id": 74229551,
"author": "Ronnie Royston",
"author_id": 4797603,
"author_profile": "https://Stackoverflow.com/users/4797603",
"pm_score": 1,
"selected": false,
"text": "display: inline-block;"
},
{
"answer_id": 74229690,
"author": "Mad7Dragon",
"author_id": 6467... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19434278/"
] |
74,229,480 | <p>Currently, when I get the annotations from the annotationManager, they are coming back empty for the current document, do we need to manage annotationMangers for each tab?</p>
<pre><code>const allAnnotList = annotationManager.getAnnotationsList();
</code></pre>
<p>Anyone with any experience using PDFTron tab view for multiple documents.</p>
<ol>
<li>Does each tab have a documentViewer or is this global and updated when the tab is changed.</li>
<li>Does the annotationManager hold all annotations or just for the current documentViewer</li>
</ol>
<p>I have narrowed down the issue to the below function call:</p>
<pre><code>currentAnnotationManger.exportAnnotations
</code></pre>
<p>currentAnnotationManger.exportAnnotations
Confirmed we have a list of annotations below:</p>
<blockquote>
</blockquote>
<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>[
{
"BU": true,
"Subject": "client-Client 1-0",
"WF": 1,
"Gz": 261,
"Hz": 197,
"Ru": 96,
"Qu": 32,
"Rotation": 0,
"le": {
"x": 309,
"y": 213
},
"AO": 50.59644256269407,
"Dz": false,
"DO": false,
"EO": false,
"ni": {
"trn-annot-maintain-aspect-ratio": "true",
"trn-unrotated-rect": "261,626,357,658"
},
"Bz": true,
"yO": false,
"UF": false,
"Pu": false,
"zO": false,
"TF": false,
"NoZoom": false,
"NoRotate": false,
"FO": true,
"Nm": null,
"TO": "Agent Id : 62b11e644180cb09e786ec7d",
"iG": "2022-10-28T03:47:54.535Z",
"hA": "d9b4efdc-af38-d203-5a41-0139451aecd4",
"xG": true,
"fp": false,
"KP": false,
"iQ": {},
"Wk": [],
"gh": null,
"uE": null,
"ZK": null,
"qr": [],
"Uo": {},
"To": {},
"CO": null,
"GO": null,
"yj": null,
"zj": null,
"aQ": 1,
"Y3": null,
"eP": "2022-10-28T03:47:50.793Z",
"CA": null,
"_xsi:type": "Stamp",
"oi": "Draft",
"Cy": "Draft",
"Ya": null,
"Vw": 1,
"canvas": {},
"K7": "bold italic 30px sans-serif",
"ToolName": "AnnotationCreateRubberStamp",
"image": {}
},
{
"BU": true,
"Subject": "agent",
"WF": 1,
"Gz": 200,
"Hz": 300,
"Ru": 96,
"Qu": 32,
"Rotation": 0,
"le": {
"x": 248,
"y": 316
},
"AO": 50.59644256269407,
"Dz": false,
"DO": false,
"EO": false,
"ni": {
"trn-annot-maintain-aspect-ratio": "true",
"trn-unrotated-rect": "200,523,296,555"
},
"Bz": true,
"yO": false,
"UF": false,
"Pu": false,
"zO": false,
"TF": false,
"NoZoom": false,
"NoRotate": false,
"FO": true,
"Nm": null,
"TO": "Agent Id : 62b11e644180cb09e786ec7d",
"iG": "2022-10-28T03:47:54.535Z",
"hA": "58dc723e-da36-5f4e-16d5-fe6ae32f5252",
"xG": true,
"fp": false,
"KP": false,
"iQ": {},
"Wk": [],
"gh": null,
"uE": null,
"ZK": null,
"qr": [],
"Uo": {},
"To": {},
"CO": null,
"GO": null,
"yj": null,
"zj": null,
"aQ": 1,
"Y3": null,
"eP": "2022-10-28T03:47:53.499Z",
"CA": null,
"_xsi:type": "Stamp",
"oi": "Draft",
"Cy": "Draft",
"Ya": null,
"Vw": 1,
"canvas": {},
"K7": "bold italic 30px sans-serif",
"ToolName": "AnnotationCreateRubberStamp",
"image": {}
}
]</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74231414,
"author": "Larry Edwardson",
"author_id": 10932123,
"author_profile": "https://Stackoverflow.com/users/10932123",
"pm_score": 0,
"selected": false,
"text": "currentAnnotationManger.exportAnnotations\n"
},
{
"answer_id": 74259420,
"author": "Larry Edwa... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10932123/"
] |
74,229,513 | <p>i have a Class called SocialNetwork with an url and an enum of social_networks. I have a regexp validation of the url depending on the social network selected, but it fails if the record is being created due to the fact that both params are nil.</p>
<pre><code>class SocialNetwork < ApplicationRecord
REGEXP = {
facebook: %r{\Ahttps://www.facebook.com/.+\z},
twitter: %r{\Ahttps://twitter.com/.+\z},
linkedin: %r{\Ahttps://www.linkedin.com/in/.+\z},
github: %r{\Ahttps://github.com/.+\z},
instagram: %r{\Ahttps://www.instagram.com/.+\z},
youtube: %r{\Ahttps://www.youtube.com/.+\z},
tiktok: %r{\Ahttps://www.tiktok.com/.+\z},
twitch: %r{\Ahttps://www.twitch.tv/.+\z},
onlyfans: %r{\Ahttps://onlyfans.com/.+\z}
}.freeze
belongs_to :user
validates :url, presence: true
validates :app, presence: true
validates :app, uniqueness: { scope: :user_id }
validate :url_match_regexp
enum app: { facebook: 0, twitter: 1, instagram: 2, linkedin: 3, youtube: 4, tiktok: 5,
twitch: 6, onlyfans: 7, github: 8 }
private
def url_match_regexp
errors.add(:url, 'is not valid') unless url.match(REGEXP[app])
end
end
</code></pre>
<p>How can i test <code>url_match_regexp</code> before the record being created?</p>
| [
{
"answer_id": 74231414,
"author": "Larry Edwardson",
"author_id": 10932123,
"author_profile": "https://Stackoverflow.com/users/10932123",
"pm_score": 0,
"selected": false,
"text": "currentAnnotationManger.exportAnnotations\n"
},
{
"answer_id": 74259420,
"author": "Larry Edwa... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10320608/"
] |
74,229,542 | <p>I just found out about guarded equations in Haskell, here's an example:</p>
<pre><code>abs n | n >= 0 = n
| otherwise = -n
</code></pre>
<p>it basically says that function <code>abs</code> returns <code>n</code> if <code>n >= 0</code>, otherwise it returns <code>-n</code>.</p>
<p>In the book it says that the the standard prelude otherwise is defined like this: <code>otherwise = True</code>, why is that?</p>
| [
{
"answer_id": 74229553,
"author": "pavel_orekhov",
"author_id": 10681828,
"author_profile": "https://Stackoverflow.com/users/10681828",
"pm_score": 2,
"selected": false,
"text": "True"
},
{
"answer_id": 74229603,
"author": "Peter Hall",
"author_id": 493729,
"author_p... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10681828/"
] |
74,229,544 | <p>I'm trying to filter a data.table when a column name is the same as a variable in my environment.</p>
<pre><code>dt = data.table(myvar = 1:10)
myvar = 2
dt[myvar %in% myvar]
</code></pre>
<p>Result:</p>
<pre><code> myvar
1: 1
2: 2
3: 3
4: 4
5: 5
6: 6
7: 7
8: 8
9: 9
10: 10
</code></pre>
<p>Desired result:</p>
<pre><code> myvar
1: 2
</code></pre>
| [
{
"answer_id": 74229565,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 2,
"selected": false,
"text": "..varname"
},
{
"answer_id": 74236557,
"author": "mnist",
"author_id": 8107362,
... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893537/"
] |
74,229,635 | <p>Just trying to generate a series (loop of 10) random hexadecimal strings.. Here's my code</p>
<pre><code>math.randomseed(os.time())
function genRanHex(length)
genRanHex = ""
for count = 1, length, 1 do
num = math.random(0,15)
genRanHex = genRanHex..string.upper(string.format("%x", num))
end
return genRanHex
end
for c = 1, 10, 1 do
print(genRanHex(8))
end
</code></pre>
<p>getting the following error:</p>
<p>lua: main.lua:13: attempt to call a string value (global 'genRanHex')
stack traceback:
main.lua:13: in main chunk
[C]: in ?</p>
<p>Thank you for any assistance</p>
| [
{
"answer_id": 74229805,
"author": "Dan Bonachea",
"author_id": 3528321,
"author_profile": "https://Stackoverflow.com/users/3528321",
"pm_score": 1,
"selected": false,
"text": "local"
},
{
"answer_id": 74231468,
"author": "LMD",
"author_id": 7185318,
"author_profile":... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20353897/"
] |
74,229,649 | <p>I use <code>gq</code> to format my Go code. I set <code>formatprg=goimports</code>.
I want to execute <code>gq</code> on save automatically. I added this line in my vimrc:</p>
<pre><code>au BufWritePost *.go normal gggqG
</code></pre>
<p>This works great, but the one thing is, because of <code>G</code>, my cursor goes to the bottom line in the buffer when I save the file (by <code>:w</code>) .
I want to keep my cursor place after running <code>gq</code>. How can I do this?</p>
<p>I know some plugins enable to do this, but I prefer not using them.</p>
| [
{
"answer_id": 74230553,
"author": "Hi computer",
"author_id": 16702058,
"author_profile": "https://Stackoverflow.com/users/16702058",
"pm_score": 0,
"selected": false,
"text": "au BufWritePost *.sh exe \"normal! ggG\\<c-o>\\<c-o>\"\n"
},
{
"answer_id": 74231955,
"author": "r... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13914809/"
] |
74,229,662 | <p>For example, I have 9 conditions lets say and i want to store the seed number within a loop that goes into the results list that contains con1-con9. In my actual code the seed number will be changing, but just have this here for simplicity.</p>
<pre><code>seed <- 500
for(x in 1:length(results)){
results$con1$seednum <- seed
}
</code></pre>
<p>I thought something like this, but does not seem to work.</p>
<pre><code>eval(parse(text= paste0("results$con", x)))$seednum <- 500
</code></pre>
<p>How can i have this such that the con1 will change to con2, con3...etc through the for loop and be able to store that seed value in each results$con1 through results$con9? I assume it has something to do with eval and parse while using the x index, but I am not sure how it can be done.</p>
<p>Thank you.</p>
| [
{
"answer_id": 74229793,
"author": "GuedesBF",
"author_id": 13972333,
"author_profile": "https://Stackoverflow.com/users/13972333",
"pm_score": 1,
"selected": false,
"text": "my_list <- mget(ls(pattern='con\\\\d+')\n"
},
{
"answer_id": 74231152,
"author": "Roland",
"autho... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13314938/"
] |
74,229,729 | <p>I have a table with many categories
Currently, I am rendering them with tr tags, each category will be displayed in a child tag</p>
<p><a href="https://i.stack.imgur.com/o7Lgj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o7Lgj.png" alt="enter image description here" /></a></p>
<p>But this causes the table layout to break when a parent cell has an increase in height</p>
<p><a href="https://i.stack.imgur.com/LhhV1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LhhV1.png" alt="enter image description here" /></a></p>
<p><code>codepend: https://codepen.io/sayuto/pen/YzvPoBO</code></p>
<p>Where did I go wrong or does someone have a better idea how to do this?
I have tried rendering a tr tag that will contain "parent" and "first child", "other children" will be rendered in the next tr, but this is very complicated, calculating rowspan is difficult.</p>
<p>I trying to find out the correct html table layout what I should to use to render table with nested categories</p>
<p>P/s: I am trying to render column by column (this makes it easier for us to gather data and load
Building data structures and load data onto tables with default rendering (line by line) is a nightmare for both the writer and the maintainer (in this case - nested categories)</p>
| [
{
"answer_id": 74229793,
"author": "GuedesBF",
"author_id": 13972333,
"author_profile": "https://Stackoverflow.com/users/13972333",
"pm_score": 1,
"selected": false,
"text": "my_list <- mget(ls(pattern='con\\\\d+')\n"
},
{
"answer_id": 74231152,
"author": "Roland",
"autho... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5952155/"
] |
74,229,730 | <p>Are there any practical ways to limit APIs from being invoked by applications outside of working hours or days in WSO2 API Manager or WSO2 Integrator Studio?</p>
<p>Some services in my company need to be called during working hours, and I have to disable them when no one is working</p>
| [
{
"answer_id": 74229793,
"author": "GuedesBF",
"author_id": 13972333,
"author_profile": "https://Stackoverflow.com/users/13972333",
"pm_score": 1,
"selected": false,
"text": "my_list <- mget(ls(pattern='con\\\\d+')\n"
},
{
"answer_id": 74231152,
"author": "Roland",
"autho... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20135571/"
] |
74,229,735 | <p><a href="https://stackoverflow.com/questions/43572387/error-215-size-width0-size-height0-occurred-when-attempting-to-display-a">Error (-215) size.width>0 && size.height>0 occurred when attempting to display an image using OpenCV</a></p>
<p>I have the similar issue with this discussion, after I read it still don't have clue for how to address mine,that I post my case here</p>
<p><em>I use raspberrypi 4 ; 32 bit, linux run python ; logitech USB camera lens ; run in virtual environment</em></p>
<ul>
<li>the python script <code>opencv_camera.py</code></li>
</ul>
<pre><code>import cv2
# define a video capture object
vid = cv2.VideoCapture(1) ########## 1- device id =1###if 1 deosn't work try 2
while(True):
ret, frame = vid.read()
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
vid.release()
cv2.destroyAllWindows()
</code></pre>
<hr />
<p>error occur:</p>
<blockquote>
<p>cv2.error: OpenCV(4.6.0) .... in function 'imshow'</p>
</blockquote>
<ul>
<li>the output:</li>
</ul>
<pre><code>(venv) joy@raspberrypi:~/Desktop $ python opencv_camera.py
[ WARN:0@0.020] global /tmp/pip-wheel-u79916uk/opencv-python_ea2489746b3a43bfb3f2b5331b7ab47a/opencv/modules/videoio/src/cap_v4l.cpp (902) open VIDEOIO(V4L2:/dev/video1): can't open camera by index
Traceback (most recent call last):
File "/home/joy/Desktop/opencv_camera.py", line 14, in <module>
cv2.imshow('frame', frame)
cv2.error: OpenCV(4.6.0) /tmp/pip-wheel-u79916uk/opencv-python_ea2489746b3a43bfb3f2b5331b7ab47a/opencv/modules/highgui/src/window.cpp:967: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'
</code></pre>
<hr />
<ul>
<li>troubleshooting status: now find out ret is none</li>
</ul>
<pre><code>import cv2
# define a video capture object
vid = cv2.VideoCapture(2) ########## 1- device id =1###if 1 deosn't work try 2
while(True):
ret, frame = vid.read()
if ret == True:
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
print("ret is empty")
break
# After the loop release the cap object
vid.release()
# Destroy all the windows
cv2.destroyAllWindows()
</code></pre>
<p>output:</p>
<pre><code>(venv) joy@raspberrypi:~/Desktop $ python opencv_camera.py
[ WARN:0@0.019] global /tmp/pip-wheel-u79916uk/opencv-python_ea2489746b3a43bfb3f2b5331b7ab47a/opencv/modules/videoio/src/cap_v4l.cpp (902) open VIDEOIO(V4L2:/dev/video2): can't open camera by index
ret is empty
</code></pre>
| [
{
"answer_id": 74229793,
"author": "GuedesBF",
"author_id": 13972333,
"author_profile": "https://Stackoverflow.com/users/13972333",
"pm_score": 1,
"selected": false,
"text": "my_list <- mget(ls(pattern='con\\\\d+')\n"
},
{
"answer_id": 74231152,
"author": "Roland",
"autho... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20000047/"
] |
74,229,811 | <p>I need to make a program to identify whether the input number is a <a href="https://en.wikipedia.org/wiki/Smith_number" rel="nofollow noreferrer">Smith number</a> or not.</p>
<p>Here is my code:</p>
<pre><code>#include <stdio.h>
void smith(int n) {
int num, sd = 0, sf = 0, i, t, c, j;
num = n;
while (num > 0) {
sd = sd + (num % 10); // Sum of digits of input number
num = num / 10;
}
num = n;
while (num > 1) // To calculate factors of the number
{
for (i = 1; i <= num; i++) {
if (num % i == 0) break;
}
c = 0;
t = i;
for (j = 1; j <= i; j++) // To check if the numbers are prime
{
if (i % j == 0) c++;
}
if (c == 2) {
while (i > 0) {
sf = sf + (i % 10);
i = i / 10;
}
}
num = num / t;
}
if (sd == sf) {
printf("Smith Number");
} else
printf("Not a Smith Number");
}
int main() {
int n;
printf("Enter a number");
scanf("%d", &n);
smith(n);
}
</code></pre>
<p>Every time I try to run the code, it just doesn't give an output.
It just takes an input and then probably goes into an infinite loop.</p>
| [
{
"answer_id": 74229793,
"author": "GuedesBF",
"author_id": 13972333,
"author_profile": "https://Stackoverflow.com/users/13972333",
"pm_score": 1,
"selected": false,
"text": "my_list <- mget(ls(pattern='con\\\\d+')\n"
},
{
"answer_id": 74231152,
"author": "Roland",
"autho... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19849468/"
] |
74,229,817 | <p>I am trying to create a program that averages image's pixel values, but so far it has just generated vertical lines.</p>
<p>This is my code so far:</p>
<pre class="lang-py prettyprint-override"><code>from typing import List
import cv2 as cv
import numpy as np
def main():
# Importing two of the same imagae for debugigng purposes
a = cv.imread("Datasets/OTIS/OTIS_PNG_Gray/Fixed Patterns/Pattern1/Pattern1_001.png", cv.IMREAD_GRAYSCALE)
b = cv.imread("Datasets/OTIS/OTIS_PNG_Gray/Fixed Patterns/Pattern1/Pattern1_001.png", cv.IMREAD_GRAYSCALE)
s = [a, b]
avg = [[0] * len(a[0])] * len(a)
print(f"rows: {len(a)} cols: {len(a[0])}")
print(f"rows: {len(avg)} cols: {len(avg[0])}")
for i in range(len(a)):
for j in range(len(a[0])):
# print(f"({i}, {j}): {temp_mean(s, i, j)}")
avg[i][j] = temp_mean(s, i, j) / 255
avim = np.array(avg)
print(f"rows: {len(avim)} cols: {len(avim[0])}")
cv.imshow("title", avim)
cv.waitKey(0)
def temp_mean(seq: List[List[List[any]]], i: int, j: int):
out = 0
for im in seq:
out += im[i][j]
return out / len(seq)
if __name__ == '__main__':
main()
</code></pre>
<p>Source Image:
<a href="https://i.stack.imgur.com/m06Ae.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m06Ae.png" alt="Source Image" /></a></p>
<p>Image generated:
<a href="https://i.stack.imgur.com/rde9E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rde9E.png" alt="Image generated" /></a></p>
| [
{
"answer_id": 74230265,
"author": "Cris Luengo",
"author_id": 7328782,
"author_profile": "https://Stackoverflow.com/users/7328782",
"pm_score": 1,
"selected": true,
"text": "avg"
}
] | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14193833/"
] |
74,229,850 | <p>I am trying to assert the value's in an array.
At this moment I made it to assert just the length:</p>
<pre class="lang-js prettyprint-override"><code>cy.get('@UrlAndAppendices')
.its('request.body.correctionInstructionAppendices')
.should('have.length', 2)
</code></pre>
<p>What is the best way to compare this?
I can make an deep equal with a fixture. But I dont think that this would be the cleanest solution for assertin just 2 value's in a array.</p>
<p><a href="https://i.stack.imgur.com/Sqp3f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Sqp3f.png" alt="Result in cypress" /></a></p>
| [
{
"answer_id": 74236758,
"author": "jjhelguero",
"author_id": 17917809,
"author_profile": "https://Stackoverflow.com/users/17917809",
"pm_score": 0,
"selected": false,
"text": "const arrValues = [2, 3]\ncy.get('@UrlAndAppendices')\n .its('request.body.correctionInstructionAppendices')\n... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19285414/"
] |
74,229,873 | <p>I have a form which gets data from the user via edit boxes and combo boxes, this information then has to be uploaded into a database table so I have to do validation. I did just that and it keeps on saying ''is not a valid integer' yet it is not even supposed to upload anything to the database table as all conditions where not met because of the null check that I did. Did I do my validation wrong?</p>
<pre><code>
unit Unit6;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Spin, ExtCtrls,unit7,unit5,unit4, DB, ADODB, Grids, DBGrids,
pngimage;
type
Tfrmupload = class(TForm)
Panel1: TPanel;
edtname: TEdit;
edtsurn: TEdit;
edtidn: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label5: TLabel;
Label6: TLabel;
Panel2: TPanel;
btnupload: TButton;
edtmail: TEdit;
cbprov: TComboBox;
Image1: TImage;
cbdiv: TComboBox;
Label4: TLabel;
procedure btnuploadClick(Sender: TObject);
procedure Label7Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmupload: Tfrmupload;
implementation
{$R *.dfm}
procedure Tfrmupload.btnuploadClick(Sender: TObject);
var
vname,vsurname,today,c,vidn,vprov,vmail,vdiv:string;
vage,year,i,age:integer;
bnotnull,bIDL,bmail,bage,byoung,valid,idrepeated:boolean;
dt:tdatetime;
begin
vname:=edtname.Text;
vsurname:=edtsurn.Text;
vidn:=edtidn.Text;
vdiv:=cbdiv.Text;
vprov:=cbprov.Text;
vmail:=edtmail.Text;
//booleans
bnotnull:=false;
bIdL:=false;
bmail:=false;
byoung:=false;
idrepeated:=false;
valid:=false;
//check if id entered is not in table already
if unit5.frmadmin.ADODetails.Locate('ID number',vidn,[]) then
begin
idrepeated:=true;
showmessage('ID Number already exists');
end;
//null check
if (vname<>'')and(vsurname<>'')and(vidn<>'')and(vprov<>'')and(vmail<>'')and(vdiv<>'') then
begin
bnotnull:=true;
end
else
begin
Showmessage('Complete All Fields!');
end;
//get current date
dt:=now;
year:=strtoint(formatdatetime('yyyy',dt));
c:=copy(vidn,1,2);
//calculate age from id number
if (strtoint(c)>=0) and (strtoint(c)<=22) then
begin
age:=year-(2000+strtoint(c));
end
else
begin
age:=year-(1900+strtoint(c));
end;
//ID length validation
if (length(vidn)=13) then
begin
bidl:=true;
end;
//check if contestant is not too young
if age<6 then
begin
showmessage('Contestant too young, cannot compete');
byoung:=true;
end;
//check if email is correct format
for i := 1 to length(vmail)do
begin
if vmail[i]='@' then
begin
bmail:=true;
end;
end;
//error message for email check
if bmail=false then
begin
showmessage('Incorrect Email Format');
end;
if bidl=false then
begin
showmessage('ID Number must be 13 characters');
end;
//checks if all the conditions are met and if so we can then upload to database
if (bnotnull=true) and (bidl=true) and (byoung=false)and (bmail=true)and (idrepeated=false) then
begin
valid:=true;
end;
if valid=true then
begin
unit5.frmadmin.ADODetails.Append;
unit5.frmadmin.ADODetails['Name(s)']:=vname;
unit5.frmadmin.ADODetails['Surname']:=vsurname;
unit5.frmadmin.ADODetails['ID Number']:=vidn;
unit5.frmadmin.ADODetails['Age']:=age;
unit5.frmadmin.ADODetails['Province']:=vprov;
unit5.frmadmin.ADODetails['Email']:=vmail;
unit5.frmadmin.ADODetails.Post;
unit4.frmcontest.ADOLead.Insert;
unit4.frmcontest.ADOLead['ID Number']:=unit4.frmcontest.DBComboID.Text;;
unit4.frmcontest.ADOLead['Name(s)']:=unit4.frmcontest.DBCombonme.Text;
unit4.frmcontest.ADOLead['Division']:=vdiv;
unit4.frmcontest.ADOLead.Post;
showmessage('Details Uploaded');
frmupload.Hide;
end;
//clears all inputs
edtname.Clear;
edtsurn.Clear;
edtidn.Clear;
cbdiv.Text:='';
cbprov.Text:='';
edtmail.Clear;
end;
procedure Tfrmupload.Label7Click(Sender: TObject);
begin
frmupload.Hide;
end;
end.
</code></pre>
| [
{
"answer_id": 74232025,
"author": "Ineffable21",
"author_id": 19733965,
"author_profile": "https://Stackoverflow.com/users/19733965",
"pm_score": -1,
"selected": false,
"text": "year:=strtoint(formatdatetime('yyyy',dt));\n"
},
{
"answer_id": 74239299,
"author": "Ehab",
"... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20344420/"
] |
74,229,879 | <p>I have two components, the parent(name Parent) and child(name Child), on the parent, i map an array and render the child, so the child appears like 4 times(number of times the child is displayed based on the mapping), i have an input field on the Child component (which will be 1 input field for the rendered child component), i am basically trying to get the values of the input field from all the rendered Child component (4 been rendered based on the mapping) and then send it to my parent component (store it in a state on the parent component).</p>
<p>mock code</p>
<p>parent component</p>
<pre class="lang-js prettyprint-override"><code>const Items = [1,2,3,4]
export const Parent= () => {
return (<div>
{Items.map((Item, index) => {
return (
<div key={index}>
<Child />
</div>
);
})}
</div>
)
}
</code></pre>
<p>child component</p>
<pre class="lang-js prettyprint-override"><code>
export const Child = () => {
const [Amount, setAmount] = useState();
return (
<input
value={Amount}
onChange={(e) => setAmount(e.target.value)}
placeholder="Amount"
/>
)
}
</code></pre>
<p>sorry for the bad code formatting.</p>
<p>This is a mock of what it looks like</p>
<p>this should give a somewhat clear understanding or image of the issue, i basically want to get all the <code>Amount</code> on the 4 render children, place it in an array and send it to the Parent component (so i can call a function that uses all the amount in an array as an argument)</p>
<p>i tried to set the values of the Child component to a state on context (it was wrong, it kept on pushing the latest field values that was edited, i am new to react so i didnt understand some of the things that were said about state lifting</p>
| [
{
"answer_id": 74232025,
"author": "Ineffable21",
"author_id": 19733965,
"author_profile": "https://Stackoverflow.com/users/19733965",
"pm_score": -1,
"selected": false,
"text": "year:=strtoint(formatdatetime('yyyy',dt));\n"
},
{
"answer_id": 74239299,
"author": "Ehab",
"... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20354029/"
] |
74,229,893 | <p>I'm having trouble with the react-native-splash-screen</p>
<h3>React-native info</h3>
<ul>
<li>Node : 16.17.0</li>
<li>Yarn : 1.22.19</li>
<li>react : 18.1.0</li>
<li>react-native : 0.70.0</li>
</ul>
<h2>Error</h2>
<p><code>MainActivityDelegate cannot be converted to Activity SplashScreen.show(this);</code></p>
<h2>MainActivity.java</h2>
<p>`</p>
<pre><code>package com.ala.com.ala;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.lockincomp.liappagent.LiappAgent;
import org.devio.rn.splashscreen.SplashScreen;
@Override
protected void onCreate(Bundle savedInstanceState) {
SplashScreen.show(this);
...my other codes
super.onCreate(null);
// super.onCreate(savedInstanceState); <- this also tried but not working
}
</code></pre>
<p>`</p>
<p>I don't know why I'm having this kind of error. because of React Native 0.7 version error? or what...please help..</p>
<p>I also tried to use react-native-bootsplash but this library also having error in</p>
<p>`@Override<br />
protected void onCreate(Bundle savedInstanceState) {</p>
<p>RNBootSplash.init(this); //this part having error in this<br />
super.onCreate(savedInstanceState); // or super.onCreate(null) with react-native-screens<br />
}`</p>
| [
{
"answer_id": 74231399,
"author": "Muhammad Awais Kayani",
"author_id": 19689690,
"author_profile": "https://Stackoverflow.com/users/19689690",
"pm_score": 1,
"selected": false,
"text": "@Override\nprotected void onCreate(Bundle savedInstanceState) {\n\n ...my other codes\n\n super.... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20354108/"
] |
74,229,902 | <p>I placed a text over an image, but when I increase the screen size the image won't follow, its just stuck at the same place, contrary to the text that responds to the screen-size and moves to the center.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.section2{
max-height: 20rem;
padding-top: 20px;
position: relative;
}
.section2 img{
padding: 20px
}
.abtus {
position: absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
width: 60%;
font-size: 1rem;
text-align: center;
padding-top: 6rem;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="section2">
<img src="assets/script.png" alt="">
<div class="abtus">
<h1>About Us</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad cum architecto eius molestiae dolore est id vero voluptatem
repellat voluptas quo beatae nulla ex soluta deleniti impedit maxime, enim omnis?</p>
</div>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74231399,
"author": "Muhammad Awais Kayani",
"author_id": 19689690,
"author_profile": "https://Stackoverflow.com/users/19689690",
"pm_score": 1,
"selected": false,
"text": "@Override\nprotected void onCreate(Bundle savedInstanceState) {\n\n ...my other codes\n\n super.... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19936860/"
] |
74,229,933 | <p>Is anyone got rejected from google play because of REQUEST_INSTALL_PACKAGES permission ?
<a href="https://i.stack.imgur.com/evHhJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/evHhJ.png" alt="rejection reason" /></a></p>
<p>I removed this permission from my app even removed plugin which used it but still got this rejection.
I checked all android manifest files, even all logs there is no REQUEST_INSTALL_PACKAGES permission</p>
| [
{
"answer_id": 74230333,
"author": "Cương Nguyễn",
"author_id": 12172908,
"author_profile": "https://Stackoverflow.com/users/12172908",
"pm_score": 2,
"selected": false,
"text": "AndroidManifest.xml"
}
] | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18107373/"
] |
74,229,953 | <p>As shown in the following react code snippet, I have a useEffect hook with a dependency 'fetchQuery'. The useEffect hook will execute if 'fetchQuery' variable changes. But right after execution of it, I want to clear the value (set to '') of that dependency variable 'fetchQuery' without triggering an infinite loop. Is there a way to do that?</p>
<pre><code>useEffect(() => {
// An async function to fetch some data
getDataModules(fetchQuery);
}, [fetchQuery]);
</code></pre>
<p>Since 'fetchQuery' is a state variable and is given as a dependency for this hook, simply clearing its value using <code>setFetchQuery('');</code> will trigger useEffect again, which I dont want.</p>
| [
{
"answer_id": 74230333,
"author": "Cương Nguyễn",
"author_id": 12172908,
"author_profile": "https://Stackoverflow.com/users/12172908",
"pm_score": 2,
"selected": false,
"text": "AndroidManifest.xml"
}
] | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16486762/"
] |
74,229,963 | <p>I understand we are able to write a condition in property as <code>ternary operator</code> as follows</p>
<pre><code>onTap: textType == "birth"
? () {
FocusScope.of(context).requestFocus(FocusNode());
showPicker(context, birthController,ref);
}
: null,
</code></pre>
<p>but when it comes to multiple conditions, how can I rewrite the code like? as the code shown below treated as syntax error.</p>
<pre><code>onTap:
if (textType == "birth"){
//do something
}else if(textType == "place"){
//do something
}else{
return null
}
</code></pre>
| [
{
"answer_id": 74229979,
"author": "Matthew Trent",
"author_id": 13029516,
"author_profile": "https://Stackoverflow.com/users/13029516",
"pm_score": 3,
"selected": true,
"text": "myVar ? \"hello\" : myVar2 ? \"hey\" : \"yo\""
},
{
"answer_id": 74230175,
"author": "manhtuan21"... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74229963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6843543/"
] |
74,230,028 | <p>I'm working on an ASP.NET Core MVC application and I have a view who do a post request as:</p>
<pre><code> $.ajax({
url:'/Advertisers/ActiveAdvertiser?id='+id+'&isActive='+!isActive,
method: 'POST',
success: function(r){
Swal.fire("Inactivated!", "Advertiser inactivated successfully", "success");
},
error: function (request) {
console.log(request.responseText)
Swal.fire("Error!", "Something went wrong, please try again`", "warning");
}
});
</code></pre>
<p>Controller:</p>
<pre><code>[HttpPost]
public async Task<JsonResult> ActiveAdvertiser(int id, bool isActive)
{
var advertiser = await _advertisersService.GetAdvertiserByAdvertiserIdAsync(id);
if (advertiser != null)
{
var model = AssingAdvertiserViewModel(advertiser, id);
model.IsActive = isActive;
var result = await _advertisersService.UpdateAdvertiserAsync(model, GetCurrentUserAsync().Id);
if (result != null)
{
return Json(new { result = "OK" });
}
}
return Json(new { result = "BadRequest" });
}
</code></pre>
<p>Post method services:</p>
<pre><code>public Task<Advertiser?> GetAdvertiserByAdvertiserIdAsync(int advertiserId)
{
return _db.Advertisers
.Include(a => a.Address)
.Include(pc => pc.PrimaryContact)
.Include(ac => ac.AlternateContact)
.FirstOrDefaultAsync(x => x.AdvertiserId == advertiserId);
}
private AdvertiserViewModel AssingAdvertiserViewModel(Advertiser advertiser, int id)
{
var model = new AdvertiserViewModel()
{
//Fill model here
};
return model;
}
public async Task<Advertiser?> UpdateAdvertiserAsync(AdvertiserViewModel model, int updatedById)
{
var advertiser = await GetAdvertiserByAdvertiserIdAsync(model.AdvertiserId);
if (advertiser is null)
return null;
advertiser.Name = model.Name;
// fill model here
await _db.SaveChangesAsync();
return advertiser;
}
</code></pre>
<p>The problem is I do the first request, and it returns Success with any issues, but if I try to do a second one, it throws an exception:</p>
<blockquote>
<p>System.InvalidOperationException: A second operation was started on
this context instance before a previous operation completed. This is
usually caused by different threads concurrently using the same
instance of DbContext.</p>
</blockquote>
<p>If I stop the project and run it again it works one time again and in the second time get the error again</p>
<p>I read about this issue in other questions, and apparently is because you don't use the await services, I check my code and almost everything uses await. Can someone see something that I don't see? Regards</p>
| [
{
"answer_id": 74229979,
"author": "Matthew Trent",
"author_id": 13029516,
"author_profile": "https://Stackoverflow.com/users/13029516",
"pm_score": 3,
"selected": true,
"text": "myVar ? \"hello\" : myVar2 ? \"hey\" : \"yo\""
},
{
"answer_id": 74230175,
"author": "manhtuan21"... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16090212/"
] |
74,230,065 | <p>html</p>
<pre><code><form [formGroup]="searchForm" (ngSubmit)="search()">
<div class="row">
<div class="col">
<input type="date" class="form-control" formControlName="startDate" >
</div>
<div class="col">
<input type="date" class="form-control" formControlName="endDate" >
</div>
<div class="col">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</code></pre>
<p>ts.</p>
<pre><code> searchForm = new FormGroup({
startDate: new FormControl(),
endDate: new FormControl(),
}
);
</code></pre>
<blockquote>
<p>i want this date
ex.
'2022-12-31'</p>
<p>but this output is</p>
<p>console.log(this.searchForm.value.startDate) Output : 2022-12-31</p>
</blockquote>
<pre><code>i try startDate = new Date(this.searchForm.value.startDate)
but Output is 1970-01-01T00:00:00
</code></pre>
| [
{
"answer_id": 74230314,
"author": "Andrew Allen",
"author_id": 4711754,
"author_profile": "https://Stackoverflow.com/users/4711754",
"pm_score": 0,
"selected": false,
"text": "const dateEmpty = new Date(“”);\nconst dateFromString = new Date(“2022-12-31”);\n \nconsole.log(dateEmpty);\n... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19970510/"
] |
74,230,075 | <p>Folder is creating Successfully but the location is something like <strong>storage/emualted/0</strong></p>
<blockquote>
<p>I'm using Enviroment.getExternalStorageDirectory methods</p>
</blockquote>
<p>I want to create publicily available folder which i could save my app's data what should i do?</p>
| [
{
"answer_id": 74230314,
"author": "Andrew Allen",
"author_id": 4711754,
"author_profile": "https://Stackoverflow.com/users/4711754",
"pm_score": 0,
"selected": false,
"text": "const dateEmpty = new Date(“”);\nconst dateFromString = new Date(“2022-12-31”);\n \nconsole.log(dateEmpty);\n... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15420019/"
] |
74,230,084 | <p>I have a class that implements the Equatable protocol, and it uses a UUID field for comparison:</p>
<pre class="lang-swift prettyprint-override"><code>class MemberViewModel {
private static var entities: [MemberViewModel] = []
private var entity: Member
let id = UUID()
init(_ entity: Member) {
self.entity = entity
}
static func members() -> [MemberViewModel] {
entities.removeAll()
try? fetch().forEach { member in
entities.append(MemberViewModel(member))
}
return entities
}
}
extension MemberViewModel: Equatable {
static func == (lhs: MemberViewModel, rhs: MemberViewModel) -> Bool {
return lhs.id == rhs.id
}
}
</code></pre>
<p>I then have a view that creates icons that when tapped should display a stroke to denote it was "selected":</p>
<pre class="lang-swift prettyprint-override"><code>struct MyView: View {
@State var selectedMember: MemberViewModel? = nil
var body: some View {
let members = MemberViewModel.members()
ScrollView(.horizontal, showsIndicators: true) {
HStack(alignment: .top, spacing: 4) {
ForEach (members, id: \.id) { member in
var isSelected: Bool = selectedMember == member
Circle()
.fill(Color(.red))
.frame(width: 48, height: 48)
.overlay() {
if isSelected {
Circle()
.stroke(Color(.black), lineWidth: 2)
}
}
.onTapGesture { selectedMember = member }
}
}
}
}
}
</code></pre>
<p>I have tried setting <code>isSelected</code> multiple ways, including the following from <a href="https://stackoverflow.com/questions/64044232/how-to-convert-a-boolean-expression-to-bindingbool-in-swiftui">another SO question</a>:</p>
<pre class="lang-swift prettyprint-override"><code>let isSelected = Binding<Bool>(get: { self.selectedMember == member }, set: { _ in })
</code></pre>
<p>When debugging using breakpoints, the value of <code>isSelected</code> is always false.</p>
<p>I'm using XCode Version 14.0.1 (14A400), and Swift 5.7.</p>
| [
{
"answer_id": 74230942,
"author": "Sreekuttan",
"author_id": 11662833,
"author_profile": "https://Stackoverflow.com/users/11662833",
"pm_score": 0,
"selected": false,
"text": "struct Member {\n \n let id = UUID()\n \n}\n\nextension Member: Equatable {\n static func == (lhs: ... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/918534/"
] |
74,230,097 | <p>Tried to google how to merge multiple dictionaries, but could not find a solution to merge values under same key in a dictionary. Although the original data is list, the expected results should be dictionary. I am stacked here, and hope someone show me a way to get resolve this.</p>
<p><strong>Original Data:</strong></p>
<pre><code>data = [
{'Supplement': {'label': 'Protein - 25.0', 'value': 1}},
{'Fruit and vegetable': {'label': 'Test - 100.0', 'value': 2}},
{'Fruit and vegetable': {'label': 'Peach - 10.0', 'value': 3}},
{'Protein': {'label': 'Yakiniku - 100.0', 'value': 4}}
]
</code></pre>
<p><strong>Expected Results:</strong></p>
<pre><code>data_merged = {
'Supplement': [ {'label': 'Protein - 25.0', 'value': 1}],
'Fruit and vegetable': [{'label': 'Test - 100.0', 'value': 2}, {'label': 'Peach - 10.0', 'value': 3}],
'Protein': [{'label': 'Yakiniku - 100.0', 'value': 4}]
}
</code></pre>
| [
{
"answer_id": 74230126,
"author": "Leg3ndary",
"author_id": 14909483,
"author_profile": "https://Stackoverflow.com/users/14909483",
"pm_score": 0,
"selected": false,
"text": "new_data = {}\n\nfor i in data:\n if not new_data[i]:\n new_data[i] = [data[i]\n else:\n new... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16566346/"
] |
74,230,144 | <p>I have a dataframe df1 which is like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Category</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>Fruit</td>
</tr>
<tr>
<td>Banana</td>
<td>Fruit</td>
</tr>
<tr>
<td>Cabbage</td>
<td>Vegetable</td>
</tr>
<tr>
<td>Apple</td>
<td>NA</td>
</tr>
<tr>
<td>Orange</td>
<td>Fruit</td>
</tr>
<tr>
<td>Cabbage</td>
<td>NA</td>
</tr>
<tr>
<td>Toy</td>
<td>Misc</td>
</tr>
<tr>
<td>Apple</td>
<td>NA</td>
</tr>
</tbody>
</table>
</div>
<p>Currently, the dataframe only has the category for the first time the Name appeared.</p>
<p>However, I would like to fill the categories within the dataframe to make it like this based on the Name:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Category</th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>Fruit</td>
</tr>
<tr>
<td>Banana</td>
<td>Fruit</td>
</tr>
<tr>
<td>Cabbage</td>
<td>Vegetable</td>
</tr>
<tr>
<td>Apple</td>
<td>Fruit</td>
</tr>
<tr>
<td>Orange</td>
<td>Fruit</td>
</tr>
<tr>
<td>Cabbage</td>
<td>Vegetable</td>
</tr>
<tr>
<td>Toy</td>
<td>Misc</td>
</tr>
<tr>
<td>Apple</td>
<td>Fruit</td>
</tr>
</tbody>
</table>
</div>
<p>Would appreciate the help! :)</p>
| [
{
"answer_id": 74230126,
"author": "Leg3ndary",
"author_id": 14909483,
"author_profile": "https://Stackoverflow.com/users/14909483",
"pm_score": 0,
"selected": false,
"text": "new_data = {}\n\nfor i in data:\n if not new_data[i]:\n new_data[i] = [data[i]\n else:\n new... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18066607/"
] |
74,230,179 | <p>I am trying to add two classes to a div tag. I am using variables with randomized values to calculate the position of the div tags. I don't know how to create a class with these randomized numbers, if it is even possible, could someone help me out?</p>
<p>I don't really know where to start but here's my code</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let xValues = []
let yValues = []
let coordinates = []
for (let i = 0; i < 10; i++) {
xValues.push(i)
yValues.push(i)
}
let x1 = xValues[Math.floor(Math.random()*xValues.length)]
let x2 = xValues[Math.floor(Math.random()*xValues.length)]
let x3 = xValues[Math.floor(Math.random()*xValues.length)]
x1 = x1 * 50
x2 = x2 * 50
x3 = x3 * 50
let y1 = yValues[Math.floor(Math.random()*yValues.length)]
let y2 = yValues[Math.floor(Math.random()*yValues.length)]
let y3 = yValues[Math.floor(Math.random()*yValues.length)]
y1 = y1 * 50
y2 = y2 * 50
y3 = y3 * 50
console.log("("+x1+", "+y1+") "+"("+x2+", "+y2+") "+"("+x3+", "+y3+")")</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
height: 100%;
width: 100%;
background-color: grey;
}
.bg{
height: 500px;
width: 500px;
background-color: white;
position: relative
}
.obst {
background-color: red;
height: 50px;
width: 50px;
display: inline-block;
}
#obst1 {
position: absolute;
top: 300px;
left: 450px;
}
#obst2 {
position: absolute;
top: 200px;
left: 200px;
}
#obst3 {
position: absolute;
top: 100px;
left: 300px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<div class="bg">
<div class="obst" id="obst1"></div>
<div class="obst" id="obst2"></div>
<div class="obst" id="obst3"></div>
</div>
<button onclick="play()"
<script src="script.js"></script>
</body></code></pre>
</div>
</div>
</p>
<p>I'm very new to coding as well as stack overflow so if I mess something up I am sorry.</p>
| [
{
"answer_id": 74230495,
"author": "Cat",
"author_id": 8223070,
"author_profile": "https://Stackoverflow.com/users/8223070",
"pm_score": 0,
"selected": false,
"text": "const\n obsts = document.querySelectorAll('.obst'),\n limit = obsts.length,\n xVals = [],\n yVals = [];\n\n// Popula... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20354410/"
] |
74,230,193 | <p>I have the list containing strings and numbers. I am trying to convert into dictionary based on the type if it is string otherwise it would become a key.</p>
<p>Input:</p>
<pre><code>lst = ['A', 1, 3, 4, 'B', 5, 'C', 2, 'D', 4]
</code></pre>
<p>Output:</p>
<pre><code>[{'A': [1, 3, 4]}, {'B': [5]}, {'C': [2]}, {'D': 4}]
</code></pre>
<p>This is my working code so far, I it is definitely not as optimized as it could be:</p>
<pre><code>main_array = []
small_array = []
se = {}
key = None
for i in range(len(lst)-1):
print(i)
if i == len(lst)-2:
if type(lst[i]) == str and type(lst[i+1]) == str:
main_array.append(lst[i])
main_array.append(lst[i+1])
elif type(lst[i]) == str and type(lst[i+1]) != str:
main_array.append({lst[i]: lst[i+1]})
elif type(lst[i]) != str and type(lst[i+1]) == str:
small_array.append(lst[i])
se.update({key: small_array})
main_array.append(se)
se = {}
small_array = []
main_array.append(lst[i+1])
elif lst[i] != type(str) and lst[i + 1] != type(str):
small_array.append(lst[i])
small_array.append(lst[i+1])
se.update({key: small_array})
main_array.append(se)
se = {}
small_array = []
else:
if type(lst[i]) == str and i != len(lst)-1:
if type(lst[i+1]) == str:
main_array.append(lst[i])
elif type(lst[i+1]) != str:
key = lst[i]
elif type(lst[i]) != str and i != len(lst)-1:
if type(lst[i+1]) == str:
small_array.append(lst[i])
se.update({key: small_array})
main_array.append(se)
se = {}
small_array = []
elif type(lst[i+1]) != str:
small_array.append(lst[i])
print(main_array)
</code></pre>
<p>Is there any way to optimize this code as I am intending to avoid nested loops?</p>
| [
{
"answer_id": 74230235,
"author": "Michael M.",
"author_id": 13376511,
"author_profile": "https://Stackoverflow.com/users/13376511",
"pm_score": 2,
"selected": false,
"text": "import collections\n\nlst = ['A', 1, 3, 4, 'B', 5, 'C', 2, 'D', 4]\n\ndct = collections.defaultdict(lambda: [])... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15749060/"
] |
74,230,245 | <p>i want filter endpoint urls starts with "/api/**" but customJwtAuthenticationFilter filter all url other.</p>
<pre><code>@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/users","/api/users").authenticated()
.anyRequest().permitAll()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().exceptionHandling().accessDeniedPage("/403").authenticationEntryPoint(jwtAuthenticationEntryPoint).and().
formLogin()
.loginPage("/login")
.defaultSuccessUrl("/users")
.failureUrl("/login?error=true")
.permitAll()
.and()
.logout().logoutSuccessUrl("/").permitAll()
.and().addFilterBefore(customJwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
</code></pre>
<p>Kindly help?</p>
<p>Thanks in Advance</p>
| [
{
"answer_id": 74230235,
"author": "Michael M.",
"author_id": 13376511,
"author_profile": "https://Stackoverflow.com/users/13376511",
"pm_score": 2,
"selected": false,
"text": "import collections\n\nlst = ['A', 1, 3, 4, 'B', 5, 'C', 2, 'D', 4]\n\ndct = collections.defaultdict(lambda: [])... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20354489/"
] |
74,230,246 | <p>Product</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>prod_id</th>
<th>prod_name</th>
</tr>
</thead>
<tbody>
<tr>
<td>10</td>
<td>Orange</td>
</tr>
<tr>
<td>11</td>
<td>Apple</td>
</tr>
<tr>
<td>12</td>
<td>Carrot</td>
</tr>
<tr>
<td>13</td>
<td>Lettuce</td>
</tr>
</tbody>
</table>
</div>
<p>Category</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>cat_id</th>
<th>cat_name</th>
</tr>
</thead>
<tbody>
<tr>
<td>20</td>
<td>Fruit</td>
</tr>
<tr>
<td>21</td>
<td>Vegetable</td>
</tr>
</tbody>
</table>
</div>
<p>Item</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>item_id</th>
<th>property_type</th>
<th>property_value</th>
</tr>
</thead>
<tbody>
<tr>
<td>30</td>
<td>fk_prod_id</td>
<td>10</td>
</tr>
<tr>
<td>30</td>
<td>fk_cat_id</td>
<td>20</td>
</tr>
<tr>
<td>31</td>
<td>fk_prod_id</td>
<td>11</td>
</tr>
<tr>
<td>31</td>
<td>fk_cat_id</td>
<td>20</td>
</tr>
<tr>
<td>32</td>
<td>fk_prod_id</td>
<td>12</td>
</tr>
<tr>
<td>32</td>
<td>fk_cat_id</td>
<td>21</td>
</tr>
</tbody>
</table>
</div>
<p>I am trying to pivot Item then left join with Product and Category to get:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>item_id</th>
<th>fk_prod_id</th>
<th>fk_cat_id</th>
<th>prod_name</th>
<th>cat_name</th>
</tr>
</thead>
<tbody>
<tr>
<td>30</td>
<td>10</td>
<td>20</td>
<td>Orange</td>
<td>Fruit</td>
</tr>
<tr>
<td>31</td>
<td>11</td>
<td>20</td>
<td>Apple</td>
<td>Fruit</td>
</tr>
<tr>
<td>32</td>
<td>12</td>
<td>21</td>
<td>Carrot</td>
<td>Vegetable</td>
</tr>
</tbody>
</table>
</div>
<p>Unfortunately:</p>
<pre><code>SELECT
item_id,
MAX(CASE WHEN property_type = 'fk_prod_id' THEN property_value END) AS fk_prod_id,
MAX(CASE WHEN property_type = 'fk_cat_id' THEN property_value END) AS fk_cat_id
FROM item AS i
LEFT JOIN product AS p ON p.prod_id = fk_prod_id
LEFT JOIN category AS c ON c.cat_id = fk_cat_id
GROUP BY item_id;
</code></pre>
<p><code>#Error Code: 1054. Unknown column 'fk_prod_id' in 'on clause'</code></p>
<p>How do I left join other table(s) after a pivot table for the above scenario?</p>
| [
{
"answer_id": 74230482,
"author": "John",
"author_id": 8330591,
"author_profile": "https://Stackoverflow.com/users/8330591",
"pm_score": 0,
"selected": false,
"text": "SELECT\n item_id,\n fk_prod_id,\n fk_cat_id,\n prod_name,\n cat_name\nFROM (\n SELECT\n item_i... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8330591/"
] |
74,230,284 | <blockquote>
<p>how to process string data like this
'Stephen Hawking Einstein'
be like this
'SH'.</p>
</blockquote>
<pre><code>Text('Stephen Hawking Einstein')
</code></pre>
| [
{
"answer_id": 74230482,
"author": "John",
"author_id": 8330591,
"author_profile": "https://Stackoverflow.com/users/8330591",
"pm_score": 0,
"selected": false,
"text": "SELECT\n item_id,\n fk_prod_id,\n fk_cat_id,\n prod_name,\n cat_name\nFROM (\n SELECT\n item_i... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19646043/"
] |
74,230,305 | <p>I am writing a code that asks for the users input for the number of rows and columns. When given the integer values, the program will print out the number of the row and the letter that will increment will be next to it, just like seat numbers in a theatre or stadium. What I am trying to do is to use a for loop and a while loop to try to split up the rows and numbers.</p>
<p>Here is an example (row is 2 and column is 3):</p>
<pre><code>1A 1B 1C
2A 2B 2C
</code></pre>
<p>However that did not work, what I have tried is to use a double for loop for the values but that didnt work. So I tried using a while loop to try and get the second row but didnt work. I can only get the first row to print out</p>
<p>Here is the code im working on:</p>
<pre><code>num_rows = int(input("Enter number of rows: "))
num_cols = int(input("Enter number of columns: "))
rangerows = num_rows + 1
rangecols = num_cols
colsnow = 0
rowsnow = 1
for i in range(1, num_rows):
while colsnow < rangecols:
print(f'{i}{chr(colsnow + 65)}', end=' ')
colsnow += 1
print()
</code></pre>
| [
{
"answer_id": 74230482,
"author": "John",
"author_id": 8330591,
"author_profile": "https://Stackoverflow.com/users/8330591",
"pm_score": 0,
"selected": false,
"text": "SELECT\n item_id,\n fk_prod_id,\n fk_cat_id,\n prod_name,\n cat_name\nFROM (\n SELECT\n item_i... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20354580/"
] |
74,230,306 | <p>I can match <code>#include<stdio.h></code> using the following regular expression in c++.</p>
<pre><code>regex ("( )*#( )*include( )*<(stdio.h)( )*>( )*")
</code></pre>
<p>But if I design a regular expression like <code>regex("( )*#( )*include( )*<(.)*.h( )*>( )*")</code>
in cpp then I find any type of header file.
But if I want to get a sub string from a header file
like,</p>
<pre><code>Suppose I have some header file like,
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<time.h>
</code></pre>
<pre><code>And from those header file, I just want to get the sub string like,
string.h
math.h
stdlib.h
time.h
</code></pre>
<p>In simply,
I want to get the string inside this symbol <code>< ></code></p>
<p>Now my Question is how to design a regular expression and write a c++ code so that I can get my expected sub string from any header file?</p>
<p>or</p>
<p>Write a c++ code to print the string inside this symbol <code>< ></code><br>using this regular expression <code>regex("( )*#( )*include( )*<(.)*.h( )*>( )*")</code> ?</p>
<p>I just design the regular expression <code>regex("( )*#( )*include( )*<(.)*.h( )*>( )*")</code>.<br>
I can't find any idea to print the string inside this symbol <code>< ></code></p>
| [
{
"answer_id": 74230482,
"author": "John",
"author_id": 8330591,
"author_profile": "https://Stackoverflow.com/users/8330591",
"pm_score": 0,
"selected": false,
"text": "SELECT\n item_id,\n fk_prod_id,\n fk_cat_id,\n prod_name,\n cat_name\nFROM (\n SELECT\n item_i... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20255740/"
] |
74,230,355 | <p>I am a beginner level python student. This is a code challenge in a udemy program related to Multiple if statements</p>
<pre><code>add_pepperoni ="Y"
extra_cheese="Y"
pizza_price =15
if add_pepperoni =="Y":
pizza_price +=2
if extra_cheese =="Y":
pizza_price +=1
else:
print(f"final price is{pizza_price}")
else:
print(pizza_price)
</code></pre>
<p>this code doesn't work.I cant figure out why. here the normal pizza price is $15. but if pepperoni is added final price should become $17.if extra cheese is added final price should be 18.</p>
| [
{
"answer_id": 74230417,
"author": "mxnthng",
"author_id": 19476231,
"author_profile": "https://Stackoverflow.com/users/19476231",
"pm_score": 0,
"selected": false,
"text": "if"
},
{
"answer_id": 74238743,
"author": "mdlatt",
"author_id": 15178790,
"author_profile": "... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20354570/"
] |
74,230,395 | <p>I need to combine ruby code with javascript, to show something which depends on the server's response.</p>
<p><strong>app/views/posts/index.html.erb</strong></p>
<pre><code><h1 class="text-center m-4 text-success">Posts</h1>
<div id="posts" data-controller="like" data-like-url-value="<%= like_posts_path %>">
<div class="row">
<% @posts.each do |post| %>
<%= render post %>
<% end %>
</div>
</div>
<script>
if(some condition){
console.log("All Posts has been loaded successfully.")
}
</script>
</code></pre>
<p><strong>app/controllers/posts_controller.rb</strong></p>
<pre><code>def index
@posts = Post.all.order(id: :desc)
if @posts.length > 0
session[:post] = true
end
end
</code></pre>
<p>I have to use the index action session variable in the index template, I don't have any idea about how to combine ruby code with javascript.</p>
| [
{
"answer_id": 74231012,
"author": "spickermann",
"author_id": 2483313,
"author_profile": "https://Stackoverflow.com/users/2483313",
"pm_score": 2,
"selected": false,
"text": "<script>"
},
{
"answer_id": 74286402,
"author": "Laxmi Pasi",
"author_id": 14817167,
"author... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18445017/"
] |
74,230,459 | <p>Hey guys so I'm writing a code for text message abbreviations and these are the following criteria:</p>
<ul>
<li>Spaces are maintained, and each word is encoded individually. A word is a consecutive string of alphabetic characters.</li>
<li>If the word is composed only of vowels, it is written exactly as in the original message.</li>
<li>If the word has at least one consonant, write only the consonants that do not have another consonant immediately before them. Do not write any vowels.</li>
<li>The letters considered vowels in these rules are 'a', 'e', 'i', 'o' and 'u'. All other letters are considered consonants.</li>
</ul>
<p>I have written a code and checked it but it is failing for the condition where if the word is composed only of vowels, it is written exactly as in the original message. My code currently is taking out all of the vowels. Like for this example, "aeiou bcdfghjklmnpqrstvwxyz" the code should return "aeiou b"
I tried using another helper function to determine when a word is all vowels but it isn't working. Any suggestions on how to implement something that could make this work? Thanks!</p>
<pre><code>def Vowel(x):
vowels = "a" "e" "i" "o" "u"
value = 0
for ch in x:
if x == vowels:
value = value + 1
return value
def isVowel(phrase):
vowel = "a" "e" "i" "o" "u"
value = 0
for ch in phrase:
if ch in vowel:
value = value + 1
return value
def noVowel(ch):
vowel = "a" "e" "i" "o" "u"
value = 0
for i in ch:
if ch not in vowel:
value = value + 1
return value
def transform(word):
before = 'a'
answer = ""
for ch in word:
if Vowel(ch):
answer += ch
if noVowel(ch) and isVowel(before):
answer += ch
before = ch
return answer
def getMessage(original):
trans = ""
for word in original.split():
trans = trans + " " + transform(word)
trans = trans.strip()
return trans
if __name__ == '__main__':
print(getMessage("aeiou b"))
</code></pre>
| [
{
"answer_id": 74231012,
"author": "spickermann",
"author_id": 2483313,
"author_profile": "https://Stackoverflow.com/users/2483313",
"pm_score": 2,
"selected": false,
"text": "<script>"
},
{
"answer_id": 74286402,
"author": "Laxmi Pasi",
"author_id": 14817167,
"author... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20274281/"
] |
74,230,463 | <p>I have a Blazor Server that has a local controller for authentication on the same project. I want to sign-in users through this controller and then redirect to homepage or previous page.</p>
<p>However, the <code>Redirect("~/")</code> function on the local controller does not seem to work. I tried with different urls including external urls but no success. I tried to solve it many times but was not able. Any help will be appreciated.</p>
<p>Login submit:</p>
<pre class="lang-cs prettyprint-override"><code>result = await httpClient.PostAsJsonAsync("Account/Login", loginParameters);
</code></pre>
<p>Controller:</p>
<pre class="lang-cs prettyprint-override"><code>public class AccountController : Controller
{
[HttpPost]
public async Task<IActionResult> Login([FromBody]LoginParameters loginParameters)
{
string userName = loginParameters.UserName;
string password = loginParameters.Password;
string redirectUrl = loginParameters.RedirectUrl;
if (env.EnvironmentName == "Development" && userName == "admin" && password == "admin")
{
var claims = new List<Claim>
{
new(ClaimTypes.Name, "admin"),
new(ClaimTypes.Email, "admin")
};
roleManager.Roles.ToList().ForEach(r => claims.Add(new Claim(ClaimTypes.Role, r.Name)));
await signInManager.SignInWithClaimsAsync(new ApplicationUser { UserName = userName, Email = userName }, false, claims);
//return Redirect("https://localhost:5001/");
//return Redirect("https://www.google.com/");
return Redirect($"~/{redirectUrl}");
}
// More stuff
}
}
</code></pre>
<p><code>Program.cs</code>:</p>
<pre class="lang-cs prettyprint-override"><code>builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped(serviceProvider =>
{
var uriHelper = serviceProvider.GetRequiredService<NavigationManager>();
return new HttpClient { BaseAddress = new Uri(uriHelper.BaseUri) };
});
builder.Services.AddHttpClient();
//...
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
app.Use((ctx, next) =>
{
ctx.Request.Scheme = "https";
return next();
});
}
else
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default","{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
app.Run();
</code></pre>
<p>Problem:</p>
<p><a href="https://i.stack.imgur.com/OPgu4.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OPgu4.gif" alt="Animation cannot redirect from controller" /></a></p>
| [
{
"answer_id": 74231012,
"author": "spickermann",
"author_id": 2483313,
"author_profile": "https://Stackoverflow.com/users/2483313",
"pm_score": 2,
"selected": false,
"text": "<script>"
},
{
"answer_id": 74286402,
"author": "Laxmi Pasi",
"author_id": 14817167,
"author... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8316900/"
] |
74,230,512 | <p>I am trying to split up my MUI Navbar into 3 sections. The left hand side is a Home icon, next to it is a text string, then finally a set of icons to the right. I have it working but the icons on the right are bunched up and I haven't been able to add space between them. The Navbar code is mostly taken from MUI website with some modifications. Your suggestions are appreciated.</p>
<pre><code> <Box sx={{ flexGrow: 1 }}> <-- The box spans the full width
<AppBar position="sticky">
<Toolbar>
<Tooltip title="Home" followCursor={true}> <-- Home Icon
<IconButton
size="large"
edge="end"
aria-label="home"
color="inherit"
>
<Logo height={30} />
</IconButton>
</Tooltip>
<Typography
variant="h5"
noWrap
component="div"
sx={{ display: { xs: 'none', sm: 'block', flex: 1 } }} <-- Takes up available space
>
&nbsp;MyApplication
</Typography>
<Box sx={{ display: { xs: 'none', md: 'flex' } }}> <-- what prop to use here?
<Tooltip title="Delete" followCursor={true}>
<IconButton
size="large"
edge="end"
aria-label="Delete"
color="inherit"
>
<DeleteIcon />
</IconButton>
</Tooltip>
<Tooltip title="Share" followCursor={true}>
<IconButton
size="large"
edge="end"
aria-label="Share"
color="inherit"
>
<ShareIcon />
</IconButton>
</Tooltip>
</Box>
</Toolbar>
</AppBar>
</Box>
</code></pre>
| [
{
"answer_id": 74231012,
"author": "spickermann",
"author_id": 2483313,
"author_profile": "https://Stackoverflow.com/users/2483313",
"pm_score": 2,
"selected": false,
"text": "<script>"
},
{
"answer_id": 74286402,
"author": "Laxmi Pasi",
"author_id": 14817167,
"author... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12990786/"
] |
74,230,516 | <p>I am solving this Leetcode problem: <a href="https://leetcode.com/problems/find-pivot-index/" rel="nofollow noreferrer">https://leetcode.com/problems/find-pivot-index/</a>
And I came up with this solution:</p>
<pre><code>import java.util.ArrayList;
import java.util.List;
public class Solution {
public int pivotIndex(int[] nums) {
Integer result = null;
List<Integer> right = new ArrayList<>(nums.length);
List<Integer> left = new ArrayList<>(nums.length);
int leftSum, rightSum;
for (int i = 0; i < nums.length; i++) {
leftSum = 0;
rightSum = 0;
for (int j = 0; j < i; j++) {
left.add(nums[j]);
}
for (int num : left) {
leftSum += num;
}
for (int j = i + 1; j < nums.length; j++) {
if (j > nums.length) {
right.add(0);
} else {
right.add(nums[j]);
}
}
for (int num : right) {
rightSum += num;
}
if (leftSum == rightSum) {
result = i;
return result;
} else {
result = -1;
left.clear();
right.clear();
}
}
return result;
}
}
</code></pre>
<p>But I'm getting Time Limit Exceeded...
Can someone help me with some advise on how to make this run faster?<br />
Before, I was instantiating a new ArrayList object at the start of the first for loop, so I changed their scope so that only one instantiation happens and just cleared the ArrayLists at the end of the for loop.<br />
Same for leftSum and rightSum, I changed their scope for the whole method and just change their value to 0 at the start of the first for loop. I figured both these changed would make it faster but apparently didn't?<br />
My code is slow somewhere else I can't detect it right now.</p>
<p>Any tips / good practices would be highly appreciated as someone who's trying to prepare for the first job interviews in this field :)</p>
| [
{
"answer_id": 74231012,
"author": "spickermann",
"author_id": 2483313,
"author_profile": "https://Stackoverflow.com/users/2483313",
"pm_score": 2,
"selected": false,
"text": "<script>"
},
{
"answer_id": 74286402,
"author": "Laxmi Pasi",
"author_id": 14817167,
"author... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18815165/"
] |
74,230,550 | <p>I have a MySQL query that searches through a zipcode database for city names. The query takes about 4 seconds, to search through 620,000 zipcodes. I would like ideas how I can make this faster.</p>
<p>First, the tables:</p>
<p>I have a table of zipcodes. Each zipcode entry has 6 ints, that refer to words. I use joins from the words, to make zipcodes: "92121, San Diego, California, United States, CA, US"</p>
<p>If I know the exact zipcode, the query is quite fast:</p>
<p><a href="https://blackvelvetcollection.com/question.txt" rel="nofollow noreferrer">Full Question</a></p>
<p>I made this link to show the table and SELECT statement since StackOverflow appears to have some bugs when posting code.</p>
<p>However, if I do NOT know the zipcode and search by name, the query is really slow, as I must accommodate searching for all permutations of all words: "San Diego, CA", "San Diego, California", "San Diego, CA", "California San Diego", "92121 San Diego CA", etc</p>
<p>In order to accommodate all the permutations, I am doing a LIKE on every term, against every column. This is really slow (4 seconds) and I feel this statement can be made much more efficient.</p>
<p>The database contains all zipcode patterns, for all countries. Maybe I can search for "US", "CA", "UK", or "AU" beforehand, and limit the query to cities within the user"s home country?</p>
<p>Thoughts?</p>
| [
{
"answer_id": 74231012,
"author": "spickermann",
"author_id": 2483313,
"author_profile": "https://Stackoverflow.com/users/2483313",
"pm_score": 2,
"selected": false,
"text": "<script>"
},
{
"answer_id": 74286402,
"author": "Laxmi Pasi",
"author_id": 14817167,
"author... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7178319/"
] |
74,230,552 | <p>When browser back button clicked the app redirects to the first url of the app. For example, current route is <code>localhost:3000</code> then I'm going to home <code>localhost:3000/home</code> and then to <code>localhost:3000/settings</code> and when I click on browser back button it redirects me to <code>localhost:3000</code> instead of <code>localhost:3000/home</code>.</p>
<p>I'm using angular 14, but when I started building the app angular was of version 13.
This is <code>app.module.ts</code>:</p>
<pre><code>@NgModule({
declarations: [AppComponent],
imports: [
...
BrowserModule,
AppRoutingModule,
],
providers: [
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
...
],
bootstrap: [AppComponent]
})
</code></pre>
<p>This is <code>app-routing.module.ts</code>:</p>
<pre><code>@NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules, onSameUrlNavigation: "reload" }),
BrowserAnimationsModule
],
exports: [RouterModule]
})
</code></pre>
<p>The routes all look like this:</p>
<pre><code>
{
path: "user/profile",
loadChildren: () => import("./user/profile/profile.module").then(m => m.ProfilePageModule),
canActivate: [LoggedGuard],
},
</code></pre>
<p>This is the navigation function that used everywhere for navigation:</p>
<pre><code>async go(path: string[], options: NavigationExtras = {}, showLoader: boolean = true) {
if(showLoader === true) {
await this.loader.start();
}
this.router.navigate(path, { replaceUrl: true, ...options});
}
</code></pre>
| [
{
"answer_id": 74231012,
"author": "spickermann",
"author_id": 2483313,
"author_profile": "https://Stackoverflow.com/users/2483313",
"pm_score": 2,
"selected": false,
"text": "<script>"
},
{
"answer_id": 74286402,
"author": "Laxmi Pasi",
"author_id": 14817167,
"author... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14494977/"
] |
74,230,557 | <p>I am pretty new to html/css/sass and I'm currently developing a website for myself. When aligning items I notice that I sometimes want a padding of 1em to the right for one item, and then a padding of 2em to the top for another item etc. I do the definitions in a .scss file like this currently:</p>
<p>_master.scss:</p>
<pre><code>:root {
--pad-neg-left-1: 0 0 0 -1em;
--pad-top-2: 2em 0 0 0;
}
.pad-neg-left-1{
padding: var(--pad-neg-left-1);
}
.pad-top-2{
padding: var(--pad-top-2);
}
</code></pre>
<p>index.html:</p>
<pre><code><div class=".pad-top-2"> Hi </div>
</code></pre>
<p>This gets big and complex really fast if I want to add classes to my html objects to fit all purposes. Instead I would like a class that can take parameters and use it maybe like this:</p>
<p>_master.scss:</p>
<pre><code>function pad(top, right, bottom, left){
padding: top right bottom left;
}
</code></pre>
<p>index.html:</p>
<pre><code><div class=".pad(2, 0, 0, 0)"> Hi </div>
</code></pre>
<p>Is this possible?</p>
<p>I could write my div as this instead: <code><div style="padding: 2 0 0 0;"> Hi </div></code> but for some reason I heard from videos that it is bad to define styling straight in html and instead use classes. Is this wrong, or can I use some other approach?</p>
| [
{
"answer_id": 74231312,
"author": "Shiva Karthik",
"author_id": 7957489,
"author_profile": "https://Stackoverflow.com/users/7957489",
"pm_score": 0,
"selected": false,
"text": " @mixin padding($top:0, $right: 0,$bottom:0, $left:0) {\n padding: $top $right $bottom $left;\n}\n\n.avatar {... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12053079/"
] |
74,230,561 | <p>My firebase authentication process is too slow?It takes about five minutes to completely create an user account and redirect! How to speed up?</p>
<p>Sharing the authentication code below(Same of that from firebase documentation)</p>
<pre><code>auth.createUserWithEmailAndPassword(email, pswd)
.addOnCompleteListener(this@RegistrationActivity) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "createUserWithEmail:success")
val user = auth.currentUser
updateUI(user)
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.exception)
Toast.makeText(
baseContext, "Authentication failed.",
Toast.LENGTH_SHORT
).show()
updateUI(null)
}
}
}
</code></pre>
<p>Being new to this I wasn't aware what to do?tried some of youtube methods but didn't help</p>
| [
{
"answer_id": 74231312,
"author": "Shiva Karthik",
"author_id": 7957489,
"author_profile": "https://Stackoverflow.com/users/7957489",
"pm_score": 0,
"selected": false,
"text": " @mixin padding($top:0, $right: 0,$bottom:0, $left:0) {\n padding: $top $right $bottom $left;\n}\n\n.avatar {... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20117118/"
] |
74,230,575 | <p>I am running my flask application with nohup command on my linux server. I am trying to save PID number as a variable or save just the PID number on output .</p>
<p>For an example , if i run my flask_application with nohup in below command</p>
<pre><code>nohup python /home/app/run_flask.py > /home/temp/run_flask.out 2> /home/temp/run_flask.err &
</code></pre>
<p>this will successfully run in the backgroup and i check if my pid running is by</p>
<pre><code> ps -ef | grep /home/app/run_flask.py
</code></pre>
<p>my server will return this</p>
<pre><code>farid 108708 1 0 23:50 pts/0 00:00:00 python /home/app/run_flask.py
farid 112265 83174 0 23:52 pts/0 00:00:00 grep --color=auto /home/app/run_flask.py
</code></pre>
<p>PID which i am trying to capture either as a variable or save it to file is 112265 so that i can include this in my shell script to kill process on certain condition . How can i achieve this ?</p>
<p>I have tried using this command and i was able to print out 112265 , however i am not sure i cant store this as variable by adding 'test1=ps ef....' and if this is the right approach . command used</p>
<pre><code>ps -ef | grep /home/app/run_flask.py | tr -s ' ' | cut -d ' ' -f2 | tail -1
</code></pre>
| [
{
"answer_id": 74231312,
"author": "Shiva Karthik",
"author_id": 7957489,
"author_profile": "https://Stackoverflow.com/users/7957489",
"pm_score": 0,
"selected": false,
"text": " @mixin padding($top:0, $right: 0,$bottom:0, $left:0) {\n padding: $top $right $bottom $left;\n}\n\n.avatar {... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14297619/"
] |
74,230,592 | <p>I have an app where im trying to set different icons for different values of text.</p>
<pre><code>import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import '../utils/colors.dart';
class WidgetCard extends StatefulWidget {
const WidgetCard({Key? key, required this.week, required this.status})
: super(key: key);
final String week;
final String status;
@override
State<WidgetCard> createState() => _WidgetCardState();
}
class _WidgetCardState extends State<WidgetCard> {
@override
void initState() {
// TODO: implement initState
super.initState();
}
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
Get.toNamed('/weekform', arguments: widget.week);
},
child: Container(
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
child: Card(
color: AppColors.yellow_accent,
elevation: 5.0,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
child: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height * (1 / 6),
padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0),
decoration: BoxDecoration(
color: AppColors.yellow_accent,
borderRadius: BorderRadius.circular(20)),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Align(
alignment: AlignmentDirectional.centerStart,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Align(
alignment: AlignmentDirectional.center,
child: Container(
height: 55.0,
child: Image.asset("assets/icons/checked.png")),
),
SizedBox(
width: 17,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Container(
width: 100,
child: Text(
widget.week,
style: GoogleFonts.poppins(
color: Colors.black,
fontSize: 18.0,
fontWeight: FontWeight.bold),
maxLines: 4,
overflow: TextOverflow.ellipsis,
),
),
Row(
children: [
Align(
alignment: AlignmentDirectional.bottomEnd,
child: Text("Status : ",
style: GoogleFonts.poppins(
color: Colors.black,
fontSize: 15.0,
fontWeight: FontWeight.normal)),
),
Align(
alignment: AlignmentDirectional.bottomEnd,
child: Text(widget.status,
style: GoogleFonts.poppins(
color: Colors.green,
fontSize: 15.0,
fontWeight: FontWeight.normal)),
),
],
),
],
),
SizedBox(
width: 10,
),
],
),
)
],
),
),
),
),
);
}
}
</code></pre>
<p>The value is stored in the string status. How can i use it in a conditional to change the icon. There are three values for status. It can either be "Approved" , "Pending" or "Rejected"</p>
<p>I tried giving a conditional <code>if(status) == "Approved"</code> ? but it gives the error</p>
<pre><code>The element type 'bool' can't be assigned to the list type 'Widget'.
</code></pre>
| [
{
"answer_id": 74230657,
"author": "Amit Singh",
"author_id": 13051247,
"author_profile": "https://Stackoverflow.com/users/13051247",
"pm_score": 1,
"selected": false,
"text": " Row(\n children:[\n \n status==\"approved\"?Icon(Icons.approve)\n \n :status... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19922441/"
] |
74,230,618 | <p>I am passing the method as follows But it is very complicated. I want to call methods directly without passing methods. Is there any way to do that?</p>
<pre><code>class Parent extends StatelessWidget {
const Parent({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Child(onPressed: onPressed);
}
onPressed() {
print("onPressed");
}
}
class Child extends StatelessWidget {
const Child({
Key? key,
required this.onPressed,
}) : super(key: key);
final Function() onPressed;
@override
Widget build(BuildContext context) {
return Grandchild(onPressed: onPressed);
}
}
class Grandchild extends StatelessWidget {
const Grandchild({
Key? key,
required this.onPressed,
}) : super(key: key);
final Function() onPressed;
@override
Widget build(BuildContext context) {
return FloatingActionButton(
backgroundColor: Colors.black,
mini: true,
child: const Icon(
Icons.cached,
color: Colors.white,
),
tooltip: 'Change Camera',
onPressed: onPressed,
);
}
}
</code></pre>
<p>I'm envisioning something like Riverpod's StateNotifierProvider, etc. where you pass methods like you pass properties, but if you can make it easier, that's fine too.</p>
| [
{
"answer_id": 74230657,
"author": "Amit Singh",
"author_id": 13051247,
"author_profile": "https://Stackoverflow.com/users/13051247",
"pm_score": 1,
"selected": false,
"text": " Row(\n children:[\n \n status==\"approved\"?Icon(Icons.approve)\n \n :status... | 2022/10/28 | [
"https://Stackoverflow.com/questions/74230618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5528270/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.