qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,277,322 | <p>Is there a way to shorten the code inside the if statement in JavaScript I'm thinking for loop but I don't know how and if it's even possible. I already put the what I think the relevant code</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var operators = document.querySelectorAll(".operators button");
var string = screenInput.innerHTML
var lastCharacter = string[string.length - 1]
console.log(lastCharacter)
if (lastCharacter === "+") {
document.getElementById("subtract-operator").disabled = true
document.getElementById("multiply-operator").disabled = true
document.getElementById("divide-operator").disabled = true
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="operators">
<button id="add-operator">+</button>
<button id="subtract-operator">-</button>
<button id="multiply-operator">*</button>
<button id="divide-operator">/</button>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74277436,
"author": "EssXTee",
"author_id": 2339619,
"author_profile": "https://Stackoverflow.com/users/2339619",
"pm_score": 2,
"selected": false,
"text": "+"
},
{
"answer_id": 74277441,
"author": "Laaouatni Anas",
"author_id": 17716837,
"author_profile": "https://Stackoverflow.com/users/17716837",
"pm_score": 1,
"selected": false,
"text": ":not()"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18314283/"
] |
74,277,324 | <p>I have nailed the issue down to the middleware as it was breaking everything. We host the site on Plesk so we understand that there maybe something that the server is doing differently.</p>
<p>However when I go to <a href="https://exampl.com/appstore" rel="nofollow noreferrer">https://exampl.com/appstore</a>
I should get a nice looking page but now I get
<a href="https://i.stack.imgur.com/HBWDC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HBWDC.png" alt="Error Message" /></a></p>
<p>I have tried everything to fix it, so I thought I would post here.</p>
<pre><code>// middleware.ts
import { NextRequest, NextResponse, userAgent } from 'next/server'
export function middleware(request: NextRequest) {
const { os } = userAgent(request)
if(request.nextUrl.pathname === "/appstore")
{
if(os.name === "iOS"){
return NextResponse.redirect('https://apps.apple.com/au/app/drn1/id1491656217')
}
if(os.name === "Android"){
return NextResponse.redirect('https://play.google.com/store/apps/details?id=com.drn1.drn_player')
}
}
};
export const config = {
matcher: [
'/appstore'
],
}
</code></pre>
<p>I can confirm however that on Vercel servers it works fine - with no issues (<a href="https://drn-1-next-js.vercel.app/appstore" rel="nofollow noreferrer">https://drn-1-next-js.vercel.app/appstore</a>).</p>
<p>This is what makes me think it's a plesk issue or the way NextJS dev teams have coded middleware.</p>
| [
{
"answer_id": 74321050,
"author": "bknights",
"author_id": 3806017,
"author_profile": "https://Stackoverflow.com/users/3806017",
"pm_score": 2,
"selected": true,
"text": "==="
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/275414/"
] |
74,277,329 | <p>i am currently working on the Contoso University project with the razor pages.
I just met 1 problem on my way and it happens when i initialize the migrations in the <code>Program.cs</code></p>
<p>For a strange reason it seems like the app cannot connect to the local database.</p>
<pre><code>using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using ContosoUniversity.Data;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddDbContext<SchoolContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("SchoolContext")));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
else
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
}
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService<SchoolContext>();
context.Database.EnsureCreated();
// DbInitializer.Initialize(context);
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
</code></pre>
<p>and the error:</p>
<pre><code>Microsoft.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SNI_PN11, error: 50 - Local
</code></pre>
<p>Everything. I just need a fix for this project.</p>
| [
{
"answer_id": 74321050,
"author": "bknights",
"author_id": 3806017,
"author_profile": "https://Stackoverflow.com/users/3806017",
"pm_score": 2,
"selected": true,
"text": "==="
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18184615/"
] |
74,277,359 | <p>I've tried a few stack examples. an i am still just rewriting what i was hoping to be adding to ... mainly we have a list of check box items each time you check it i would like existing items to turn into a list of those object so we can use them on a 'comparing' page</p>
<pre><code>const handleChange = () => {
localStorage.setItem("item", JSON.stringify(products)); <-- works as expected
var existingItems: any[] = [];
existingItems?.push({ products });
localStorage.setItem("compareItems", JSON.stringify(existingItems));
};
</code></pre>
<p>existingItems is always = to products i want existing items to = [{item}, {item},] and so on</p>
<p>detail of what products would be:
products (object of key and values frm api) = {name: "Product 1", description: "Product 1", isActiveForEntry: true, displayRank: 0, sku: "ABC123"}</p>
| [
{
"answer_id": 74321050,
"author": "bknights",
"author_id": 3806017,
"author_profile": "https://Stackoverflow.com/users/3806017",
"pm_score": 2,
"selected": true,
"text": "==="
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11145976/"
] |
74,277,360 | <p>I'm trying to make a code where I want to action on <strong>onPress</strong> button to assign a screen or section where my scroller should go as I wanted, the below code is perfectly coded using <strong>class component</strong>, but my entire code Im coding is in functional components and i have no idea how to convert this <strong>class component</strong> into <strong>functional component</strong> help indeed.</p>
<p><strong>Apps.js</strong></p>
<pre><code>import React, { Component } from 'react';
import {
Dimensions,
Platform,
ScrollView,
StyleSheet,
Text,
Button,
TouchableOpacity,
View
} from 'react-native';
let scrollYPos = 0;
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
screenHeight: Dimensions.get('window').height,
screenWidth: Dimensions.get('window').width,
};
}
scrollToB = () => {
scrollYPos = this.state.screenHeight * 1;
this.scroller.scrollTo({ x: 0, y: scrollYPos });
console.log("test", scrollYPos)
};
scrollToC = () => {
scrollYPos = this.state.screenHeight * 2;
this.scroller.scrollTo({ x: 0, y: scrollYPos });
};
scrollToTop = () => {
this.scroller.scrollTo({ x: 0, y: 0 });
};
render() {
return (
<ScrollView style={styles.container} ref={(scroller) => { this.scroller = scroller }}>
<View style={[styles.screen, styles.screenA]}>
<Button
onPress={this.scrollToB}
title="sctoll to B"
/>
<Button
title="sctoll to C"
onPress={this.scrollToC}
/>
<Button
title="sctoll to Top"
onPress={this.scrollToTop}
/>
<Text style={styles.letter}>A</Text>
<View style={styles.scrollButton}>
<Text style={styles.scrollButtonText}>Scroll to B</Text>
</View>
</View>
<View style={[styles.screen, styles.screenB]}>
<Text style={styles.letter}>B</Text>
<View style={styles.scrollButton}>
<Text style={styles.scrollButtonText}>Scroll to C</Text>
</View>
</View>
<View style={[styles.screen, styles.screenC]}>
<Text style={styles.letter}>C</Text>
<View style={styles.scrollButton}>
<Text style={styles.scrollButtonText}>Scroll to Top</Text>
</View>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
screen: {
backgroundColor: 'yellow',
flexDirection: 'column',
height: Dimensions.get('window').height,
justifyContent: 'center'
},
screenA: {
backgroundColor: '#F7CAC9',
},
screenB: {
backgroundColor: '#92A8D1',
},
screenC: {
backgroundColor: '#88B04B',
},
});
</code></pre>
| [
{
"answer_id": 74277398,
"author": "jesus marmol",
"author_id": 20102799,
"author_profile": "https://Stackoverflow.com/users/20102799",
"pm_score": 0,
"selected": false,
"text": "<a href =\"idofthatView>"
},
{
"answer_id": 74277453,
"author": "user20386762",
"author_id": 20386762,
"author_profile": "https://Stackoverflow.com/users/20386762",
"pm_score": 3,
"selected": true,
"text": "import React, { Component, useState } from 'react';\nimport {\n Dimensions,\n Platform,\n ScrollView,\n StyleSheet,\n Text,\n Button,\n TouchableOpacity,\n View\n} from 'react-native';\n\nlet scrollYPos = 0;\n\nexport default App = () => {\n const [screenHeight, setScreenHeight] = useState(Dimensions.get('window').height)\n const [screenWidth, setScreenWidth] = useState(Dimensions.get('window').width)\n\n const scrollToB = () => {\n scrollYPos = screenHeight * 1;\n this.scroller.scrollTo({ x: 0, y: scrollYPos });\n console.log(\"test\", scrollYPos)\n };\n const scrollToC = () => {\n scrollYPos = screenHeight * 2;\n this.scroller.scrollTo({ x: 0, y: scrollYPos });\n };\n const scrollToTop = () => {\n this.scroller.scrollTo({ x: 0, y: 0 });\n };\n\n return (\n <ScrollView style={styles.container} ref={(scroller) => { this.scroller = scroller }}>\n <View style={[styles.screen, styles.screenA]}>\n <Button\n onPress={scrollToB}\n title=\"sctoll to B\"\n />\n <Button\n title=\"sctoll to C\"\n onPress={scrollToC}\n />\n <Button\n title=\"sctoll to Top\"\n onPress={scrollToTop}\n />\n <Text style={styles.letter}>A</Text>\n <View style={styles.scrollButton}>\n <Text style={styles.scrollButtonText}>Scroll to B</Text>\n </View>\n </View>\n <View style={[styles.screen, styles.screenB]}>\n <Text style={styles.letter}>B</Text>\n <View style={styles.scrollButton}>\n <Text style={styles.scrollButtonText}>Scroll to C</Text>\n </View>\n </View>\n <View style={[styles.screen, styles.screenC]}>\n <Text style={styles.letter}>C</Text>\n <View style={styles.scrollButton}>\n <Text style={styles.scrollButtonText}>Scroll to Top</Text>\n </View>\n </View>\n </ScrollView>\n );\n }\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n },\n screen: {\n backgroundColor: 'yellow',\n flexDirection: 'column',\n height: Dimensions.get('window').height,\n justifyContent: 'center'\n },\n screenA: {\n backgroundColor: '#F7CAC9',\n },\n screenB: {\n backgroundColor: '#92A8D1',\n },\n screenC: {\n backgroundColor: '#88B04B',\n },\n});\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10082168/"
] |
74,277,401 | <p>A collection of books and movies are already parsed and read into a dict of dicts. The program asks a user to enter a query string to search against multiple fields in the collection: title, author, and publisher. The search should perform partial string matching and be case insensitive. All matching books should be displayed.</p>
<p>Suppose there are 3 books and 3 movies.</p>
<pre><code>
library_collections = {'books': {17104: {'Title': 'A River', 'Author': 'Elisha Mitchell', 'Publisher': 'FPG Publishing', 'Pages': '345', 'Year': '2014', 'Copies': 2, 'Available': 2, 'ID': 17104}, 37115: {'Title': 'Aim High', 'Author': 'George Tayloe Winston', 'Publisher': 'Manning Hall Press', 'Pages': '663', 'Year': '2014', 'Copies': 5, 'Available': 5, 'ID': 37115}}, 'movies': {27002: {'Title': 'Adventures of Argo', 'Director': 'Jonathan Trumbull Jr', 'Length': '102', 'Genre': 'Drama', 'Year': '2014', 'Copies': 3, 'Available': 3, 'ID': 27002}, 17003: {'Title': 'African Queen', 'Director': 'Frederick Muhlenberg', 'Length': '98', 'Genre': 'Drama', 'Year': '2011', 'Copies': 2, 'Available': 2, 'ID': 17003}, 57004: {'Title': 'Alice May', 'Director': 'Jonathan Dayton', 'Length': '117', 'Genre': 'Drama', 'Year': '2014', 'Copies': 2, 'Available': 2, 'ID': 57004}}}
query = input('Please enter a query string to search: ')
for key, value in library_collections.items():
if query.lower() in value:
print(key,value)
print()
</code></pre>
<p>It prints nothing to the console, can anyone help?</p>
| [
{
"answer_id": 74277398,
"author": "jesus marmol",
"author_id": 20102799,
"author_profile": "https://Stackoverflow.com/users/20102799",
"pm_score": 0,
"selected": false,
"text": "<a href =\"idofthatView>"
},
{
"answer_id": 74277453,
"author": "user20386762",
"author_id": 20386762,
"author_profile": "https://Stackoverflow.com/users/20386762",
"pm_score": 3,
"selected": true,
"text": "import React, { Component, useState } from 'react';\nimport {\n Dimensions,\n Platform,\n ScrollView,\n StyleSheet,\n Text,\n Button,\n TouchableOpacity,\n View\n} from 'react-native';\n\nlet scrollYPos = 0;\n\nexport default App = () => {\n const [screenHeight, setScreenHeight] = useState(Dimensions.get('window').height)\n const [screenWidth, setScreenWidth] = useState(Dimensions.get('window').width)\n\n const scrollToB = () => {\n scrollYPos = screenHeight * 1;\n this.scroller.scrollTo({ x: 0, y: scrollYPos });\n console.log(\"test\", scrollYPos)\n };\n const scrollToC = () => {\n scrollYPos = screenHeight * 2;\n this.scroller.scrollTo({ x: 0, y: scrollYPos });\n };\n const scrollToTop = () => {\n this.scroller.scrollTo({ x: 0, y: 0 });\n };\n\n return (\n <ScrollView style={styles.container} ref={(scroller) => { this.scroller = scroller }}>\n <View style={[styles.screen, styles.screenA]}>\n <Button\n onPress={scrollToB}\n title=\"sctoll to B\"\n />\n <Button\n title=\"sctoll to C\"\n onPress={scrollToC}\n />\n <Button\n title=\"sctoll to Top\"\n onPress={scrollToTop}\n />\n <Text style={styles.letter}>A</Text>\n <View style={styles.scrollButton}>\n <Text style={styles.scrollButtonText}>Scroll to B</Text>\n </View>\n </View>\n <View style={[styles.screen, styles.screenB]}>\n <Text style={styles.letter}>B</Text>\n <View style={styles.scrollButton}>\n <Text style={styles.scrollButtonText}>Scroll to C</Text>\n </View>\n </View>\n <View style={[styles.screen, styles.screenC]}>\n <Text style={styles.letter}>C</Text>\n <View style={styles.scrollButton}>\n <Text style={styles.scrollButtonText}>Scroll to Top</Text>\n </View>\n </View>\n </ScrollView>\n );\n }\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n },\n screen: {\n backgroundColor: 'yellow',\n flexDirection: 'column',\n height: Dimensions.get('window').height,\n justifyContent: 'center'\n },\n screenA: {\n backgroundColor: '#F7CAC9',\n },\n screenB: {\n backgroundColor: '#92A8D1',\n },\n screenC: {\n backgroundColor: '#88B04B',\n },\n});\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20178894/"
] |
74,277,420 | <p>I'm trying to write a conditional Regex to achieve the following:</p>
<pre><code>If the word "apple" or "orange" is present within a string:
there must be at least 2 occurrences of the word "HORSE" (upper-case)
else
there must be at least 1 occurrence of the word "HORSE" (upper-case)
</code></pre>
<p>What I wrote so far:</p>
<p><code>(?(?=((apple|orange).*))(HORSE.*){2}|(HORSE.*){1})</code></p>
<p>I was expecting this Regex to work as I'm following the pattern <code>(?(?=regex)then|else)</code>.</p>
<p>However, it looks like <code>(HORSE.*){1}</code> is always evaluated instead. Why?</p>
<p><a href="https://regex101.com/r/V5s8hV/1" rel="nofollow noreferrer">https://regex101.com/r/V5s8hV/1</a></p>
| [
{
"answer_id": 74277505,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": false,
"text": "HORSE"
},
{
"answer_id": 74278854,
"author": "bobble bubble",
"author_id": 5527985,
"author_profile": "https://Stackoverflow.com/users/5527985",
"pm_score": 3,
"selected": true,
"text": "^(?=(?:.*?\\b(apple|orange)\\b)?)(.*?\\bHORSE\\b)(?(1)(?2))\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15965157/"
] |
74,277,433 | <p>I have a simple query:</p>
<pre><code>dim res = (From x In db.INVENTORies
Where x.INVENTORY_ACTIVATION_DATE IsNot Nothing).count
</code></pre>
<p>I need to run this for 14 different date fields, so how do I run this where INVENTORY_ACTIVATION_DATE can be a variable/dynamic?</p>
<p>something like:</p>
<p>function GetCount(aField as string) as integer</p>
<pre><code>return (From x In db.INVENTORies
Where x.**<Use aField here>** IsNot Nothing).count
</code></pre>
<p>end function</p>
<p>Thanks in advance.
Steve</p>
<p>I've tried Dynamic Linq and PredicateBuilder, but there are no good examples for my scenario.</p>
| [
{
"answer_id": 74277505,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": false,
"text": "HORSE"
},
{
"answer_id": 74278854,
"author": "bobble bubble",
"author_id": 5527985,
"author_profile": "https://Stackoverflow.com/users/5527985",
"pm_score": 3,
"selected": true,
"text": "^(?=(?:.*?\\b(apple|orange)\\b)?)(.*?\\bHORSE\\b)(?(1)(?2))\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5112317/"
] |
74,277,437 | <p>I'm trying to display a table listing the Country codes (iso3166) in a postgresql db onto an html page using Spring Boot and Angular, the parameter name in the http response lists "number" when instead I want it to list "nbr".</p>
<p>The SQL table has 4 columns</p>
<ul>
<li>name (varchar) unique</li>
<li>alpha2 (varchar) PK unique</li>
<li>alpha3 (varchar) unique</li>
<li>nbr (int4)</li>
</ul>
<p>My Spring Boot Models is the following:</p>
<pre><code>@Entity
@Table(name = "iso3166")
public class Country {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private String alpha2;
@Column(name = "name")
private String name;
@Column(name = "alpha3")
private String alpha3;
@Column(name = "nbr")
private int nbr;
public Country()
{
}
public Country(String name, String alpha2, String alpha3, int nbr)
{
this.name = name;
this.alpha2 = alpha2;
this.alpha3 = alpha3;
this.nbr = nbr;
}
/*
getters and settings + toString()
*/
</code></pre>
<p>The repository uses JPARepository</p>
<pre><code>public interface ICountryRepository extends JpaRepository<Country, String> {
}
</code></pre>
<p>And the Controller has only the findAll() method</p>
<pre><code>@RestController
@RequestMapping({"/api"})
public class CountryController {
@Autowired
ICountryRepository countryRepository;
@GetMapping
public List<Country> findAll(){
List<Country> country = countryRepository.findAll();
return country;
}
}
</code></pre>
<p>Running spring-boot and opening localhost in chrome, the table shows up just fine.
<a href="https://i.stack.imgur.com/ecmNh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ecmNh.png" alt="enter image description here" /></a></p>
<p>However, looking at the Response tab under Network, it shows up like this
<a href="https://i.stack.imgur.com/Uyu67.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Uyu67.png" alt="enter image description here" /></a>
Shows the same thing if I go to http://localhost:8080/api</p>
<p>[{"alpha2":"AX","name":"AALAND ISLANDS","alpha3":"ALA","number":248},{"alpha2":"AF","name":"AFGHANISTAN","alpha3":"AFG","number":4},{"alpha2":"AL","name":"ALBANIA","alpha3":"ALB","number":8},{"alpha2":"DZ","name":"ALGERIA","alpha3":"DZA","number":12},{"alpha2":"AS","name":"AMERICAN SAMOA","alpha3":"ASM","number":16},{"alpha2":"AD","name":"ANDORRA","alpha3":"AND","number":20},{"alpha2":"AO","name":"ANGOLA","alpha3":"AGO","number":24},</p>
<p>Why does the Http Response return the "nbr" field as "number" instead? And how can I change it to show up as "nbr" in the Http response? Does something happen in the background in Spring Boot when formulating the http response that I can't control?</p>
| [
{
"answer_id": 74277505,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": false,
"text": "HORSE"
},
{
"answer_id": 74278854,
"author": "bobble bubble",
"author_id": 5527985,
"author_profile": "https://Stackoverflow.com/users/5527985",
"pm_score": 3,
"selected": true,
"text": "^(?=(?:.*?\\b(apple|orange)\\b)?)(.*?\\bHORSE\\b)(?(1)(?2))\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7877351/"
] |
74,277,475 | <p>I am trying to figure out the logic for a fee addition which renews everymonth. The idea is a charge candidates for only processing months, which means only when they get a contribution.</p>
<p>Currently, what I am doing is checking the month of current contribution and if that changes, I charge the Candidate the extra 7.99 fee.
Shared below is a snippet from my candidate.rb</p>
<pre><code> def determine_fee(amount_cents)
amount = ((amount_cents * ((merchant_rate.to_f * 100) + 2.9) / 100) + 25).to_i #normal fee
unless fee_paid_on&.month == Time.zone.now.month # comparing with current month
amount = ((amount_cents * ((merchant_rate.to_f * 100) + 2.9) / 100) + 25 + 799).to_i #fee to be added for first contribution of every month
self.update_attributes(fee_paid_on: Time.zone.now)
end
amount
end
</code></pre>
<p>However, the draw back with this approach is that Candidates are not charged as per 30 day time interval.For instance, the first contribution came at 28th of Nov, it would be charged the extra 7.99 and the rest of the contributions for Nov would be charged wihtout the 7.99 fee. And again, if they receive a contribution on 1st of dec, it would be charged the extra 7.99.
Instead, i would want to the first contribution which comes after 28th of Dec to be charged the extra 7.99.</p>
<p>I am considering adding an extra month and comparing the fee, but cant establish the logic given the limited time. Any suggestion would be appreciated</p>
<p>Contribution_form.rb:</p>
<pre><code>def process_stripe_payment
applicable_fee = candidate.determine_fee(amount_cents)
Stripe::Charge.create({
amount: amount_cents,
currency: candidate.candidate_country[candidate.country.to_s.to_sym][:currency],
source: stripe_token,
application_fee_amount: applicable_fee,
# application_fee_amount: ((amount_cents * ((candidate.merchant_rate.to_f * 100) + 2.9) / 100) + 25).to_i,
statement_descriptor_suffix: "#{get_statement_descriptor.to_s.upcase}",
on_behalf_of: candidate.stripe_gateway_id,
transfer_data: {
destination: candidate.stripe_gateway_id,
},
}, stripe_version: '2019-12-03',)
end
</code></pre>
| [
{
"answer_id": 74277505,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 1,
"selected": false,
"text": "HORSE"
},
{
"answer_id": 74278854,
"author": "bobble bubble",
"author_id": 5527985,
"author_profile": "https://Stackoverflow.com/users/5527985",
"pm_score": 3,
"selected": true,
"text": "^(?=(?:.*?\\b(apple|orange)\\b)?)(.*?\\bHORSE\\b)(?(1)(?2))\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8339401/"
] |
74,277,485 | <p>So I have an array of 15 Flying Objects, The flyingObjects class consists of 1 variable (Price: Double) with its getters and setters.
I also have an airplane class that extends FlyingObjects, a helicopter class that extends Airplane and quadrotor and multirotor class that extends helicopter. On the other side of the tree I have a UAV class that extends FlyingObjects, a MAV class that extends UAV and a AD class that extends UAV.</p>
<p>Here is the array:</p>
<pre><code> FlyingObjects [] test = new FlyingObjects[7];
test[0] = new Uav(10,43);
test[1] = new AgriculturalDrone(8000,780000,"Chase",2400);
test[2] = new Uav(10,5);
test[3] = new Mav(0.5,140000,"trooper",10);
test[4] = new Multirotor("Hexa",140000,200,185,2021,1,4);
test[5] = new Helicopter("Robinson",199000,250,100,2018,7);
test[6] = new Airplane("Boeing",350000,450);
</code></pre>
<p>Now I need to write a method that will get me the most expensive and least expensive UAV in my array (note that the price is always the second attribute in the UAV's constructors).
for some reason my method always return the first UAV in the array as the least expensive and the last UAV in the array as the most expensive.
Any tip on how to fix this issue?</p>
<pre><code> public static void findLeastAndMostExpensiveUAV(FlyingObjects[] flyingObjects) {
int mostExpensive = -1;
int leastExpensive =1000000000;
boolean hasUav = false;
if(flyingObjects == null) {
System.out.println("There is no UAV");
}
for(int i = 0;i<flyingObjects.length;i++) {
if (flyingObjects[i] instanceof Uav) {
Uav a = (Uav) flyingObjects[i];
if (a.getPrice() >= mostExpensive) {
mostExpensive = i;
}if (a.getPrice() <= leastExpensive){
leastExpensive = i;
}
if(!hasUav) {
hasUav = true;
}
}
}
if(!hasUav) {
System.out.println("There is no UAV");
}
else {
System.out.println("\nInformation about the most expensive UAV: \n"+ flyingObjects[mostExpensive]+"\n");
System.out.println("Information about the least expensive UAV: \n"+flyingObjects[leastExpensive]);
}
}
</code></pre>
| [
{
"answer_id": 74277591,
"author": "Ben Borchard",
"author_id": 4054720,
"author_profile": "https://Stackoverflow.com/users/4054720",
"pm_score": 3,
"selected": true,
"text": "mostExpensive"
},
{
"answer_id": 74277993,
"author": "chptr-one",
"author_id": 13797513,
"author_profile": "https://Stackoverflow.com/users/13797513",
"pm_score": 1,
"selected": false,
"text": "var stat = Arrays.stream(flyingObjects)\n .filter(o -> o instanceof UAV)\n .collect(Collectors.teeing(\n Collectors.minBy(Comparator.comparingDouble(FlyingObject::getPrice)),\n Collectors.maxBy(Comparator.comparingDouble(FlyingObject::getPrice)),\n (min, max) -> new MinMaxStatistic<>(min.orElse(null), max.orElse(null))));\n\nFlyingObject min = stat.min;\nFlyingObject max = stat.max;\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17332091/"
] |
74,277,492 | <p>I have a json value as below</p>
<pre><code>"BookShops": [
{
"Name": "Modern",
"BookID": [
"101"
]
},
{
"Name": "Windshore",
"BookID": [
"102"
]
},
{
"Name": "Winter",
"BookID": [
"105"
]
},
]
</code></pre>
<p>Each of element of bookshops have only one bookID (even their type is int array) I want to move bookID into List Of Int just like the expect result</p>
<pre><code>"GlobalBookID":[101,102,105]
</code></pre>
<p>that define in class as</p>
<pre><code>List<int> GlobalBookIDs
</code></pre>
<p>Can I know to translate it in single line ?</p>
| [
{
"answer_id": 74277509,
"author": "rotgers",
"author_id": 2223566,
"author_profile": "https://Stackoverflow.com/users/2223566",
"pm_score": 3,
"selected": true,
"text": "BookID"
},
{
"answer_id": 74277969,
"author": "Dmitry Bychenko",
"author_id": 2319407,
"author_profile": "https://Stackoverflow.com/users/2319407",
"pm_score": 1,
"selected": false,
"text": "BookID"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17194305/"
] |
74,277,498 | <p>I am learning BS4. I parsed some div class. But I want to get data in div code. `</p>
<pre><code>[<div class="handlebarData theme_is_whitehot" data-enrollment='{"available":{"id":21313,"enrollmentStatus":{"status":{"code":"C","description":"Closed"},"enrolledCount":17,"reservedCount":0,"waitlistedCount":0,"minEnroll":0,"maxEnroll":17,"maxWaitlist":0,"openReserved":0}},"history":{"id":21313,"enrollmentStatus":{"status":{"code":"C","description":"Closed"},"enrolledCount":17,"reservedCount":0,"waitlistedCount":0,"minEnroll":0,"maxEnroll":17,"maxWaitlist":0,"openReserved":0}}}' data-image='{"imagePath":"/sites/default/files/styles/xlarge/public/COLWRIT-18-2.jpeg","uri":"public://COLWRIT-18-2.jpeg"}' data-json='{"id":21313,"number":"003","component":{"code":"SEM","description":"Seminar"},"displayName":"2023 Spring COLWRIT R4B 003 SEM 003","instructionMode":{"code":"P","description":"In-Person Instruction"},"type":{"code":"E","description":"Enrollment","formalDescription":"Enrollment Section"},"academicOrganization":{"code":"COLWRIT","description":"College Writing Programs","formalDescription":"College Writing Programs"},"academicGroup":{"code":"CLS","description":"L&amp;S","formalDescription":"College of Letters and Science"},"startDate":"2023-01-17","endDate":"2023-05-05","status":{"code":"A","description":"Active"},"association":{"primary":true,"primaryAssociatedComponent":{"code":"SEM","description":"Seminar"},"primaryAssociatedSectionId":21313,"primaryAssociatedSectionIds":[21313],"associatedClass":3},"enrollmentStatus":{"status":{"code":"C","description":"Closed"},"enrolledCount":17,"reservedCount":0,"waitlistedCount":0,"minEnroll":0,"maxEnroll":17,"maxWaitlist":0,"openReserved":0},"printInScheduleOfClasses":true,"addConsentRequired":{"code":"N","description":"No Special Consent Required"},"dropConsentRequired":{"code":"N","description":"No Special Consent Required"},"graded":true,"feesExist":false,"roomShare":false,"sectionAttributes":[{"attribute":{"code":"CCLV","description":"CRSE LEVEL","formalDescription":"Academic Course Level"},"value":{"code":"UGLD","description":"UG Lower Division","formalDescription":"Undergraduate Lower Division Course"}},{"attribute":{"code":"FLEX","description":"FLEX","formalDescription":"Flexible Scheduling Approved"},"value":{"code":"FULLFLEX","description":"All Formats Regardless of Term","formalDescription":"Approved Flex Sched of all Formats for any Term"}},{"attribute":{"code":"TIE","description":"Instr Type","formalDescription":"Instructional Activity Types"},"value":{"code":"SEMT","description":"Seminar-Topical","formalDescription":"Transmitting the Knowledge Base"}},{"attribute":{"code":"VUOC","description":"VCREDIT","formalDescription":"Variable Units of Credit"},"value":{"code":"F","description":"Fixed","formalDescription":"Fixed Unit 1 Value"}},{"attribute":{"code":"NOTE","formalDescription":"Class Notes"},"value":{"code":"2","formalDescription":"Enrollment is restricted to students who have satisfied the first half of the Reading and Composition requirement. This course satisfies the second half of the Reading and Composition requirement."}},{"attribute":{"code":"NOTE","formalDescription":"Special Title"},"value":{"code":"4","formalDescription":"The High Stakes in Sports Culture"}},{"attribute":{"code":"NOTE","formalDescription":"Class Description"},"value":{"code":"6","formalDescription":"Don\u2019t worry, you don\u2019t necessarily have to be athletic to take this class- you don\u2019t even have to like sports (although you can)! Sports is based on ability and talent, but it can deviate, influenced by various social structures. Key questions guiding the course include: what is the role of sports in politics and activism? How is the culture of sports disneyfied and commercialized? Is sports journalism evolving? How do fans impact the culture? In this course, we\u2019ll explore this divergence in the culture of sports and its relationship with journalism, media, gentrification, body and fandom."}}],"roomCharacteristics":[{"code":"04","description":"AV-Computer Data Display","quantity":1},{"code":"09","description":"AV-DVD Player","quantity":1},{"code":"51","description":"Seating-Movable Desks","quantity":1}],"meetings":[{"number":1,"meetsDays":"MoWeFr","meetsMonday":true,"meetsTuesday":false,"meetsWednesday":true,"meetsThursday":false,"meetsFriday":true,"meetsSaturday":false,"meetsSunday":false,"startTime":"11:00:00","endTime":"11:59:00","location":{"code":"SOCS118","description":"Social Sciences Building 118"},"building":{"code":"1761","description":"Social Sci"},"assignedInstructors":[{"assignmentNumber":1,"instructor":{"identifiers":[{"type":"campus-uid","id":"972764","disclose":true}],"names":[{"type":{"code":"FRM","description":"Former"},"familyName":"Asakawa","givenName":"Chisako","formattedName":"Chisako Asakawa","disclose":false,"uiControl":{"code":"N","description":"Do Not Display"},"fromDate":"2014-07-07"},{"type":{"code":"PRF","description":"Preferred"},"familyName":"Cole","givenName":"Chisako","formattedName":"Chisako A Cole","disclose":true,"uiControl":{"code":"U","description":"Edit - No Delete"},"fromDate":"2020-06-08"},{"type":{"code":"PRI","description":"Primary"},"familyName":"Cole","givenName":"Chisako","formattedName":"Chisako A Cole","disclose":true,"uiControl":{"code":"D","description":"Display Only"},"fromDate":"2020-06-08"}]},"role":{"code":"PI","description":"1-TIC","formalDescription":"Teaching and In Charge"},"contactMinutes":0,"printInScheduleOfClasses":true,"gradeRosterAccess":{"code":"A","description":"Approve","formalDescription":"Approve"}}],"startDate":"2023-01-17","endDate":"2023-05-05","meetingTopic":[]}],"class":{"course":{"identifiers":[{"type":"cs-course-id","id":"104067"}],"subjectArea":{"code":"COLWRIT","description":"College Writing Programs"},"catalogNumber":{"prefix":"R","number":"4","suffix":"B","formatted":"R4B"},"displayName":"COLWRIT R4B","title":"Reading, Composition, and Research","transcriptTitle":"READ,COMP,RESEARCH","requisites":{"code":"000991","description":"R&amp;C Part B Prerequisite","formalDescription":"Must complete the First Half of the Reading &amp; Composition Requirement."}},"offeringNumber":1,"session":{"term":{"id":"2232","name":"2023 Spring"},"id":"1","name":"Regular Academic Session"},"number":"003","displayName":"2023 Spring COLWRIT R4B 003","allowedUnits":{"minimum":4,"maximum":4,"forAcademicProgress":4,"forFinancialAid":4},"gradingBasis":{"code":"GRD","description":"Graded"},"requirementDesignation":{"code":"RC2","description":"Reading and Composition B"}},"attributes":{"CCLV":[{"attribute":{"code":"CCLV","description":"CRSE LEVEL","formalDescription":"Academic Course Level"},"value":{"code":"UGLD","description":"UG Lower Division","formalDescription":"Undergraduate Lower Division Course"}}],"FLEX":[{"attribute":{"code":"FLEX","description":"FLEX","formalDescription":"Flexible Scheduling Approved"},"value":{"code":"FULLFLEX","description":"All Formats Regardless of Term","formalDescription":"Approved Flex Sched of all Formats for any Term"}}],"TIE":[{"attribute":{"code":"TIE","description":"Instr Type","formalDescription":"Instructional Activity Types"},"value":{"code":"SEMT","description":"Seminar-Topical","formalDescription":"Transmitting the Knowledge Base"}}],"VUOC":[{"attribute":{"code":"VUOC","description":"VCREDIT","formalDescription":"Variable Units of Credit"},"value":{"code":"F","description":"Fixed","formalDescription":"Fixed Unit 1 Value"}}],"NOTE":{"class-notes":{"attribute":{"code":"NOTE","formalDescription":"Class Notes"},"value":{"code":"2","formalDescription":"Enrollment is restricted to students who have satisfied the first half of the Reading and Composition requirement. This course satisfies the second half of the Reading and Composition requirement."}},"special-title":{"attribute":{"code":"NOTE","formalDescription":"Special Title"},"value":{"code":"4","formalDescription":"The High Stakes in Sports Culture"}},"class-description":{"attribute":{"code":"NOTE","formalDescription":"Class Description"},"value":{"code":"6","formalDescription":"Don\u2019t worry, you don\u2019t necessarily have to be athletic to take this class- you don\u2019t even have to like sports (although you can)! Sports is based on ability and talent, but it can deviate, influenced by various social structures. Key questions guiding the course include: what is the role of sports in politics and activism? How is the culture of sports disneyfied and commercialized? Is sports journalism evolving? How do fans impact the culture? In this course, we\u2019ll explore this divergence in the culture of sports and its relationship with journalism, media, gentrification, body and fandom."}}}},"course":{"identifiers":[{"type":"cms-id","id":"354fc2b0-d2ac-420c-97ed-1f33b9f78ef1"},{"type":"cs-course-id","id":"104067"},{"type":"cms-version-independent-id","id":"bb35aa4e-7385-403d-803d-6fcc4770676b"}],"subjectArea":{"code":"COLWRIT","description":"College Writing Programs"},"catalogNumber":{"prefix":"R","number":"4","suffix":"B","formatted":"R4B"},"classSubjectArea":{"code":"COLWRIT","description":"College Writing Programs"},"displayName":"COLWRIT R4B","classDisplayName":"COLWRIT R4B","formerDisplayName":"","title":"Reading, Composition, and Research","transcriptTitle":"READ,COMP,RESEARCH ","description":"A lecture\/seminar satisfying the second half of the Reading &amp; Composition requirement, R4B offers structured and sustained practice in the processes used in reading, critical analysis, and writing. Students engage with thematically-related materials from a range of genres and media. In response, they craft short pieces leading to longer expository and\/or argumentative essays. Students develop a research question, draft a research essay, gather, evaluate, and synthesize information from various sources. Elements of the research process--a proposal, an annotated bibliography, an abstract, a works cited list, etc.--are submitted with the final report in a research portfolio. Students write a minimum of 32 pages of prose.\n","academicCareer":{"code":"UGRD","description":"Undergraduate"},"academicGroup":{"code":"CLS","description":"Clg of Letters &amp; Science"},"academicOrganization":{"code":"COLWRIT","description":"College Writing Programs"},"departmentNicknames":"COL WRIT!COLLEGE WRITING!CW!","primaryInstructionMethod":{"code":"SEM","description":"Student-instructor coverage of course materials"},"credit":{"type":"fixed","value":{"fixed":{"units":4}}},"gradingBasis":{"code":"graded","description":"graded"},"blindGrading":false,"status":{"code":"ACTIVE","description":"ACTIVE"},"fromDate":"2021-08-18","toDate":"2099-12-19","createdDate":"2021-03-30","updatedDate":"2021-04-23","printInCatalog":true,"printInstructors":true,"anyFeesExist":false,"finalExam":{"code":"N","description":"No final exam"},"instructorDropConsentRequired":false,"allowMultipleEnrollments":false,"spansMultipleTerms":false,"multipleTermNumber":0,"contactHours":7.5,"workloadHours":30,"tie":{"code":"SEMT","description":"SEMT"},"cip":{"code":"MISSINGcipCode","description":"MISSINGcipCode"},"hegis":{"code":"MISSINGhegisCode","description":"MISSINGhegisCode"},"repeatability":{"repeatable":false},"preparation":{"requiredText":"Previously passed an R_A course with a letter grade of C- or better.\nPreviously passed an articulated R_A course with a letter grade of C- or better.\nScore a 4 on the Advanced Placement Exam in English Literature and Composition.\nScore a 4 or 5 on the Advanced Placement Exam in English Language and Composition.\nScore of 5, 6, or 7 on the International Baccalaureate Higher Level Examination in English.","requiredCourses":[]},"creditRestriction":{"restrictionText":"","restrictionCourses":{"creditRestrictionCourses":[{"course":{"identifiers":[{"type":"cs-course-id","id":"104067"},{"type":"cms-version-independent-id","id":"bb35aa4e-7385-403d-803d-6fcc4770676b"}],"displayName":"COLWRIT R4B"},"maxCreditPercentage":100},{"course":{"identifiers":[{"type":"cs-course-id","id":"104067"},{"type":"cms-version-independent-id","id":"bb35aa4e-7385-403d-803d-6fcc4770676b"}],"displayName":"COLWRIT R4B"},"maxCreditPercentage":100}]}},"proposedInstructors":["Staff"],"formatsOffered":{"description":"One and one-half hours of lecture and one and one-half hours of seminar per week. Four hours of lecture and three and one-half hours of seminar per week for 6 weeks. Three hours of seminar\/discussion per week. ","formats":[{"termsAllowed":{"termNames":["Summer"]},"sessionType":"6","description":"3.5 hours of seminar and 4.0 hours of lecture per week","aggregateMinContactHours":7.5,"aggregateMaxContactHours":7.5,"minWorkloadHours":30,"maxWorkloadHours":30,"anyFeesExist":false,"components":[{"instructionMethod":{"code":"LEC","description":"Instructor presentation of course materials"},"primary":false,"minContactHours":4,"maxContactHours":4,"finalExam":[],"feesExist":false},{"instructionMethod":{"code":"WRK","description":"Outside Work Hours"},"primary":false,"minContactHours":22.5,"maxContactHours":22.5,"finalExam":[],"feesExist":false},{"instructionMethod":{"code":"SEM","description":"Student-instructor coverage of course materials"},"primary":true,"minContactHours":3.5,"maxContactHours":3.5,"finalExam":[],"feesExist":false}]},{"termsAllowed":{"termNames":["Fall"]},"sessionType":"15","description":"1.5 hours of seminar and 1.5 hours of lecture per week","aggregateMinContactHours":3,"aggregateMaxContactHours":3,"minWorkloadHours":12,"maxWorkloadHours":12,"anyFeesExist":false,"components":[{"instructionMethod":{"code":"SEM","description":"Student-instructor coverage of course materials"},"primary":true,"minContactHours":1.5,"maxContactHours":1.5,"finalExam":[],"feesExist":false},{"instructionMethod":{"code":"LEC","description":"Instructor presentation of course materials"},"primary":false,"minContactHours":1.5,"maxContactHours":1.5,"finalExam":[],"feesExist":false},{"instructionMethod":{"code":"WRK","description":"Outside Work Hours"},"primary":false,"minContactHours":9,"maxContactHours":9,"finalExam":[],"feesExist":false}]},{"termsAllowed":{"termNames":["Spring"]},"sessionType":"15","description":"1.5 hours of seminar and 1.5 hours of lecture per week","aggregateMinContactHours":3,"aggregateMaxContactHours":3,"minWorkloadHours":12,"maxWorkloadHours":12,"anyFeesExist":false,"components":[{"instructionMethod":{"code":"SEM","description":"Student-instructor coverage of course materials"},"primary":true,"minContactHours":1.5,"maxContactHours":1.5,"finalExam":[],"feesExist":false},{"instructionMethod":{"code":"LEC","description":"Instructor presentation of course materials"},"primary":false,"minContactHours":1.5,"maxContactHours":1.5,"finalExam":[],"feesExist":false},{"instructionMethod":{"code":"WRK","description":"Outside Work Hours"},"primary":false,"minContactHours":9,"maxContactHours":9,"finalExam":[],"feesExist":false}]}],"typicallyOffered":{"terms":{"termNames":["Summer","Fall","Spring"]},"comments":""},"summerOnly":false},"requirementsFulfilled":[{"code":"RC2","description":"Second half of the Reading and Composition Requirement"}]},"subjectName":"COLWRIT","resources":[]}' data-node='{"termName":"2023 Spring-1",
"nid":"743547",
"nodeURL":"/content/2023-spring-colwrit-r4b-003-sem-003",
"nodeUpdated":"11/1/22, 12:12am",
"deptLink":"http://writing.berkeley.edu/",
"buildingURL":""}' data-term-details="{&quot;sessionDescription&quot;:&quot;Spring 2023&quot;,&quot;summerFees&quot;:&quot;&quot;,&quot;textbookInfo&quot;:&quot;See class syllabus or https:\/\/calstudentstore.berkeley.edu\/textbooks for the most current information.\r\n&lt;p&gt;&lt;a class='cc-button cc-small-button' href=https:\/\/calstudentstore.berkeley.edu\/textbooks for the most current information.'&gt;Textbook Lookup&lt;\/a&gt;&lt;\/p&gt;\r\nGuide to Open, Free, &amp; Affordable Course Materials\r\n&lt;p&gt;&lt;a class='cc-button cc-small-button' href=https:\/\/guides.lib.berkeley.edu\/affordable-resources&gt;eTextbooks&lt;\/a&gt;&lt;\/p&gt;&quot;,&quot;callToAction&quot;:&quot;&quot;,&quot;showFinalExamLocation&quot;:&quot;false&quot;,&quot;reservedSeatsInfo&quot;:null,&quot;enrollmentPhases&quot;:[{&quot;phase_name&quot;:&quot;Phase 1 for Continuing Students&quot;,&quot;phase_dates&quot;:{&quot;value&quot;:&quot;2022-10-17 00:00:00&quot;,&quot;value2&quot;:&quot;2022-11-06 00:00:00&quot;,&quot;timezone&quot;:&quot;America\/Los_Angeles&quot;,&quot;timezone_db&quot;:&quot;America\/Los_Angeles&quot;,&quot;date_type&quot;:&quot;datetime&quot;}},{&quot;phase_name&quot;:&quot;Phase 2 for Continuing Students&quot;,&quot;phase_dates&quot;:{&quot;value&quot;:&quot;2022-11-14 00:00:00&quot;,&quot;value2&quot;:&quot;2023-01-08 00:00:00&quot;,&quot;timezone&quot;:&quot;America\/Los_Angeles&quot;,&quot;timezone_db&quot;:&quot;America\/Los_Angeles&quot;,&quot;date_type&quot;:&quot;datetime&quot;}},{&quot;phase_name&quot;:&quot;Adjustment Period&quot;,&quot;phase_dates&quot;:{&quot;value&quot;:&quot;2023-01-09 00:00:00&quot;,&quot;value2&quot;:&quot;2023-03-24 00:00:00&quot;,&quot;timezone&quot;:&quot;America\/Los_Angeles&quot;,&quot;timezone_db&quot;:&quot;America\/Los_Angeles&quot;,&quot;date_type&quot;:&quot;datetime&quot;}},{&quot;phase_name&quot;:&quot;Phase 1 for New Undergraduate Students&quot;,&quot;phase_dates&quot;:{&quot;value&quot;:&quot;2022-11-08 00:00:00&quot;,&quot;value2&quot;:&quot;2023-01-08 00:00:00&quot;,&quot;timezone&quot;:&quot;America\/Los_Angeles&quot;,&quot;timezone_db&quot;:&quot;America\/Los_Angeles&quot;,&quot;date_type&quot;:&quot;datetime&quot;}}]}" id="">
<div class="hbr" data-template="classFull"></div>
</div>]
</code></pre>
<p>`</p>
<p>I want to get only "minEnroll":0 this data but its very complicated. How can I get this. Should I use selenium</p>
<p>I tried using only BS4. Maybe I should use selenium but I dont want it</p>
| [
{
"answer_id": 74277509,
"author": "rotgers",
"author_id": 2223566,
"author_profile": "https://Stackoverflow.com/users/2223566",
"pm_score": 3,
"selected": true,
"text": "BookID"
},
{
"answer_id": 74277969,
"author": "Dmitry Bychenko",
"author_id": 2319407,
"author_profile": "https://Stackoverflow.com/users/2319407",
"pm_score": 1,
"selected": false,
"text": "BookID"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20388953/"
] |
74,277,508 | <p>I want to build an app (in react js) for myself, my family, and some close friends (+/- 40 people). But having this app live, anyone could go on the apps web address and submit a sign up form, and yes I can write db rules that would prevent reading and mutating the data. But still the unknown user would have an empty account created. And yes if they login they would see nothing, but I don’t want them to even have an account. My idea is have a table/document with known e-mails, and only allow sign up to users if their e-mail match the one in this table/document. As the way I understand this would filter out any possible unknown “user” actors from having an account on my app. Another implementation I’m thinking of doing is when I add the e-mail to this list the e-mail owner would receive an e-mail that contains an invite link to sign up.</p>
<p>Now my question are:</p>
<p>Is this doable ?</p>
<p>If so how can I do this utilizing supabase with prisma ? And or can this be done in firebase ? I know these are 2 different worlds, but at the moment these are my only db options.</p>
<p>If y’all can point me in the right direction, what to research, or what step I should take; I would more than grateful.</p>
<p>I tried googling, but found nothing so far.</p>
| [
{
"answer_id": 74277509,
"author": "rotgers",
"author_id": 2223566,
"author_profile": "https://Stackoverflow.com/users/2223566",
"pm_score": 3,
"selected": true,
"text": "BookID"
},
{
"answer_id": 74277969,
"author": "Dmitry Bychenko",
"author_id": 2319407,
"author_profile": "https://Stackoverflow.com/users/2319407",
"pm_score": 1,
"selected": false,
"text": "BookID"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20221375/"
] |
74,277,520 | <pre><code>circle_elem = ['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy']
</code></pre>
<p>I want to simultaneously cycle/rotate each element of the above list in place
somthing like:</p>
<pre><code>circle_elem = ['bcdea', 'ghijf', 'lmnok', 'qrstp', 'vwxyu']
circle_elem = ['cdeab', 'hijfg', 'mnokl', 'rstpq', 'wxyuv']
#etc...........
</code></pre>
<p>The length of each elements in my list will always be the same</p>
<p>I TRIED:</p>
<pre><code>new_cycled_list = circular_shifts(circle_elem)
print(new_cycled_list) ##but its rotating the entire list
# and
for i in cycle(circle_elem): #but its rotating the entire list
print(i)
for ii in itertools.product(circle_elem): #this doesnt iterate all elemens separately
print(ii)
</code></pre>
<p>Any better ways to achieve the above is highly welcome.</p>
| [
{
"answer_id": 74277630,
"author": "Vincent Rupp",
"author_id": 4024409,
"author_profile": "https://Stackoverflow.com/users/4024409",
"pm_score": 0,
"selected": false,
"text": "circle_elem = ['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy']\nfirst_cycle = [y[1:]+y[0] for y in circle_elem]\n"
},
{
"answer_id": 74277651,
"author": "Axeltherabbit",
"author_id": 8340761,
"author_profile": "https://Stackoverflow.com/users/8340761",
"pm_score": 0,
"selected": false,
"text": ">>> class Cycler():\n... def __init__(self, data):\n... self.data = data\n... def __str__(self):\n... return self.data\n... def rshift(self):\n... if self.data:\n... self.data = self.data[-1] + self.data[:-1]\n... def lshift(self):\n... if self.data:\n... self.data = self.data[1:] + self.data[0]\n"
},
{
"answer_id": 74277670,
"author": "Samwise",
"author_id": 3799759,
"author_profile": "https://Stackoverflow.com/users/3799759",
"pm_score": 1,
"selected": false,
"text": ">>> def circular_shifts(elems, step=1):\n... return [e[step%len(e):] + e[:step%len(e)] for e in elems]\n...\n>>> circle_elem = ['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy']\n>>> for i in range(5):\n... print(circular_shifts(circle_elem, i))\n...\n['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy']\n['bcdea', 'ghijf', 'lmnok', 'qrstp', 'vwxyu']\n['cdeab', 'hijfg', 'mnokl', 'rstpq', 'wxyuv']\n['deabc', 'ijfgh', 'noklm', 'stpqr', 'xyuvw']\n['eabcd', 'jfghi', 'oklmn', 'tpqrs', 'yuvwx']\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19413504/"
] |
74,277,551 | <p>I am using this Perl module JSON::XS to convert a Hash to JSON , where i am creating the hash on the fly and converting it to json using the below :</p>
<pre><code>print encode_json \%hash;
</code></pre>
<p>the JSON is converted to something like this :</p>
<pre><code>{
"info": ["test","test2"],
"name": "test",
"uid": "1"
}
</code></pre>
<p>I have a .js file which have the below format and want to embed the above json using the same format on the .js in addition to the entries which are on the .js , the entries on the .js looks like this</p>
<pre><code>{
info: ['test','test2'],
name: 'test',
uid: '1'
}
</code></pre>
<p>i.e removing the ' from the keys and replacing "" with '' on the values ?any idea how to achieve this?</p>
| [
{
"answer_id": 74308893,
"author": "Narek",
"author_id": 12109508,
"author_profile": "https://Stackoverflow.com/users/12109508",
"pm_score": -1,
"selected": false,
"text": "my $json = encode_json \\%hash;\n$json =~ s/\"/'/g;\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13778586/"
] |
74,277,559 | <p>The stored procedure only has 1 declared parameter as varchar(max).</p>
<p>I need to pass multiple parameters so I combine them in a string string such as below:</p>
<pre><code>"Ref=2211010001165381;Src=ONLN;,Ref=2211010001165481;Src=ONLN;,Ref=2211010001165581;Src=ONLN;"
</code></pre>
<p>How can I split the values and assign them in their respective columns?</p>
<p>Below is my current query wherein Column Ref looks good:</p>
<pre class="lang-sql prettyprint-override"><code>WHILE LEN(@LISTMIXTRD) > 0 BEGIN
select REPLACE(LEFT(@LISTMIXTRD, CHARINDEX(';Src=', @LISTMIXTRD+';Src=')-1),'Ref=','') as Ref , LEFT(@LISTMIXTRD, CHARINDEX(';Src=', @LISTMIXTRD+';Src=')-1) as Src SET @LISTMIXTRD = STUFF(@LISTMIXTRD, 1, CHARINDEX(',', @LISTMIXTRD+','), '')
END
</code></pre>
| [
{
"answer_id": 74277781,
"author": "Larnu",
"author_id": 2029983,
"author_profile": "https://Stackoverflow.com/users/2029983",
"pm_score": 2,
"selected": false,
"text": "DECLARE @YourParameter nvarchar(MAX) = N'\"Ref=2211010001165381;Src=ONLN;,Ref=2211010001165481;Src=ONLN;,Ref=2211010001165581;Src=ONLN;\"';\n\nSELECT OJ.Ref,\n OJ.Src\nFROM STRING_SPLIT(@YourParameter,',') SS\n CROSS APPLY (VALUES(TRIM('\"; ' FROM SS.[value])))V(Trimmed)\n CROSS APPLY (VALUES(CONCAT('{\"',REPLACE(REPLACE(V.Trimmed,'=','\":\"'),';', '\",\"'),'\"}')))J(JSON)\n CROSS APPLY OPENJSON(J.JSON)\n WITH(Ref varchar(20),\n Src varchar(4)) OJ;\n"
},
{
"answer_id": 74278076,
"author": "John Cappelletti",
"author_id": 1570000,
"author_profile": "https://Stackoverflow.com/users/1570000",
"pm_score": 2,
"selected": true,
"text": "Declare @S varchar(max) ='Ref=2211010001165381;Src=ONLN;,Ref=2211010001165481;Src=ONLN;,Ref=2211010001165581;Src=ONLN;'\n\nSelect Ref = max(case when B.value like 'Ref=%' then substring(B.value,5,250) end)\n ,Src = max(case when B.value like 'Src=%' then substring(B.value,5,250) end)\n From string_split(@S,',') A\n Cross Apply string_split(A.value,';') B\n Group By A.value\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7689261/"
] |
74,277,569 | <p>I am currently wrapping my head around function binding and what binding actually is C++. Function binding is assigning an address to function?
Does only refer to when the function is called? or does binding occur when function the function is called?</p>
<p>Here is the program</p>
<pre><code>#include <iostream>
int one() { return 1; }
int main()
{
// 1. Does binding occur here when the function pointer is assigned the address of the function
int (*one_ptr)() = one;
// 2. or does binding occur here when the function is called
one_ptr();
}
</code></pre>
<p>Does binding occur when the function pointer is assigned the address of the function:</p>
<pre><code>int (*one_ptr)() = one;
</code></pre>
<p>or does the binding occur when the function is called:</p>
<pre><code>one_ptr();
</code></pre>
<p>Here is the relevant objdump of the program:</p>
<pre><code>0000000000001169 <_Z3onev>:
1169: f3 0f 1e fa endbr64
116d: 55 push rbp
116e: 48 89 e5 mov rbp,rsp
1171: b8 01 00 00 00 mov eax,0x1
1176: 5d pop rbp
1177: c3 ret
0000000000001178 <main>:
1178: f3 0f 1e fa endbr64
117c: 55 push rbp
117d: 48 89 e5 mov rbp,rsp
1180: 48 83 ec 10 sub rsp,0x10
1184: 48 8d 05 de ff ff ff lea rax,[rip+0xffffffffffffffde] # 1169 <_Z3onev>
118b: 48 89 45 f8 mov QWORD PTR [rbp-0x8],rax
118f: 48 8b 45 f8 mov rax,QWORD PTR [rbp-0x8]
1193: ff d0 call rax
1195: b8 00 00 00 00 mov eax,0x0
119a: c9 leave
119b: c3 ret
</code></pre>
<p>This is the assembly version of the function pointer being declared and initialized</p>
<pre><code>lea rax,[rip+0xffffffffffffffde] # 1169 <_Z3onev>
mov QWORD PTR [rbp-0x8],rax
</code></pre>
<p>Here, relative rip addressing is used to assign the address of the function to the local variable. The address of the function is stored in <code>rax</code> as we can see here</p>
<pre><code>lea rax,[rip+0xffffffffffffffde] # 1169 <_Z3onev>
</code></pre>
<p>So calling <code>rax</code> makes sense. It is an indirect function call (I believe).</p>
<pre><code>call rax
</code></pre>
<p>So, is the function is bound to <code>00000001169</code>, the address of <code>one()</code>? And in this case, it's static bound because the objdump is able to determine the address of the function could be determined at compile time.</p>
| [
{
"answer_id": 74278254,
"author": "rturrado",
"author_id": 260313,
"author_profile": "https://Stackoverflow.com/users/260313",
"pm_score": 1,
"selected": false,
"text": "one()"
},
{
"answer_id": 74278264,
"author": "Nicol Bolas",
"author_id": 734069,
"author_profile": "https://Stackoverflow.com/users/734069",
"pm_score": 2,
"selected": false,
"text": "one_ptr"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17934059/"
] |
74,277,636 | <p>I have a string array of product IDs, like this:
["A", "A", "B", "A"]
And another integer array of prices, like this:
[30, 50, 10, 40]</p>
<p>What would be the best way to produce a Javascript object with the unique item and its total cost, as the order of the integers are the prices associated with the same order of product numbers, so ideally it would return an object like this i.e.</p>
<p>{"A": 120, "B": 10}</p>
<p>Thank you!</p>
<p>I am relatively new to Javascript and SQL but I have tried using a foreach statement which I used successfully to produce a unique count of the item when I extract just that column into an array but not the problem as described above.</p>
| [
{
"answer_id": 74277686,
"author": "epascarello",
"author_id": 14104,
"author_profile": "https://Stackoverflow.com/users/14104",
"pm_score": 3,
"selected": true,
"text": "const productIds = [\"A\", \"A\", \"B\", \"A\"];\nconst prices = [30, 50, 10, 40]\n\nconst totals = productIds.reduce((acc, key, index) => {\n acc[key] = (acc[key] || 0) + prices[index];\n return acc;\n}, {});\n\nconsole.log(totals);"
},
{
"answer_id": 74277755,
"author": "Sowmen Rahman",
"author_id": 15658056,
"author_profile": "https://Stackoverflow.com/users/15658056",
"pm_score": 0,
"selected": false,
"text": "function getSummation(productIds, prices) {\n const store = {};\n for (let i=0; i < productIds.length; i++) {\n if (!store[productIds[i]])\n store[productIds[i]] = 0;\n \n store[productIds[i]] += prices[i];\n }\n return store;\n}\n"
},
{
"answer_id": 74277825,
"author": "mplungjan",
"author_id": 295783,
"author_profile": "https://Stackoverflow.com/users/295783",
"pm_score": 0,
"selected": false,
"text": "const products = [\"A\", \"A\", \"B\", \"A\"];\nconst prices = [30, 50, 10, 40];\nconst obj = products\n .reduce((acc,cur,i) => (acc[cur] = (acc[cur] ??= 0) + prices[i], acc),{});\nconsole.log(obj)"
},
{
"answer_id": 74277965,
"author": "Volodymyr Sichka",
"author_id": 5333324,
"author_profile": "https://Stackoverflow.com/users/5333324",
"pm_score": 0,
"selected": false,
"text": "const keys = [\"A\", \"A\", \"B\", \"A\"];\nconst values = [30, 50, 10, 40];\n\nconst result = keys.reduce((t, v, i) => ({...t, [v]: (t[v] || 0) + values[i]}), {});\nconsole.log(result);"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6852804/"
] |
74,277,645 | <p>Hello I'm using the RetroAcheivements API to build a Swift Package. Here is the JSON response:</p>
<pre class="lang-json prettyprint-override"><code>{
"recent": [
[
{
"GameID": "11310",
"ConsoleID": "12",
"ConsoleName": "PlayStation",
"Title": "Wild Arms",
"ImageIcon": "/Images/058584.png",
"LastPlayed": "2022-11-01 13:32:47",
"NumPossibleAchievements": "156",
"PossibleScore": "1075",
"NumAchieved": "15",
"ScoreAchieved": "80",
"NumAchievedHardcore": 0,
"ScoreAchievedHardcore": 0
},
{
"GameID": "11332",
"ConsoleID": "12",
"ConsoleName": "PlayStation",
"Title": "Final Fantasy Origins",
"ImageIcon": "/Images/060249.png",
"LastPlayed": "2022-10-29 07:01:53",
"NumPossibleAchievements": "120",
"PossibleScore": "945",
"NumAchieved": "4",
"ScoreAchieved": "18",
"NumAchievedHardcore": 0,
"ScoreAchievedHardcore": 0
},
{
"GameID": "11248",
"ConsoleID": "12",
"ConsoleName": "PlayStation",
"Title": "Xenogears",
"ImageIcon": "/Images/049196.png",
"LastPlayed": "2022-10-28 07:51:38",
"NumPossibleAchievements": "82",
"PossibleScore": "670",
"NumAchieved": 0,
"ScoreAchieved": 0,
"NumAchievedHardcore": 0,
"ScoreAchievedHardcore": 0
},
{
"GameID": "11255",
"ConsoleID": "12",
"ConsoleName": "PlayStation",
"Title": "Suikoden",
"ImageIcon": "/Images/054686.png",
"LastPlayed": "2022-10-28 04:55:52",
"NumPossibleAchievements": "92",
"PossibleScore": "800",
"NumAchieved": "6",
"ScoreAchieved": "30",
"NumAchievedHardcore": 0,
"ScoreAchievedHardcore": 0
},
{
"GameID": "11320",
"ConsoleID": "12",
"ConsoleName": "PlayStation",
"Title": "Gran Turismo",
"ImageIcon": "/Images/060107.png",
"LastPlayed": "2022-10-16 13:40:43",
"NumPossibleAchievements": "68",
"PossibleScore": "585",
"NumAchieved": 0,
"ScoreAchieved": 0,
"NumAchievedHardcore": 0,
"ScoreAchievedHardcore": 0
},
{
"GameID": "319",
"ConsoleID": "3",
"ConsoleName": "SNES",
"Title": "Chrono Trigger",
"ImageIcon": "/Images/063507.png",
"LastPlayed": "2022-10-11 15:50:15",
"NumPossibleAchievements": "77",
"PossibleScore": "600",
"NumAchieved": 0,
"ScoreAchieved": 0,
"NumAchievedHardcore": 0,
"ScoreAchievedHardcore": 0
}
]
]
}
</code></pre>
<p>And here is my Swift model struct generated using Quicktype.io:</p>
<pre class="lang-swift prettyprint-override"><code>struct Recents: Codable {
let recent: [[Recent]]
}
struct Recent: Codable {
let gameID, consoleID, consoleName, title: String
let imageIcon, lastPlayed: String
let numPossibleAchievements, possibleScore: Achieved
let numAchieved, scoreAchieved: Achieved
let numAchievedHardcore, scoreAchievedHardcore: Achieved
enum CodingKeys: String, CodingKey {
case gameID = "GameID"
case consoleID = "ConsoleID"
case consoleName = "ConsoleName"
case title = "Title"
case imageIcon = "ImageIcon"
case lastPlayed = "LastPlayed"
case numPossibleAchievements = "NumPossibleAchievements"
case possibleScore = "PossibleScore"
case numAchieved = "NumAchieved"
case scoreAchieved = "ScoreAchieved"
case numAchievedHardcore = "NumAchievedHardcore"
case scoreAchievedHardcore = "ScoreAchievedHardcore"
}
}
enum Achieved: Codable {
case integer(Int)
case string(String)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let x = try? container.decode(Int.self) {
self = .integer(x)
return
}
if let x = try? container.decode(String.self) {
self = .string(x)
return
}
throw DecodingError.typeMismatch(Achieved.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for Achieved"))
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .integer(let x):
try container.encode(x)
case .string(let x):
try container.encode(x)
}
}
}
</code></pre>
<p>Here is my HTTP request code:</p>
<pre class="lang-swift prettyprint-override"><code>func getRecentGames(User: String,KEY: String,OtherUser: String){
let RECENT_URL = "https://ra.hfc-essentials.com/user_recent.php?user=+\(User)+&key=+\(KEY)+&member=\(OtherUser)&results=10&mode=json"
print(RECENT_URL)
let task = session.dataTask(with: URLRequest(url: URL(string: RECENT_URL)!)) { data, response, error in
if let error = error{
print(error)
}
if let data = data{
do{
let decodedData = try JSONDecoder().decode(Recents.self, from: data)
print(decodedData.recent.joined().first!.numAchieved)
}
catch{
print(error)
}
}
}
task.resume()
}
</code></pre>
<p>How can I access the <code>NumAchievedHardcore</code> property, which can be an Int or a String sometimes? When I decode and access them like this:</p>
<pre class="lang-swift prettyprint-override"><code>print(decodedData.recent.joined().first!.numAchieved)
</code></pre>
<p>I get this output:</p>
<blockquote>
<p>string("15")</p>
</blockquote>
<p>How can I access it normally so that it does not give <code>string()</code> or <code>int()</code> as output and instead gives only the Int or String values?</p>
| [
{
"answer_id": 74277686,
"author": "epascarello",
"author_id": 14104,
"author_profile": "https://Stackoverflow.com/users/14104",
"pm_score": 3,
"selected": true,
"text": "const productIds = [\"A\", \"A\", \"B\", \"A\"];\nconst prices = [30, 50, 10, 40]\n\nconst totals = productIds.reduce((acc, key, index) => {\n acc[key] = (acc[key] || 0) + prices[index];\n return acc;\n}, {});\n\nconsole.log(totals);"
},
{
"answer_id": 74277755,
"author": "Sowmen Rahman",
"author_id": 15658056,
"author_profile": "https://Stackoverflow.com/users/15658056",
"pm_score": 0,
"selected": false,
"text": "function getSummation(productIds, prices) {\n const store = {};\n for (let i=0; i < productIds.length; i++) {\n if (!store[productIds[i]])\n store[productIds[i]] = 0;\n \n store[productIds[i]] += prices[i];\n }\n return store;\n}\n"
},
{
"answer_id": 74277825,
"author": "mplungjan",
"author_id": 295783,
"author_profile": "https://Stackoverflow.com/users/295783",
"pm_score": 0,
"selected": false,
"text": "const products = [\"A\", \"A\", \"B\", \"A\"];\nconst prices = [30, 50, 10, 40];\nconst obj = products\n .reduce((acc,cur,i) => (acc[cur] = (acc[cur] ??= 0) + prices[i], acc),{});\nconsole.log(obj)"
},
{
"answer_id": 74277965,
"author": "Volodymyr Sichka",
"author_id": 5333324,
"author_profile": "https://Stackoverflow.com/users/5333324",
"pm_score": 0,
"selected": false,
"text": "const keys = [\"A\", \"A\", \"B\", \"A\"];\nconst values = [30, 50, 10, 40];\n\nconst result = keys.reduce((t, v, i) => ({...t, [v]: (t[v] || 0) + values[i]}), {});\nconsole.log(result);"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11640506/"
] |
74,277,652 | <p>Hi I have my secrets in Secretmanager in one project and want to know how to copy them or migrate them to other project.</p>
<p>Is there a mechanism to do it smoothly.</p>
| [
{
"answer_id": 74356895,
"author": "Nben",
"author_id": 3157795,
"author_profile": "https://Stackoverflow.com/users/3157795",
"pm_score": 1,
"selected": false,
"text": "gcloud config set project [SOURCE_PROJECT]"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10141456/"
] |
74,277,731 | <p>I know it has been countlessly asked and I assure you that I've read a lot of posts, articles, etc., and watched a lot of videos but nothing seems to click.</p>
<p>so there we go :</p>
<p>Here are 2 arrays with partial information about every person</p>
<pre><code>
let arr1 = [{id:00, name:Ben, city:Philadelphia}, {id:01, name:Alice, city:Frankfurt}, {id:02, name:Detlef, city:Vienna}]
let arr2 = [{id:02, age:18}, {id:00, age:39}, {id:01, age:75}]
</code></pre>
<p>And there is the desired final result: an array including the name, city, and age of each person</p>
<pre><code>let arr3 = [{name:Ben, city:Philadelphia, age:39}, {name:Alice, city:Frankfurt, age:75 }, {name:Detlef, city:Vienna, age:18}]
</code></pre>
<p>What's the situation? Two arrays both containing objects. each nested object has an id. That id is the common key in each array of objects.</p>
<p>What do you want to do? : I want to create a third array including information from both arrays (from arr1: name and city; from arr2:age).</p>
<p>What have you tried so far? : I couldn't manage to achieve anything worth showing. this minimal example is intended to show you a simple example of my current situation which is: I've got an array that is in the LocalStorage on one hand and an API on the other, both contain some info regarding particular objects (let's say, persons). I want to create an array that will contain all the information regarding each person for easier manipulation afterward (DOM generation, etc.).</p>
<p>I've managed to store both arrays in two "local" arrays but the problem is still there: I can't figure out how to make an array where items are getting their key/value from two separate sources.</p>
<p>Thank you for your help!</p>
| [
{
"answer_id": 74356895,
"author": "Nben",
"author_id": 3157795,
"author_profile": "https://Stackoverflow.com/users/3157795",
"pm_score": 1,
"selected": false,
"text": "gcloud config set project [SOURCE_PROJECT]"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19128772/"
] |
74,277,740 | <p>I have fields like first name and last name and i want to make sure no number is passed in them. I am using formik. Is there a way to do this?</p>
| [
{
"answer_id": 74356895,
"author": "Nben",
"author_id": 3157795,
"author_profile": "https://Stackoverflow.com/users/3157795",
"pm_score": 1,
"selected": false,
"text": "gcloud config set project [SOURCE_PROJECT]"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8076491/"
] |
74,277,756 | <p>I created a python script in VS Code that runs perfectly fine.</p>
<p>I am trying to turn it into an executable for ease of access and use.</p>
<p>I have a macbook air m1 and everything should be up to date.</p>
<p>I installed pyinstaller with <code>pip install pyinstaller</code>.</p>
<p>When I run <code>pyinstall #filename</code> I get everything to run fine including the python executable inside the folder.</p>
<p>I have also tried <code>pyinstaller --windowed #filename</code> and it works fine as well according to the stuff that pops up.</p>
<p>When I run the executable my terminal opens for half a second and spews something and then it dissapears. When I check my taskbar I see terminal still open so I click on it. it shows just a blank terminal and I cannot scroll up to see what was running before hand.</p>
<p>I am not sure what I am doing wrong that is causing the exe to not run but when I run <code>python3 #filename</code> in the terminal everything runs fine.</p>
<p>Any help would be appreciated</p>
<p>I have tried not a whole lot because I am not sure what the error really is</p>
<p>I expect that when I run the python exe that was created I will get the terminal opening up and the first lines of my code asking for user input will run.</p>
<p>instead I get the terminal opening up and getting some gibberish I do not have time to read and then the terminal blanks out and I cannot see what it did.</p>
| [
{
"answer_id": 74278783,
"author": "D.L",
"author_id": 7318120,
"author_profile": "https://Stackoverflow.com/users/7318120",
"pm_score": 0,
"selected": false,
"text": "ios"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19361898/"
] |
74,277,771 | <p>I have written a code to read a csv file in c. The file contains data of games and i am supposed to read it and sort it according to the score and print the top 10 rated games. The code is as follows:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define tablesize 18626
typedef struct
{
char title[200];
char platform[20];
char Score[20];
char release_year[20];
} dict;
void printValues(dict *values)
{
for (int i = 0; i < 100; i++)
{
printf("title->%s,platform->%s,Score->%s,release->%s\n", values[i].title, values[i].platform, values[i].Score, values[i].release_year);
}
}
void sort(dict *values)
{
for (int i = 0; i < tablesize; i++)
{
for (int j = i + 1; j < tablesize; j++)
{
int a = *values[i].Score - '0';
int b = *values[j].Score - '0';
// printf("%d %d\n",values[i].Score,values[j].Score);
if (a < b)
{
dict temp = values[i];
values[i] = values[j];
values[j] = temp;
}
}
}
}
int main()
{
FILE *fp = fopen("t4_ign.csv", "r");
if (!fp)
{
printf("Error");
return 0;
}
char buff[1024];
int row = 0, column = 0;
int count = 0;
dict *values = NULL;
int i = 0;
while (fgets(buff, 1024, fp))
{
column = 0;
row++;
count++;
values = realloc(values, sizeof(dict) * count);
if (NULL == values)
{
perror("realloc");
break;
}
if (row == 1)
{
continue;
}
char *field = strtok(buff, ",");
while (field)
{
if (column == 0)
{
strcpy(values[i].title, field);
}
if (column == 1)
{
strcpy(values[i].platform, field);
}
if (column == 2)
{
strcpy(values[i].Score, field);
}
if (column == 3)
{
strcpy(values[i].release_year, field);
}
field = strtok(NULL, ",");
column++;
}
i++;
}
fclose(fp);
printf("File loaded!\n", fp);
sort(values);
printValues(values);
free(values);
return 0;
}
</code></pre>
<p>The problem i am facing is that the CSV file's Title field has commas in it and it thus differentiates the data separated by the commas as different columns which gives an error in loading the data in the struct.</p>
<p>Here are two example lines of the input file. Quotes are used when the title contains commas.</p>
<pre class="lang-none prettyprint-override"><code>"The Chronicles of Narnia: The Lion, The Witch and The Wardrobe",PlayStation 2,8,2005
The Chronicles of Narnia: Prince Caspian,Wireless,5,2008
</code></pre>
<p>Any suggestions? Thanks in advance.</p>
| [
{
"answer_id": 74280204,
"author": "Weather Vane",
"author_id": 4142924,
"author_profile": "https://Stackoverflow.com/users/4142924",
"pm_score": 2,
"selected": false,
"text": "\""
},
{
"answer_id": 74280464,
"author": "Andreas Wenzel",
"author_id": 12149471,
"author_profile": "https://Stackoverflow.com/users/12149471",
"pm_score": 0,
"selected": false,
"text": "strtok"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15682594/"
] |
74,277,774 | <p>what is the actual syntax for the for loop?
what I want to do is to calculate 2 number variables inside a function using a for a loop.
I am going over and over the internet and I cannot find anything that can help me specifically for this task I was given to do.
I am not looking for the answers, just for a guideline or a hint.
or just give me the syntax and I will try my best to adjust it to my needs.
just so you have a better understanding of the task, here it is.</p>
<pre><code>Features
Instead of hardcoding Y (the result of the Fibonacci of X), calculate it with a for loop
The calculation should be wrapped in a function, that gets X as an argument, and returns Y
After the function, you should call the function, and assign the returned value in your HTML to present to the user
</code></pre>
<p>btw, i know that i did not put the innerHTML correcly, and also i did not do the syntax right, this is actually what i am asking here.</p>
<p>thank you!!</p>
<p>i have tried this:</p>
<pre><code>var answer = document.getElementsByClassName("paragraph")
function calc (x){
for (let a = 2; a <= x; a++){
answer = document.textContent("this is a pr")
}
return calc
}
calc(2)
</code></pre>
| [
{
"answer_id": 74278270,
"author": "Frash",
"author_id": 11476283,
"author_profile": "https://Stackoverflow.com/users/11476283",
"pm_score": 1,
"selected": false,
"text": ".querySelectorAll"
},
{
"answer_id": 74278427,
"author": "Tarun Kumar Sao",
"author_id": 20389385,
"author_profile": "https://Stackoverflow.com/users/20389385",
"pm_score": 0,
"selected": false,
"text": "function calc(x){\n let sum = 0;\n for (let a=0; a<x; a++){\n sum+=a;\n }\n return sum;\n}\nconsole.log(calc(5));"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20386686/"
] |
74,277,780 | <p>I am creating a Choose Your Own adventure browser game.
I have realised that all the majority of the data that I want to fill the page (choices, selection etc...) I want to pull from my JSON and dynamically fill the page.</p>
<p>Still, I'll need to create components files to be able to create hooks routes to point at the components locations.</p>
<p>I am sure that there is a way to do this dynamically (instead than create every element manually), but I am pretty new of react, and it doesn't come up anything on top of my mind. I would gladly appreciate any help on the matter.</p>
<p>Example code of a page:</p>
<pre><code>import React from "react";
import Navigation from "components/Navigation/Navigation";
const Page1 = () => {
return (
<>
Page 1
<Navigation room={1} />
</>
);
};
export default Page1;
</code></pre>
<p>The value of "room={1}" it is indicating the id of the json is where it will pull the info. I already built this and it works. So I just have to load a number that is growing progressively.</p>
<p>What I want to try to achieve it is to have this piece of component generated to X number of entries that I have in the JSON.</p>
<p>As well I need to generate dynamically this part of the code</p>
<pre><code><Routes>
<Route path="/cyoa/page1" element={<Page1 />} />
<Route path="/cyoa/page2" element={<Page2 />} />
<Route path="/cyoa/page3" element={<Page3 />} />
<Route path="/cyoa/page4" element={<Page4 />} />
</Routes>
</code></pre>
<p>If you could please point me on the right direction I would really appreciate it.</p>
<p>You can find the whole code over here: <a href="https://github.com/Littlemad/cyoa" rel="nofollow noreferrer">https://github.com/Littlemad/cyoa</a></p>
| [
{
"answer_id": 74278270,
"author": "Frash",
"author_id": 11476283,
"author_profile": "https://Stackoverflow.com/users/11476283",
"pm_score": 1,
"selected": false,
"text": ".querySelectorAll"
},
{
"answer_id": 74278427,
"author": "Tarun Kumar Sao",
"author_id": 20389385,
"author_profile": "https://Stackoverflow.com/users/20389385",
"pm_score": 0,
"selected": false,
"text": "function calc(x){\n let sum = 0;\n for (let a=0; a<x; a++){\n sum+=a;\n }\n return sum;\n}\nconsole.log(calc(5));"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/477546/"
] |
74,277,788 | <p>I am trying to cast an Object to HashMap<String, Object> in a neat, robust way. So far, every way I tried produces compiler warnings or errors. What is the proper way to do it? I have checked the internet and tried the following:</p>
<pre><code>HashMap<String, Object> map = (HashMap<String, Object>) object;
</code></pre>
<p>The code above gives an unchecked conversion warning.</p>
<pre><code>HashMap<String, Object> map = new HashMap<>();
if (object instanceof Map<String, Object>){
map = (Map<String, Object>) object;
}
</code></pre>
<p>The code above gives an error, which says that objects cannot be compared to parameterized collections.</p>
<pre><code>HashMap<String, Object> map = new HashMap<>();
if (object instanceof Map){
Map genericMap = (Map) object;
for (Object key : genericMap.keySet()){
if (key instanceof String){
map.put((String) key, genericMap.get(key));
}
else{
throw new KeyException();
}
}
}
</code></pre>
<p>The code above yields a warning that "Map is a raw type. References to generic type Map<K,V> should be parameterized."</p>
<p>So what would be the proper way to do this? Thank you in advance!</p>
| [
{
"answer_id": 74277857,
"author": "mmartinez04",
"author_id": 20131874,
"author_profile": "https://Stackoverflow.com/users/20131874",
"pm_score": 0,
"selected": false,
"text": "@SuppressWarnings(\"unchecked\")"
},
{
"answer_id": 74277898,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 4,
"selected": true,
"text": "Object"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2532280/"
] |
74,277,796 | <p>Me need check list to lengt, but why it don't work.</p>
<p>I want deteche object, i want make destroy block as minecraft</p>
<p>How i make it:</p>
<p>i set list of objects</p>
<p>if collider touch X object and left button click - destroy target from list in first position, but if X object is X object - don't destroy object in the list</p>
<p>But i get error: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index - if collider touch obejcts: WorldMap, Water, Berries</p>
<p>i can't tell about this in details.
Best review my code:</p>
<pre><code>
using System.Collections.Generic;
using System.Collections;
using UnityEngine;
public class GetTarget : MonoBehaviour
{
[Header("Координаты блока")] // block positions
public int positionX;
public int positionY;
public int positionZ;
[Header("Получение цели")] // set list for block to destroy
public static List<GameObject> target = new List<GameObject>();
private void OnTriggerStay(Collider collider)
{
target.Insert(0, collider.gameObject);
if(target[0].name == "WorldMap") // can't destroy world map
{
if(target.Count != 0)
{
Debug.Log("Вы не можете получить " + target[0]); // you can't get (test message)
target.Remove(collider.gameObject);
}
}
if(target[0].name == "Water") // you can't destroy water in structure
{
if(target.Count != 0)
{
Debug.Log("Вы не можете получить " + target[0]); // you can't get (test message)
target.Remove(collider.gameObject);
}
}
if(target[0].name == "Berries") // you can't destroy berries
{
if(target.Count != 0)
{
Debug.Log("Вы не можете получить " + target[0]); // you can't get (test message)
target.Remove(collider.gameObject);
}
}
}
private void Update() // i get position for collider
{
Vector3 positions = transform.position;
positionX = (int)Mathf.Round(gameObject.transform.position.x);
positionY = (int)Mathf.Round(gameObject.transform.position.y);
positionZ = (int)Mathf.Round(gameObject.transform.position.z);
// set position for collider - positions = transfrom.position
positions.x = positionX;
positions.y = positionY;
positions.z = positionZ;
}
}
</code></pre>
| [
{
"answer_id": 74277857,
"author": "mmartinez04",
"author_id": 20131874,
"author_profile": "https://Stackoverflow.com/users/20131874",
"pm_score": 0,
"selected": false,
"text": "@SuppressWarnings(\"unchecked\")"
},
{
"answer_id": 74277898,
"author": "John Bollinger",
"author_id": 2402272,
"author_profile": "https://Stackoverflow.com/users/2402272",
"pm_score": 4,
"selected": true,
"text": "Object"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20364027/"
] |
74,277,809 | <p>I am trying to add custom instructions in X86_64 (amd64) ISA. I will create a binary using these instructions and then I'll run it in gem5 simulator. To find the list of unused opcodes, I am referring to <a href="http://ref.x86asm.net/coder64.html" rel="nofollow noreferrer">http://ref.x86asm.net/coder64.html</a>. However, the website only lists the single byte unused opcodes. What I am looking for is the decoder grammar of amd64 CPUs so that I can find what sequences of binary would be invalid. I tried to test out some random binary sequences to see if they are invalid and I was able to find some (for example <code>0xc5000c</code> is an invalid 3 byte instruction). However, I would like to have the grammar which amd64 CPUs use to decode the instructions to derive even longer invalid binary sequences. Are there any resources available for this task?</p>
<p>Currently, to find binary sequences, I am using a C program which looks like:</p>
<pre><code>int main()
{
asm volatile(".byte 0x06" ::: "memory");
asm volatile(".byte 0x07" ::: "memory");
asm volatile(".byte 0x0E" ::: "memory");
asm volatile(".byte 0x16" ::: "memory");
asm volatile(".byte 0x17" ::: "memory");
asm volatile(".byte 0x1E" ::: "memory");
asm volatile(".byte 0x1F" ::: "memory");
asm volatile(".byte 0x27" ::: "memory");
asm volatile(".byte 0x2F" ::: "memory");
asm volatile(".byte 0x37" ::: "memory");
asm volatile(".byte 0x3F" ::: "memory");
asm volatile(".byte 0x60" ::: "memory");
asm volatile(".byte 0x61" ::: "memory");
asm volatile(".byte 0x62" ::: "memory");
asm volatile(".byte 0x82" ::: "memory");
asm volatile(".byte 0x9A" ::: "memory");
asm volatile(".byte 0xC4" ::: "memory");
asm volatile(".byte 0xC5" ::: "memory");
asm volatile(".byte 0xD4" ::: "memory");
asm volatile(".byte 0xD5" ::: "memory");
asm volatile(".byte 0xD6" ::: "memory");
asm volatile(".byte 0xEA" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x00" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x01" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x02" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x03" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x04" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x05" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x06" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x07" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x08" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x09" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x0A" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x0B" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x0C" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x0D" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x0E" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x0F" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x10" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x11" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x13" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x17" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x18" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x19" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x1A" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x1B" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x1C" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x1D" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x1E" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x1F" ::: "memory");
asm volatile(".byte 0xC5, 0x00, 0x01" ::: "memory");
return 0;
}
</code></pre>
<p>To see if the instruction is invalid, I compile the program to an executable and then dump its binary with <code>objdump</code> using the following command:
<code>gcc main.c && objdump -D -j .text a.out</code>. When I run this with the C program I get:</p>
<pre><code>...
10ed: c6 05 1c 2f 00 00 01 movb $0x1,0x2f1c(%rip) # 4010 <__TMC_END__>
10f4: 5d pop %rbp
10f5: c3 ret
10f6: 66 2e 0f 1f 84 00 00 cs nopw 0x0(%rax,%rax,1)
10fd: 00 00 00
1100: c3 ret
1101: 66 66 2e 0f 1f 84 00 data16 cs nopw 0x0(%rax,%rax,1)
1108: 00 00 00 00
110c: 0f 1f 40 00 nopl 0x0(%rax)
0000000000001110 <frame_dummy>:
1110: f3 0f 1e fa endbr64
1114: e9 67 ff ff ff jmp 1080 <register_tm_clones>
0000000000001119 <main>:
1119: 55 push %rbp
111a: 48 89 e5 mov %rsp,%rbp
111d: 06 (bad)
111e: 07 (bad)
111f: 0e (bad)
1120: 16 (bad)
1121: 17 (bad)
1122: 1e (bad)
1123: 1f (bad)
1124: 27 (bad)
1125: 2f (bad)
1126: 37 (bad)
1127: 3f (bad)
1128: 60 (bad)
1129: 61 (bad)
112a: 62 82 (bad)
112c: 9a (bad)
112d: c4 (bad)
112e: c5 d4 d5 (bad)
1131: d6 (bad)
1132: ea (bad)
1133: c5 00 00 (bad)
1136: c5 00 01 (bad)
1139: c5 00 02 (bad)
113c: c5 00 03 (bad)
113f: c5 00 04 (bad)
1142: c5 00 05 (bad)
1145: c5 00 06 (bad)
1148: c5 00 07 (bad)
114b: c5 00 08 (bad)
114e: c5 00 09 (bad)
1151: c5 00 0a (bad)
1154: c5 00 0b (bad)
1157: c5 00 0c (bad)
115a: c5 00 0d (bad)
115d: c5 00 0e (bad)
1160: c5 00 0f (bad)
1163: c5 00 10 (bad)
1166: c5 00 11 (bad)
1169: c5 00 13 (bad)
116c: c5 00 17 (bad)
116f: c5 00 18 (bad)
1172: c5 00 19 (bad)
1175: c5 00 1a (bad)
1178: c5 00 1b (bad)
117b: c5 00 1c (bad)
117e: c5 00 1d (bad)
1181: c5 00 1e (bad)
1184: c5 00 1f (bad)
1187: c5 00 01 (bad)
118a: b8 00 00 00 00 mov $0x0,%eax
118f: 5d pop %rbp
1190: c3 ret
</code></pre>
<p>What I am looking for is a faster way to find such invalid binary sequences which would preferably not involve the brute force approach that I am using.</p>
| [
{
"answer_id": 74278524,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "UD1"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19827830/"
] |
74,277,818 | <p>Newbie at coding, doing this for university. I have written a dictionary which translates codons into single letter amino acids. However, my function can't find the keys in the dict and just adds an X to the list I've made. See code below:</p>
<pre><code>codon_table = {('TTT', 'TTC'): 'F',
('TTA', 'TTG', 'CTT', 'CTC', 'CTA', 'CTG'): 'L',
('ATT', 'ATC', 'ATA'): 'I',
('ATG'): 'M',
('GTT', 'GTC', 'GTA', 'GTG'): 'V',
('TCT', 'TCC', 'TCA', 'TCG'): 'S',
('CCT', 'CCC', 'CCA', 'CCG'): 'P',
('ACT', 'ACC', 'ACA', 'ACG'): 'T',
('GCT', 'GCC', 'GCA', 'GCG'): 'A',
('TAT', 'TAC'): 'Y',
('CAT', 'CAC'): 'H',
('CAA', 'CAG'): 'Q',
('AAT', 'AAC'): 'N',
('AAA', 'AAG'): 'K',
('GAT', 'GAC'): 'D',
('GAA', 'GAG'): 'E',
('TGT', 'TGC'): 'C',
('TGG'): 'W',
('CGT', 'CGC', 'CGA', 'CGG', 'AGA', 'AGG'): 'R',
('AGT', 'AGC'): 'S',
('GGT', 'GGC', 'GGA', 'GGG'): 'G',
('TAA', 'TAG', 'TGA'): '*',
}
AA_seq = []
input_DNA = str(input('Please input a DNA string: '))
def translate_dna():
list(input_DNA)
global AA_seq
for codon in range(0, len(input_DNA), 3):
if codon in codon_table:
AA_seq = codon_table[codon]
AA_seq.append(codon_table[codon])
else:
AA_seq.append('X')
print(str(' '.join(AA_seq)).strip('[]').replace("'", ""))
translate_dna()
</code></pre>
<p>Inputted a DNA sequence, eg TGCATGCTACGTAGCGGACCTGG, which would only return XXXXXXX. What I would expect is a string of single letters corresponding to the amino acids in the dict.</p>
<p>I've been staring at it for the best part of an hour, so I figured it's time to ask the experts. Thanks in advance.</p>
| [
{
"answer_id": 74277953,
"author": "Jimpsoni",
"author_id": 18195201,
"author_profile": "https://Stackoverflow.com/users/18195201",
"pm_score": 0,
"selected": false,
"text": "for"
},
{
"answer_id": 74277964,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 1,
"selected": false,
"text": "from functools import cache\n\ncodon_table = {('TTT', 'TTC'): 'F',\n ('TTA', 'TTG', 'CTT', 'CTC', 'CTA', 'CTG'): 'L',\n ('ATT', 'ATC', 'ATA'): 'I',\n ('ATG'): 'M',\n ('GTT', 'GTC', 'GTA', 'GTG'): 'V',\n ('TCT', 'TCC', 'TCA', 'TCG'): 'S',\n ('CCT', 'CCC', 'CCA', 'CCG'): 'P',\n ('ACT', 'ACC', 'ACA', 'ACG'): 'T',\n ('GCT', 'GCC', 'GCA', 'GCG'): 'A',\n ('TAT', 'TAC'): 'Y',\n ('CAT', 'CAC'): 'H',\n ('CAA', 'CAG'): 'Q',\n ('AAT', 'AAC'): 'N',\n ('AAA', 'AAG'): 'K',\n ('GAT', 'GAC'): 'D',\n ('GAA', 'GAG'): 'E',\n ('TGT', 'TGC'): 'C',\n ('TGG'): 'W',\n ('CGT', 'CGC', 'CGA', 'CGG', 'AGA', 'AGG'): 'R',\n ('AGT', 'AGC'): 'S',\n ('GGT', 'GGC', 'GGA', 'GGG'): 'G',\n ('TAA', 'TAG', 'TGA'): '*',\n }\n\n@cache\ndef lookup(codon):\n for k, v in codon_table.items():\n if codon in k:\n return v\n return '?'\n\n\nsequence = 'TGCATGCTACGTAGCGGACCTGG'\n\nAA_Seq = []\n\nfor i in range(0, len(sequence), 3):\n AA_Seq.append(lookup(sequence[i:i+3]))\n\nprint(AA_Seq)\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20389154/"
] |
74,277,835 | <p>I am attempting to use <code>ggplot2</code> to create a weighted density plot showing the distribution of two groups that each account for a fraction of a certain distribution. The difficulty that I am encountering stems from the fact that although both groups have the same number of observations in the data, they have different weightings, and I would like for each group's area in the graph to reflect this difference in weightings.</p>
<p>My data look something like this.</p>
<pre><code>var <- sort(rnorm(1000, mean = 5, sd = 2))
df <- tibble(id = c(rep(1, 1000), rep(2, 1000)),
var = c(var,var),
weight = c(rep(.1, 500), rep(.2, 500), rep(.9, 500), rep(.8, 500)))
</code></pre>
<p>Observe that, group 1 is given low weightings (.1 or .2) while group 2 is given high weighting of (.9 or .8). Also observe that for any given value of <code>var</code> has weightings that add up to 1. In the real data, the shares accounted for by each group differ in a more complex manner across the distribution of <code>var</code>.</p>
<p>I have tried plotting this data as follows, and although using weight captures the way that the distributions vary within each group, it does not capture the way that the distribution varies <em>between</em> groups.</p>
<pre><code>library(ggplot2)
var <- rnorm(1000, mean = 5, sd = 2)
df %>%
ggplot(aes(x = var, group = id, fill = factor(id), weight = weight)) +
geom_density(position = 'stack')
</code></pre>
<p>The resulting plot looks something like this.
<a href="https://i.stack.imgur.com/2EYD8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2EYD8.png" alt="enter image description here" /></a></p>
<p>It is clear that the groups do not account for around 15% and 85% of the area under the density curve respectively, but the issue is clearer to see when we use <code>position = 'fill'</code>.</p>
<p><a href="https://i.stack.imgur.com/pHzkI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pHzkI.png" alt="enter image description here" /></a></p>
<p>Each group seems to take up a similar area, apparently because the weighting is applied before grouping is accounted for. I would like to see a solution that results in the area associated with group 1 being commensurate with it's weight (i.e. much smaller than the area associated with group 2).</p>
<p>To clarify, it is the height associated with each group that should differ. In the above plot, the line of demarcation between group 1 and group 2 should be significantly higher, making the area taken up by group 1 significantly smaller.</p>
| [
{
"answer_id": 74278790,
"author": "Quinten",
"author_id": 14282714,
"author_profile": "https://Stackoverflow.com/users/14282714",
"pm_score": 0,
"selected": false,
"text": "library(ggplot2)\nlibrary(dplyr)\n\n# Stacked\ndf %>%\n mutate(weighted_var = var*weight) %>%\n ggplot(aes(x = weighted_var, fill = factor(id), group = id)) +\n geom_density(position = 'stack')\n"
},
{
"answer_id": 74278977,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 3,
"selected": true,
"text": "geom_area"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9358374/"
] |
74,277,849 | <p>I am at the beggining of Get Programming with Haskell and just learned lambda functions. As an exercise I tried to convert the following example to use a lambda.</p>
<pre><code>calcChange owed given =
if change > 0
then change
else 0
where change = given - owed
</code></pre>
<p><code>calcChange 9 7</code> returns <code>0</code> and <code>calcChange 7 9</code> returns <code>2</code></p>
<p>Now, here is my attempt</p>
<pre><code>calcChange owed given =
(\change ->
if change > 0
then change
else 0
) given - owed
</code></pre>
<p>which fails: <code>calcChange 7 9</code> returns <code>2</code> but <code>calcChange 9 7</code> returns <code>-2</code>.</p>
<p>What is wrong with my attempt?</p>
| [
{
"answer_id": 74277937,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "change"
},
{
"answer_id": 74277998,
"author": "molbdnilo",
"author_id": 404970,
"author_profile": "https://Stackoverflow.com/users/404970",
"pm_score": 2,
"selected": false,
"text": "given"
},
{
"answer_id": 74278273,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 1,
"selected": false,
"text": "(\\change ->\n if change > 0\n then change\n else 0\n) given - owed\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15005121/"
] |
74,277,868 | <p>I have a field that is integer format <code>20220801</code> that needs to be converted to a date field. I then need to use this field in a WHERE clause compared against the <code>CURRENT DATE</code>. This is specifically for DB2.</p>
<p>Every time I try to do this I receive this error message:</p>
<p><a href="https://i.stack.imgur.com/ZROLU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZROLU.png" alt="DB2 Error Message" /></a></p>
<p>Here are some snippets I've tried unsuccessfully, each time returning the above error</p>
<pre><code>SELECT
DATE(TIMESTAMP_FORMAT(CHAR(BWDUED), 'YYYYMMDD')) AS DUE_DATE,
CURRENT DATE AS TODAY_DATE
FROM
SCHEMA.TABLE
WHERE
DATE(TIMESTAMP_FORMAT(CHAR(BWDUED), 'YYYYMMDD')) = CURRENT_DATE
</code></pre>
<pre><code>SELECT
DATE(TO_DATE(CHAR(BWDUED), 'YYYYMMDD')) AS DUE_DATE,
CURRENT DATE AS TODAY_DATE
FROM
SCHEMA.TABLE
WHERE
DATE(TO_DATE(CHAR(BWDUED), 'YYYYMMDD')) = CURRENT_DATE
</code></pre>
<p>I've looked at many of the answers on here, but none of them have gotten me past this error. Any help on navigating this would be appreciated!</p>
| [
{
"answer_id": 74277937,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "change"
},
{
"answer_id": 74277998,
"author": "molbdnilo",
"author_id": 404970,
"author_profile": "https://Stackoverflow.com/users/404970",
"pm_score": 2,
"selected": false,
"text": "given"
},
{
"answer_id": 74278273,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 1,
"selected": false,
"text": "(\\change ->\n if change > 0\n then change\n else 0\n) given - owed\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17196927/"
] |
74,277,873 | <p>I wanted to calculate the user scroll height , so I created a custom hook. and I wanted to share this value to another component. but it doesnt work.
code:</p>
<pre><code>const useScroll = () => {
let scrollHeight = useRef(0);
const scroll = () => {
scrollHeight.current =
window.pageYOffset ||
(document.documentElement || document.body.parentNode || document.body)
.scrollTop;
};
useEffect(() => {
window.addEventListener("scroll", scroll);
return () => {
window.removeEventListener("scroll", () => {});
};
}, []);
return scrollHeight.current;
};
export default useScroll;
</code></pre>
<p>the value is not updating here.</p>
<p>but if I use <code>useState </code> here , it works. but that causes tremendous amount of component re-rendering. can you have any idea , how its happening?</p>
| [
{
"answer_id": 74277937,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "change"
},
{
"answer_id": 74277998,
"author": "molbdnilo",
"author_id": 404970,
"author_profile": "https://Stackoverflow.com/users/404970",
"pm_score": 2,
"selected": false,
"text": "given"
},
{
"answer_id": 74278273,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 1,
"selected": false,
"text": "(\\change ->\n if change > 0\n then change\n else 0\n) given - owed\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19761597/"
] |
74,277,878 | <p>I have a list (in a dataframe) that looks like this:</p>
<pre><code>oddnum = [1, 3, 5, 7, 9, 11, 23]
</code></pre>
<p>I want to create a new list that looks like this:</p>
<pre><code>newlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 23]
</code></pre>
<ol>
<li><p>I want to test if the distance between two numbers is 2 (if oddnum[index+1]-oddnum[index] == 2)</p>
</li>
<li><p>If the distance is 2, then I want to add the number following oddnum[index] and create a new list (oddnum[index] + 1)</p>
</li>
<li><p>If the distance is greater than two, keep the list as is</p>
</li>
</ol>
<p>I keep getting key error because (I think) the list runs out of [index] and [index+1] no longer exists once it reaches the end of the list. How do I do this?</p>
| [
{
"answer_id": 74277937,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "change"
},
{
"answer_id": 74277998,
"author": "molbdnilo",
"author_id": 404970,
"author_profile": "https://Stackoverflow.com/users/404970",
"pm_score": 2,
"selected": false,
"text": "given"
},
{
"answer_id": 74278273,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 1,
"selected": false,
"text": "(\\change ->\n if change > 0\n then change\n else 0\n) given - owed\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15141497/"
] |
74,277,879 | <p>Let's say you have the following component "template1" which is a template for all the ids you want. But also let's assume there are several other of these templates as well as "home", "about us" etc. So let's say you have so many ids that it isn't feasible to make individual pages for them. How would you go about doing this in a scalable way? The way I am seeing it in my minds eye would be something like /template1/5Exo4a /template2/5Exo4a for the same id accross multiple templates or /template1/5Exo4a /template1/5A3z4a for same template but different ids.</p>
<p>I am using vite + react typescript and currently have my app.tsx set up like so. Where SidePanel selects the individual ids etc. So would I need to step up that functionality to the app.tsx? Or am I able to just pass the ids back somehow?</p>
<pre><code>function App() {
return (
<Router>
<div className="App">
<SidePanel/>
<Routes>
<Route path="/" element={<Home />}/>
<Route path="/template1" element={<template1/>}/>
<Route path="/template2" element={<template2/>}/>
<Route path="/template3" element={<template3/>}/>
<Route path="/template4" element={<template4/>}/>
<Route path="/template5" element={<template5/>}/>
</Routes>
<SecondaryPanel/>
</div>
</Router>
)
}
</code></pre>
| [
{
"answer_id": 74277937,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": "change"
},
{
"answer_id": 74277998,
"author": "molbdnilo",
"author_id": 404970,
"author_profile": "https://Stackoverflow.com/users/404970",
"pm_score": 2,
"selected": false,
"text": "given"
},
{
"answer_id": 74278273,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 1,
"selected": false,
"text": "(\\change ->\n if change > 0\n then change\n else 0\n) given - owed\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8684461/"
] |
74,277,888 | <p>I am trying to test individual components for my Angular project following the guidelines set up in the official Cypress <a href="https://docs.cypress.io/guides/component-testing/testing-angular#Selecting-the-StepperComponent" rel="nofollow noreferrer">documentation</a>.</p>
<p>I have created the following <code>cy.ts</code> file for one of my components</p>
<pre><code>import {SpInputComponent} from "[abriged]/sp-input.component";
describe('Sp-Input component', () => {
it('mounts', () => {
cy.mount('<app-sp-input></app-sp-input>', {
declarations: [SpInputComponent]
})
})
})
</code></pre>
<p>Unfortunately, when I try to run the test in Cypress, I get the following <code>NullInjectionError</code>.
<a href="https://i.stack.imgur.com/X3QH4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X3QH4.png" alt="enter image description here" /></a></p>
<p>The component in question uses a service that is dependent on <code>HttpClient</code> (i.e. uses <code>HttpClient</code> in its constructor). I tried importing the <code>HttpClient</code> module as well as the service that uses it into the test file without success.</p>
<p>Any suggestions would be appreciated.</p>
| [
{
"answer_id": 74279151,
"author": "Yew Hong Tat",
"author_id": 1925886,
"author_profile": "https://Stackoverflow.com/users/1925886",
"pm_score": 0,
"selected": false,
"text": "describe('Sp-Input component', () => {\n it('mounts', () => {\n cy.mount('<app-sp-input></app-sp-input>', {\n declarations: [SpInputComponent],\n imports: [HttpClientTestingModule] // <-- you need this\n })\n })\n})\n"
},
{
"answer_id": 74279153,
"author": "E. Maggini",
"author_id": 796446,
"author_profile": "https://Stackoverflow.com/users/796446",
"pm_score": 0,
"selected": false,
"text": "import {SpInputComponent} from \"[abriged]/sp-input.component\";\nimport { HttpClientTestingModule } from '@angular/common/http/testing';\n\ndescribe('Sp-Input component', () => {\n it('mounts', () => {\n cy.mount('<app-sp-input></app-sp-input>', {\n declarations: [SpInputComponent],\n providers: [HttpClientTestingModule]\n })\n })\n})\n"
},
{
"answer_id": 74280698,
"author": "liberlux",
"author_id": 18794136,
"author_profile": "https://Stackoverflow.com/users/18794136",
"pm_score": 1,
"selected": false,
"text": "ToolboxRepositoryService"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18794136/"
] |
74,277,931 | <p>I need to retrieve the local (not server) machine name on an intranet web application. After a lot of searching, it looks like the below should work...</p>
<pre><code>Dim Name As String = (Dns.GetHostEntry(Request.ServerVariables("REMOTE_HOST")).HostName)
</code></pre>
<p>However, this returns the error "No such host is known". Any ideas where I'm going wrong here?</p>
<p>Thanks</p>
| [
{
"answer_id": 74279151,
"author": "Yew Hong Tat",
"author_id": 1925886,
"author_profile": "https://Stackoverflow.com/users/1925886",
"pm_score": 0,
"selected": false,
"text": "describe('Sp-Input component', () => {\n it('mounts', () => {\n cy.mount('<app-sp-input></app-sp-input>', {\n declarations: [SpInputComponent],\n imports: [HttpClientTestingModule] // <-- you need this\n })\n })\n})\n"
},
{
"answer_id": 74279153,
"author": "E. Maggini",
"author_id": 796446,
"author_profile": "https://Stackoverflow.com/users/796446",
"pm_score": 0,
"selected": false,
"text": "import {SpInputComponent} from \"[abriged]/sp-input.component\";\nimport { HttpClientTestingModule } from '@angular/common/http/testing';\n\ndescribe('Sp-Input component', () => {\n it('mounts', () => {\n cy.mount('<app-sp-input></app-sp-input>', {\n declarations: [SpInputComponent],\n providers: [HttpClientTestingModule]\n })\n })\n})\n"
},
{
"answer_id": 74280698,
"author": "liberlux",
"author_id": 18794136,
"author_profile": "https://Stackoverflow.com/users/18794136",
"pm_score": 1,
"selected": false,
"text": "ToolboxRepositoryService"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8070705/"
] |
74,277,945 | <p>I have a unit test class method that currently takes 1 parameter but I want to extend it to receive 2 parameters with the latter being the number of times invocation is met on a mock object.
What I currently have is something like this, which doesn't compile successfully due to errors</p>
<pre><code>[Theory]
[InlineData("", Times.Never)]
[InlineData("test", Times.Once)]
public async void PostAsync_SendAsync_VerifyOnce(string id, Times outcome)
{
var mockClients = new Mock<IHubClients>();
...
...
...
mockClients.Verify(clients => clients.Client(id), outcome);
}
</code></pre>
<p>Is it possible to achieve something like this? So in theory both tests here should pass, the first will never be invocated as the first parameter is blank and the second test will be invocated once as the parameter is valid.</p>
| [
{
"answer_id": 74278029,
"author": "YungDeiza",
"author_id": 19214431,
"author_profile": "https://Stackoverflow.com/users/19214431",
"pm_score": 3,
"selected": true,
"text": "Times.Exactly"
},
{
"answer_id": 74278182,
"author": "pfx",
"author_id": 9200675,
"author_profile": "https://Stackoverflow.com/users/9200675",
"pm_score": 1,
"selected": false,
"text": "TheoryData"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1138980/"
] |
74,277,957 | <p>I need to compose a regular expression for string, with a max length of 6 characters, containing only Latin letters in lowercase, with an optional underscore separator, without underscore starting and trailing.</p>
<p>I tried the following</p>
<pre><code>^[a-z_]{1,6}$
</code></pre>
<p>But it allows underscore at the start and the end.</p>
<p>I also tried:</p>
<pre><code>^([a-z]_?[a-z]){1,6}$
^(([a-z]+)_?([a-z]+)){1,6}$
^([a-z](?:_?)[a-z]){1,6}$
</code></pre>
<p>But nothing works. Please help.</p>
<p><strong>Expecting:</strong></p>
<p><strong>Valid:</strong></p>
<p>ex_bar</p>
<p><strong>Not valid:</strong></p>
<p>_exbar</p>
<p>exbar_</p>
<p>_test_</p>
| [
{
"answer_id": 74278009,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": true,
"text": "^(?!.{7,}$)[a-z](?:[a-z_]*[a-z])*$\n"
},
{
"answer_id": 74278059,
"author": "JRiggles",
"author_id": 8512262,
"author_profile": "https://Stackoverflow.com/users/8512262",
"pm_score": 2,
"selected": false,
"text": "^(?!_)[a-z_]{0,5}[a-z]$"
},
{
"answer_id": 74278165,
"author": "Samuel Cook",
"author_id": 1714715,
"author_profile": "https://Stackoverflow.com/users/1714715",
"pm_score": 1,
"selected": false,
"text": "(?!^_)([a-z_]{6})(?<!_$)"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14297019/"
] |
74,277,983 | <p>Here is my code I also tried it without quotes but it gives me ('html' is not defined) error</p>
<pre><code>@app.route('/entry')
def entry_page() -> 'html':
return render_template('entry.html',
the_title='Welcome to searchtools on the web!')
app.run()
</code></pre>
| [
{
"answer_id": 74278009,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": true,
"text": "^(?!.{7,}$)[a-z](?:[a-z_]*[a-z])*$\n"
},
{
"answer_id": 74278059,
"author": "JRiggles",
"author_id": 8512262,
"author_profile": "https://Stackoverflow.com/users/8512262",
"pm_score": 2,
"selected": false,
"text": "^(?!_)[a-z_]{0,5}[a-z]$"
},
{
"answer_id": 74278165,
"author": "Samuel Cook",
"author_id": 1714715,
"author_profile": "https://Stackoverflow.com/users/1714715",
"pm_score": 1,
"selected": false,
"text": "(?!^_)([a-z_]{6})(?<!_$)"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16673694/"
] |
74,277,985 | <p><a href="https://i.stack.imgur.com/GXLqP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GXLqP.png" alt="enter image description here" /></a></p>
<p>This is a python code for Rock Paper Scissor game, played by the user and computer. The score of the user is the variable and the score of the computer is computer_score which are incremented if the conditions fulfilled. The incrementation is not working as player1_score remains 0 even after winning and computer_score is incrementing every five times the loop runs, even when it is losing.
Here is the whole code:</p>
<pre><code>import random
hand = ["R","P","S"]
def game():
player1_score = 0
computer_score = 0
i=0
while (i<5):
print("Enter R for ROCK \nEnter P for PAPER\nEnter S for SCISOR")
your_hand = input(player1 + " picks: ").upper()
if your_hand not in hand:
continue
computer_hand = random.randint(0,2)
print("Computer picks: ", hand[computer_hand])
if your_hand == "R" and computer_hand == "S":
player1_score += 1
print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score))
elif your_hand == "P" and computer_hand == "R":
player1_score += 1
print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score))
elif your_hand == "S" and computer_hand == "P":
player1_score += 1
print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score))
else:
computer_score += 1
print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score))
i += 1
print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score))
print("\t\t\tWELCOME TO ROCK PAPER SCISORS!")
print("\t\t\tRemember this: \n\t\t\t\t SCISORS KILLS PAPER \n\t\t\t\t PAPER KILLS STONE \n\t\t\t\t STONE KILLS SCISORS")
player1 = input("Player 1 Enter your name: ")
print("Player 2: Hello! " + player1 +". I am your COMPUTER!")
print("SO SHALL WE : \n\t1. PLAY \n\t2. EXIT")
start = int(input("Enter the choice: "))
if start == 1:
game()
else:
exit()
</code></pre>
<p>Where should I make the change?</p>
| [
{
"answer_id": 74278009,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": true,
"text": "^(?!.{7,}$)[a-z](?:[a-z_]*[a-z])*$\n"
},
{
"answer_id": 74278059,
"author": "JRiggles",
"author_id": 8512262,
"author_profile": "https://Stackoverflow.com/users/8512262",
"pm_score": 2,
"selected": false,
"text": "^(?!_)[a-z_]{0,5}[a-z]$"
},
{
"answer_id": 74278165,
"author": "Samuel Cook",
"author_id": 1714715,
"author_profile": "https://Stackoverflow.com/users/1714715",
"pm_score": 1,
"selected": false,
"text": "(?!^_)([a-z_]{6})(?<!_$)"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74277985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20084630/"
] |
74,278,022 | <p>I have to write a program that takes a String as user input and then prints a substring that starts with the first vowel of the String and ends with the last. So for instance if my String is : "Hi I have a dog named Patch", the printed substring would be : "i I have a dog named Pa"</p>
<p>This is the code I have now:</p>
<pre><code>import java.util.Scanner;
import java.util.*;
public class SousChaineVoyelle {
private static Scanner sc;
public static void main (String[] args) {
sc = new Scanner(System.in);
System.out.print("Enter a String: ");
String str = sc.nextLine();
int pos1 = 0;
int pos2 = 0;
int i;
int j;
boolean isVowel1 = false;
boolean isVowel2 = false;
for (i = 0; i < str.length(); i++){
if (str.charAt(i) == 'A' || str.charAt(i) == 'a' ||
chaine.charAt(i) == 'E' || str.charAt(i) == 'e' ||
str.charAt(i) == 'I' || str.charAt(i) == 'i' ||
str.charAt(i) == 'O' || str.charAt(i) == 'o' ||
str.charAt(i) == 'U' || str.charAt(i) == 'u' ||
str.charAt(i) == 'Y' || str.charAt(i) == 'y'){
isVowel1 = true;
break;
}
}
if (isVowel1){
pos1 = str.charAt(i);
}
for (j = str.length() - 1; j > i; j--){
if (str.charAt(j) == 'A' || str.charAt(j) == 'a' ||
str.charAt(j) == 'E' || str.charAt(j) == 'e' ||
str.charAt(j) == 'I' || str.charAt(j) == 'i' ||
str.charAt(j) == 'O' || str.charAt(j) == 'o' ||
str.charAt(j) == 'U' || str.charAt(j) == 'u' ||
str.charAt(j) == 'Y' || str.charAt(j) == 'y'){
isVowel2 = true;
break;
}
}
if (isVowel2){
pos2 = str.charAt(j);
}
String sub = chaine.substring(pos1, pos2);
System.out.print(The substring from the first vowel to the last is "\"" + sub +"\"");
}
}
this got me this:
</code></pre>
<p>Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 22
at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:55)
at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:52)
at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:213)
at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:210)
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:98)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:106)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:302)
at java.base/java.lang.String.checkIndex(String.java:4557)
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:46)
at java.base/java.lang.String.charAt(String.java:1515)
at SousChaineVoyelle.main(SousChaineVoyelle.java:33)</p>
<pre><code></code></pre>
| [
{
"answer_id": 74279051,
"author": "Bohemian",
"author_id": 256196,
"author_profile": "https://Stackoverflow.com/users/256196",
"pm_score": 1,
"selected": false,
"text": "str = str.replaceAll(\"(?i)^[^aeiou]*|[^aeiou]*$\", \"\");\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20389234/"
] |
74,278,084 | <p>I am getting id of single product from backend using match.params but I got error please help me to solve this error</p>
<pre><code>
import React, { useEffect } from "react";
import Carousel from "react-material-ui-carousel";
import "./ProductDetail.css";
import { useSelector, useDispatch } from "react-redux";
import { getProductDetails } from "../../actions/productActions";
const ProductDetail = ({ match }) => {
const dispatch = useDispatch();
const { product, loading, error } = useSelector(
(state) => state.productDetail
);
useEffect(
() => {
dispatch(getProductDetails(match.params.id));
},
[dispatch, match.params.id]
);
</code></pre>
<p>I am getting this error:</p>
<p>TypeError: Cannot read properties of undefined (reading 'params')</p>
<pre><code> | useEffect(
15 | () => {
16 | dispatch(getProductDetails(match.params.id));
> 17 | },
| ^ 18 | [dispatch, match.params.id]
19 | );
</code></pre>
<blockquote class="spoiler">
<p> please provide the solution of this or any other way to do this ??</p>
</blockquote>
| [
{
"answer_id": 74279051,
"author": "Bohemian",
"author_id": 256196,
"author_profile": "https://Stackoverflow.com/users/256196",
"pm_score": 1,
"selected": false,
"text": "str = str.replaceAll(\"(?i)^[^aeiou]*|[^aeiou]*$\", \"\");\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20389263/"
] |
74,278,089 | <p>Hi i wanna draw a pyramid that look like this</p>
<pre><code> /\
/ \
/ \
/______\
</code></pre>
<p>in Microsoft visual studio c# language but it's not working</p>
<p>i used this code in Microsoft visual studio</p>
<pre><code>using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(" /\ ");
Console.WriteLine(" / \ ");
Console.WriteLine(" / \ ");
Console.WriteLine("/______\ ");
Console.ReadLine();
}
}
}
</code></pre>
<p>but it's not working</p>
<pre><code>please explain to me if possible why not working why your code is working in other words (what i need to know )
</code></pre>
| [
{
"answer_id": 74279051,
"author": "Bohemian",
"author_id": 256196,
"author_profile": "https://Stackoverflow.com/users/256196",
"pm_score": 1,
"selected": false,
"text": "str = str.replaceAll(\"(?i)^[^aeiou]*|[^aeiou]*$\", \"\");\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20389274/"
] |
74,278,096 | <p>In my app, I need an array of diagnosis codes in the form of
['Z57.1', 'Z74.3', 'M51.2'] so I can have access to each of them.</p>
<p>However, when mapping through diagnosis codes, I get [Array(3)] in the console instead of ['Z57.1', 'Z74.3', 'M51.2'], meaning I can't get access to the codes.</p>
<p>How do you map through patient.entries to return ['Z57.1', 'Z74.3', 'M51.2'] in the console instead of [Array(3)]?</p>
<pre><code> const patient = {
id: 'd2773598-f723-11e9-8f0b-362b9e155667',
name: 'Martin Riggs',
dateOfBirth: '1979-01-30',
ssn: '300179-777A',
gender: Gender.male,
occupation: 'Cop',
entries: [
{
id: 'fcd59fa6-c4b4-4fec-ac4d-df4fe1f85f62',
date: '2019-08-05',
type: 'OccupationalHealthcare',
specialist: 'MD House',
employerName: 'HyPD',
diagnosisCodes: ['Z57.1', 'Z74.3', 'M51.2'],
description:
'Patient mistakenly found himself in a nuclear plant waste site without protection gear. Very minor radiation poisoning. ',
sickLeave: {
startDate: '2019-08-05',
endDate: '2019-08-28',
},
},
],
},
const codes = patient?.entries.map(c => c.diagnosisCodes);
</code></pre>
<p>const codes returns:</p>
<pre><code>[Array(3)]
0
:
(3) ['Z57.1', 'Z74.3', 'M51.2']
length
:
1
[[Prototype]]
:
Array(0)
</code></pre>
| [
{
"answer_id": 74278119,
"author": "Mr. Polywhirl",
"author_id": 1762224,
"author_profile": "https://Stackoverflow.com/users/1762224",
"pm_score": 2,
"selected": false,
"text": "Array.prototype.flatMap"
},
{
"answer_id": 74278233,
"author": "Volodymyr Sichka",
"author_id": 5333324,
"author_profile": "https://Stackoverflow.com/users/5333324",
"pm_score": 1,
"selected": false,
"text": "const patient = {\n id: 'd2773598-f723-11e9-8f0b-362b9e155667',\n name: 'Martin Riggs',\n dateOfBirth: '1979-01-30',\n ssn: '300179-777A',\n //gender: Gender.male,\n occupation: 'Cop',\n entries: [\n {\n id: 'fcd59fa6-c4b4-4fec-ac4d-df4fe1f85f62',\n date: '2019-08-05',\n type: 'OccupationalHealthcare',\n specialist: 'MD House',\n employerName: 'HyPD',\n diagnosisCodes: ['Z57.1', 'Z74.3', 'M51.2'],\n description:\n 'Patient mistakenly found himself in a nuclear plant waste site without protection gear. Very minor radiation poisoning. ',\n sickLeave: {\n startDate: '2019-08-05',\n endDate: '2019-08-28'\n }\n }\n ]\n };\n \nconst codes = patient.entries.reduce((t, v) => [...t, ...v.diagnosisCodes], []);\nconsole.log(codes);"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12894011/"
] |
74,278,106 | <p>I have a <code>TextField</code> to enter the amount as follows:</p>
<pre class="lang-kotlin prettyprint-override"><code>@OptIn(ExperimentalMaterialApi::class)
@Composable
fun AmountTextField(
modifier: Modifier,
sendMoneyViewModel: SendMoneyViewModel,
isReadOnly: Boolean,
focusManager: FocusManager
) {
val paymentAmount = sendMoneyViewModel.paymentAmount.collectAsState()
val focusRequester = remember { FocusRequester() }
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
val interactionSource = remember { MutableInteractionSource() }
Row(
modifier = modifier,
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Spacer(modifier = Modifier.weight(1f))
Text(
modifier = Modifier.wrapContentWidth(),
text = stringResource(id = R.string.rupee_symbol),
color = Black191919,
fontSize = 36.sp,
fontFamily = composeFontFamily,
fontWeight = getFontWeight(FontWeightEnum.EXTRA_BOLD)
)
BasicTextField(
modifier = Modifier
.focusRequester(focusRequester)
.background(color = YellowFFFFEAEA)
.height(IntrinsicSize.Min)
.width(IntrinsicSize.Min)
.clipToBounds(),
value = paymentAmount.value,
onValueChange = {
sendMoneyViewModel.onAmountValueChanged(it)
},
interactionSource = interactionSource,
visualTransformation = CurrencyMaskTransformation(SendMoneyViewModel.AMOUNT_MAX_LENGTH),
singleLine = true,
textStyle = TextStyle(
color = Black191919,
fontSize = 36.sp,
fontFamily = composeFontFamily,
fontWeight = getFontWeight(FontWeightEnum.EXTRA_BOLD),
textAlign = TextAlign.Center
),
keyboardActions = KeyboardActions(onDone = {
if (paymentAmount.value.isNotBlank()) {
focusManager.moveFocus(FocusDirection.Next)
}
}),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number, autoCorrect = false, imeAction = ImeAction.Next
),
readOnly = isReadOnly
) {
TextFieldDefaults.TextFieldDecorationBox(
value = paymentAmount.value,
visualTransformation = CurrencyMaskTransformation(SendMoneyViewModel.AMOUNT_MAX_LENGTH),
innerTextField = it,
singleLine = true,
enabled = !isReadOnly,
interactionSource = interactionSource,
contentPadding = PaddingValues(0.dp),
placeholder = { AmountFieldPlaceholder() },
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.Transparent,
cursorColor = Color.Black,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent
)
)
}
Spacer(modifier = Modifier.weight(1f))
}
}
@Composable
fun AmountFieldPlaceholder() {
Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
Text(
modifier = Modifier
.wrapContentWidth()
.align(Alignment.Center),
text = "0",
fontSize = 36.sp,
fontFamily = composeFontFamily,
fontWeight = getFontWeight(FontWeightEnum.EXTRA_BOLD),
color = GreyE3E5E5,
textAlign = TextAlign.Center
)
}
}
</code></pre>
<p>Initially it looks like this:
<a href="https://i.stack.imgur.com/5qLyD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5qLyD.png" alt="enter image description here" /></a></p>
<p>After typing "12", it's looking like this:
<a href="https://i.stack.imgur.com/DhFIT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DhFIT.png" alt="enter image description here" /></a>
You can see that text "1" is cutting off.</p>
<p>Ideally it should look like this after typing 1234567:
<a href="https://i.stack.imgur.com/UMGMh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UMGMh.png" alt="enter image description here" /></a></p>
<p>But apart from actual text size, it has extra inner padding also from start and end. So it can be unexpectedly scrolled as follows:</p>
<p><a href="https://i.stack.imgur.com/0ZZvo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0ZZvo.png" alt="enter image description here" /></a></p>
<p>Why TextField is having extra inner padding from start and end. Due to this, text is cutting while typing.</p>
<p>I have tried many solutions like:
<a href="https://stackoverflow.com/questions/67719981/resizeable-basictextfield-in-jetpack-compose">Resizeable BasicTextField in Jetpack Compose</a></p>
<p>I also tried to set WindowInsets, but nothing is working.</p>
| [
{
"answer_id": 74278119,
"author": "Mr. Polywhirl",
"author_id": 1762224,
"author_profile": "https://Stackoverflow.com/users/1762224",
"pm_score": 2,
"selected": false,
"text": "Array.prototype.flatMap"
},
{
"answer_id": 74278233,
"author": "Volodymyr Sichka",
"author_id": 5333324,
"author_profile": "https://Stackoverflow.com/users/5333324",
"pm_score": 1,
"selected": false,
"text": "const patient = {\n id: 'd2773598-f723-11e9-8f0b-362b9e155667',\n name: 'Martin Riggs',\n dateOfBirth: '1979-01-30',\n ssn: '300179-777A',\n //gender: Gender.male,\n occupation: 'Cop',\n entries: [\n {\n id: 'fcd59fa6-c4b4-4fec-ac4d-df4fe1f85f62',\n date: '2019-08-05',\n type: 'OccupationalHealthcare',\n specialist: 'MD House',\n employerName: 'HyPD',\n diagnosisCodes: ['Z57.1', 'Z74.3', 'M51.2'],\n description:\n 'Patient mistakenly found himself in a nuclear plant waste site without protection gear. Very minor radiation poisoning. ',\n sickLeave: {\n startDate: '2019-08-05',\n endDate: '2019-08-28'\n }\n }\n ]\n };\n \nconst codes = patient.entries.reduce((t, v) => [...t, ...v.diagnosisCodes], []);\nconsole.log(codes);"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4001244/"
] |
74,278,149 | <p>I am trying to create a button to change a bar chart to switch between 2 columns on the y axis (side by side bars) and 1 column.
First option of toggle:
<a href="https://i.stack.imgur.com/a2xjm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a2xjm.png" alt="First option of toggle" /></a>
Second option of toggle:
<a href="https://i.stack.imgur.com/KJRAr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KJRAr.png" alt="Second option of toggle" /></a>
I am using a button that increments a document property by 1 each time it is clicked, and a custom expression for the y axis which checks the value of the document property and changes the axis accordingly.
The custom expression is an if statement, checking if it is odd or even, and then changing the columns.
(Side note - I have not tried solving this using an iron python script)</p>
<p>I tried</p>
<pre><code>If( ${DocProp} % 2 = 0, (UniqueCount([moa]) , UniqueCount([jp_cluster])),(UniqueCount([moa])))
</code></pre>
<p>But received the error:</p>
<pre><code>Expected ')' but found ',' on line 1 character 37.
</code></pre>
<p>I knew the comma between the two columns might cause a problem by interfering with the if statement, so I tried a case statement:</p>
<pre><code>case ${RemoveJPCluster} % 2 when 0 then (UniqueCount([moa]), UniqueCount([jp_cluster])) else UniqueCount([moa]) end
</code></pre>
<p>But this throws the same error:</p>
<pre><code>Expected ')' but found ',' on line 1 character 44.
</code></pre>
<p>I have also tried:
+
AND
NEST</p>
<p>Any help on this? Is it even possible? I don't know why I can't surround the two columns with brackets and call it a day...</p>
| [
{
"answer_id": 74278119,
"author": "Mr. Polywhirl",
"author_id": 1762224,
"author_profile": "https://Stackoverflow.com/users/1762224",
"pm_score": 2,
"selected": false,
"text": "Array.prototype.flatMap"
},
{
"answer_id": 74278233,
"author": "Volodymyr Sichka",
"author_id": 5333324,
"author_profile": "https://Stackoverflow.com/users/5333324",
"pm_score": 1,
"selected": false,
"text": "const patient = {\n id: 'd2773598-f723-11e9-8f0b-362b9e155667',\n name: 'Martin Riggs',\n dateOfBirth: '1979-01-30',\n ssn: '300179-777A',\n //gender: Gender.male,\n occupation: 'Cop',\n entries: [\n {\n id: 'fcd59fa6-c4b4-4fec-ac4d-df4fe1f85f62',\n date: '2019-08-05',\n type: 'OccupationalHealthcare',\n specialist: 'MD House',\n employerName: 'HyPD',\n diagnosisCodes: ['Z57.1', 'Z74.3', 'M51.2'],\n description:\n 'Patient mistakenly found himself in a nuclear plant waste site without protection gear. Very minor radiation poisoning. ',\n sickLeave: {\n startDate: '2019-08-05',\n endDate: '2019-08-28'\n }\n }\n ]\n };\n \nconst codes = patient.entries.reduce((t, v) => [...t, ...v.diagnosisCodes], []);\nconsole.log(codes);"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14851377/"
] |
74,278,160 | <p>I have installed python on my computer in the <code>AppData\local\programs\python</code> location on my computer. I got the installation file from the python website. I cannot use the installation packages from the Microsoft store due to an authorization error (even though I unchecked the boxes in the App Execution Aliases page in settings). I am on my personal computer on which there are no other users.</p>
<p>When I go into my command prompt, and run the command:</p>
<pre><code>python --versions
</code></pre>
<p>I get an error saying:</p>
<pre><code>Python was not found; run without arguments to install from the Microsoft Store, or
disable this shortcut from Settings > Manage App Execution Aliases.
</code></pre>
<p>either I do not understand what this error is requiring me to do, or there is something else I am doing wrong.</p>
| [
{
"answer_id": 74278119,
"author": "Mr. Polywhirl",
"author_id": 1762224,
"author_profile": "https://Stackoverflow.com/users/1762224",
"pm_score": 2,
"selected": false,
"text": "Array.prototype.flatMap"
},
{
"answer_id": 74278233,
"author": "Volodymyr Sichka",
"author_id": 5333324,
"author_profile": "https://Stackoverflow.com/users/5333324",
"pm_score": 1,
"selected": false,
"text": "const patient = {\n id: 'd2773598-f723-11e9-8f0b-362b9e155667',\n name: 'Martin Riggs',\n dateOfBirth: '1979-01-30',\n ssn: '300179-777A',\n //gender: Gender.male,\n occupation: 'Cop',\n entries: [\n {\n id: 'fcd59fa6-c4b4-4fec-ac4d-df4fe1f85f62',\n date: '2019-08-05',\n type: 'OccupationalHealthcare',\n specialist: 'MD House',\n employerName: 'HyPD',\n diagnosisCodes: ['Z57.1', 'Z74.3', 'M51.2'],\n description:\n 'Patient mistakenly found himself in a nuclear plant waste site without protection gear. Very minor radiation poisoning. ',\n sickLeave: {\n startDate: '2019-08-05',\n endDate: '2019-08-28'\n }\n }\n ]\n };\n \nconst codes = patient.entries.reduce((t, v) => [...t, ...v.diagnosisCodes], []);\nconsole.log(codes);"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19452666/"
] |
74,278,168 | <p>Is there a function to <strong>all</strong> pairwise means (or sums, etc) of 2 lists in python?</p>
<p>I can write a nested loop to do this:</p>
<pre><code>import numpy as np
A = [1,2,3]
B = [8,12,11]
C = np.empty((len(A),len(B)))
for i, x in enumerate(A):
for j, y in enumerate(B):
C[i][j] = np.mean([x,y])
</code></pre>
<p>result:</p>
<pre><code>array([[4.5, 6.5, 6. ],
[5. , 7. , 6.5],
[5.5, 7.5, 7. ]])
</code></pre>
<p>but it feels like this is a very roundabout way to do this.
I guess there is an option for a nested list comprehension as well, but that also seems ugly.</p>
<p>Is there a more pythonic solution?</p>
| [
{
"answer_id": 74278271,
"author": "The Myth",
"author_id": 15042008,
"author_profile": "https://Stackoverflow.com/users/15042008",
"pm_score": 1,
"selected": false,
"text": "zip()"
},
{
"answer_id": 74278274,
"author": "ILS",
"author_id": 10017662,
"author_profile": "https://Stackoverflow.com/users/10017662",
"pm_score": 2,
"selected": false,
"text": "numpy"
},
{
"answer_id": 74278339,
"author": "msi_gerva",
"author_id": 1913367,
"author_profile": "https://Stackoverflow.com/users/1913367",
"pm_score": 1,
"selected": false,
"text": "C= [[(xx+yy)/2 for yy in B] for xx in A]\n"
},
{
"answer_id": 74282769,
"author": "Chrysophylaxs",
"author_id": 9499196,
"author_profile": "https://Stackoverflow.com/users/9499196",
"pm_score": 3,
"selected": true,
"text": "A = [1, 2, 3]\nB = [8, 12, 11]\nC = np.add.outer(A, B) / 2\n# array([[4.5, 6.5, 6. ],\n# [5. , 7. , 6.5],\n# [5.5, 7.5, 7. ]])\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5170442/"
] |
74,278,172 | <p>I'm trying to do trigonometry in JavaScript. When I try run this code in the terminal:</p>
<pre><code>function angle(deg, min, sec) { return (deg) + (min / 60) + (sec / 3600); }
let deg2 = 89, min2 = 45, sec2 = 0, dist2 = 11.27;
let lat2 = (Math.sin(angle(deg2, min2, sec2))) * dist2;
let long2 = (Math.cos(angle(deg2, min2, sec2))) * dist2;
console.log("lat2 , long2 : " + lat2 + " , " + long2);
</code></pre>
<p>I get this:</p>
<pre><code>lat2 , long2 : 11.011462356910855 , -2.400124322266507
</code></pre>
<p>instead of this:</p>
<pre><code>lat2 , long2 : 11.269892717722677 , 0.049174495639093
</code></pre>
<p>I tried swapping the <code>cos</code> and <code>sin</code> with each other but no luck. Also tried to replace <code>cos</code> with <code>tan</code> and still different result. Also replaced <code>sin</code> with <code>tan</code> and still not correct.</p>
| [
{
"answer_id": 74278271,
"author": "The Myth",
"author_id": 15042008,
"author_profile": "https://Stackoverflow.com/users/15042008",
"pm_score": 1,
"selected": false,
"text": "zip()"
},
{
"answer_id": 74278274,
"author": "ILS",
"author_id": 10017662,
"author_profile": "https://Stackoverflow.com/users/10017662",
"pm_score": 2,
"selected": false,
"text": "numpy"
},
{
"answer_id": 74278339,
"author": "msi_gerva",
"author_id": 1913367,
"author_profile": "https://Stackoverflow.com/users/1913367",
"pm_score": 1,
"selected": false,
"text": "C= [[(xx+yy)/2 for yy in B] for xx in A]\n"
},
{
"answer_id": 74282769,
"author": "Chrysophylaxs",
"author_id": 9499196,
"author_profile": "https://Stackoverflow.com/users/9499196",
"pm_score": 3,
"selected": true,
"text": "A = [1, 2, 3]\nB = [8, 12, 11]\nC = np.add.outer(A, B) / 2\n# array([[4.5, 6.5, 6. ],\n# [5. , 7. , 6.5],\n# [5.5, 7.5, 7. ]])\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19954687/"
] |
74,278,181 | <p>I am developing a .NET Core 6 application.</p>
<p>In one part of the code I have this:</p>
<pre class="lang-cs prettyprint-override"><code>catch (Exception ex)
{
_logger.LogError(ex.GetMessage());
string error = "Por favor, contáctese con soporte técnico.";
if (ex.InnerException != null)
error = string.Concat("\n\n", ex.InnerException.Message);
return Json($"ERROR: Existió un error al iniciar sesión. {error}");
}
</code></pre>
<p>when I pass the mouse over <code>ex</code> in <code>ex.GetMessage()</code>, this warning appears:</p>
<p><a href="https://i.stack.imgur.com/YHVyJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YHVyJ.png" alt="enter image description here" /></a></p>
<p>that means "ex is not NULL here". What is that? How can I deal with this?</p>
| [
{
"answer_id": 74278271,
"author": "The Myth",
"author_id": 15042008,
"author_profile": "https://Stackoverflow.com/users/15042008",
"pm_score": 1,
"selected": false,
"text": "zip()"
},
{
"answer_id": 74278274,
"author": "ILS",
"author_id": 10017662,
"author_profile": "https://Stackoverflow.com/users/10017662",
"pm_score": 2,
"selected": false,
"text": "numpy"
},
{
"answer_id": 74278339,
"author": "msi_gerva",
"author_id": 1913367,
"author_profile": "https://Stackoverflow.com/users/1913367",
"pm_score": 1,
"selected": false,
"text": "C= [[(xx+yy)/2 for yy in B] for xx in A]\n"
},
{
"answer_id": 74282769,
"author": "Chrysophylaxs",
"author_id": 9499196,
"author_profile": "https://Stackoverflow.com/users/9499196",
"pm_score": 3,
"selected": true,
"text": "A = [1, 2, 3]\nB = [8, 12, 11]\nC = np.add.outer(A, B) / 2\n# array([[4.5, 6.5, 6. ],\n# [5. , 7. , 6.5],\n# [5.5, 7.5, 7. ]])\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048588/"
] |
74,278,207 | <p>For a Python dataframe (based on some criteria) I am able to select the index value (a date) (='first date') as well as the index value (a date) corresponding to the very last row ('last date').</p>
<p>I would like to calculate explicitly the difference (in days) between 'first date' and 'last date' (should be = 3 (number of days)). How can I do it for this case?</p>
<p>Many thanks in advance!</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({"date": ['2021-3-22', '2021-3-23', '2021-3-24', '2021-3-25', '2021-3-26'],
"x": ['1', 1, 'nan', 'nan', 'nan' ]})
df1.set_index('date', inplace=True)
df1
date x
2021-3-22 1
2021-3-23 1
2021-3-24 nan
2021-3-25 nan
2021-3-26 nan
print('first date:', df1.x[df1.x == 1].tail(1).index.values)
first date: ['2021-3-23']
(=d1)
print('last date:', df1.tail(1).index.values)
last date: ['2021-3-26']
(=d2)
d2-d1=?
</code></pre>
<p>Many thanks in advance!</p>
| [
{
"answer_id": 74278337,
"author": "nilanjan_dk",
"author_id": 11500187,
"author_profile": "https://Stackoverflow.com/users/11500187",
"pm_score": 1,
"selected": false,
"text": "(pd.to_datetime(df1.tail(1).index.values, format='%Y-%m-%d') \n - pd.to_datetime(df1.x[df1.x == 1].tail(1).index.values, format='%Y-%m-%d')).days[0]\n"
},
{
"answer_id": 74278348,
"author": "alec_djinn",
"author_id": 3190076,
"author_profile": "https://Stackoverflow.com/users/3190076",
"pm_score": 3,
"selected": true,
"text": "'date'"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18836406/"
] |
74,278,235 | <p>Let's say I have a main class in java that receives a matrix[][], like: `</p>
<pre><code>public main[] findBall(int[][] grid) {
}
</code></pre>
<p>`
And then the user enters the imput:</p>
<pre><code>[[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]]
</code></pre>
<p>I know it's a 5x5 but only because I saw what the user typed, how do I get the matrix size->(5x5) or any other size that they may type? or is there another way to navigate through it without knowing the size?</p>
<p>I tried nothing, I'm a beginner in Java so bear with me.</p>
| [
{
"answer_id": 74278337,
"author": "nilanjan_dk",
"author_id": 11500187,
"author_profile": "https://Stackoverflow.com/users/11500187",
"pm_score": 1,
"selected": false,
"text": "(pd.to_datetime(df1.tail(1).index.values, format='%Y-%m-%d') \n - pd.to_datetime(df1.x[df1.x == 1].tail(1).index.values, format='%Y-%m-%d')).days[0]\n"
},
{
"answer_id": 74278348,
"author": "alec_djinn",
"author_id": 3190076,
"author_profile": "https://Stackoverflow.com/users/3190076",
"pm_score": 3,
"selected": true,
"text": "'date'"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19366635/"
] |
74,278,257 | <p>Not too sure how I would go about this; how would I get the import function to see stuff like styles? I assume since it's XML and not straight-up HTML, it wouldn't be possible.</p>
<pre><code><li>1</li><li>2</li><li><span style="color:red"><strong>3</strong> </span></li><li>4</li>
</code></pre>
<p>So out of the list, I want the import to only import ones that are either red or set to strong. Not too sure if XML can do this, and if not, would there be any other way?</p>
<p>XML path = <code>/html/body/div[1]/div/article/div/div[1]/div/div/div[3]/div/div/div[2]/div[1]/ul</code></p>
| [
{
"answer_id": 74278337,
"author": "nilanjan_dk",
"author_id": 11500187,
"author_profile": "https://Stackoverflow.com/users/11500187",
"pm_score": 1,
"selected": false,
"text": "(pd.to_datetime(df1.tail(1).index.values, format='%Y-%m-%d') \n - pd.to_datetime(df1.x[df1.x == 1].tail(1).index.values, format='%Y-%m-%d')).days[0]\n"
},
{
"answer_id": 74278348,
"author": "alec_djinn",
"author_id": 3190076,
"author_profile": "https://Stackoverflow.com/users/3190076",
"pm_score": 3,
"selected": true,
"text": "'date'"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20389476/"
] |
74,278,290 | <p><strong>Short Summary</strong>
I am running multiple sql queries (each committed separately) within one session via pyodbc. In a few queries we call <code>SET TRANSACTION ISOLATION LEVEL SNAPSHOT;</code>, begin a transaction, do some work, commit the transaction and then call <code>SET TRANSACTION ISOLATION LEVEL READ COMMITTED;</code> But even though we have set the transaction isolation level back to READ COMMITTED we get the error</p>
<blockquote>
<p>pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Transaction failed because this DDL statement is not allowed inside a snapshot isolation transaction. Since metadata is not versioned, a metadata change can lead to inconsistency if mixed within snapshot isolation. (3964) (SQLExecDirectW)')</p>
</blockquote>
<p>I don't understand why we're getting this error when we're no longer within snapshot isolation.</p>
<p><strong>Full Details</strong></p>
<p>I am migrating a large legacy SQL process from PHP to Python. Briefly, a PHP job calls a series of SQL statements in order (all within a single session) to populate several dozen large tables. This includes many intermediary steps with temp tables. (We are in the process of decoupling ourselves from this legacy process but for now we are stuck with it.)</p>
<p>I'm moving that legacy process into Python for maintainability reasons, using pyodbc. While this has been largely painless I am finding a strange difference in behaviors from PHP to Python around TRANSACTION ISOLATION LEVEL.</p>
<p>Early in the process we switch to ISOLATION LEVEL SNAPSHOT:</p>
<pre><code> SET TRANSACTION ISOLATION LEVEL SNAPSHOT;
BEGIN TRANSACTION;
DECLARE @current_refresh_id BIGINT = :current_refresh_id;
DECLARE @CurRowID INT = 1;
DECLARE @TotalCount INT = (SELECT COUNT(*) FROM #product_data);
WHILE (1 = 1)
BEGIN
-- a complex insert into a table tblSomeTableOne using joins, etc, done in batches
END
COMMIT TRANSACTION;
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
</code></pre>
<p>We then call many other SQL statements with no issue. I've added a query before each of them to verify that we're using ReadCommited transaction level after the above SQL statement (taken from <a href="https://stackoverflow.com/a/1038184/1411376">this answer</a>):</p>
<pre><code>SELECT CASE transaction_isolation_level
WHEN 0 THEN 'Unspecified'
WHEN 1 THEN 'ReadUncommitted'
WHEN 2 THEN 'ReadCommitted'
WHEN 3 THEN 'Repeatable'
WHEN 4 THEN 'Serializable'
WHEN 5 THEN 'Snapshot' END AS TRANSACTION_ISOLATION_LEVEL
FROM sys.dm_exec_sessions
where session_id = @@SPID;
</code></pre>
<p>The query shows that the transaction level is in fact ReadCommitted.</p>
<p>However, later in the code I run this DDL on a temp table that has already been created:</p>
<pre><code> SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
BEGIN TRANSACTION;
ALTER TABLE #already_populated_temp_table ADD RowNum INT IDENTITY;
CREATE UNIQUE INDEX ix_psi_RowNum ON #already_populated_temp_table (RowNum);
ALTER INDEX ALL ON #already_populated_temp_table REBUILD;
COMMIT TRANSACTION;
</code></pre>
<p>This fails with the following exception:</p>
<blockquote>
<p>pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Transaction failed because this DDL statement is not allowed inside a snapshot isolation transaction. Since metadata is not versioned, a metadata change can lead to inconsistency if mixed within snapshot isolation. (3964) (SQLExecDirectW)')</p>
</blockquote>
<p>This confuses me because if I check the isolation level immediately prior to this error, I get ReadCommitted, not Snapshot.</p>
<p>For context pyodbc is running with autocommit=True, all our SQL statements are executed as part of a single session. These SQL statements work fine in PHP and they work in python/pyodbc as well in limited test cases, but they fail when running our "full" legacy process in python/pyodbc. (The only difference between test cases and the full process is the amount of data, the SQL is identical.)</p>
<p>Apologies for not including a fully reproducible example but the actual legacy process is massive and proprietary.</p>
<p><strong>Update One</strong>
I added a query to check the transaction state to see if autocommit has somehow been disabled, causing us to be stuck in the SNAPSHOT transaction.</p>
<pre><code>IF @@TRANCOUNT = 0 SELECT 'No current transaction, autocommit mode (default)'
</code></pre>
<p>ELSE IF @@OPTIONS & 2 = 0 SELECT 'Implicit transactions is off, explicit transaction is currently running'
ELSE SELECT 'Implicit transactions is on, implicit or explicit transaction is currently running'</p>
<p>When I run my queries over a limited dataset (~16000 records) All my queries run with autocommit mode. But when I run my queries over the full dataset (~3 million records), one of the queries that uses a SNAPSHOT isolation transaction changes subsequent queries to <code>Implicit transactions is off, explicit transaction is currently running</code>. So They're still stuck in that query's snapshot transaction even though that transaction is told to commit.</p>
<p>Here is a modified version of that query:</p>
<pre><code>SET TRANSACTION ISOLATION LEVEL SNAPSHOT;
BEGIN TRANSACTION;
DECLARE @my_param BIGINT = :my_param;
DECLARE @CurRowID INT = 1;
DECLARE @TotalCount INT = (SELECT COUNT(*) FROM #product_data);
WHILE (1 = 1)
BEGIN
--dramatically simplified from the real query
;WITH some_data AS (
SELECT t1.A, t1.B FROM #temp_table_1 t1
WHERE t1.RowNum BETWEEN @CurRowID AND @CurRowID + :batch_size - 1
)
INSERT INTO tblMyTable (A, B, Param)
SELECT some_data.A,
some_data.B,
@my_param
FROM some_data
OPTION(RECOMPILE,MAXDOP 8)
SET @CurRowID += :batch_size;
IF @CurRowID > @TotalCount BREAK;
WAITFOR DELAY :wait_time;
END
COMMIT TRANSACTION;
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
</code></pre>
<p>What I don't understand is why the above query will successfully commit the transaction and set the isolation level back to READ COMMITTED when running on a smaller set (16k records) but it doesn't actually commit the transaction on larger sets (~3M records).</p>
<p>(We do the OPTION RECOMPILE because the actual query in this loop performs very poorly without recompile, because the number of records etc can change dramatically between executions.)</p>
| [
{
"answer_id": 74278337,
"author": "nilanjan_dk",
"author_id": 11500187,
"author_profile": "https://Stackoverflow.com/users/11500187",
"pm_score": 1,
"selected": false,
"text": "(pd.to_datetime(df1.tail(1).index.values, format='%Y-%m-%d') \n - pd.to_datetime(df1.x[df1.x == 1].tail(1).index.values, format='%Y-%m-%d')).days[0]\n"
},
{
"answer_id": 74278348,
"author": "alec_djinn",
"author_id": 3190076,
"author_profile": "https://Stackoverflow.com/users/3190076",
"pm_score": 3,
"selected": true,
"text": "'date'"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1411376/"
] |
74,278,318 | <p>I have this web page:</p>
<p><a href="https://tr.uspoloassn.com/erkek-beyaz-polo-yaka-t-shirt-basic-50249146-vr013/" rel="nofollow noreferrer">https://tr.uspoloassn.com/erkek-beyaz-polo-yaka-t-shirt-basic-50249146-vr013/</a></p>
<p>that contains this html:</p>
<p><a href="https://i.stack.imgur.com/5MS8k.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5MS8k.png" alt="html" /></a></p>
<p>this code has the sizes in it. you can see that some class has: js-variant and some has js-variant disabled</p>
<p>what i want is to select the text where the class is js-variant using web scraping.</p>
<pre><code>I tried doing: response.css('a.js-variant ::text').extract()
</code></pre>
<p>but this does not work properly and gives all the values even the ones that has a class disabled in it.</p>
<p>how can I do that?</p>
| [
{
"answer_id": 74278337,
"author": "nilanjan_dk",
"author_id": 11500187,
"author_profile": "https://Stackoverflow.com/users/11500187",
"pm_score": 1,
"selected": false,
"text": "(pd.to_datetime(df1.tail(1).index.values, format='%Y-%m-%d') \n - pd.to_datetime(df1.x[df1.x == 1].tail(1).index.values, format='%Y-%m-%d')).days[0]\n"
},
{
"answer_id": 74278348,
"author": "alec_djinn",
"author_id": 3190076,
"author_profile": "https://Stackoverflow.com/users/3190076",
"pm_score": 3,
"selected": true,
"text": "'date'"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16616665/"
] |
74,278,350 | <p>Does anyone know if trellis panels can be configured or customized? I'm looking to move my "Post-Inspection" panel below my "Pre-Inspection" panel.</p>
<p>Thanks!</p>
<p><a href="https://i.stack.imgur.com/8dOxj.png" rel="nofollow noreferrer">Spotfire Picture</a></p>
| [
{
"answer_id": 74278337,
"author": "nilanjan_dk",
"author_id": 11500187,
"author_profile": "https://Stackoverflow.com/users/11500187",
"pm_score": 1,
"selected": false,
"text": "(pd.to_datetime(df1.tail(1).index.values, format='%Y-%m-%d') \n - pd.to_datetime(df1.x[df1.x == 1].tail(1).index.values, format='%Y-%m-%d')).days[0]\n"
},
{
"answer_id": 74278348,
"author": "alec_djinn",
"author_id": 3190076,
"author_profile": "https://Stackoverflow.com/users/3190076",
"pm_score": 3,
"selected": true,
"text": "'date'"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19822352/"
] |
74,278,372 | <p>I'm trying to make an sql request that turned out surprisingly difficult to me (or maybe this is just the end of the day, sigh).</p>
<p>I have 3 tables:</p>
<p>Team:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td>3</td>
</tr>
</tbody>
</table>
</div>
<p>Team member table:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>team_id</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>1</td>
</tr>
<tr>
<td>5</td>
<td>2</td>
</tr>
<tr>
<td>6</td>
<td>2</td>
</tr>
<tr>
<td>7</td>
<td>2</td>
</tr>
<tr>
<td>8</td>
<td>2</td>
</tr>
<tr>
<td>9</td>
<td>3</td>
</tr>
<tr>
<td>10</td>
<td>3</td>
</tr>
<tr>
<td>11</td>
<td>3</td>
</tr>
<tr>
<td>12</td>
<td>3</td>
</tr>
</tbody>
</table>
</div>
<p>Team member info table:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>team_member_id</th>
<th>department_id</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>12</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>43</td>
</tr>
<tr>
<td>5</td>
<td>3</td>
<td>23</td>
</tr>
<tr>
<td>7</td>
<td>4</td>
<td>12</td>
</tr>
<tr>
<td>9</td>
<td>5</td>
<td>12</td>
</tr>
<tr>
<td>11</td>
<td>6</td>
<td>12</td>
</tr>
<tr>
<td>13</td>
<td>7</td>
<td>12</td>
</tr>
<tr>
<td>15</td>
<td>8</td>
<td>12</td>
</tr>
<tr>
<td>17</td>
<td>9</td>
<td>43</td>
</tr>
<tr>
<td>19</td>
<td>10</td>
<td>23</td>
</tr>
<tr>
<td>21</td>
<td>11</td>
<td>14</td>
</tr>
<tr>
<td>23</td>
<td>12</td>
<td>23</td>
</tr>
</tbody>
</table>
</div>
<p>These tables are simplified, so don't pay much attention to its structure.</p>
<p>What I need to do is to find <code>id</code>s of teams which consists of members that belong to SINGLE <code>department_id</code> and this department id should be a parameter.</p>
<p>So in our example I need to find teams, which members belong to department 12.</p>
<p>This is team(id=2) since it consists of members id=5,6,7,8 and all of them belong to department 12.
Team 1 and Team 3 doesn't suit our needs since its members belong to multiple departments: (12, 43, 23) and (43, 23, 14) respectively.</p>
<p>Thanks a lot!</p>
<p>UPD:</p>
<p>I came to solution:</p>
<pre><code>Select M.team_id
From Team_Member As M Inner Join Team_Member_Info As I On (M.id=I.team_member_id)
Group by M.team_id
Having count(*) = 1
And avg(I.department_id)=12;
</code></pre>
<p>but the accepted one looks cleaner to me (and moreover it is probably more performant)</p>
| [
{
"answer_id": 74278337,
"author": "nilanjan_dk",
"author_id": 11500187,
"author_profile": "https://Stackoverflow.com/users/11500187",
"pm_score": 1,
"selected": false,
"text": "(pd.to_datetime(df1.tail(1).index.values, format='%Y-%m-%d') \n - pd.to_datetime(df1.x[df1.x == 1].tail(1).index.values, format='%Y-%m-%d')).days[0]\n"
},
{
"answer_id": 74278348,
"author": "alec_djinn",
"author_id": 3190076,
"author_profile": "https://Stackoverflow.com/users/3190076",
"pm_score": 3,
"selected": true,
"text": "'date'"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199519/"
] |
74,278,373 | <p>I'm trying to write a test for my smart contract in hardhat with js, I want to check somethings in case a call to my contract fails the problem is that when the line of "failed contract call" runs it reverts the whole block of test and will not run the rest of it.
how can I make it work?</p>
<pre><code>some code 1
await contract.function()
// contract call fails intentionally
some code 2
</code></pre>
<p>I need the result of "some code 2" but I just get an error that the call has failed.</p>
| [
{
"answer_id": 74278445,
"author": "Volodymyr Sichka",
"author_id": 5333324,
"author_profile": "https://Stackoverflow.com/users/5333324",
"pm_score": 0,
"selected": false,
"text": "chai"
},
{
"answer_id": 74282208,
"author": "Petr Hejda",
"author_id": 1693192,
"author_profile": "https://Stackoverflow.com/users/1693192",
"pm_score": 2,
"selected": true,
"text": "expect()"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19359463/"
] |
74,278,400 | <p>JavaScript only!
I'm trying to get the index after clicked on one element from a dropdown menu.
I'm already getting the text value but not the index. How can I solve this?</p>
<p>1)This is how I get the text value after clicking on a month:</p>
<pre><code>const monthText = document.querySelector(".month-text");
const months = document.querySelectorAll(".month-value");
const monthsEl = Array.from(months);
months.forEach((el) =\> {
el.onclick = function () {
const monthSelected = (monthText.textContent = this.innerHTML);
console.log(monthSelected);
};
});
</code></pre>
<p>2)I'm getting the index but with hard code ("May"):</p>
<pre><code>const monthsArr = monthsEl.map((el) => el.textContent);
console.log(monthsArr);
const index = monthsArr.indexOf("May");
console.log(index);
</code></pre>
<p><a href="https://i.stack.imgur.com/WoYI9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WoYI9.png" alt="As you can see, I'm getting the string object, the selected month after clicked and the hard-coded index" /></a></p>
| [
{
"answer_id": 74278703,
"author": "Ace",
"author_id": 16098819,
"author_profile": "https://Stackoverflow.com/users/16098819",
"pm_score": 0,
"selected": false,
"text": "const monthsArr = monthsEl.map((el, index) => el.textContent = el.index);\n"
},
{
"answer_id": 74278869,
"author": "Amit Sharma",
"author_id": 6827830,
"author_profile": "https://Stackoverflow.com/users/6827830",
"pm_score": 1,
"selected": true,
"text": "months.map((el, index) => {\n el.onclick = function () {\n const indexValue = index;\n const monthSelected = (monthText.textContent = this.innerHTML);\n console.log('Month ' + monthSelected + 'is at ' + index + 1 + 'position');\n};\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20389479/"
] |
74,278,403 | <p>So from my understanding, mutex and binary semaphore are very similar but I just want to know what are some specific application or circumstances that using mutex is better than binary semaphore or viceversa</p>
| [
{
"answer_id": 74278703,
"author": "Ace",
"author_id": 16098819,
"author_profile": "https://Stackoverflow.com/users/16098819",
"pm_score": 0,
"selected": false,
"text": "const monthsArr = monthsEl.map((el, index) => el.textContent = el.index);\n"
},
{
"answer_id": 74278869,
"author": "Amit Sharma",
"author_id": 6827830,
"author_profile": "https://Stackoverflow.com/users/6827830",
"pm_score": 1,
"selected": true,
"text": "months.map((el, index) => {\n el.onclick = function () {\n const indexValue = index;\n const monthSelected = (monthText.textContent = this.innerHTML);\n console.log('Month ' + monthSelected + 'is at ' + index + 1 + 'position');\n};\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13990358/"
] |
74,278,420 | <p>Metamask Confirm button not working, couldn't confirm transaction for a smart contract.</p>
<p>I use JS and WalletConnectProvider (website project). Connecting to Metamask by WalletConnect, then call transfer function for custom token contract. I use the same code on desktop and it works and transferring token. Exactly the same code doesn't work on mobile (for Metamask Mobile app). Checked IOS and also Android - the same issue.
Please tell me what is wrong with my code:</p>
<pre><code>
<script src="https://cdn.jsdelivr.net/npm/@walletconnect/web3-provider@1.8.0/dist/umd/index.min.js"></script>
<script src="https://[mywebsitescriptspath]/web3.min.js"></script> // 1.8.0
<script type="text/javascript">
var contract
var accountFrom
const ABI = "... abi here....."
var provider = new WalletConnectProvider.default({
infuraId: 'my infura id',
rpc: {
1: "https://mainnet.infura.io/v3/[myinfuraid]",
56: "https://bsc-dataseed.binance.org/"
},
})
const contractAddress = '0xcontraddresshere'
const receiver = '0xreceiveraddresshere'
var connect = async () => {
await provider.enable()
var web3 = new Web3(provider)
web3.givenProvider = web3.currentProvider
web3.eth.givenProvider = web3.currentProvider
web3.eth.accounts.givenProvider = web3.currentProvider
window.w3 = web3
contract = new w3.eth.Contract(ABI, contractAddress)
await w3.eth.getAccounts().then(accounts => {
accountFrom = accounts[0]
})
}
connect()
// function called after the button click
var sendtransaction = async () => {
let vall = 100
let calcAmount = w3.utils.toWei(vall.toString())
let transfer = await contract.methods.transfer(receiver, calcAmount);
await transfer.send({from: accountFrom})
.on('transactionHash', function(hash){
console.log(hash)
})
}
</script>
</code></pre>
<p><a href="https://i.stack.imgur.com/vR19j.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vR19j.jpg" alt="enter image description here" /></a></p>
<p>I tried many different things but it doesn't work.</p>
<p>Tested on wifi, on 4g, on different mobile browsers, on different smartphones (android and IOS).
no success.</p>
<p>The problem started from 5.9.0 Metamask app version.</p>
<p>UPDATE:
Now at 5.10.0 version it doesn't recognize custom contract token. For example when I want to transfer 1 token, it shows 1 BNB.
Last version was better :))</p>
<p>There are open issues on github:</p>
<ol>
<li><a href="https://github.com/MetaMask/metamask-mobile/issues/5193" rel="nofollow noreferrer">https://github.com/MetaMask/metamask-mobile/issues/5193</a></li>
<li><a href="https://github.com/MetaMask/metamask-mobile/issues/5235" rel="nofollow noreferrer">https://github.com/MetaMask/metamask-mobile/issues/5235</a></li>
<li><a href="https://github.com/MetaMask/metamask-mobile/issues/5260" rel="nofollow noreferrer">https://github.com/MetaMask/metamask-mobile/issues/5260</a></li>
</ol>
<p>No solution till now - after 14 days.</p>
| [
{
"answer_id": 74278703,
"author": "Ace",
"author_id": 16098819,
"author_profile": "https://Stackoverflow.com/users/16098819",
"pm_score": 0,
"selected": false,
"text": "const monthsArr = monthsEl.map((el, index) => el.textContent = el.index);\n"
},
{
"answer_id": 74278869,
"author": "Amit Sharma",
"author_id": 6827830,
"author_profile": "https://Stackoverflow.com/users/6827830",
"pm_score": 1,
"selected": true,
"text": "months.map((el, index) => {\n el.onclick = function () {\n const indexValue = index;\n const monthSelected = (monthText.textContent = this.innerHTML);\n console.log('Month ' + monthSelected + 'is at ' + index + 1 + 'position');\n};\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6820117/"
] |
74,278,423 | <pre><code><body>
<tbody id="data-table">
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</tbody>
</body>
</code></pre>
<p>I need a fast way to find the texts contained within each <code><td></code></p>
<p>I tried</p>
<pre><code>main_table = driver.find_element(By.ID, "data-table")
for i in range(3):
main_table.find_element(By.XPATH, "tr[" + str(i + 1) + "]/td[1]").text
main_table.find_element(By.XPATH, "tr[" + str(i + 1) + "]/td[2]").text
main_table.find_element(By.XPATH, "tr[" + str(i + 1) + "]/td[3]").text
</code></pre>
<p>this is incredibly slow... nearly 200ms for each search<br />
this simple loop takes over 3 x 3 x 200 ms or 1.8 sec</p>
<p>the actual data I need to extract is even bigger, its over 100 <code>tr</code> and each having 5 <code>td</code><br />
this takes over 100 secs to complete</p>
<p>is there a faster way to do this?</p>
<p>I was wondering if there is a way to just extract all the tags under the main table for example</p>
<pre><code>extracted_data = main_table.get_all_tags()
for tr in extracted_data:
for td in tr:
print(td.text)
</code></pre>
<p>the idea is we extract all the sub-tags data and then use pure python to further extract the sub data instead of crawling it using <code>find_element</code></p>
| [
{
"answer_id": 74278703,
"author": "Ace",
"author_id": 16098819,
"author_profile": "https://Stackoverflow.com/users/16098819",
"pm_score": 0,
"selected": false,
"text": "const monthsArr = monthsEl.map((el, index) => el.textContent = el.index);\n"
},
{
"answer_id": 74278869,
"author": "Amit Sharma",
"author_id": 6827830,
"author_profile": "https://Stackoverflow.com/users/6827830",
"pm_score": 1,
"selected": true,
"text": "months.map((el, index) => {\n el.onclick = function () {\n const indexValue = index;\n const monthSelected = (monthText.textContent = this.innerHTML);\n console.log('Month ' + monthSelected + 'is at ' + index + 1 + 'position');\n};\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12052202/"
] |
74,278,453 | <p>I'm trying to achieve below cardview arc shape on cardview border/stroke.
Already tried to search on google but didn't find any relevant answer that suits with requirement.</p>
<p>Any lead or help will be appriciated.</p>
<p><a href="https://i.stack.imgur.com/KY9kp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KY9kp.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74285035,
"author": "Thracian",
"author_id": 5457853,
"author_profile": "https://Stackoverflow.com/users/5457853",
"pm_score": 4,
"selected": true,
"text": "arcTo"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7945455/"
] |
74,278,473 | <pre><code>print(bytes('ba', 'utf-16'))
</code></pre>
<p>Result :</p>
<pre><code>b'\xff\xfeb\x00a\x00'
</code></pre>
<p>I understand utf-16 means every character will take 16 bits means <code>00000000 00000000</code> in binary and i understand there are 16 bits here <code>x00a</code> means <code>x00 = 00000000</code> and <code>a = 01000001</code> so both gives <code>x00a</code> it is clear to my mind like this but here is the confusion:</p>
<pre><code>\xff\xfeb
</code></pre>
<p>1 - What is this ?????????</p>
<p>2 - Why <code>fe</code> ??? it should be x00</p>
<p>i have read a lot of wikipedia articles but it is still not clear</p>
| [
{
"answer_id": 74285035,
"author": "Thracian",
"author_id": 5457853,
"author_profile": "https://Stackoverflow.com/users/5457853",
"pm_score": 4,
"selected": true,
"text": "arcTo"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,278,474 | <p>A 2 dimensional array with a size of NxN, composed of <code>1</code> and <code>0</code>.</p>
<p>A neighbor is a <code>1</code> in the <em>north / south / west / east</em> of the index</p>
<p>Recursively find how many neighbors an index in the array has (neighbors that touch other neighbors are also included).</p>
<p>For the array I built I should get <code>6</code>, but instead I get a <strong>stack overflow exception</strong>, and I don't get why.</p>
<p>Below is my 7x7 array, that for index <code>2, 5</code> should return the value of <code>6</code>.</p>
<p>Example:</p>
<pre><code>static void Main(string[] args)
{
int[,] arr = {
{ 0,0,0,1,0,0,0 },
{ 1,0,0,1,1,0,0 },
{ 0,0,0,0,1,1,0 },
{ 0,0,0,0,1,0,0 },
{ 0,0,0,0,0,0,0 },
{ 0,1,1,1,1,0,0 },
{ 1,0,0,1,0,0,0 },
};
Console.WriteLine(Recursive(arr,2,5));
Console.ReadLine();
}
</code></pre>
<p>Routine under test:</p>
<pre><code>static public int Recursive(int[,] arr, int x, int y)
{
if (x < 0 || y < 0 || x > arr.GetLength(0) || y > arr.GetLength(1))
{
return 0;
}
// check if a 1 has neighbors
if (arr[x, y] == 1)
{
return 1 +
Recursive(arr, x - 1, y) +
Recursive(arr, x + 1, y) +
Recursive(arr, x, y - 1) +
Recursive(arr, x, y + 1);
}
else
{
return 0;
}
}
</code></pre>
| [
{
"answer_id": 74278557,
"author": "Dmitry Bychenko",
"author_id": 2319407,
"author_profile": "https://Stackoverflow.com/users/2319407",
"pm_score": 2,
"selected": false,
"text": "Recursive(arr, x, y)"
},
{
"answer_id": 74278584,
"author": "JonasH",
"author_id": 12342238,
"author_profile": "https://Stackoverflow.com/users/12342238",
"pm_score": 1,
"selected": false,
"text": "int[,] arr = { {1, 1 }}\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19899372/"
] |
74,278,504 | <p>{
"string": "This is a <strong>bold</strong> string"
}</p>
<p>I want to get the bold text to display it into the UI, and the string is coming from JSON file. Also, this string will be translated into another languages.
Like: - i18next.t('string')</p>
<p>I tried using and also passing tried changing the text nature, while passing it into i18next.t.</p>
| [
{
"answer_id": 74279805,
"author": "sanurah",
"author_id": 4079056,
"author_profile": "https://Stackoverflow.com/users/4079056",
"pm_score": 0,
"selected": false,
"text": "export function App(props) {\n\n const { t } = useTranslation();\n let str = boldStringPart();\n\n return (\n //word bold is already wrapped around b tag, so translate\n <div className='App'>\n <p>{ t(str) }</p>\n </div>\n );\n\n function boldStringPart() {\n let myjson = { \"string\": \"This is a bold string\" };\n //at this point it is english and we add b tag around word \"bold\"\n let newString = myjson.string.replace('bold', '<b>bold</b>');\n }\n}\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17941005/"
] |
74,278,522 | <p>I have a table like this:</p>
<pre><code>value ts
2.0 1
3.0 5
7.0 3
1.0 2
5.0 4
</code></pre>
<p>I need to select max value, min value and value with max ts. Is it possible to do it with one query? Is there an aggregate function which returns the first value from table? If so, I could do something like</p>
<pre><code>select max(value), min(value), first(value) from table order by ts desc;
</code></pre>
<p>(For this query max value is 7.0, min value is 1.0, and value with max ts is 3.0)</p>
| [
{
"answer_id": 74279045,
"author": "Ivan Yuzafatau",
"author_id": 1889110,
"author_profile": "https://Stackoverflow.com/users/1889110",
"pm_score": 1,
"selected": false,
"text": "SELECT\n t2.max_value,\n t2.min_value,\n t1.value\nFROM\n table AS t1\n JOIN\n (\n SELECT\n MAX(value) AS max_value,\n MIN(value) AS min_value,\n MAX(ts) AS max_ts\n FROM\n table\n ) AS t2 ON t2.max_ts = t1.ts \n"
},
{
"answer_id": 74280805,
"author": "The Impaler",
"author_id": 6436191,
"author_profile": "https://Stackoverflow.com/users/6436191",
"pm_score": 0,
"selected": false,
"text": "select min(value), max(value), (select value from t order by ts desc limit 1) from t\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14385918/"
] |
74,278,530 | <p>In my React JS project, I have a <strong>RequireAuth.js</strong> which is used to check if the user is authorized every time they change pages.
As an example, inside the const "confirmToken", I'm calling an async function that returns <code>true</code> if the user's token is valid or <code>false</code>.</p>
<pre class="lang-js prettyprint-override"><code>const confirmToken = async () => {
return await check();
};
var v = confirmToken().then((result) => {
return result;
});
</code></pre>
<p>It's working. But the variable <code>v</code> is returning as <code>Promise</code>.</p>
<pre><code>Promise {[[PromiseState]]: 'pending', [[PromiseResult]]: undefined}
</code></pre>
<p>I've checked other similar questions on Stack, but I still don't know what I'm getting wrong here.
Is there no way to return the boolean in a new variable?
My code is like this. The <code>allowedRoles</code> is a list of user levels that are passed in the route with RequireAuth.</p>
<pre class="lang-js prettyprint-override"><code>const RequireAuth = ({ allowedRoles }) => {
const location = useLocation();
try {
var t = UseToken();
var l = UseLevel();
} catch (error) {
return <Navigate to="/" state={{ from: location }} replace />;
}
const confirmToken = async () => {
return await checkToken(t);
};
var v = confirmToken().then((result) => {
return result;
});
return v & (l in allowedRoles) ? (
<Outlet />
) : v ? (
<Navigate to="/noAuthorized" state={{ from: location }} replace />
) : (
<Navigate to="/" state={{ from: location }} replace />
);
};
</code></pre>
<p><em>Obs: I am probably doing something really wrong here.</em></p>
<p>I need it to return a boolean so that the ternary works in the <code>return()</code>.</p>
| [
{
"answer_id": 74279045,
"author": "Ivan Yuzafatau",
"author_id": 1889110,
"author_profile": "https://Stackoverflow.com/users/1889110",
"pm_score": 1,
"selected": false,
"text": "SELECT\n t2.max_value,\n t2.min_value,\n t1.value\nFROM\n table AS t1\n JOIN\n (\n SELECT\n MAX(value) AS max_value,\n MIN(value) AS min_value,\n MAX(ts) AS max_ts\n FROM\n table\n ) AS t2 ON t2.max_ts = t1.ts \n"
},
{
"answer_id": 74280805,
"author": "The Impaler",
"author_id": 6436191,
"author_profile": "https://Stackoverflow.com/users/6436191",
"pm_score": 0,
"selected": false,
"text": "select min(value), max(value), (select value from t order by ts desc limit 1) from t\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12208182/"
] |
74,278,547 | <p>We have mysql table with below columns. I am given startDate and endDate and now I have to fetch rows between those dates. Can some one please help with mysql query with how I can get those rows?</p>
<p>For example if startDate is November 2021 and endDate is March 2022. Then query should select rows with the months between these dates.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>month</th>
<th>year</th>
<th>values</th>
</tr>
</thead>
<tbody>
<tr>
<td>09</td>
<td>2021</td>
<td>30</td>
</tr>
<tr>
<td>10</td>
<td>2021</td>
<td>40</td>
</tr>
<tr>
<td>11</td>
<td>2021</td>
<td>90</td>
</tr>
<tr>
<td>12</td>
<td>2021</td>
<td>10</td>
</tr>
<tr>
<td>01</td>
<td>2022</td>
<td>25</td>
</tr>
<tr>
<td>02</td>
<td>2022</td>
<td>15</td>
</tr>
<tr>
<td>03</td>
<td>2022</td>
<td>89</td>
</tr>
</tbody>
</table>
</div> | [
{
"answer_id": 74279045,
"author": "Ivan Yuzafatau",
"author_id": 1889110,
"author_profile": "https://Stackoverflow.com/users/1889110",
"pm_score": 1,
"selected": false,
"text": "SELECT\n t2.max_value,\n t2.min_value,\n t1.value\nFROM\n table AS t1\n JOIN\n (\n SELECT\n MAX(value) AS max_value,\n MIN(value) AS min_value,\n MAX(ts) AS max_ts\n FROM\n table\n ) AS t2 ON t2.max_ts = t1.ts \n"
},
{
"answer_id": 74280805,
"author": "The Impaler",
"author_id": 6436191,
"author_profile": "https://Stackoverflow.com/users/6436191",
"pm_score": 0,
"selected": false,
"text": "select min(value), max(value), (select value from t order by ts desc limit 1) from t\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8861430/"
] |
74,278,549 | <p>Entering a list comprehension into GHCi does not generate a list, the final square brackets are missing, and the console freezes. This is what I have come up with:</p>
<pre><code>[13*x + 3 | x <- [1..], rem (13*x + 3) 12 == 5, mod (13*x + 3) 11 == 0, 13*x + 3 <= 1000]
</code></pre>
<p>I believe the problem lies either with <code>x <- [1..]</code>, or <code>13*x + 3 <= 1000</code>. By <code>13*x + 3 <= 1000</code> I meant to determine the upper limit of the values x in <code>x <- [1..]</code> can take.</p>
<p>I'm given back a result <code>[341</code>, but it does the second square bracket is missing, and the console freezes.</p>
| [
{
"answer_id": 74278772,
"author": "Fyodor Soikin",
"author_id": 180286,
"author_profile": "https://Stackoverflow.com/users/180286",
"pm_score": 4,
"selected": true,
"text": "x"
},
{
"answer_id": 74283405,
"author": "Ben",
"author_id": 450128,
"author_profile": "https://Stackoverflow.com/users/450128",
"pm_score": -1,
"selected": false,
"text": "[ 13*x + 3 -- produce numbers of the form 13*x + 3\n| x <- [1..] -- by searching all x from [1..]\n, rem (13*x + 3) 12 == 5 -- allowing only x that meet this condition\n, mod (13*x + 3) 11 == 0 -- and this condition\n, 13*x + 3 <= 1000 -- and this condition\n]\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20373628/"
] |
74,278,559 | <p>If I have something like this:</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><div class="layout" background-color="#363636">
<div class="card">
<div data-src="https://example.com">Hello world</div>
</div>
<div class="card">
<div data-src="https://example2.com">Hello world</div>
</div>
<div class="card">
<div data-src="https://exampl3.com">Hello world</div>
</div>
<div class="card">
<div data-src="https://exampl4.com">Hello world</div>
</div>
<div class="card">
<div data-src="https://exampl5.com">Hello world</div>
</div>
<div class="card">
<div data-src="https://exampl6.com">Hello world</div>
</div>
<div class="card">
<div data-src="https://exampl7.com">Hello world</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>How can hide everything else (including the layout div) except for the element with attribute data-src="https://exampl4.com" using only CSS?</p>
| [
{
"answer_id": 74278700,
"author": "Muhammad Zarith",
"author_id": 17683245,
"author_profile": "https://Stackoverflow.com/users/17683245",
"pm_score": 0,
"selected": false,
"text": ".layout{\n visibility : hidden;\n}\n\n.layout > .card-visible {\n visibility: visible;\n}"
},
{
"answer_id": 74278829,
"author": "Rocky Barua",
"author_id": 16801529,
"author_profile": "https://Stackoverflow.com/users/16801529",
"pm_score": 2,
"selected": false,
"text": "[data-value: \"exact value\"]"
},
{
"answer_id": 74278909,
"author": "HackerFrosch",
"author_id": 20357737,
"author_profile": "https://Stackoverflow.com/users/20357737",
"pm_score": 0,
"selected": false,
"text": "visibility: hidden"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15648623/"
] |
74,278,563 | <p>I am trying to install a msi file using msiexec on Windows. This msi can be installed either into the default ProgramFiles dir or a custom dir specified in the msiexec command.
For example when the custom dir is specified, the command looks like this:</p>
<pre><code>msiexec /i installer_name.msi CUSTOM_DIR="C:\TEST" ALLUSERS=1
</code></pre>
<p>When CUSTOM_DIR is not specified then the command is</p>
<pre><code>msiexec /i installer_name.msi ALLUSERS=1
</code></pre>
<p>For this to work, I am changing a Wix file and creating Custom Action and Custom Action Id.</p>
<p>When CUSTOM_DIR is passed by the installer, then</p>
<pre><code><Custom Action='InstallAppCustom' Before='InstallFinalize'>VersionNT64 and (CUSTOM_DIR) and (ALLUSERS=1)</Custom>
</code></pre>
<p>and when the CUSTOM_DIR is not passed then</p>
<pre><code><Custom Action='InstallApp' Before='InstallFinalize'>VersionNT64 and (Not CUSTOM_DIR) and (ALLUSERS=1)</Custom>
</code></pre>
<p>My questions are:</p>
<ol>
<li><p>Is this the right way to check whether CUSTOM_DIR is passed or not? or any other right way to check it?</p>
</li>
<li><p>The issue here is that, irrespective of whether CUSTOM_DIR is passed or not, InstallAppCustom gets executed in the InstallExecuteSequence.</p>
</li>
</ol>
| [
{
"answer_id": 74291776,
"author": "scaler",
"author_id": 18161750,
"author_profile": "https://Stackoverflow.com/users/18161750",
"pm_score": 1,
"selected": false,
"text": "msiexec /i yourmsi /l*v setup.log"
},
{
"answer_id": 74364364,
"author": "hago",
"author_id": 8406780,
"author_profile": "https://Stackoverflow.com/users/8406780",
"pm_score": 0,
"selected": false,
"text": "<Property Id=\"DllPath32\" Value=\"[ProgramFilesFolder]\\App Name\\dependencies\"/>\n<Property Id=\"DllPath64\" Value=\"[ProgramFiles64Folder]\\App Name\\dependencies\"/>\n\n<!--CustomAction Id='SetDllPath64' Property='DllPath64' Value='[ProgramFiles64Folder]\\\\App Name' Return='check' /-->\n<!--CustomAction Id='SetDllPath32' Property='DllPath32' Value='[ProgramFilesFolder]\\\\App Name' Return='check' /-->\n\n<!--Custom Action='SetDllPath64' After='AppSearch'>VersionNT64</Custom-->\n<!--Custom Action='SetDllPath32' After='AppSearch'>Not VersionNT64</Custom-->\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8406780/"
] |
74,278,574 | <p>Below is the code from my <code>.htaccess</code> file:</p>
<pre><code>RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php74” package as the default “PHP” programming language.
<IfModule mime_module>
AddHandler application/x-httpd-ea-php74 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit
</code></pre>
<p>Below is what I want to search and replace:</p>
<ol>
<li><p><code>https://example.com/video-17i8mp51/27628401/0/ok-ask-me-right</code>
to
<code>https://example.com/video-17i8mp51/ok-ask-me-right</code></p>
</li>
<li><p><code>https://example.com/search/full+movie?top&id=57448561</code>
to
<code>https://example.com/search/full+movie</code></p>
</li>
<li><p>This URL is in over 10k of my site content's
<code>https://anothersiteurl.com/search/full+movie</code>
to
<code>https://mysiteurl.com/search/full+movie</code></p>
</li>
</ol>
| [
{
"answer_id": 74282888,
"author": "Aaron Meese",
"author_id": 6456163,
"author_profile": "https://Stackoverflow.com/users/6456163",
"pm_score": 0,
"selected": false,
"text": "RewriteEngine On\nRewriteBase /\n\n# First request:\n# Convert https://example.com/video-17i8mp51/27628401/0/ok-ask-me-right to\n# https://example.com/video-17i8mp51/ok-ask-me-right\nRewriteRule ^(video-[^/]+)/.+/(.+)/?$ $1/$2 [L]\n\n# Second request:\n# Convert https://example.com/search/full+movie?top&id=57448561 to\n# https://example.com/search/full+movie\nRewriteRule ^ %{REQUEST_URI}?\n\n# Third request:\n# Convert https://anothersiteurl.com/search/full+movie to\n# https://mysiteurl.com/search/full+movie\nRewriteRule ^(.*)$ https://mysiteurl.com/$1 [R=301,L]\n"
},
{
"answer_id": 74283413,
"author": "MrWhite",
"author_id": 369434,
"author_profile": "https://Stackoverflow.com/users/369434",
"pm_score": 1,
"selected": false,
"text": "https://example.com/video-17i8mp51/27628401/0/ok-ask-me-right"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19774446/"
] |
74,278,583 | <p>I want to interact with the Google's <a href="https://developers.google.com/drive/api" rel="nofollow noreferrer">Drive API</a> from a Cloud Function for Firebase. For authentication / authorization, I am currently relying on <code>getClient</code>, which I believe uses the Service Account exposed in the Cloud Function environment:</p>
<pre class="lang-js prettyprint-override"><code>import { google } from 'googleapis';
// Within the Cloud Function body:
const auth = await google.auth.getClient({
scopes: [
'https://www.googleapis.com/auth/drive.file',
],
});
const driveAPI = google.drive({ version: 'v3', auth });
// read files, create file etc. using `driveAPI`...
</code></pre>
<p>The above approach works, as long as target directories / files list the email address of the service account as an editor.</p>
<p>However, I'd like to interact with the Drive API <em>on behalf of another user</em> (which I control), so that this user becomes (for example) the owner of files being created. How can I achieve this?</p>
| [
{
"answer_id": 74282888,
"author": "Aaron Meese",
"author_id": 6456163,
"author_profile": "https://Stackoverflow.com/users/6456163",
"pm_score": 0,
"selected": false,
"text": "RewriteEngine On\nRewriteBase /\n\n# First request:\n# Convert https://example.com/video-17i8mp51/27628401/0/ok-ask-me-right to\n# https://example.com/video-17i8mp51/ok-ask-me-right\nRewriteRule ^(video-[^/]+)/.+/(.+)/?$ $1/$2 [L]\n\n# Second request:\n# Convert https://example.com/search/full+movie?top&id=57448561 to\n# https://example.com/search/full+movie\nRewriteRule ^ %{REQUEST_URI}?\n\n# Third request:\n# Convert https://anothersiteurl.com/search/full+movie to\n# https://mysiteurl.com/search/full+movie\nRewriteRule ^(.*)$ https://mysiteurl.com/$1 [R=301,L]\n"
},
{
"answer_id": 74283413,
"author": "MrWhite",
"author_id": 369434,
"author_profile": "https://Stackoverflow.com/users/369434",
"pm_score": 1,
"selected": false,
"text": "https://example.com/video-17i8mp51/27628401/0/ok-ask-me-right"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1023827/"
] |
74,278,644 | <pre class="lang-c prettyprint-override"><code>void main(){
int a;
scanf("%d",&a); // Need to check there is no character entered
printf("%d",a);
}
</code></pre>
<p>Here if i pass abc it will print <code>0</code>, if i pass <code>123abc</code> it will print <code>123</code>, but i need to throw an error in both the conditions.</p>
<p>Here how to check whether only numbers are being entered as input and to throw an error message if character is entered as input.
Is it possible to check keeping int as input datatype or should i use char array and check for isalpha condition by traversing the array.</p>
| [
{
"answer_id": 74278791,
"author": "William Pursell",
"author_id": 140750,
"author_profile": "https://Stackoverflow.com/users/140750",
"pm_score": 0,
"selected": false,
"text": "scanf"
},
{
"answer_id": 74278836,
"author": "CGi03",
"author_id": 18646208,
"author_profile": "https://Stackoverflow.com/users/18646208",
"pm_score": 2,
"selected": true,
"text": "#include <stdio.h>\n\nint main(void)\n{\n int number;\n printf(\"Your input: \");\n while(scanf(\"%d\", &number)!=1 || getchar()!='\\n')\n {\n scanf(\"%*[^\\n]%*c\");\n printf(\"you must enter an integer: \");\n }\n\n printf(\"%d\\n\", number);\n\n return 0;\n}\n"
},
{
"answer_id": 74280531,
"author": "willydlw",
"author_id": 2336843,
"author_profile": "https://Stackoverflow.com/users/2336843",
"pm_score": 0,
"selected": false,
"text": "#include <stdio.h>\n\n\nint main(void)\n{\n int returnValue;\n int number;\n \n /* \n scanf(\"%d\", &number) will return a value of 1 if it successfully reads an \n integer value. Otherwise it will return a value of 0 if it fails to read an \n integer value.\n\n The specifier d says to extract any number of decimal digits (0-9),\n optionally preceded by a sign (+ or -). \n \n Suppose the user enters the following input: -3 followed by the enter key press.\n \n Think of scanf as reading one input character at a time. The first character read\n is the minus sign '-'. Since the number may start with a minus, scanf reads the\n next character '3'. This is a decimal digit which fits the integer pattern. \n The next character is the enter key press '\\n' which causes scanf to stop reading\n the input. The characters '-' '3' are converted to the integer value -3 and \n are stored in the variable named number.\n\n The scanf function successfully read one integer value, so it returns a value\n of 1 and stores it in the variable returnValue.\n\n \n Suppose the user enters the following input: -3.0\n The value of -3 is read and stored in the variable number. When scanf reads \n the character '.', it stops reading information from the input stream \n because this character is not a decimal digit. The value -3 is stored in\n the variable number. The scanf function returns a value of 1 because it \n successfully read an integer.\n\n The characters '.' '0' '\\n' still remain in the standard input (stdin) buffer,\n waiting to be read from the input stream. The next time scanf is called \n to read from the stream, it will try to read the '.' If the program needs \n to read another number, we write code to clear the input stream of all \n remaining characters so that scanf does not fail when next trying to read \n numeric input.\n\n \n Suppose the user enters the following input: a-1\n\n The character 'a' is not a numeric digit. It will not be read from the \n input stream. scanf will return a value of zero and will not write \n write any value into the memory of the variable number.\n\n The characters 'a' '-' '1' \\n' all remain in the input stream.\n\n scanf will skip over leading whitespace characters when trying to read an integer.\n */\n \n returnValue = scanf(\"%d\", &number);\n\n printf(\"number: %d, returnValue: %d\\n\", number, returnValue);\n \n return 0;\n}\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14501169/"
] |
74,278,661 | <p>I'm trying to read 3 lines from the text file using the <code>getline()</code> function.</p>
<p>It was working fine when I was reading 2 lines, as I was able to differentiate by calculating if it's an odd or even line. But with 3 lines, it's not possible that way. So, is there any way to do this using the <code>getline()</code> function?</p>
<p>This is how the data looks in the text file:</p>
<p><a href="https://i.stack.imgur.com/agczT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/agczT.png" alt="image" /></a></p>
<p>I want to read it in a way that each set of 3 lines represents a separate node in the code. So, the 1st line of a node is the name of the contact, the 2nd line of a node is the contact group, and the 3rd line is the phone number. In that way, I have data for multiple nodes stored in a series.</p>
<pre><code>void reopenCB() {
bool isEmpty;
ifstream myfile("contactbook.txt");
if (myfile.is_open() & myfile.peek() != EOF) {
int i = 0;
while (getline(myfile, x)) {
if (i % 2 == 0) {
if (head == NULL) {
Node *newer = new Node;
newer->name = x;
newer->next = NULL;
newer->prev == NULL;
head = newer;
} else {
Node *newer = new Node;
newer->name = x;
newer->next = NULL;
Node *temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newer;
newer->prev = temp;
}
} else if (i % 2 != 0) {
Node *temp = head;
if (temp->phone_number == 0) {
stringstream convert(x);
convert >> z;
temp->phone_number = z;
} else {
Node *temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
stringstream convert(x);
convert >> z;
temp->phone_number = z;
}
}
}
myfile.close();
} else {
cout << " File is Empty so Cannot open...Sorry" << endl;
}
}
</code></pre>
<p>This was working fine when I'd read 2 lines, but now as I have 3 lines, it's not reading correct values.</p>
<p><strong>EDIT:</strong></p>
<p>Updated code, as suggested:</p>
<pre><code>void reopenCB() {
bool isEmpty;
ifstream myfile("contactbook.txt");
if (myfile.is_open() & myfile.peek() != EOF) {
int i = 0;
while (getline(myfile, x)) {
if (i % 3 == 0) {
if (head == NULL) {
Node *newer = new Node;
newer->name = x;
newer->next = NULL;
newer->prev == NULL;
head = newer;
} else {
Node *newer = new Node;
newer->name = x;
newer->next = NULL;
Node *temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newer;
newer->prev = temp;
}
} else if (i % 3 == 1) {
Node *temp = head;
if (temp->group_name == "") {
temp->group_name = y;
} else {
Node *temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->group_name = y;
}
} else if (i % 3 == 2) {
Node *temp = head;
if (temp->phone_number == 0) {
stringstream convert(x);
convert >> z;
temp->phone_number = z;
} else {
Node *temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
stringstream convert(x);
convert >> z;
temp->phone_number = z;
}
}
i++;
}
myfile.close();
} else {
cout << " File is Empty so Cannot open...Sorry" << endl;
}
}
</code></pre>
| [
{
"answer_id": 74278926,
"author": "Some programmer dude",
"author_id": 440558,
"author_profile": "https://Stackoverflow.com/users/440558",
"pm_score": 3,
"selected": false,
"text": "std::string name1, name2, phone;\nwhile (std::getline(myfile, name1) &&\n std::getline(myfile, name2) &&\n std::getline(myfile, phone))\n{\n // Create a node and initialize it with all values\n // Add the node to your list\n}\n"
},
{
"answer_id": 74279026,
"author": "Kolbjørn",
"author_id": 10433833,
"author_profile": "https://Stackoverflow.com/users/10433833",
"pm_score": 0,
"selected": false,
"text": "if (i % 2 == 0)"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18537079/"
] |
74,278,663 | <p>I have created a form with a submit button using mat-raised-button but it does nothing</p>
<p>I was expecting it to print something to console using the onSubmit() function in my TS file.
I tried using a normal button but still not working. What am I doing wrong here.</p>
<p>HTML:
`</p>
<pre><code><div class="center">
<form class="my-form" (ngSubmit)="onSubmit()">
<p>
<mat-form-field appearance="legacy">
<mat-label>First name</mat-label>
<input type="text" name= "firstname" matInput ngModel>
</mat-form-field>
</p>
<p>
<mat-form-field appearance="legacy">
<mat-label>Last name</mat-label>
<input type="text" name= "lastname" matInput ngModel>
</mat-form-field>
</p>
<p>
<mat-form-field appearance="legacy">
<mat-label>Employee number</mat-label>
<input type="text" name= "employeenumber" matInput ngModel>
</mat-form-field>
</p>
<p>
<mat-form-field appearance="legacy">
<mat-label>Favorite Superhero</mat-label>
<input type="text" name= "favoritesuperhero" matInput ngModel>
</mat-form-field>
</p>
<p>
<mat-form-field appearance="legacy">
<mat-label>Email</mat-label>
<input type="text" name= "email" matInput ngModel>
</mat-form-field>
</p>
<a mat-raised-button type="submit" class="btncolor">Sign Up!</a>
</form>
</div>
</code></pre>
<p>`</p>
<p>TS;</p>
<p>`</p>
<pre><code>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-signupform',
templateUrl: './signupform.component.html',
styleUrls: ['./signupform.component.scss']
})
export class SignupformComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
onSubmit(){
console.log('Sign up complete')
}
}
</code></pre>
<p>`</p>
| [
{
"answer_id": 74278729,
"author": "Yew Hong Tat",
"author_id": 1925886,
"author_profile": "https://Stackoverflow.com/users/1925886",
"pm_score": 0,
"selected": false,
"text": "<a mat-raised-button type=\"submit\" class=\"btncolor\" (click)=\"onSubmit()\">Sign Up!</a>\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8876662/"
] |
74,278,681 | <p>Here is a minimal reproducible example:</p>
<pre class="lang-py prettyprint-override"><code>class Attribut:
def __init__(
self,
name: str,
other_name: str,
):
self.name: str = name
self.other_name: str = other_name
def __eq__(self, other):
if isinstance(other, Attribut):
return self.name == other.name and self.other_name == other.other_name
else:
return NotImplemented
def __hash__(self):
return 0
</code></pre>
<p>If I try to do:</p>
<pre class="lang-py prettyprint-override"><code>a = Attribut("lol", "a")
print(a==4)
</code></pre>
<p>I thought I would get <code>NotImplemented</code>, but instead I get <code>False</code>.</p>
<p>EDIT: (following chepner's answer)
Comparing one object from one class to an object to another class instead of comparing it to an integer:</p>
<pre class="lang-py prettyprint-override"><code>class Attribut:
def __init__(
self,
name: str,
other_name: str,
):
self.name: str = name
self.other_name: str = other_name
def __eq__(self, other):
if isinstance(other, Attribut):
return self.name == other.name and self.other_name == other.other_name
else:
return NotImplemented
def __hash__(self):
return 0
class Attribut2:
def __init__(
self,
name: str,
other_name: str,
):
self.name: str = name
self.other_name: str = other_name
def __eq__(self, other):
if isinstance(other, Attribut2):
return self.name == other.name and self.other_name == other.other_name
else:
return NotImplemented
def __hash__(self):
return 1
a = Attribut("lol", "a")
b = Attribut2("lol", "b")
print(a==b)
</code></pre>
<p>I also get <code>False</code>.</p>
<p>Also, what is the point of overriding <code>__hash__</code>, I cannot find a situation where this is useful?</p>
| [
{
"answer_id": 74278729,
"author": "Yew Hong Tat",
"author_id": 1925886,
"author_profile": "https://Stackoverflow.com/users/1925886",
"pm_score": 0,
"selected": false,
"text": "<a mat-raised-button type=\"submit\" class=\"btncolor\" (click)=\"onSubmit()\">Sign Up!</a>\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11092636/"
] |
74,278,695 | <p>I want to delete the <strong>Unnamed</strong> columns in the following data frame <code>df</code> (to download from <a href="https://data.london.gov.uk/dataset/earnings-place-residence-borough" rel="nofollow noreferrer">this link</a>):</p>
<pre><code>df1 = pd.read_excel('./earnings-residence-borough.xlsx', sheet_name='Total, weekly', skiprows=[1, 2], header=0)
df1.head(5)
</code></pre>
<p><a href="https://i.stack.imgur.com/Hr2rU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hr2rU.jpg" alt="enter image description here" /></a></p>
<pre><code>print(df.columns)
</code></pre>
<p>Out:</p>
<pre><code>Index([ 'Code', 'Area', 2002, 'Unnamed: 3',
2003, 'Unnamed: 5', 2004, 'Unnamed: 7',
2005, 'Unnamed: 9', 2006],
dtype='object')
</code></pre>
<p>Can someone help? Thanks.</p>
<p>I have tried several methods and I get errors, eg.:</p>
<ul>
<li><p>Solution 1:</p>
<p><code>df.loc[:, ~df.columns.str.contains('^Unnamed')]</code></p>
</li>
</ul>
<p>Out:</p>
<pre><code>`TypeError: bad operand type for unary ~: 'Index'`
</code></pre>
<ul>
<li><p>Solution 2:</p>
<p><code>remove_cols = [col for col in df.columns if 'Unnamed' in col] df.drop(remove_cols, axis='columns', inplace=True)</code></p>
</li>
</ul>
<p>Out:</p>
<pre><code>`TypeError: argument of type 'int' is not iterable`
</code></pre>
<ul>
<li><p>Solution 3:</p>
<p><code>df.drop(df.columns[df.columns.str.contains('Unnamed',case = False)],axis = 1, inplace = True)</code></p>
</li>
</ul>
<p>Out:</p>
<pre><code>ValueError: Cannot mask with non-boolean array containing NA / NaN values
df.columns.str.contains('^Unnamed')
</code></pre>
<p>Out:</p>
<pre><code>Index([False, False, nan, True, nan, True, nan, True, nan, True,
nan, True, nan, True, nan, True, nan, True, nan, True,
nan, True, nan, True, nan, True, nan, True, nan, True,
nan, True, nan, True, nan, True, nan, True, nan, True,
nan, True],
dtype='object')
</code></pre>
| [
{
"answer_id": 74278806,
"author": "jacl613 max31",
"author_id": 20132308,
"author_profile": "https://Stackoverflow.com/users/20132308",
"pm_score": 2,
"selected": true,
"text": "cols = [col for col in df.columns.values if 'Unnamed' not in str(col)]\ndf = df[cols]\n"
},
{
"answer_id": 74282977,
"author": "ah bon",
"author_id": 8410477,
"author_profile": "https://Stackoverflow.com/users/8410477",
"pm_score": 0,
"selected": false,
"text": "df.drop(df.filter(regex=\"Unname\"), axis=1, inplace=True)"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8410477/"
] |
74,278,705 | <p>I have a MacBook air and have tried opening Python in terminal but when I open it, it opens Python interactive mode. Does anyone know how to open Python script mode please.</p>
<p>I’ve tried typing in things such as Python or Python 3 like safari suggests but that didn’t work.</p>
| [
{
"answer_id": 74278806,
"author": "jacl613 max31",
"author_id": 20132308,
"author_profile": "https://Stackoverflow.com/users/20132308",
"pm_score": 2,
"selected": true,
"text": "cols = [col for col in df.columns.values if 'Unnamed' not in str(col)]\ndf = df[cols]\n"
},
{
"answer_id": 74282977,
"author": "ah bon",
"author_id": 8410477,
"author_profile": "https://Stackoverflow.com/users/8410477",
"pm_score": 0,
"selected": false,
"text": "df.drop(df.filter(regex=\"Unname\"), axis=1, inplace=True)"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20104014/"
] |
74,278,713 | <p>I want to select all elements matching <code>nth-child(2n)</code> in a list except for the first matching element; for example...</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>li:nth-child(2n) {
background: red;
}
li:nth-child(2) {
background: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
<li>Six</li>
<li>Seven</li>
<li>Eight</li>
<li>Nine</li>
<li>Ten</li>
</ul></code></pre>
</div>
</div>
</p>
<p>The result of this is that only Four, Six, Eight and Ten have a red background color.</p>
<p>I would like to know if there's a better way of expressing the CSS rules though, and if it's possible to express as a single rule:</p>
<pre class="lang-css prettyprint-override"><code>li:nth-child(2n) {
background: red;
}
li:nth-child(2) {
background: none;
}
</code></pre>
<p>Can these be combined and still behave the same way?</p>
| [
{
"answer_id": 74278754,
"author": "Sean",
"author_id": 5351721,
"author_profile": "https://Stackoverflow.com/users/5351721",
"pm_score": 3,
"selected": true,
"text": ":not()"
},
{
"answer_id": 74278875,
"author": "kalawaja",
"author_id": 19503844,
"author_profile": "https://Stackoverflow.com/users/19503844",
"pm_score": -1,
"selected": false,
"text": "li:nth-child(2n+4) {\n background: red;\n}\n"
},
{
"answer_id": 74278886,
"author": "j08691",
"author_id": 616443,
"author_profile": "https://Stackoverflow.com/users/616443",
"pm_score": 1,
"selected": false,
"text": "li:nth-child(2n + 4)"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1033686/"
] |
74,278,732 | <p>I was working with loops and stuck with this problem.</p>
<p>I had <em><strong>declared a variable outside the main code</strong></em> and then <strong>used it in the loop</strong>, but when I am returning the value of that variable after that loop, <em><strong>I am unable to get that value again</strong></em>.</p>
<pre><code>int n;
int main () {
// Sum of N natural numbers using FOR LOOP
// 1st METHOD
cin>>n;
int sum = 0;
for(int i=1 ; i<=n ; i++){
sum=sum+i;
}
cout<<"\nThe sum of first "<<n<<" natural number is : "<<sum<<endl;
// 2nd METHOD
int sum4=0;
for( n ; n>0 ; n--){
sum4+=n;
}
cout<<"\nThe sum of first "<< :: n<<" natural number is : "<<sum4<<endl;
// Sum of N natural numbers using WHILE LOOP
int sum1=0;
while(n>0){
sum1+=n;
n--;
}
cout<<"\nThe sum of first "<<n<<" natural number is : "<<sum1<<endl;
// Sum of N natural numbers using DO WHILE LOOP
int sum2=0;
do{
sum2+=n;
n--;
} while(n>0);
cout<<"\nThe sum of first "<<n<<" natural number is : "<<sum2<<endl;
return 0;
}
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>The sum of first 55 natural number is : 1540
The sum of first **0** natural number is : 1540
The sum of first **0 **natural number is : **0**
The sum of first **-1** natural number is : **0**
</code></pre>
<p>Can I declare a universal variable and use it in a loop, and at the same time after the loop quits it does not change the value of that variable and give the output as declared?</p>
| [
{
"answer_id": 74278967,
"author": "Caleth",
"author_id": 2610810,
"author_profile": "https://Stackoverflow.com/users/2610810",
"pm_score": 3,
"selected": true,
"text": "for(int i=n; i>0 ; i--){\n sum4+=i;\n}\n\nint sum1=0;\nint i = n;\nwhile(i>0){\n sum1+=i;\n i--;\n}\n\nint sum2=0;\ni = n;\ndo{\n sum2+=i;\n i--;\n} while(i>0);\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20389642/"
] |
74,278,763 | <p>I am trying to figure out how to write a integer value to the end of my file. The value is <code>size</code>.</p>
<pre><code>DWORD size = 12314432;
BOOL ret = WriteFile(hFile, size, sizeof(DWORD), NULL, NULL);
</code></pre>
<p>However <code>WriteFile()</code> requires that parameter 3 be of type <code>LPCVOID</code> so I am not sure how I would give it the DWORD instead.</p>
<p>I have tried..</p>
<pre><code>unsigned char b[sizeof(DWORD)] = {0};
sprintf(b, "%d", size);
WriteFile(hFile, b, sizeof(DWORD), NULL, NULL);
</code></pre>
<p>However this just puts the hex value of each digit. So if size=1234 then it would write "31 32 33 44" to end of the file.</p>
<p>I would like the end of the file to just get the number in 4 bytes.</p>
| [
{
"answer_id": 74278802,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 0,
"selected": false,
"text": "(void*)&size"
},
{
"answer_id": 74278825,
"author": "the busybee",
"author_id": 11294831,
"author_profile": "https://Stackoverflow.com/users/11294831",
"pm_score": 2,
"selected": false,
"text": "DWORD size = 12314432;\nBOOL ret = WriteFile(hFile, &size, sizeof size, NULL, NULL);\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20389799/"
] |
74,278,780 | <p>I have a <em>.tsv</em> file from which I've created a <strong>pyhton dictionary</strong> where the <em>keys</em> are all the <strong>movie_id</strong> and the <em>values</em> are the <strong>features</strong> (every movie has a different number of features).</p>
<h2>Here's an example of my dictionary:</h2>
<p><a href="https://i.stack.imgur.com/iySxB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iySxB.png" alt="enter image description here" /></a></p>
<h1>Goal to achieve:</h1>
<p>From this dictionary I want to create an <em><strong>item-features sparse matrix</strong></em> to use for a recommender system project.
At the end I would like to have a <strong>binary sparse matrix</strong> with 1 when a movie has a certain feature.
Something like this:</p>
<p><a href="https://i.stack.imgur.com/6LW5Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6LW5Y.png" alt="enter image description here" /></a></p>
<h1>My code:</h1>
<h3>To create the dictionary:</h3>
<pre><code>def Dictionary():
d={}
l=[]
with open(filepath_mapping) as f:
for line in f.readlines():
line = line.split()
key = int(line[0])
value = [int(el) for el in line[1:]]
d[key] = value
return(d)
movie_features_dict = Dictionary()
</code></pre>
<h3>To create the item-features matrix from the dictionary:</h3>
<pre><code>n = len(movie_features_dict)
value_lengths = [len(v) for v in movie_features_dict.values()]
d = max(value_lengths)
print(f"ITEM*FEATURES matrix shape: {n,d}\n")
item_feature_matrix = sp.dok_matrix((n,d), dtype=np.int8)
for movie_ids, features in movie_features_dict.items():
item_feature_matrix[movie_ids, features] = 1
item_feature_matrix = item_feature_matrix.tocsr()
print(item_feature_matrix.shape)
</code></pre>
<h3>Issues:</h3>
<p>I have 22069 movies and the movie with the maximum number of features should have 885 features, so theoretically I should have a <strong>22069*885 matrix</strong>, but with the code I've written I continue having this error:</p>
<pre><code>raise IndexError('index (%d) out of range' % max_indx)
IndexError: index (614734) out of range
</code></pre>
| [
{
"answer_id": 74278802,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 0,
"selected": false,
"text": "(void*)&size"
},
{
"answer_id": 74278825,
"author": "the busybee",
"author_id": 11294831,
"author_profile": "https://Stackoverflow.com/users/11294831",
"pm_score": 2,
"selected": false,
"text": "DWORD size = 12314432;\nBOOL ret = WriteFile(hFile, &size, sizeof size, NULL, NULL);\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14846176/"
] |
74,278,850 | <p>I am doing this as an pattern matching exercise.</p>
<p>I would like to have a function that will work on both <code>Num</code> type and <code>List</code> type. For example:</p>
<pre><code>double 20
double [1,2,3,4,5]
</code></pre>
<p>The code works till</p>
<pre><code>double [] = []
double (x : xs) = (2 * x) : (double xs)
main = do
let x = [1,2,3,4,5]
print (double x)
</code></pre>
<p>But when I try:</p>
<pre><code>double x = x + x
double [] = []
double (x : xs) = (2 * x) : (double xs)
main = do
let x = [1,2,3,4,5]
print (double 20)
print (double x)
</code></pre>
<p>It gives error.</p>
<p>What should be done here?</p>
| [
{
"answer_id": 74279175,
"author": "Haren S",
"author_id": 10763533,
"author_profile": "https://Stackoverflow.com/users/10763533",
"pm_score": 4,
"selected": true,
"text": "Integer"
},
{
"answer_id": 74279269,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 2,
"selected": false,
"text": "Either Int [Int]"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772898/"
] |
74,278,851 | <p>I have a long list of dates (starting from 1942-1-1 00:00:00 to 2012-12-31 24:00:00). These are associated with some amounts respectively (see below). Is there a way to first filter all amounts for one day separately, and then add them up together?</p>
<p>For example for 1942-01-01, how to find all values (amounts) that occur in this day (from time 0 to 24) and then sum them together?</p>
<pre><code> time amount
DateTime Float64
1942-01-01T00:00:00 7.0
1942-01-02T00:00:00 0.2
1942-01-03T00:00:00 2.1
1942-01-04T00:00:00 3.0
:
2012-12-31T23:00:00 4.0
2012-12-31T24:00:00 0.0
</code></pre>
<pre><code>df = CSV.read(path, DataFrame)
for i in 1:24
filter(r ->hour(r.time) == i, df)
end
</code></pre>
| [
{
"answer_id": 74279169,
"author": "Bogumił Kamiński",
"author_id": 1269567,
"author_profile": "https://Stackoverflow.com/users/1269567",
"pm_score": 3,
"selected": true,
"text": "julia> df = DataFrame(time=[DateTime(2020, 1, rand(1:2), rand(0:23)) for _ in 1:100], amount=rand(100))\n100×2 DataFrame\n Row │ time amount\n │ DateTime Float64\n─────┼────────────────────────────────\n 1 │ 2020-01-02T16:00:00 0.29325\n 2 │ 2020-01-02T02:00:00 0.376917\n 3 │ 2020-01-02T09:00:00 0.11849\n 4 │ 2020-01-02T04:00:00 0.462997\n ⋮ │ ⋮ ⋮\n 97 │ 2020-01-02T18:00:00 0.750604\n 98 │ 2020-01-01T13:00:00 0.179414\n 99 │ 2020-01-01T15:00:00 0.552547\n 100 │ 2020-01-01T02:00:00 0.769066\n 92 rows omitted\n\njulia> transform!(df, :time => ByRow(Date) => :date, :time => ByRow(hour) => :hour)\n100×4 DataFrame\n Row │ time amount date hour\n │ DateTime Float64 Date Int64\n─────┼───────────────────────────────────────────────────\n 1 │ 2020-01-02T16:00:00 0.29325 2020-01-02 16\n 2 │ 2020-01-02T02:00:00 0.376917 2020-01-02 2\n 3 │ 2020-01-02T09:00:00 0.11849 2020-01-02 9\n 4 │ 2020-01-02T04:00:00 0.462997 2020-01-02 4\n ⋮ │ ⋮ ⋮ ⋮ ⋮\n 97 │ 2020-01-02T18:00:00 0.750604 2020-01-02 18\n 98 │ 2020-01-01T13:00:00 0.179414 2020-01-01 13\n 99 │ 2020-01-01T15:00:00 0.552547 2020-01-01 15\n 100 │ 2020-01-01T02:00:00 0.769066 2020-01-01 2\n 92 rows omitted\n\njulia> unstack(df, :hour, :date, :amount, combine=sum, fill=0)\n24×3 DataFrame\n Row │ hour 2020-01-02 2020-01-01\n │ Int64 Float64 Float64\n─────┼───────────────────────────────\n 1 │ 16 1.06636 0.949414\n 2 │ 2 0.990913 1.43032\n 3 │ 9 0.183206 3.16363\n 4 │ 4 1.24055 0.57196\n ⋮ │ ⋮ ⋮ ⋮\n 21 │ 10 0.0 0.492397\n 22 │ 14 0.393438 0.0\n 23 │ 21 0.0 0.487992\n 24 │ 8 0.848852 0.0\n 16 rows omitted\n"
},
{
"answer_id": 74281910,
"author": "julia_user123",
"author_id": 20392047,
"author_profile": "https://Stackoverflow.com/users/20392047",
"pm_score": 3,
"selected": false,
"text": "InMemoryDatasets.jl"
},
{
"answer_id": 74282582,
"author": "giantmoa",
"author_id": 20258205,
"author_profile": "https://Stackoverflow.com/users/20258205",
"pm_score": 3,
"selected": false,
"text": "using InMemoryDatasets\nds=Dataset(time=DateTime(\"1942-01-01\"):Hour(1):DateTime(\"2012-12-31\"))\nds.amount = rand(nrow(ds))\ndatefmt(x) = round(x, Hour, RoundDown)\nsetformat!(ds, :time=>datefmt)\ncombine(gatherby(ds,:time), :amount=>IMD.sum)\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20389649/"
] |
74,278,898 | <p>I'm making a transformer using <code>tensorflow.keras</code> and having issues understanding how the <code>attention_mask</code> works for a <code>MultiHeadAttention</code> layer.</p>
<p>My input is 3-dimensional data. For example, let's assume my whole dataset has 10 elements, each one with length no more than 4:</p>
<pre class="lang-py prettyprint-override"><code># whole data
[
# first item
[
[ 1, 2, 3],
[ 1, 2, 3],
[np.nan, np.nan, np.nan],
[np.nan, np.nan, np.nan],
],
# second item
[
[ 1, 2, 3],
[ 5, 8, 2],
[ 3, 7, 8],
[ 4, 6, 2],
],
... # 8 more items
]
</code></pre>
<p>So, my mask looks like:</p>
<pre class="lang-py prettyprint-override"><code># assume this is a numpy array
mask = [
[
[1, 1, 1],
[1, 1, 1],
[0, 0, 0],
[0, 0, 0],
],
[
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
],
...
]
</code></pre>
<p>So the shape of the mask til now is <code>[10, 4, 3]</code>. Let's say I use <code>batch_size = 5</code>. Now, according documentation, <code>attention_mask</code> shape should be <code>[B, T, S]</code> (batch_size, query_size, key_size). In the example case should be <code>[5, 4, 4]</code>?</p>
<h2>Question</h2>
<p><strong>If the mask is calculated only once, what 5 items should I give as a mask? This sounds counterintuitive to me. How should I build the mask?</strong></p>
<p>According <a href="https://stackoverflow.com/questions/67805117/multiheadattention-attention-mask-keras-tensorflow-example">this</a> answer, head_size should be also taken in account, so they also do:</p>
<pre class="lang-py prettyprint-override"><code>mask = mask[:, tf.newaxis, tf.newaxis, :]
</code></pre>
<h2>What I've tested</h2>
<p>The only time I manage to run the transformer successfully using the <code>attention_mask</code> is when I do:</p>
<pre class="lang-py prettyprint-override"><code>mask = np.ones((batch_size, data.shape[1], data.shape[2]))
mask = mask[:, tf.newaxis, tf.newaxis, :]
</code></pre>
<p>Obviously that mask makes no sense, because it is all ones, but it was just to test if it had the correct shape.</p>
<h2>The model</h2>
<p>I'm using practically the same code from the <code>keras</code> <a href="https://keras.io/examples/timeseries/timeseries_classification_transformer/" rel="nofollow noreferrer">example</a> transformer for time series classification</p>
<pre class="lang-py prettyprint-override"><code>def transformer_encoder(inputs, head_size, num_heads, ff_dim, dropout=0.0, mask=None):
# Normalization and Attention
x = layers.LayerNormalization(epsilon=1e-6)(inputs)
x = layers.MultiHeadAttention(
key_dim=head_size, num_heads=num_heads, dropout=dropout
)(x, x, attention_mask=mask)
x = layers.Dropout(dropout)(x)
res = x + inputs
# Feed Forward Part
x = layers.LayerNormalization(epsilon=1e-6)(res)
x = layers.Conv1D(filters=ff_dim, kernel_size=1, activation="relu")(x)
x = layers.Dropout(dropout)(x)
x = layers.Conv1D(filters=inputs.shape[-1], kernel_size=1)(x)
return x + res
def build_model(
n_classes,
input_shape,
head_size,
num_heads,
ff_dim,
num_transformer_blocks,
mlp_units,
dropout=0.0,
mlp_dropout=0.0,
input_mask=None,
) -> keras.Model:
inputs = keras.Input(shape=input_shape)
x = inputs
for _ in range(num_transformer_blocks):
x = transformer_encoder(x, head_size, num_heads, ff_dim, dropout, input_mask)
x = layers.GlobalAveragePooling2D(data_format="channels_first")(x)
for dim in mlp_units:
x = layers.Dense(dim, activation="relu")(x)
x = layers.Dropout(mlp_dropout)(x)
outputs = layers.Dense(n_classes, activation="softmax")(x)
return keras.Model(inputs, outputs)
</code></pre>
| [
{
"answer_id": 74293100,
"author": "V.M",
"author_id": 8143158,
"author_profile": "https://Stackoverflow.com/users/8143158",
"pm_score": 1,
"selected": false,
"text": "MultiHeadAttention"
},
{
"answer_id": 74329767,
"author": "Jorge Morgado",
"author_id": 11915595,
"author_profile": "https://Stackoverflow.com/users/11915595",
"pm_score": 1,
"selected": true,
"text": "TransformerBlock"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11915595/"
] |
74,278,899 | <p>Sorry for noob question. Just started learning coding with Python - beginners level.
Wasn't able to find in the net what I require.
Creating function to loop through the entire line, in order to find right combination - 7,8,9 - regardless of input length and of target position, and return 'true' if found. Wasn't able to devise the function correctly. Not sure how to devise function clearly and at all this far.
Your help is much appreciated.
This is what I came up with so far (not working of course):</p>
<pre><code>def _11(n):
for loop in range(len(n)):
if n[loop]==[7,8,9]:
return True
else:
return False
print(_11([1000,10,11,34,67,89,334,5567,6534,765,2,3,5,6,112,7,8,9,11111]))
</code></pre>
<p>It always returns False. Tried with (*n) to no avail.</p>
| [
{
"answer_id": 74279039,
"author": "E Joseph",
"author_id": 18011737,
"author_profile": "https://Stackoverflow.com/users/18011737",
"pm_score": 0,
"selected": false,
"text": "import re\n\ndef _11(n):\n if re.search(\"(?<![0-9-.'])7, 8, 9(?![0-9.])\",str(n)):\n return True\n return False\n\nprint(_11([27,8,9]))\n"
},
{
"answer_id": 74279056,
"author": "Carson",
"author_id": 4930913,
"author_profile": "https://Stackoverflow.com/users/4930913",
"pm_score": 0,
"selected": false,
"text": "n[loop]"
},
{
"answer_id": 74279219,
"author": "user3435121",
"author_id": 3435121,
"author_profile": "https://Stackoverflow.com/users/3435121",
"pm_score": 0,
"selected": false,
"text": "def _11(n):\n for loop in range(len(n)-3):\n if n[loop:loop+3]==[7,8,9]:\n return True\n else:\n return False\nprint(_11([1000,10,11,34,67,89,334,5567,6534,765,2,3,5,6,112,7,8,9,11111]))\n"
},
{
"answer_id": 74320938,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 1,
"selected": false,
"text": "from timeit import timeit\n\ndef _11(n, t):\n offset = 0\n lt = len(t)\n m = len(n) - lt\n while offset < m:\n try:\n offset += n[offset:].index(t[0])\n if n[offset:offset+lt] == t:\n return True\n offset += 1\n except ValueError:\n break\n return False\n\ndef _11a(n, t):\n for index in range(len(n) - len(t)):\n if n[index:index + len(t)] == t:\n return True\n return False\n\nn = [1000,10,11,34,67,89,334,5567,6534,765,2,3,5,6,112,7,8,9,11111]\nt = [7, 8, 9]\n\nfor func in _11, _11a:\n print(func.__name__, timeit(lambda: func(n, t)))\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20389605/"
] |
74,278,933 | <p>Im working with C on MacOS, when i compile the program by myself with</p>
<pre class="lang-none prettyprint-override"><code>gcc main.c -o prog $(sdl2-config --cflags --libs)
</code></pre>
<p>It works fine, but when i try to make it work with a makefile i keep facing this error</p>
<pre class="lang-none prettyprint-override"><code>gcc -o main.o -c main.c prog
clang: warning: prog: 'linker' input unused [-Wunused-command-line-argument]
main.c:1:10: fatal error: 'SDL.h' file not found
#include <SDL.h>
</code></pre>
<p>There is my code</p>
<pre><code>#include <SDL2/SDL.h>
#include <stdio.h>
#include <stdbool.h>
int main (int argc, char **argv)
{
SDL_Window *window = NULL;
if ( SDL_Init(SDL_INIT_VIDEO) != 0)
{
SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
exit(EXIT_FAILURE);
}
window = SDL_CreateWindow("Bomberman", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_MINIMIZED);
if (window == NULL)
{
SDL_Log("Unable to create window: %s", SDL_GetError());
exit(EXIT_FAILURE);
}
bool window_open = true;
while (window_open)
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
window_open = false;
}
}
}
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
</code></pre>
<p>And here is my makefile</p>
<pre><code>main.o: main.c
gcc -o main.o -c main.c prog $(sdl2-config --cflags --libs)
</code></pre>
| [
{
"answer_id": 74279039,
"author": "E Joseph",
"author_id": 18011737,
"author_profile": "https://Stackoverflow.com/users/18011737",
"pm_score": 0,
"selected": false,
"text": "import re\n\ndef _11(n):\n if re.search(\"(?<![0-9-.'])7, 8, 9(?![0-9.])\",str(n)):\n return True\n return False\n\nprint(_11([27,8,9]))\n"
},
{
"answer_id": 74279056,
"author": "Carson",
"author_id": 4930913,
"author_profile": "https://Stackoverflow.com/users/4930913",
"pm_score": 0,
"selected": false,
"text": "n[loop]"
},
{
"answer_id": 74279219,
"author": "user3435121",
"author_id": 3435121,
"author_profile": "https://Stackoverflow.com/users/3435121",
"pm_score": 0,
"selected": false,
"text": "def _11(n):\n for loop in range(len(n)-3):\n if n[loop:loop+3]==[7,8,9]:\n return True\n else:\n return False\nprint(_11([1000,10,11,34,67,89,334,5567,6534,765,2,3,5,6,112,7,8,9,11111]))\n"
},
{
"answer_id": 74320938,
"author": "Cobra",
"author_id": 17580381,
"author_profile": "https://Stackoverflow.com/users/17580381",
"pm_score": 1,
"selected": false,
"text": "from timeit import timeit\n\ndef _11(n, t):\n offset = 0\n lt = len(t)\n m = len(n) - lt\n while offset < m:\n try:\n offset += n[offset:].index(t[0])\n if n[offset:offset+lt] == t:\n return True\n offset += 1\n except ValueError:\n break\n return False\n\ndef _11a(n, t):\n for index in range(len(n) - len(t)):\n if n[index:index + len(t)] == t:\n return True\n return False\n\nn = [1000,10,11,34,67,89,334,5567,6534,765,2,3,5,6,112,7,8,9,11111]\nt = [7, 8, 9]\n\nfor func in _11, _11a:\n print(func.__name__, timeit(lambda: func(n, t)))\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18428648/"
] |
74,278,962 | <p>I have class Movie. Movie constructor should provide a generation of unique product id within the application no matter how many products are created. You also need to define a field with the name of the movie. But according to the condition, for this I have to use Symbol data type. How can i do this?</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>class Movie {
constructor(name) {
//here I need to generate a unique id;
//here I need to define name fields
}
}</code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74279426,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": 0,
"selected": false,
"text": "class Movie {\n sym = Symbol('symbol description')\n\n constructor(name) {\n this.symInConstructor = Symbol('symbol description')\n // this.sym != this.symInConstructor\n // M1.sym == M2.sym <=> M1 == M2\n }\n}\n// remeber, Symbol() != Symbol(), each call creates a unique one\n"
},
{
"answer_id": 74279528,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": -1,
"selected": false,
"text": "const MovieName = Symbol('a key for MovieName') \n\nclass Movie {\n\n [MovieName] = \"The Movie\";\n\n [\"myString\"] = \"is equivalent to:\"\n // myString = \"is equivalent to:\"\n // and must be used for Symbols as\n\n constructor() {\n this[MovieName] = \"The Movie in constructor\"\n }\n\n // may keep is somewhere like this for usage in other places\n static movieNameSymbol = MovieName\n}\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74278962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20291334/"
] |
74,279,000 | <p>I'm using the latest Vaadin 14 LTS Verson (14.8.20)
Upon building my project, intellij suggested installing the npm packages from the automatically created package.json.
NPM then told me it found 12 vulnerabilities of which 11 have a high severity.
So is Vaadin using outdated packages here? Is it dangerous to use this in production?
The output of npm audit fix is:</p>
<pre><code>up to date, audited 1276 packages in 7s
79 packages are looking for funding
run `npm fund` for details
# npm audit report
ansi-html <0.0.8
Severity: high
Uncontrolled Resource Consumption in ansi-html - https://github.com/advisories/GHSA-whgm-jr23-g3j9
fix available via `npm audit fix --force`
Will install webpack-dev-server@3.11.3, which is outside the stated dependency range
node_modules/ansi-html
webpack-dev-server 2.0.0-beta - 4.7.2
Depends on vulnerable versions of ansi-html
Depends on vulnerable versions of chokidar
Depends on vulnerable versions of selfsigned
node_modules/webpack-dev-server
glob-parent <5.1.2
Severity: high
glob-parent before 5.1.2 vulnerable to Regular Expression Denial of Service in enclosure regex - https://github.com/advisories/GHSA-ww39-953v-wcq6
fix available via `npm audit fix --force`
Will install copy-webpack-plugin@11.0.0, which is a breaking change
node_modules/copy-webpack-plugin/node_modules/glob-parent
node_modules/watchpack-chokidar2/node_modules/glob-parent
node_modules/webpack-dev-server/node_modules/glob-parent
chokidar 1.0.0-rc1 - 2.1.8
Depends on vulnerable versions of glob-parent
node_modules/watchpack-chokidar2/node_modules/chokidar
node_modules/webpack-dev-server/node_modules/chokidar
watchpack-chokidar2 *
Depends on vulnerable versions of chokidar
node_modules/watchpack-chokidar2
watchpack 1.7.2 - 1.7.5
Depends on vulnerable versions of watchpack-chokidar2
node_modules/watchpack
copy-webpack-plugin 5.0.1 - 5.1.2
Depends on vulnerable versions of glob-parent
node_modules/copy-webpack-plugin
highcharts <=8.2.2
Severity: high
Cross-Site Scripting in highcharts - https://github.com/advisories/GHSA-gr4j-r575-g665
Options structure open to Cross-site Scripting if passed unfiltered - https://github.com/advisories/GHSA-8j65-4pcq-xq95
fix available via `npm audit fix --force`
Will install @vaadin/vaadin-charts@23.2.7, which is a breaking change
node_modules/@vaadin/vaadin-shrinkwrap/node_modules/highcharts
node_modules/highcharts
@vaadin/vaadin-charts <=6.2.0-beta1 || 6.2.1 - 22.0.0-rc1
Depends on vulnerable versions of highcharts
node_modules/@vaadin/vaadin-charts
node_modules/@vaadin/vaadin-shrinkwrap/node_modules/@vaadin/vaadin-charts
@vaadin/vaadin-shrinkwrap <=22.0.0-rc1
Depends on vulnerable versions of @vaadin/vaadin-charts
node_modules/@vaadin/vaadin-shrinkwrap
node-forge <=1.2.1
Severity: high
Open Redirect in node-forge - https://github.com/advisories/GHSA-8fr3-hfg3-gpgp
Prototype Pollution in node-forge debug API. - https://github.com/advisories/GHSA-5rrq-pxf6-6jx5
Improper Verification of Cryptographic Signature in `node-forge` - https://github.com/advisories/GHSA-2r2c-g63r-vccr
Improper Verification of Cryptographic Signature in node-forge - https://github.com/advisories/GHSA-x4jg-mjrx-434g
Improper Verification of Cryptographic Signature in node-forge - https://github.com/advisories/GHSA-cfm4-qjh2-4765
URL parsing in node-forge could lead to undesired behavior. - https://github.com/advisories/GHSA-gf8q-jrpm-jvxq
fix available via `npm audit fix --force`
Will install webpack-dev-server@3.11.3, which is outside the stated dependency range
node_modules/node-forge
selfsigned 1.1.1 - 1.10.14
Depends on vulnerable versions of node-forge
node_modules/selfsigned
12 vulnerabilities (1 moderate, 11 high)
To address issues that do not require attention, run:
npm audit fix
To address all issues (including breaking changes), run:
npm audit fix --force
(base) jonas@scadsnb28 IdeaProjects/de4l-client (master *%) npm install 1 ↵
up to date, audited 1276 packages in 3s
79 packages are looking for funding
run `npm fund` for details
12 vulnerabilities (1 moderate, 11 high)
To address issues that do not require attention, run:
npm audit fix
To address all issues (including breaking changes), run:
npm audit fix --force
Run `npm audit` for details.
</code></pre>
| [
{
"answer_id": 74630081,
"author": "Manolo Carrasco Moñino",
"author_id": 280410,
"author_profile": "https://Stackoverflow.com/users/280410",
"pm_score": 2,
"selected": false,
"text": "package.json"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74279000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5161107/"
] |
74,279,024 | <p>I have the following example</p>
<pre><code><div class="myClass">
<div>
<div>
<p>1</p>
</div>
</div>
<p>2</p>
<div>
</div>
<p>3</p>
</div>
</code></pre>
<p>How can I extract the 3 p tags using goquery or CSS selectors (or both)
Maybe in this case the selector would be "div.myClass"</p>
| [
{
"answer_id": 74279139,
"author": "HackerFrosch",
"author_id": 20357737,
"author_profile": "https://Stackoverflow.com/users/20357737",
"pm_score": 3,
"selected": true,
"text": ".myClass"
},
{
"answer_id": 74286494,
"author": "何聊生",
"author_id": 5978648,
"author_profile": "https://Stackoverflow.com/users/5978648",
"pm_score": 1,
"selected": false,
"text": "p {/* Selects all p elements */}"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74279024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9820269/"
] |
74,279,052 | <p>I've got these functions:</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>const precisionRound = (number, precision = 0) => {
const factor = 10 ** precision;
return Math.round(number * factor) / factor;
};
const superParseFloat = (numberish, precision = 2) => {
if (!!numberish) {
return precisionRound(parseFloat(numberish.toString().replace(/[^0-9.-]/g, '')), precision);
}
return 0;
}
console.log(
superParseFloat('www 111'),
superParseFloat('222'),
superParseFloat(333),
superParseFloat(null),
superParseFloat(undefined),
superParseFloat('some text')
)</code></pre>
</div>
</div>
</p>
<p>It should replace all non numeric characters from string with '', and only return numbers, for example:</p>
<pre><code>superParseFloat('www 111') => 111
superParseFloat('222') => 222
superParseFloat(333)) => 333
</code></pre>
<p>For 'null', 'undefined' or for a string without numeric characters it should return 0, eg.:</p>
<pre><code>superParseFloat(null) => 0
superParseFloat(undefined) => 0
superParseFloat('some text') => 0
</code></pre>
<p>It works fine apart from when I'm passing a string without numeric characters. Then it returns NaN, for example:</p>
<p><code>superParseFloat('some text')</code> returns <code>NaN</code></p>
<p>I think it's something to with putting another if statement using isNaN() for return value but I can't figure out how to use it (if i'm right in thinking at all?)</p>
| [
{
"answer_id": 74279139,
"author": "HackerFrosch",
"author_id": 20357737,
"author_profile": "https://Stackoverflow.com/users/20357737",
"pm_score": 3,
"selected": true,
"text": ".myClass"
},
{
"answer_id": 74286494,
"author": "何聊生",
"author_id": 5978648,
"author_profile": "https://Stackoverflow.com/users/5978648",
"pm_score": 1,
"selected": false,
"text": "p {/* Selects all p elements */}"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74279052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6523359/"
] |
74,279,059 | <p>i am trying to find the name of the row which shows the highest value of a singular column in my data frame, I have tried using</p>
<p><code> rownames(which.max(df[,1]))</code>
and</p>
<p><code> rownames(df)[apply(df,1,which.ax)]</code></p>
<p>however the first piece of code only gives me the word 'NULL' and the second piece of code provides me a long list of many row names.</p>
<p>using <code>which.max(df[,1])</code> provides me with the correct number, but not the corresponding name of the row i am looking for.</p>
<p>Thanks for any help</p>
| [
{
"answer_id": 74279074,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": true,
"text": " rownames(df)[which.max(df[[1]])]\n"
},
{
"answer_id": 74279157,
"author": "Quinten",
"author_id": 14282714,
"author_profile": "https://Stackoverflow.com/users/14282714",
"pm_score": 2,
"selected": false,
"text": "max.col"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74279059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20285663/"
] |
74,279,119 | <pre><code>comboList = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
#duplicate values wont be entered into these test lists to begin with so idc about that
testList1 = [0,1,2]
testList2 = [1,2,4,7]
testList3 = [0,2,3,6,5,69,4,6,1]
testList4 = [2,1,3] #this needs to return false
def testfunc(mainList, sublist):#This is the trash func
for list in mainList:
y1 = 0
x1 = 0
while x1 < len(sublist):
if sublist[x1] in list:
y1 = y1 + 1
if y1 == 3:
return True
x1 = x1 + 1
return False
if testfunc(comboList,testList1):
print("Test1 Pass")
else:
print("Test1 Fail")
if testfunc(comboList,testList2):
print("Test2 Pass")
else:
print("Test2 Fail")
if testfunc(comboList,testList3):
print("Test3 Pass")
else:
print("Test3 Fail")
if testfunc(comboList,testList4):
print("Test4 Fail")
else:
print("Test4 Pass")
</code></pre>
<p>I am fairly new to to this and I would like some feedback on how to write this more elegantly, this function is currently doing exactly what I want it to do but there should be a better way of doing it especially in python.</p>
| [
{
"answer_id": 74279243,
"author": "user19077881",
"author_id": 19077881,
"author_profile": "https://Stackoverflow.com/users/19077881",
"pm_score": -1,
"selected": false,
"text": "comboList = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]\n#duplicate values wont be entered into these test lists to begin with so idc about that\n\ntestlists = {'test1': [0,1,2], 'test2': [1,2,4,7], 'test3': [0,2,3,6,5,69,4,6,1], 'test4': [2,1,3]}\n\ndef testfunc(mainList, sublist):\n for mylist in mainList:\n count = 0\n for item in sublist:\n if item in mylist:\n count += 1\n if count == 3:\n return True\n return False\n\nfor name, test in testlists.items():\n if testfunc(comboList, test):\n print(name, ' Passed')\n else:\n print(name, ' Failed')\n"
},
{
"answer_id": 74279340,
"author": "Ulises Bussi",
"author_id": 17194418,
"author_profile": "https://Stackoverflow.com/users/17194418",
"pm_score": -1,
"selected": false,
"text": "\ndef testfunc(mainList,sublist): \n for l in mainList: \n if sum(x in l for x in sublist) == len(l):\n return True\n return False\n"
},
{
"answer_id": 74279458,
"author": "Stuart",
"author_id": 567595,
"author_profile": "https://Stackoverflow.com/users/567595",
"pm_score": 1,
"selected": true,
"text": "def has_n_items(iterable, n):\n \"\"\" Check whether an iterable has at least n items \"\"\"\n for i, _ in enumerate(iterable, 1):\n if i == n:\n return True\n return False\n\ndef has_three_members(a, b):\n \"\"\" Test whether at least three members of b are found in a \"\"\"\n return has_n_items((item for item in b if item in a), 3)\n \ndef test_func(a, b):\n \"\"\" Test whether at least three members of list b are found in any of the sublists of list of lists a \"\"\"\n return any(has_three_members(b, items) for sublist in a)\n"
},
{
"answer_id": 74279591,
"author": "AirSquid",
"author_id": 10789207,
"author_profile": "https://Stackoverflow.com/users/10789207",
"pm_score": -1,
"selected": false,
"text": "sets"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74279119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15229197/"
] |
74,279,125 | <p>I've written a simple code:</p>
<pre class="lang-perl prettyprint-override"><code>sub euler-ex ($x) of Seq {
1, { $x**++$ / [×] 1 .. ++$ } ... Inf }
say " 5: " ~ euler-ex(5)[^20] ~ " = " ~ [+](euler-ex(5)[^20]);
</code></pre>
<p>The output:</p>
<pre><code>5: 1 5 12.5 20.833333 26.041667 26.041667 21.701389 15.500992 9.68812 5.382289 2.6911445 1.22324748 0.50968645 0.19603325 0.07001187499 0.023337291662 0.0072929036444 0.00214497166011 0.000595825461143 0.000156796173985 = 148.41310786833832
</code></pre>
<p>How to specify the number of digits on that output, i.e. on the decimals coming out of the explicit generator of the sequence?</p>
| [
{
"answer_id": 74280871,
"author": "Coke",
"author_id": 581475,
"author_profile": "https://Stackoverflow.com/users/581475",
"pm_score": 4,
"selected": true,
"text": "say \" 5: \" ~ euler-ex(5)[^20].fmt(\"%0.10f\") ~ \"=\" ~ [+](euler-ex(5)[^20]).fmt(\"%0.10f\");\n"
},
{
"answer_id": 74281341,
"author": "Mustafa Aydın",
"author_id": 9332187,
"author_profile": "https://Stackoverflow.com/users/9332187",
"pm_score": 2,
"selected": false,
"text": "round"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74279125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12212606/"
] |
74,279,127 | <p>First of all thank you for this amazing space to learn from you all, I have the following question. I created a code that imports data from several APIs and it performs various statistical operations around the data. And it returns 1 result number, which is helpful to see if the model is correct.
The code is built around 4 (or more), static variables. What I want is to create a range of number for each of those variables and test all possible combinations in the code, that returns the top 10 highest result numbers.
it looks like this:</p>
<pre><code>
#I would want to test i.e. variable_1 in a range from (-0.004 to 0.004 at 0.001 increments), the same for the other variables until I can get the top 10 highest result_number
variable_1 = 0.004
variable_2 = 0.005
variable_3 = 30
result_number = 0
def my_code():
global variable_1, variable_2, variable_3
#perform all the operations utilizing the variables
return result_number
</code></pre>
<p>Please let me know if it is clear, or if you have any idea how to attack this.
Thank YOU!!</p>
<p>I am new to Python so I am still trying to figure out how to loop and record the highest numbers as it goes. The code is fairly long so it will take a few hours for the simmulation</p>
| [
{
"answer_id": 74279388,
"author": "Alex P",
"author_id": 11554968,
"author_profile": "https://Stackoverflow.com/users/11554968",
"pm_score": 2,
"selected": true,
"text": "best_result = None\nfor variable_1 in range(-4, 4, 1):\n result = my_code()\n if best_result is None or best_result > result:\n best_result = result\n"
},
{
"answer_id": 74279476,
"author": "Ulises Bussi",
"author_id": 17194418,
"author_profile": "https://Stackoverflow.com/users/17194418",
"pm_score": 0,
"selected": false,
"text": "import numpy as np\n\nvariable_1 = 0.004\nvariable_2 = 0.005\nvariable_3 = 30\nresult_number = 0\n\ndef my_code():\n global variable_1, variable_2, variable_3\n result_number = 0\n result_number += variable_1 in np.arange(-0.004,0.005,0.001)\n result_number += variable_2 in np.arange(-0.004,0.005,0.001)\n result_number += variable_3 in np.arange(22,28,1)\n return result_number\n\n\nmy_code()\n"
}
] | 2022/11/01 | [
"https://Stackoverflow.com/questions/74279127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20056201/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.