qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,542,405
|
<p>Is there any easy way convert List to other model data?</p>
<p>this is my model:</p>
<pre><code>class Account {
String name;
double balance;
Account({required this.name, required this.balance});
}
class CategoryAccount {
String type;
List<Account> items;
CategoryAccount({required this.type, required this.items});
}
</code></pre>
<p>this is sourceData:</p>
<pre><code>List<Account> sourceData = [
Account(name: 'cash', balance: 100),
Account(name: 'cash', balance: 200),
Account(name: 'bank', balance: 300),
Account(name: 'creditor', balance: 400),
];
</code></pre>
<p>I want sourceData convert to finalData:</p>
<pre><code>List<CategoryAccount> finalData = [
CategoryAccount(
type: 'cash',
items: [
Account(name: 'cash', balance: 100),
Account(name: 'cash', balance: 200),
],
),
CategoryAccount(
type: 'bank',
items: [
Account(name: 'bank', balance: 300),
],
),
CategoryAccount(
type: 'creditor',
items: [
Account(name: 'creditor', balance: 300),
],
),
];
</code></pre>
<p>In Dart I saw the following method for a List : asMap(), but it's not doing what i expect: it use the list index as key. My questions:</p>
<p>Do you known anything in Dart libraries to do this ?</p>
|
[
{
"answer_id": 74542656,
"author": "Manjesh Kumar Sharma",
"author_id": 19296050,
"author_profile": "https://Stackoverflow.com/users/19296050",
"pm_score": 1,
"selected": true,
"text": "<div class=\"px-10 sm:px-10 md:px-12 bg-white border-2 border-white border-t-pglightgrey\">\n <div class='relative max-w-6xl mx-auto pt-20 sm:pt-24 lg:pt-32'>\n <h1 class=\"h-[8rem] sm:h-[4rem] font-semibold text-4xl sm:text-5xl lg:text-6xl tracking-tight text-center bg-clip-text text-transparent bg-gradient-to-r from-pink-500 to-violet-500\"><span class=\"text-center\">Testing Image grapes plane page<span/></h1>\n </div>\n</div>"
},
{
"answer_id": 74546320,
"author": "Nirmal Singh",
"author_id": 4903005,
"author_profile": "https://Stackoverflow.com/users/4903005",
"pm_score": 1,
"selected": false,
"text": "<div class=\"px-10 sm:px-10 md:px-12 bg-white border-2 border-white border-t-pglightgrey\">\n<div class='relative max-w-6xl mx-auto pt-20 sm:pt-24 lg:pt-32'>\n <h1 class=\"font-semibold text-4xl pb-3 sm:text-5xl leading-tight sm:leading-tight lg:leading-relaxed lg:text-6xl tracking-tight text-center bg-clip-text text-transparent bg-gradient-to-r from-pink-500 to-violet-500\">Testing Image grapes plane page</h1>\n</div>\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10797820/"
] |
74,542,424
|
<p>Please see this expected image below, in screenshot it is looking big but I want to make it very small, for that you can see my textview dimensions..<a href="https://i.stack.imgur.com/wJXMV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wJXMV.png" alt="image" /></a></p>
<p>This is my output after spending whole day on this, <strong>but the problem is + is not coming into center</strong>: <a href="https://i.stack.imgur.com/Ki25o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ki25o.png" alt="enter image description here" /></a></p>
<p>Now this is my XML:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
</data>
<androidx.cardview.widget.CardView
style="@style/match_match"
android:layout_margin="@dimen/dimen_16"
android:background="@drawable/product_list_cardview_border"
app:cardCornerRadius="@dimen/dimen_2">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="@dimen/dimen_16">
...
...
<com.test.consumer.utils.CustomTextViewV2
android:id="@+id/tv_item_plus"
android:layout_width="12dp"
android:layout_height="12dp"
android:layout_marginEnd="@dimen/dimen_10"
android:background="@drawable/shape_circle_style_item_default"
android:text="+"
android:textStyle="bold"
android:gravity="center"
android:textColor="@color/color_black"
android:textSize="9sp"
app:customFont="@string/font_raleway_semibold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintEnd_toStartOf="@+id/tv_final_mrp" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</code></pre>
<p>Please note: I don't want to take any other nested view, the ideal solution fix should be: Textview should be inside parent constraint layout.</p>
<p>Background drawable:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke
android:width="@dimen/dimen_1"
android:color="@color/color_moderate_gray_shade_one" />
<solid android:color="@android:color/transparent" />
</shape>
</code></pre>
<p>Also, I tried with imageview as well!</p>
|
[
{
"answer_id": 74542656,
"author": "Manjesh Kumar Sharma",
"author_id": 19296050,
"author_profile": "https://Stackoverflow.com/users/19296050",
"pm_score": 1,
"selected": true,
"text": "<div class=\"px-10 sm:px-10 md:px-12 bg-white border-2 border-white border-t-pglightgrey\">\n <div class='relative max-w-6xl mx-auto pt-20 sm:pt-24 lg:pt-32'>\n <h1 class=\"h-[8rem] sm:h-[4rem] font-semibold text-4xl sm:text-5xl lg:text-6xl tracking-tight text-center bg-clip-text text-transparent bg-gradient-to-r from-pink-500 to-violet-500\"><span class=\"text-center\">Testing Image grapes plane page<span/></h1>\n </div>\n</div>"
},
{
"answer_id": 74546320,
"author": "Nirmal Singh",
"author_id": 4903005,
"author_profile": "https://Stackoverflow.com/users/4903005",
"pm_score": 1,
"selected": false,
"text": "<div class=\"px-10 sm:px-10 md:px-12 bg-white border-2 border-white border-t-pglightgrey\">\n<div class='relative max-w-6xl mx-auto pt-20 sm:pt-24 lg:pt-32'>\n <h1 class=\"font-semibold text-4xl pb-3 sm:text-5xl leading-tight sm:leading-tight lg:leading-relaxed lg:text-6xl tracking-tight text-center bg-clip-text text-transparent bg-gradient-to-r from-pink-500 to-violet-500\">Testing Image grapes plane page</h1>\n</div>\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19428652/"
] |
74,542,435
|
<p>I'm making a website and on one of my pages I have this button that when clicked, should take a haiku from a JSON file that contains over 5000 and display it to the user. Currently I do this the following way.</p>
<pre><code><script>
const haikuUrl = 'http://mywebsite/haikus.json';
async function getHaiku() {
const num = Math.floor(Math.random() * 5145);
const response = await fetch(haikuUrl);
const data = await response.json();
const {line1, line2, line3} = data[num];
document.getElementById('line1').textContent = line1;
document.getElementById('line2').textContent = line2;
document.getElementById('line3').textContent = line3;
}
document.getElementById('haikuButton').addEventListener('click', () => {
getHaiku();
});
</script>
</code></pre>
<p>I'm pretty much new to JS, and after looking around and watching some videos this was the only way I could get this to work but I'm pretty much sure there has to be a better way to do this. Right now, I'm having to load the whole file every time just to get 1 random object from the JSON. What I'd like to have is a constant or a variable that just sits there waiting for the user to ask for a random one. Something like this:</p>
<pre><code><script>
const data= [{},{},{}...{}]; //an array of all the haikus loaded once at the beginning
function getHaiku() {
const num = Math.floor(Math.random() * 5145);
const {line1, line2, line3} = data[num];
document.getElementById('line1').textContent = line1;
document.getElementById('line2').textContent = line2;
document.getElementById('line3').textContent = line3;
}
document.getElementById('haikuButton').addEventListener('click', () => {
getHaiku();
});
</script>
</code></pre>
<p>So pretty much the same just without the having to fetch the whole data every time.</p>
<p>I guess one option could be to hardcode the whole dataset into the js file into a variable, but something tells me there's got to be a better way.</p>
|
[
{
"answer_id": 74542656,
"author": "Manjesh Kumar Sharma",
"author_id": 19296050,
"author_profile": "https://Stackoverflow.com/users/19296050",
"pm_score": 1,
"selected": true,
"text": "<div class=\"px-10 sm:px-10 md:px-12 bg-white border-2 border-white border-t-pglightgrey\">\n <div class='relative max-w-6xl mx-auto pt-20 sm:pt-24 lg:pt-32'>\n <h1 class=\"h-[8rem] sm:h-[4rem] font-semibold text-4xl sm:text-5xl lg:text-6xl tracking-tight text-center bg-clip-text text-transparent bg-gradient-to-r from-pink-500 to-violet-500\"><span class=\"text-center\">Testing Image grapes plane page<span/></h1>\n </div>\n</div>"
},
{
"answer_id": 74546320,
"author": "Nirmal Singh",
"author_id": 4903005,
"author_profile": "https://Stackoverflow.com/users/4903005",
"pm_score": 1,
"selected": false,
"text": "<div class=\"px-10 sm:px-10 md:px-12 bg-white border-2 border-white border-t-pglightgrey\">\n<div class='relative max-w-6xl mx-auto pt-20 sm:pt-24 lg:pt-32'>\n <h1 class=\"font-semibold text-4xl pb-3 sm:text-5xl leading-tight sm:leading-tight lg:leading-relaxed lg:text-6xl tracking-tight text-center bg-clip-text text-transparent bg-gradient-to-r from-pink-500 to-violet-500\">Testing Image grapes plane page</h1>\n</div>\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12980737/"
] |
74,542,460
|
<p><strong>Context</strong></p>
<p>I have a repository with hundreds of committed and pushed commits.
Now I have 10 committed but not yet pushed commit on my local git repository, I would like to create a new branch locally, and move all the 10 commits to that branch, doing all this locally. Then when I will be online next time I would like to sync my remote with that exact state. (As far as I see this case is not the same as <a href="https://stackoverflow.com/q/5066041/1157814">moving committed (but not pushed) changes to a new branch after pull</a> because that is only one single commit)</p>
<p><strong>Question</strong></p>
<p>Is this possible at all? If yes what is the most efficient way?
(please be aware I am not a git guru)</p>
|
[
{
"answer_id": 74542517,
"author": "Özgür Murat Sağdıçoğlu",
"author_id": 5106317,
"author_profile": "https://Stackoverflow.com/users/5106317",
"pm_score": 1,
"selected": false,
"text": "git checkout -b your_new_branch_name\n # after creating a new branch reset your master or main\n# assuming current branch is master (or main)\ngit reset --hard origin/master (or main)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1157814/"
] |
74,542,469
|
<p>I have a df similar to the following:</p>
<pre><code>df <- data.frame(name = c("billy","billy","sarah","sarah","sarah","sarah","sarah","sarah","sarah","linda","linda","linda","linda","linda","linda"),
data = c("soccer","8-01-1992","basketball","soccer","10-19-1995","10-25-1995","basketball","11-24-1995",6,"hockey","soccer","basketball","12-21-2001","12-30-2001","1-19-2002"),
event = c("joins.project","joins.when","joins.project","joins.project1","joins.when","joins.when1","participation.project","participation.when","participation.repetitions","joins.project","joins.project1","joins.project2","joins.when","joins.when1","joins.when2"))
> df
name data event
1 billy soccer joins.project
2 billy 8-01-1992 joins.when
3 sarah basketball joins.project
4 sarah soccer joins.project1
5 sarah 10-19-1995 joins.when
6 sarah 10-25-1995 joins.when1
7 sarah basketball participation.project
8 sarah 11-24-1995 participation.when
9 sarah 6 participation.repetitions
10 linda hockey joins.project
11 linda soccer joins.project1
12 linda basketball joins.project2
13 linda 12-21-2001 joins.when
14 linda 12-30-2001 joins.when1
15 linda 1-19-2002 joins.when2
</code></pre>
<p>My desired output is below.</p>
<pre><code>new_df <- data.frame(name = c("billy", "sarah", "sarah", "sarah", "linda", "linda", "linda"),
join_or_particip = c("join", "join", "join", "participate", "join", "join", "join"),
sport = c("soccer", "basketball", "soccer", "basketball", "hockey", "soccer", "basketball"),
when = c("8-01-1992", "10-19-1995", "10-25-1995", "11-24-1995", "12-21-2001", "12-30-2001", "1-19-2002"),
repetitions = c(NA, NA, NA, 6, NA, NA, NA))
new_df
name join_or_particip sport when repetitions
1 billy join soccer 8-01-1992 NA
2 sarah join basketball 10-19-1995 NA
3 sarah join soccer 10-25-1995 NA
4 sarah participate basketball 11-24-1995 6
5 linda join hockey 12-21-2001 NA
6 linda join soccer 12-30-2001 NA
7 linda join basketball 1-19-2002 NA
</code></pre>
<p>I imagine I need to use <code>spread()</code> to achieve this but I'm not sure how to account for the fact that certain rows in <code>df</code> are linked (i.e., "joins.project1" and "joins.when1" go together). A bit of further context: this is a dataset of people who "joined" or "participated" in between 1 and 200+ "sports" on different dates. If they "participated" there is an additional variable called "repetitions" (i.e., how many times they participated).</p>
|
[
{
"answer_id": 74542517,
"author": "Özgür Murat Sağdıçoğlu",
"author_id": 5106317,
"author_profile": "https://Stackoverflow.com/users/5106317",
"pm_score": 1,
"selected": false,
"text": "git checkout -b your_new_branch_name\n # after creating a new branch reset your master or main\n# assuming current branch is master (or main)\ngit reset --hard origin/master (or main)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17951615/"
] |
74,542,474
|
<p><em>This is not a duplicate Q. Please don't mark this as that.</em></p>
<p>Following is not I want</p>
<pre class="lang-js prettyprint-override"><code>import { EntityRepository, Repository } from "typeorm";
import { Test } from "./test.model";
import { Injectable } from "@nestjs/common";
@EntityRepository(Test)
export class TestRepository extends Repository<Test> {}
</code></pre>
<p>the <code>@EntityRepository</code> decorator is now deprecated.</p>
<p>I also don't want to make a fake repository like in here:
<a href="https://stackoverflow.com/a/73352265/5420070">https://stackoverflow.com/a/73352265/5420070</a></p>
<p>Don't want this either as I've to extract <code>manager</code> from <code>dataSource</code>, I don't want this because I think this is not the best way.</p>
<pre class="lang-js prettyprint-override"><code> export const UserRepository = dataSource.getRepository(User).extend({
// ^^^^^^^^^^ from where this came from
findByName(firstName: string, lastName: string) {
return this.createQueryBuilder("user")
.where("user.firstName = :firstName", { firstName })
.andWhere("user.lastName = :lastName", { lastName })
.getMany()
},
})
</code></pre>
<p>Found above in: <a href="https://orkhan.gitbook.io/typeorm/docs/custom-repository#how-to-create-custom-repository" rel="nofollow noreferrer">https://orkhan.gitbook.io/typeorm/docs/custom-repository#how-to-create-custom-repository</a></p>
<p>I don't think this is in NestJS context.</p>
<p>What I want
Want to know right way to make custom repository in latest version of NestJS (v9) & TypeORM (v0.3). In <code>@EntityRepository</code> deprecation note, they said that need to extend the repo to create custom repo like <code>someRepo.extend({})</code>. I want to know how to do it in NestJS way</p>
|
[
{
"answer_id": 74543151,
"author": "Kazi Akib Javed",
"author_id": 14257546,
"author_profile": "https://Stackoverflow.com/users/14257546",
"pm_score": 0,
"selected": false,
"text": "import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from \"typeorm\";\nimport { CustomBaseEntity } from \"../core/custom-base.entity\";//custom-made\n@Entity({name: 'rcon_log', schema: 'dbo'})\nexport class LogEntity extends CustomBaseEntity{\n------------your code-----------\n}\n"
},
{
"answer_id": 74546046,
"author": "A. Maitre",
"author_id": 6383583,
"author_profile": "https://Stackoverflow.com/users/6383583",
"pm_score": 2,
"selected": true,
"text": "UserEntity UserRepository UserService UserRepository UserService UserModule UserRepository UserEntity import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class UserEntity {\n @PrimaryGeneratedColumn()\n id: number;\n\n @Column()\n firstName: string;\n\n @Column()\n lastName: string;\n\n @Column({ default: true })\n isActive: boolean;\n}\n import { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\nimport { UserEntity } from './user.entity';\n\nexport class UserRepository extends Repository<UserEntity> {\n constructor(\n @InjectRepository(UserEntity)\n private userRepository: Repository<UserEntity>\n ) {\n super(userRepository.target, userRepository.manager, userRepository.queryRunner);\n }\n\n // sample method for demo purposes\n async findByEmail(email: string): Promise<UserEntity> {\n return await this.userRepository.findOneBy({ email }); // could also be this.findOneBy({ email });, but depending on your IDE/TS settings, could warn that userRepository is not used though. Up to you to use either of the 2 methods\n }\n \n // your other custom methods in your repo...\n}\n import { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { UserRepository } from './user.repository';\nimport { UserEntity } from './user.entity';\n\n@Injectable()\nexport class UserService {\n constructor(\n private readonly userRepository: UserRepository, // import as usual\n ) {}\n\n findAll(): Promise<UserEntity[]> {\n return this.userRepository.find();\n }\n \n // call your repo method\n findOneByEmail(email: string): Promise<UserEntity> {\n return this.userRepository.findByEmail({ email });\n }\n\n findOne(id: number): Promise<UserEntity> {\n return this.userRepository.findOneBy({ id });\n }\n\n async remove(id: string): Promise<void> {\n await this.userRepository.delete(id);\n }\n \n // your other custom methods in your service...\n}\n UserModule import { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { UserService } from './user.service';\nimport { UserController } from './user.controller';\nimport { UserEntity } from './user.entity';\n\n@Module({\n imports: [TypeOrmModule.forFeature([UserEntity])], // here we provide the TypeOrm support as usual, specifically for our UserEntity in this case\n providers: [UserService, UserRepository], // here we provide our custom repo\n controllers: [UserController],\n exports: [UserService, UserRepository] // add this only if you use service and/or custom repo within another module/service\n})\nexport class UserModule {}\n UserModule AppModule UserRepository UserService manager queryRunnner UserRepository UserModule UserRepository"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5420070/"
] |
74,542,487
|
<p>I am creating Screen components Separate to use such components like card, textfields so we can easily use it on web.
I am getting issue of passing data between components, Dont use the method of golbal varibales if i am sending data to components it only show componets but I want to send data to component but Navigate to main screen.</p>
<p>I am trying this method without creating Global variable file.</p>
|
[
{
"answer_id": 74542600,
"author": "Abdullatif Eida",
"author_id": 20570798,
"author_profile": "https://Stackoverflow.com/users/20570798",
"pm_score": 1,
"selected": false,
"text": "class YourPgae extends StatefulWidget {\nfinal int wabtedvar;\nconst YourPgae({super.key, required this.wabtedvar});\n\n@override\nState<YourPgae> createState() => _YourPgaeState();\n}\n"
},
{
"answer_id": 74543256,
"author": "Hari Krishna",
"author_id": 14466358,
"author_profile": "https://Stackoverflow.com/users/14466358",
"pm_score": 0,
"selected": false,
"text": "enter code here"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20374963/"
] |
74,542,495
|
<p>I have a field column that contains values like</p>
<pre><code>4
12,3
8,5,6,7
</code></pre>
<p>I'm going to write a SELECT statement, whose result would be:</p>
<pre><code>4
12
8
</code></pre>
<p>How can I do it?</p>
|
[
{
"answer_id": 74542600,
"author": "Abdullatif Eida",
"author_id": 20570798,
"author_profile": "https://Stackoverflow.com/users/20570798",
"pm_score": 1,
"selected": false,
"text": "class YourPgae extends StatefulWidget {\nfinal int wabtedvar;\nconst YourPgae({super.key, required this.wabtedvar});\n\n@override\nState<YourPgae> createState() => _YourPgaeState();\n}\n"
},
{
"answer_id": 74543256,
"author": "Hari Krishna",
"author_id": 14466358,
"author_profile": "https://Stackoverflow.com/users/14466358",
"pm_score": 0,
"selected": false,
"text": "enter code here"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19681180/"
] |
74,542,508
|
<p>Some common R functions have argument names that end with a single dot.</p>
<p>For example, the warning() function shows the following in the usage section when looking at the documentation with ?warning:</p>
<pre><code> warning(..., call. = TRUE, immediate. = FALSE, noBreaks. = FALSE,
domain = NULL)
</code></pre>
<p>With the exception of "domain", all of the arguments with names have names that end in dots.</p>
<p>Similarly, the default prcomp() function from the 'stats' library shows the following in its usage instructions:</p>
<pre><code> prcomp(x, retx = TRUE, center = TRUE, scale. = FALSE,
tol = NULL, rank. = NULL, ...)
</code></pre>
<p>The arguments "scale." and "rank." end with a dot, and all of the others do not. It seems particularly weird that "scale." ends with a dot but "center" does not.</p>
<p>I know a dot is a permitted character in a variable name with R, and that I could name a variable <code>this.variable.name.is.full.of.dots.</code> if I wanted to - but since the dot being the last character in the names of certain function arguments seems to be a recurring theme in common R functions, does this have a special meaning?</p>
|
[
{
"answer_id": 74542600,
"author": "Abdullatif Eida",
"author_id": 20570798,
"author_profile": "https://Stackoverflow.com/users/20570798",
"pm_score": 1,
"selected": false,
"text": "class YourPgae extends StatefulWidget {\nfinal int wabtedvar;\nconst YourPgae({super.key, required this.wabtedvar});\n\n@override\nState<YourPgae> createState() => _YourPgaeState();\n}\n"
},
{
"answer_id": 74543256,
"author": "Hari Krishna",
"author_id": 14466358,
"author_profile": "https://Stackoverflow.com/users/14466358",
"pm_score": 0,
"selected": false,
"text": "enter code here"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9843100/"
] |
74,542,542
|
<p>I have a <code>Base</code> which has two child classes. <code>bar</code> creates a <code>unique_ptr</code> who's type is <code>Base</code> and attempts to initialize it with one of its child classes.</p>
<p>Certainly I can't downcast without being explicit of the type which I don't want to do. Are there ways around it?</p>
<pre><code>struct Base
{
};
struct A : public Base
{
int val;
};
struct B : public Base
{
int val;
};
struct C : public Base
{
// does not have val
};
void bar(bool x, int value)
{
std::unique_ptr<Base> ptr;
if (x)
{
ptr = std::make_unique<A>();
}
else
{
ptr = std::make_unique<B>();
}
ptr->val = value; // ERROR
}
</code></pre>
|
[
{
"answer_id": 74542678,
"author": "user17732522",
"author_id": 17732522,
"author_profile": "https://Stackoverflow.com/users/17732522",
"pm_score": 0,
"selected": false,
"text": "void bar(bool x, int value)\n{\n auto make_ptr = [&]<typename T>(){\n auto ptr = std::make_unique<T>();\n ptr->val = value;\n return ptr;\n };\n\n std::unique_ptr<Base> ptr;\n if (x)\n {\n ptr = make_ptr.operator()<A>();\n }\n else\n {\n ptr = make_ptr.operator()<B>();\n }\n}\n template<typename T>\nstruct type_identity {\n using type = T;\n};\n\nvoid bar(bool x, int value)\n{\n auto make_ptr = [&](auto t){\n using T = typename decltype(t)::type;\n auto ptr = std::make_unique<T>();\n ptr->val = value;\n return ptr;\n };\n\n std::unique_ptr<Base> ptr;\n if (x)\n {\n ptr = make_ptr(type_identity<A>{});\n }\n else\n {\n ptr = make_ptr(type_identity<B>{});\n }\n}\n val std::unique_ptr<Base> std::unique_ptr<IntermediateBase>"
},
{
"answer_id": 74542728,
"author": "n. m.",
"author_id": 775806,
"author_profile": "https://Stackoverflow.com/users/775806",
"pm_score": 2,
"selected": false,
"text": "*ptr val *ptr *ptr Base val *ptr val Base val BaseWithVal"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12497236/"
] |
74,542,555
|
<p>I have created a popup for edit functionality in my todo app and I need to get the id of the task for the purpose. using route is not giving a correct result. Is there any other way I can achieve it? I have given the code below.</p>
<p><code>this.id = this.route.snapshot.params['id'];</code></p>
<pre><code> console.log(this.formData.value);
this.todoService.editTasks(this.id, this.formData.value).subscribe((res: any)=>{
console.log('update successful');
// this.router.navigateByUrl('/tasks');
})
}```
</code></pre>
|
[
{
"answer_id": 74543925,
"author": "Goutham Harshith",
"author_id": 11917182,
"author_profile": "https://Stackoverflow.com/users/11917182",
"pm_score": 0,
"selected": false,
"text": "// import\nimport { ActivatedRoute } from '@angular/router';\n\n//dependency injection\n constructor(private route: ActivatedRoute) { }\n\n//implementation\n ngOnInit() {\n this.route.paramMap.subscribe(\n params => {\n this.id= params.get('id'); // This is the required Id\n })\n }\n"
},
{
"answer_id": 74544198,
"author": "Chady BAGHDADI",
"author_id": 16227834,
"author_profile": "https://Stackoverflow.com/users/16227834",
"pm_score": 2,
"selected": true,
"text": "{path: \"edit/:id\", component: someComponent}\n import { ActivatedRoute } from '@angular/router';\n constructor(private route: ActivatedRoute) {}\n\n ngOnInit(){\n //you need to unsubscribe in the ngOnDestroy \n this.subscription = this.route.paramMap.subscribe(params=> {\n //i use + to convert the id to a number type\n let id =+params.get('id');\n }\n //To prevent memory leak\n ngOnDestroy(): void {\n if (this.subscription)\n this.subscription.unsubscribe()\n }\n ngOnInit(){\n\nlet id =this.route.snapshot.paramMap.get('id');\n\n }\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16953799/"
] |
74,542,561
|
<p>I've added a stamina system in my game, but when I try do call the function there's a few problems happening:
I can't jump when my character is sprinting and when I jump and press the sprint button my character doesn't fall anymore, he basically just flies.</p>
<pre><code>PlayerController
</code></pre>
<pre><code>private Vector3 playerVelocity;
private bool groundedPlayer;
private CharacterController controller;
private PlayerControls playerControls;
private InputManager inputManager;
public HealthBar healthBar;
public StaminaBar staminaBar;
public int currentHealth;
public int maxHealth = 100;
public int currentStamina;
public int maxStamina = 100;
public int staminaDrain = 10;
[SerializeField]
private float playerSpeed = 2.0f;
[SerializeField]
private float playerRunSpeed= 1f;
[SerializeField]
private float jumpHeight = 1.0f;
[SerializeField]
private float gravityValue = -9.81f;
private Transform cameraTransform;
private void Start()
{
currentHealth = maxHealth;
healthBar.SetMaxHealth(maxHealth);
currentStamina = maxStamina;
staminaBar.SetMaxStamina(maxStamina);
controller = GetComponent<CharacterController>();
inputManager = InputManager.Instance;
cameraTransform = Camera.main.transform;
//player = GameObject.Find("Player");
}
void Update()
{
groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector2 movement = inputManager.GetPlayerMovement();
Vector3 move = new Vector3(movement.x, 0f, movement.y);
move = cameraTransform.forward * move.z + cameraTransform.right * move.x;
move.y = 0f;
//controller.Move(move * Time.deltaTime * playerSpeed);
if(inputManager.isRunning && currentStamina > 0)
{
controller.Move(move * playerRunSpeed * Time.deltaTime);
staminaBar.UseStamina(staminaDrain);
staminaBar.staminaSlider.value = currentStamina;
}
else
{
controller.Move(move * Time.deltaTime * playerSpeed);
}
// Changes the height position of the player..
if (inputManager.PlayerJumpedThisFrame() && groundedPlayer)
{
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
}
</code></pre>
<p>StaminaBar script</p>
<pre><code>public class StaminaBar : MonoBehaviour
{
public Slider staminaSlider;
private PlayerController playerController;
private WaitForSeconds regenTick = new WaitForSeconds(0.1f);
private Coroutine regen;
public void SetMaxStamina(int stamina){
staminaSlider.maxValue = stamina;
staminaSlider.value = stamina;
}
public void SetStamina(int stamina){
staminaSlider.value = stamina;
}
public void UseStamina(int amount){
if(playerController.currentStamina - amount >= 0){
playerController.currentStamina -= amount;
staminaSlider.value = playerController.currentStamina;
Debug.Log("Losing Stamina");
if(regen != null)
StopCoroutine(regen);
regen = StartCoroutine(RegenStamina());
}
else
{
Debug.Log("NotEnoughStamina");
}
}
private IEnumerator RegenStamina()
{
yield return new WaitForSeconds(2);
while(playerController.currentStamina < playerController.maxStamina){
playerController.currentStamina += playerController.maxStamina/100;
staminaSlider.value = playerController.currentStamina;
yield return regenTick;
}
regen = null;
}
}
</code></pre>
<p>Input Manager</p>
<pre><code>{
private StaminaBar staminaBar;
private PlayerController playerController;
[SerializeField]
private float bulletHitMissDistance = 25f;
[SerializeField]
private Transform bulletParent;
[SerializeField]
private Transform barrelTransform;
[SerializeField]
private GameObject bulletPrefab;
[SerializeField]
private float damage = 100;
public float impactForce = 30;
public float fireRate = 8f;
WaitForSeconds rapidFireWait;
public bool isRunning;
private static InputManager _instance;
public static InputManager Instance
{
get {
return _instance;
}
}
private PlayerControls playerControls;
private Transform cameraTransform;
Coroutine fireCoroutine;
private void Awake()
{
if(_instance != null && _instance != this)
{
Destroy(this.gameObject);
}
else
{
_instance = this;
}
playerControls = new PlayerControls();
//Cursor.visible = false;
rapidFireWait = new WaitForSeconds(1/fireRate);
cameraTransform = Camera.main.transform;
playerControls.Player.RunStart.performed += x => Running();
playerControls.Player.RunEnd.performed += x => RunningStop();
playerControls.Player.Shoot.started += _ => StartFiring();
playerControls.Player.Shoot.canceled += _ => StopFiring();
}
private void OnEnable()
{
playerControls.Enable();
//playerControls.Player.Shoot.performed += _ => StartFiring();
}
private void OnDisable()
{
playerControls.Disable();
//playerControls.Player.Shoot.performed += _ => StopFiring();
}
void StartFiring()
{
fireCoroutine = StartCoroutine(RapidFire());
}
void StopFiring()
{
if(fireCoroutine != null)
{
StopCoroutine(fireCoroutine);
}
}
public Vector2 GetPlayerMovement()
{
return playerControls.Player.Movement.ReadValue<Vector2>();
}
public Vector2 GetMouseDelta(){
return playerControls.Player.Look.ReadValue<Vector2>();
}
public bool PlayerJumpedThisFrame(){
return playerControls.Player.Jump.triggered;
}
public void Shooting()
{
RaycastHit hit;
//creates the bullet
GameObject bullet = GameObject.Instantiate(bulletPrefab, barrelTransform.position, Quaternion.identity, bulletParent);
BulletController bulletController = bullet.GetComponent<BulletController>();
//shoots the bullet forwards
if (Physics.Raycast(cameraTransform.position, cameraTransform.forward, out hit, Mathf.Infinity))
{
//checks if the bullet hit something
bulletController.target = hit.point;
bulletController.hit = true;
//makes enemy take damage
Enemy takingDamage = hit.transform.GetComponent<Enemy>();
if (takingDamage != null)
{
takingDamage.TakeDamage(damage);
}
//makes enemy go backwards when hit
if(hit.rigidbody != null)
{
hit.rigidbody.AddForce(-hit.normal * impactForce);
}
}
else
{
bulletController.target = cameraTransform.position + cameraTransform.forward * bulletHitMissDistance;
bulletController.hit = false;
}
}
public IEnumerator RapidFire()
{
while(true)
{
Shooting();
yield return rapidFireWait;
}
}
public void Running()
{
/* if(playerController.currentStamina > 0){
isRunning = true;
staminaBar.UseStamina(playerController.staminaDrain);
staminaBar.staminaSlider.value = playerController.currentStamina;
} */
isRunning = true;
}
public void RunningStop(){
isRunning =false;
}
}
</code></pre>
<p>I'm using unity new input system and tried to call the function in two different ways: in the isRunning and when I actually do the sprint function.</p>
<p>I was expecting the player to lose 10 stamina every time I press the sprint button, I was trying to figure that out before trying to make him lose stamina while the button is pressed.</p>
<p>I've seen a couple videos on YouTube, which is where I got the code from, but can't find out what I'm doing wrong when calling the function, I've had similar problems before when trying to call a TakeDamage function but I guess that's a different question.</p>
|
[
{
"answer_id": 74557605,
"author": "derHugo",
"author_id": 7111561,
"author_profile": "https://Stackoverflow.com/users/7111561",
"pm_score": 2,
"selected": true,
"text": "PlayerController StaminaBar PlayerController StaminaBar InputManager PlayerController StaminaBar StaminaBar public class PlayerController : MonoBehaviour\n{\n [Header(\"Own References\")]\n [SerializeField] private CharacterController _controller;\n\n [Header(\"Scene References\")]\n [SerializeField] private Transform _cameraTransform;\n [SerializeField] private InputManager _inputManager;\n\n // In general always make you stuff as encapsulated as possible\n // -> nobody should be able to change these except you via the Inspector\n // (Values you are anyway not gonna change at all you could also convert to \"const\")\n [Header(\"Settings\")]\n [SerializeField] private float _maxHealth = 100f;\n [SerializeField] private float _maxStamina = 100f;\n [SerializeField] private float _staminaDrainPerSecond = 2f;\n [SerializeField] private float _secondsDelayBeforeStaminaRegen = 1f;\n [SerializeField] private float _staminaRegenPerSecond = 2f;\n [SerializeField] private float _playerSpeed = 1f;\n [SerializeField] private float _playerRunSpeed = 2f;\n [SerializeField] private float _jumpHeight = 1f;\n [SerializeField] private float _gravityValue = -9.81f;\n\n // Your runtime valus\n private float _staminaRegenDelayTimer;\n private float _currentHealt;\n private float _currentStamina;\n\n // You only need a single float for this\n private float _currentYVelocity;\n\n // EVENTS we expose so other classes can react to those\n public UnityEvent OnDeath;\n public UnityEvent<float> OnHealthChanged;\n public UnityEvent<float> OnStaminaChanged;\n\n // Provide public read-only access to the settings so your visuals can access those for their setup\n public float MaxHealth => _maxHealth;\n public float MaxStamina => _maxStamina;\n\n // And then use properties for your runtime values\n // whenever you set the value you do additional stuff like cleaning the value and invoke according events\n public float currentHealth\n {\n get => _currentHealt;\n private set\n {\n _currentHealt = Mathf.Clamp(value, 0, _maxHealth);\n\n OnHealthChanged.Invoke(_currentHealt);\n\n if (value <= 0f)\n {\n OnDeath.Invoke();\n }\n }\n }\n\n public float currentStamina\n {\n get => _currentStamina;\n private set\n {\n _currentStamina = Mathf.Clamp(value, 0, _maxStamina);\n\n OnStaminaChanged.Invoke(_currentStamina);\n }\n }\n\n private void Awake()\n {\n // As a thumb rule to avoid issues with order I usually initialize everything I an in Awake\n if (!_controller) _controller = GetComponent<CharacterController>();\n\n currentHealth = MaxHealth;\n currentStamina = MaxStamina;\n }\n\n private void Start()\n {\n // in start do the things were you depend on others already being initialized\n if (!_inputManager) _inputManager = InputManager.Instance;\n if (!_cameraTransform) _cameraTransform = Camera.main.transform;\n }\n\n private void Update()\n {\n UpdateStamina();\n\n UpdateHorizontalMovement();\n\n UpdateVerticalMovement();\n }\n\n private void UpdateStamina()\n {\n if (_inputManager.IsRunning)\n {\n // drain your stamina -> also informs all listeners\n currentStamina -= _staminaDrainPerSecond * Time.deltaTime;\n\n // reset the regen timer\n _staminaRegenDelayTimer = _secondsDelayBeforeStaminaRegen;\n }\n else\n {\n // only if not pressing run start the regen timer\n if (_staminaRegenDelayTimer > 0)\n {\n _staminaRegenDelayTimer -= Time.deltaTime;\n }\n else\n {\n // once timer is finished start regen\n currentStamina += _staminaRegenPerSecond * Time.deltaTime;\n }\n }\n }\n\n private void UpdateHorizontalMovement()\n {\n var movement = _inputManager.PlayerMovement;\n var move = _cameraTransform.forward * movement.y + _cameraTransform.right * movement.x;\n move.y = 0f;\n move *= _inputManager.IsRunning && currentStamina > 0 ? _playerRunSpeed : _playerSpeed;\n _controller.Move(move * Time.deltaTime);\n }\n\n private void UpdateVerticalMovement()\n {\n if (_controller.isGrounded)\n {\n if (_inputManager.JumpedThisFrame)\n {\n _currentYVelocity += Mathf.Sqrt(_jumpHeight * -3.0f * _gravityValue);\n }\n else if (_currentYVelocity < 0)\n {\n _currentYVelocity = 0f;\n }\n }\n else\n {\n _currentYVelocity += _gravityValue * Time.deltaTime;\n }\n\n _controller.Move(Vector3.up * _currentYVelocity * Time.deltaTime);\n }\n}\n StaminaBar PlayerController public class StaminaBar : MonoBehaviour\n{\n [SerializeField] private Slider _staminaSlider;\n [SerializeField] private PlayerController _playerController;\n\n private void Awake()\n {\n // or wherever you get the reference from\n if (!_playerController) _playerController = FindObjectOfType<PlayerController>();\n\n // poll the setting from the player\n _staminaSlider.maxValue = _playerController.MaxStamina;\n\n // attach a callback to the event \n _playerController.OnStaminaChanged.AddListener(OnStaminaChanged);\n\n // just to be sure invoke the callback once immediately with the current value\n // so we don't have to wait for the first actual event invocation\n OnStaminaChanged(_playerController.currentStamina);\n }\n\n private void OnDestroy() \n {\n if(_playerController) _playerController.OnStaminaChanged.RemoveListener(OnStaminaChanged);\n }\n\n // This will now be called whenever the stamina has changed\n private void OnStaminaChanged(float stamina)\n {\n _staminaSlider.value = stamina;\n }\n}\n InputManager public class InputManager : MonoBehaviour\n{\n [Header(\"Own references\")]\n [SerializeField] private Transform _bulletParent;\n [SerializeField] private Transform _barrelTransform;\n\n [Header(\"Scene references\")]\n [SerializeField] private Transform _cameraTransform;\n\n // By using the correct component right away you can later skip \"GetComponent\"\n [Header(\"Assets\")]\n [SerializeField] private BulletController _bulletPrefab;\n\n [Header(\"Settings\")]\n [SerializeField] private float _bulletHitMissDistance = 25f;\n [SerializeField] private float _damage = 100;\n [SerializeField] private float _impactForce = 30;\n [SerializeField] private float _fireRate = 8f;\n\n public static InputManager Instance { get; private set; }\n\n // Again I would use properties here\n // You don't want anything else to set the \"isRunning\" flag\n // And the others don't need to be methods either\n public bool IsRunning { get; private set; }\n public Vector2 PlayerMovement => _playerControls.Player.Movement.ReadValue<Vector2>();\n public Vector2 MouseDelta => _playerControls.Player.Look.ReadValue<Vector2>();\n public bool JumpedThisFrame => _playerControls.Player.Jump.triggered;\n\n private Coroutine _fireCoroutine;\n private PlayerControls _playerControls;\n private WaitForSeconds _rapidFireWait;\n\n private void Awake()\n {\n if (Instance != null && Instance != this)\n {\n Destroy(gameObject);\n }\n else\n {\n Instance = this;\n }\n\n _playerControls = new PlayerControls();\n\n //Cursor.visible = false;\n\n _rapidFireWait = new WaitForSeconds(1 / _fireRate);\n _cameraTransform = Camera.main.transform;\n\n _playerControls.Player.RunStart.performed += _ => Running();\n _playerControls.Player.RunEnd.performed += _ => RunningStop();\n _playerControls.Player.Shoot.started += _ => StartFiring();\n _playerControls.Player.Shoot.canceled += _ => StopFiring();\n }\n\n private void OnEnable()\n {\n _playerControls.Enable();\n }\n\n private void OnDisable()\n {\n _playerControls.Disable();\n }\n\n private void StartFiring()\n {\n _fireCoroutine = StartCoroutine(RapidFire());\n }\n\n private void StopFiring()\n {\n if (_fireCoroutine != null)\n {\n StopCoroutine(_fireCoroutine);\n _fireCoroutine = null;\n }\n }\n\n private void Shooting()\n {\n var bulletController = Instantiate(_bulletPrefab, _barrelTransform.position, Quaternion.identity, _bulletParent);\n\n if (Physics.Raycast(_cameraTransform.position, _cameraTransform.forward, out var hit, Mathf.Infinity))\n {\n bulletController.target = hit.point;\n bulletController.hit = true;\n\n if (hit.transform.TryGetComponent<Enemy>(out var enemy))\n {\n enemy.TakeDamage(_damage);\n }\n\n if (hit.rigidbody != null)\n {\n hit.rigidbody.AddForce(-hit.normal * _impactForce);\n }\n }\n else\n {\n bulletController.target = _cameraTransform.position + _cameraTransform.forward * _bulletHitMissDistance;\n bulletController.hit = false;\n }\n }\n\n private IEnumerator RapidFire()\n {\n while (true)\n {\n Shooting();\n yield return _rapidFireWait;\n }\n }\n\n private void Running()\n {\n IsRunning = true;\n }\n\n private void RunningStop()\n {\n IsRunning = false;\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20563979/"
] |
74,542,565
|
<pre><code><script src="https://pie-meister.github.io/PieMeister-with-Progress.min.js"></script>
<pie-chart className="nested" offset="top">
<style>
path {
stroke-linecap: round;
stroke-width: 90;
}
[color1] {
stroke: #BFBDB2;
stroke-width: 50;
}
[color2] {
stroke: #26BDD8;
stroke-width: 60;
}
[color3] {
stroke: #824BF1;
}
[part="path"]:not([y]) {
stroke: #BFBDB2;
stroke-width: 60;
opacity: 0.4;
}
</style>
</code></pre>
<p>I was using this library pie-master and it had styled attributes as shown above.
I want to implement the similar in react.</p>
|
[
{
"answer_id": 74557605,
"author": "derHugo",
"author_id": 7111561,
"author_profile": "https://Stackoverflow.com/users/7111561",
"pm_score": 2,
"selected": true,
"text": "PlayerController StaminaBar PlayerController StaminaBar InputManager PlayerController StaminaBar StaminaBar public class PlayerController : MonoBehaviour\n{\n [Header(\"Own References\")]\n [SerializeField] private CharacterController _controller;\n\n [Header(\"Scene References\")]\n [SerializeField] private Transform _cameraTransform;\n [SerializeField] private InputManager _inputManager;\n\n // In general always make you stuff as encapsulated as possible\n // -> nobody should be able to change these except you via the Inspector\n // (Values you are anyway not gonna change at all you could also convert to \"const\")\n [Header(\"Settings\")]\n [SerializeField] private float _maxHealth = 100f;\n [SerializeField] private float _maxStamina = 100f;\n [SerializeField] private float _staminaDrainPerSecond = 2f;\n [SerializeField] private float _secondsDelayBeforeStaminaRegen = 1f;\n [SerializeField] private float _staminaRegenPerSecond = 2f;\n [SerializeField] private float _playerSpeed = 1f;\n [SerializeField] private float _playerRunSpeed = 2f;\n [SerializeField] private float _jumpHeight = 1f;\n [SerializeField] private float _gravityValue = -9.81f;\n\n // Your runtime valus\n private float _staminaRegenDelayTimer;\n private float _currentHealt;\n private float _currentStamina;\n\n // You only need a single float for this\n private float _currentYVelocity;\n\n // EVENTS we expose so other classes can react to those\n public UnityEvent OnDeath;\n public UnityEvent<float> OnHealthChanged;\n public UnityEvent<float> OnStaminaChanged;\n\n // Provide public read-only access to the settings so your visuals can access those for their setup\n public float MaxHealth => _maxHealth;\n public float MaxStamina => _maxStamina;\n\n // And then use properties for your runtime values\n // whenever you set the value you do additional stuff like cleaning the value and invoke according events\n public float currentHealth\n {\n get => _currentHealt;\n private set\n {\n _currentHealt = Mathf.Clamp(value, 0, _maxHealth);\n\n OnHealthChanged.Invoke(_currentHealt);\n\n if (value <= 0f)\n {\n OnDeath.Invoke();\n }\n }\n }\n\n public float currentStamina\n {\n get => _currentStamina;\n private set\n {\n _currentStamina = Mathf.Clamp(value, 0, _maxStamina);\n\n OnStaminaChanged.Invoke(_currentStamina);\n }\n }\n\n private void Awake()\n {\n // As a thumb rule to avoid issues with order I usually initialize everything I an in Awake\n if (!_controller) _controller = GetComponent<CharacterController>();\n\n currentHealth = MaxHealth;\n currentStamina = MaxStamina;\n }\n\n private void Start()\n {\n // in start do the things were you depend on others already being initialized\n if (!_inputManager) _inputManager = InputManager.Instance;\n if (!_cameraTransform) _cameraTransform = Camera.main.transform;\n }\n\n private void Update()\n {\n UpdateStamina();\n\n UpdateHorizontalMovement();\n\n UpdateVerticalMovement();\n }\n\n private void UpdateStamina()\n {\n if (_inputManager.IsRunning)\n {\n // drain your stamina -> also informs all listeners\n currentStamina -= _staminaDrainPerSecond * Time.deltaTime;\n\n // reset the regen timer\n _staminaRegenDelayTimer = _secondsDelayBeforeStaminaRegen;\n }\n else\n {\n // only if not pressing run start the regen timer\n if (_staminaRegenDelayTimer > 0)\n {\n _staminaRegenDelayTimer -= Time.deltaTime;\n }\n else\n {\n // once timer is finished start regen\n currentStamina += _staminaRegenPerSecond * Time.deltaTime;\n }\n }\n }\n\n private void UpdateHorizontalMovement()\n {\n var movement = _inputManager.PlayerMovement;\n var move = _cameraTransform.forward * movement.y + _cameraTransform.right * movement.x;\n move.y = 0f;\n move *= _inputManager.IsRunning && currentStamina > 0 ? _playerRunSpeed : _playerSpeed;\n _controller.Move(move * Time.deltaTime);\n }\n\n private void UpdateVerticalMovement()\n {\n if (_controller.isGrounded)\n {\n if (_inputManager.JumpedThisFrame)\n {\n _currentYVelocity += Mathf.Sqrt(_jumpHeight * -3.0f * _gravityValue);\n }\n else if (_currentYVelocity < 0)\n {\n _currentYVelocity = 0f;\n }\n }\n else\n {\n _currentYVelocity += _gravityValue * Time.deltaTime;\n }\n\n _controller.Move(Vector3.up * _currentYVelocity * Time.deltaTime);\n }\n}\n StaminaBar PlayerController public class StaminaBar : MonoBehaviour\n{\n [SerializeField] private Slider _staminaSlider;\n [SerializeField] private PlayerController _playerController;\n\n private void Awake()\n {\n // or wherever you get the reference from\n if (!_playerController) _playerController = FindObjectOfType<PlayerController>();\n\n // poll the setting from the player\n _staminaSlider.maxValue = _playerController.MaxStamina;\n\n // attach a callback to the event \n _playerController.OnStaminaChanged.AddListener(OnStaminaChanged);\n\n // just to be sure invoke the callback once immediately with the current value\n // so we don't have to wait for the first actual event invocation\n OnStaminaChanged(_playerController.currentStamina);\n }\n\n private void OnDestroy() \n {\n if(_playerController) _playerController.OnStaminaChanged.RemoveListener(OnStaminaChanged);\n }\n\n // This will now be called whenever the stamina has changed\n private void OnStaminaChanged(float stamina)\n {\n _staminaSlider.value = stamina;\n }\n}\n InputManager public class InputManager : MonoBehaviour\n{\n [Header(\"Own references\")]\n [SerializeField] private Transform _bulletParent;\n [SerializeField] private Transform _barrelTransform;\n\n [Header(\"Scene references\")]\n [SerializeField] private Transform _cameraTransform;\n\n // By using the correct component right away you can later skip \"GetComponent\"\n [Header(\"Assets\")]\n [SerializeField] private BulletController _bulletPrefab;\n\n [Header(\"Settings\")]\n [SerializeField] private float _bulletHitMissDistance = 25f;\n [SerializeField] private float _damage = 100;\n [SerializeField] private float _impactForce = 30;\n [SerializeField] private float _fireRate = 8f;\n\n public static InputManager Instance { get; private set; }\n\n // Again I would use properties here\n // You don't want anything else to set the \"isRunning\" flag\n // And the others don't need to be methods either\n public bool IsRunning { get; private set; }\n public Vector2 PlayerMovement => _playerControls.Player.Movement.ReadValue<Vector2>();\n public Vector2 MouseDelta => _playerControls.Player.Look.ReadValue<Vector2>();\n public bool JumpedThisFrame => _playerControls.Player.Jump.triggered;\n\n private Coroutine _fireCoroutine;\n private PlayerControls _playerControls;\n private WaitForSeconds _rapidFireWait;\n\n private void Awake()\n {\n if (Instance != null && Instance != this)\n {\n Destroy(gameObject);\n }\n else\n {\n Instance = this;\n }\n\n _playerControls = new PlayerControls();\n\n //Cursor.visible = false;\n\n _rapidFireWait = new WaitForSeconds(1 / _fireRate);\n _cameraTransform = Camera.main.transform;\n\n _playerControls.Player.RunStart.performed += _ => Running();\n _playerControls.Player.RunEnd.performed += _ => RunningStop();\n _playerControls.Player.Shoot.started += _ => StartFiring();\n _playerControls.Player.Shoot.canceled += _ => StopFiring();\n }\n\n private void OnEnable()\n {\n _playerControls.Enable();\n }\n\n private void OnDisable()\n {\n _playerControls.Disable();\n }\n\n private void StartFiring()\n {\n _fireCoroutine = StartCoroutine(RapidFire());\n }\n\n private void StopFiring()\n {\n if (_fireCoroutine != null)\n {\n StopCoroutine(_fireCoroutine);\n _fireCoroutine = null;\n }\n }\n\n private void Shooting()\n {\n var bulletController = Instantiate(_bulletPrefab, _barrelTransform.position, Quaternion.identity, _bulletParent);\n\n if (Physics.Raycast(_cameraTransform.position, _cameraTransform.forward, out var hit, Mathf.Infinity))\n {\n bulletController.target = hit.point;\n bulletController.hit = true;\n\n if (hit.transform.TryGetComponent<Enemy>(out var enemy))\n {\n enemy.TakeDamage(_damage);\n }\n\n if (hit.rigidbody != null)\n {\n hit.rigidbody.AddForce(-hit.normal * _impactForce);\n }\n }\n else\n {\n bulletController.target = _cameraTransform.position + _cameraTransform.forward * _bulletHitMissDistance;\n bulletController.hit = false;\n }\n }\n\n private IEnumerator RapidFire()\n {\n while (true)\n {\n Shooting();\n yield return _rapidFireWait;\n }\n }\n\n private void Running()\n {\n IsRunning = true;\n }\n\n private void RunningStop()\n {\n IsRunning = false;\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16695879/"
] |
74,542,597
|
<p>i have a a number of xml files with me, whose format is:</p>
<pre><code><objects>
<object>
<record>
<invoice_source>EMAIL</invoice_source>
<invoice_capture_date>2022-11-18</invoice_capture_date>
<document_type>INVOICE</document_type>
<data_capture_provider_code>00001</data_capture_provider_code>
<data_capture_provider_reference>1264</data_capture_provider_reference>
<document_capture_provide_code>00002</document_capture_provide_code>
<document_capture_provider_ref>1264</document_capture_provider_ref>
<rows/>
</record>
</object>
</objects>
</code></pre>
<p>there is two root objects in this xml. i want to remove one of them using. i want the xml to look like this:</p>
<pre><code> <objects>
<record>
<invoice_source>EMAIL</invoice_source>
<invoice_capture_date>2022-11-18</invoice_capture_date>
<document_type>INVOICE</document_type>
<data_capture_provider_code>00001</data_capture_provider_code>
<data_capture_provider_reference>1264</data_capture_provider_reference>
<document_capture_provide_code>00002</document_capture_provide_code>
<document_capture_provider_ref>1264</document_capture_provider_ref>
<rows/>
</record>
</objects>
</code></pre>
<p>i have a folder full of this files. i want to do it using python. is there any way.</p>
|
[
{
"answer_id": 74557605,
"author": "derHugo",
"author_id": 7111561,
"author_profile": "https://Stackoverflow.com/users/7111561",
"pm_score": 2,
"selected": true,
"text": "PlayerController StaminaBar PlayerController StaminaBar InputManager PlayerController StaminaBar StaminaBar public class PlayerController : MonoBehaviour\n{\n [Header(\"Own References\")]\n [SerializeField] private CharacterController _controller;\n\n [Header(\"Scene References\")]\n [SerializeField] private Transform _cameraTransform;\n [SerializeField] private InputManager _inputManager;\n\n // In general always make you stuff as encapsulated as possible\n // -> nobody should be able to change these except you via the Inspector\n // (Values you are anyway not gonna change at all you could also convert to \"const\")\n [Header(\"Settings\")]\n [SerializeField] private float _maxHealth = 100f;\n [SerializeField] private float _maxStamina = 100f;\n [SerializeField] private float _staminaDrainPerSecond = 2f;\n [SerializeField] private float _secondsDelayBeforeStaminaRegen = 1f;\n [SerializeField] private float _staminaRegenPerSecond = 2f;\n [SerializeField] private float _playerSpeed = 1f;\n [SerializeField] private float _playerRunSpeed = 2f;\n [SerializeField] private float _jumpHeight = 1f;\n [SerializeField] private float _gravityValue = -9.81f;\n\n // Your runtime valus\n private float _staminaRegenDelayTimer;\n private float _currentHealt;\n private float _currentStamina;\n\n // You only need a single float for this\n private float _currentYVelocity;\n\n // EVENTS we expose so other classes can react to those\n public UnityEvent OnDeath;\n public UnityEvent<float> OnHealthChanged;\n public UnityEvent<float> OnStaminaChanged;\n\n // Provide public read-only access to the settings so your visuals can access those for their setup\n public float MaxHealth => _maxHealth;\n public float MaxStamina => _maxStamina;\n\n // And then use properties for your runtime values\n // whenever you set the value you do additional stuff like cleaning the value and invoke according events\n public float currentHealth\n {\n get => _currentHealt;\n private set\n {\n _currentHealt = Mathf.Clamp(value, 0, _maxHealth);\n\n OnHealthChanged.Invoke(_currentHealt);\n\n if (value <= 0f)\n {\n OnDeath.Invoke();\n }\n }\n }\n\n public float currentStamina\n {\n get => _currentStamina;\n private set\n {\n _currentStamina = Mathf.Clamp(value, 0, _maxStamina);\n\n OnStaminaChanged.Invoke(_currentStamina);\n }\n }\n\n private void Awake()\n {\n // As a thumb rule to avoid issues with order I usually initialize everything I an in Awake\n if (!_controller) _controller = GetComponent<CharacterController>();\n\n currentHealth = MaxHealth;\n currentStamina = MaxStamina;\n }\n\n private void Start()\n {\n // in start do the things were you depend on others already being initialized\n if (!_inputManager) _inputManager = InputManager.Instance;\n if (!_cameraTransform) _cameraTransform = Camera.main.transform;\n }\n\n private void Update()\n {\n UpdateStamina();\n\n UpdateHorizontalMovement();\n\n UpdateVerticalMovement();\n }\n\n private void UpdateStamina()\n {\n if (_inputManager.IsRunning)\n {\n // drain your stamina -> also informs all listeners\n currentStamina -= _staminaDrainPerSecond * Time.deltaTime;\n\n // reset the regen timer\n _staminaRegenDelayTimer = _secondsDelayBeforeStaminaRegen;\n }\n else\n {\n // only if not pressing run start the regen timer\n if (_staminaRegenDelayTimer > 0)\n {\n _staminaRegenDelayTimer -= Time.deltaTime;\n }\n else\n {\n // once timer is finished start regen\n currentStamina += _staminaRegenPerSecond * Time.deltaTime;\n }\n }\n }\n\n private void UpdateHorizontalMovement()\n {\n var movement = _inputManager.PlayerMovement;\n var move = _cameraTransform.forward * movement.y + _cameraTransform.right * movement.x;\n move.y = 0f;\n move *= _inputManager.IsRunning && currentStamina > 0 ? _playerRunSpeed : _playerSpeed;\n _controller.Move(move * Time.deltaTime);\n }\n\n private void UpdateVerticalMovement()\n {\n if (_controller.isGrounded)\n {\n if (_inputManager.JumpedThisFrame)\n {\n _currentYVelocity += Mathf.Sqrt(_jumpHeight * -3.0f * _gravityValue);\n }\n else if (_currentYVelocity < 0)\n {\n _currentYVelocity = 0f;\n }\n }\n else\n {\n _currentYVelocity += _gravityValue * Time.deltaTime;\n }\n\n _controller.Move(Vector3.up * _currentYVelocity * Time.deltaTime);\n }\n}\n StaminaBar PlayerController public class StaminaBar : MonoBehaviour\n{\n [SerializeField] private Slider _staminaSlider;\n [SerializeField] private PlayerController _playerController;\n\n private void Awake()\n {\n // or wherever you get the reference from\n if (!_playerController) _playerController = FindObjectOfType<PlayerController>();\n\n // poll the setting from the player\n _staminaSlider.maxValue = _playerController.MaxStamina;\n\n // attach a callback to the event \n _playerController.OnStaminaChanged.AddListener(OnStaminaChanged);\n\n // just to be sure invoke the callback once immediately with the current value\n // so we don't have to wait for the first actual event invocation\n OnStaminaChanged(_playerController.currentStamina);\n }\n\n private void OnDestroy() \n {\n if(_playerController) _playerController.OnStaminaChanged.RemoveListener(OnStaminaChanged);\n }\n\n // This will now be called whenever the stamina has changed\n private void OnStaminaChanged(float stamina)\n {\n _staminaSlider.value = stamina;\n }\n}\n InputManager public class InputManager : MonoBehaviour\n{\n [Header(\"Own references\")]\n [SerializeField] private Transform _bulletParent;\n [SerializeField] private Transform _barrelTransform;\n\n [Header(\"Scene references\")]\n [SerializeField] private Transform _cameraTransform;\n\n // By using the correct component right away you can later skip \"GetComponent\"\n [Header(\"Assets\")]\n [SerializeField] private BulletController _bulletPrefab;\n\n [Header(\"Settings\")]\n [SerializeField] private float _bulletHitMissDistance = 25f;\n [SerializeField] private float _damage = 100;\n [SerializeField] private float _impactForce = 30;\n [SerializeField] private float _fireRate = 8f;\n\n public static InputManager Instance { get; private set; }\n\n // Again I would use properties here\n // You don't want anything else to set the \"isRunning\" flag\n // And the others don't need to be methods either\n public bool IsRunning { get; private set; }\n public Vector2 PlayerMovement => _playerControls.Player.Movement.ReadValue<Vector2>();\n public Vector2 MouseDelta => _playerControls.Player.Look.ReadValue<Vector2>();\n public bool JumpedThisFrame => _playerControls.Player.Jump.triggered;\n\n private Coroutine _fireCoroutine;\n private PlayerControls _playerControls;\n private WaitForSeconds _rapidFireWait;\n\n private void Awake()\n {\n if (Instance != null && Instance != this)\n {\n Destroy(gameObject);\n }\n else\n {\n Instance = this;\n }\n\n _playerControls = new PlayerControls();\n\n //Cursor.visible = false;\n\n _rapidFireWait = new WaitForSeconds(1 / _fireRate);\n _cameraTransform = Camera.main.transform;\n\n _playerControls.Player.RunStart.performed += _ => Running();\n _playerControls.Player.RunEnd.performed += _ => RunningStop();\n _playerControls.Player.Shoot.started += _ => StartFiring();\n _playerControls.Player.Shoot.canceled += _ => StopFiring();\n }\n\n private void OnEnable()\n {\n _playerControls.Enable();\n }\n\n private void OnDisable()\n {\n _playerControls.Disable();\n }\n\n private void StartFiring()\n {\n _fireCoroutine = StartCoroutine(RapidFire());\n }\n\n private void StopFiring()\n {\n if (_fireCoroutine != null)\n {\n StopCoroutine(_fireCoroutine);\n _fireCoroutine = null;\n }\n }\n\n private void Shooting()\n {\n var bulletController = Instantiate(_bulletPrefab, _barrelTransform.position, Quaternion.identity, _bulletParent);\n\n if (Physics.Raycast(_cameraTransform.position, _cameraTransform.forward, out var hit, Mathf.Infinity))\n {\n bulletController.target = hit.point;\n bulletController.hit = true;\n\n if (hit.transform.TryGetComponent<Enemy>(out var enemy))\n {\n enemy.TakeDamage(_damage);\n }\n\n if (hit.rigidbody != null)\n {\n hit.rigidbody.AddForce(-hit.normal * _impactForce);\n }\n }\n else\n {\n bulletController.target = _cameraTransform.position + _cameraTransform.forward * _bulletHitMissDistance;\n bulletController.hit = false;\n }\n }\n\n private IEnumerator RapidFire()\n {\n while (true)\n {\n Shooting();\n yield return _rapidFireWait;\n }\n }\n\n private void Running()\n {\n IsRunning = true;\n }\n\n private void RunningStop()\n {\n IsRunning = false;\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20397498/"
] |
74,542,609
|
<p>I am working in webflow(a website platform) and pasting a JSON-LD script in a content field. The field is mapped to the section of the webpage.</p>
<p>All the double quotes " in the JSON script are getting switched to "</p>
<p>Is there a line of code that I can add to the script that will switch them back?</p>
<p>I tried inserting the following before the <code></script></code> tag
<code>.replace(/&quot;/g, '\"') </code>
and <code>.replace(/&quot;/g, '\\"')</code>
and neither one worked.</p>
<p>Here's what the code looks like on the backend before publishing</p>
<pre><code><script type='application/ld+json'>
{Schema}
.replace(/&quot;/g, '\\"')
</script>
</code></pre>
<p>And this is what it renders on the live site</p>
<pre><code><script type='application/ld+json'>
{ &quot;@context&quot;: &quot;https://schema.org&quot;, &quot;@type&quot;: &quot;FAQPage&quot;, &quot;mainEntity&quot;: [{ &quot;@type&quot;: &quot;Question&quot;, &quot;name&quot;: &quot;How quickly can I get my certificate of insurance?&quot;, &quot;acceptedAnswer&quot;: { &quot;@type&quot;: &quot;Answer&quot;, &quot;text&quot;: Certificates are usually issued 24 hours after the policy is bound.&quot; } }]
}
.replace(/&quot;/g, '\\"')
</script>
</code></pre>
|
[
{
"answer_id": 74557605,
"author": "derHugo",
"author_id": 7111561,
"author_profile": "https://Stackoverflow.com/users/7111561",
"pm_score": 2,
"selected": true,
"text": "PlayerController StaminaBar PlayerController StaminaBar InputManager PlayerController StaminaBar StaminaBar public class PlayerController : MonoBehaviour\n{\n [Header(\"Own References\")]\n [SerializeField] private CharacterController _controller;\n\n [Header(\"Scene References\")]\n [SerializeField] private Transform _cameraTransform;\n [SerializeField] private InputManager _inputManager;\n\n // In general always make you stuff as encapsulated as possible\n // -> nobody should be able to change these except you via the Inspector\n // (Values you are anyway not gonna change at all you could also convert to \"const\")\n [Header(\"Settings\")]\n [SerializeField] private float _maxHealth = 100f;\n [SerializeField] private float _maxStamina = 100f;\n [SerializeField] private float _staminaDrainPerSecond = 2f;\n [SerializeField] private float _secondsDelayBeforeStaminaRegen = 1f;\n [SerializeField] private float _staminaRegenPerSecond = 2f;\n [SerializeField] private float _playerSpeed = 1f;\n [SerializeField] private float _playerRunSpeed = 2f;\n [SerializeField] private float _jumpHeight = 1f;\n [SerializeField] private float _gravityValue = -9.81f;\n\n // Your runtime valus\n private float _staminaRegenDelayTimer;\n private float _currentHealt;\n private float _currentStamina;\n\n // You only need a single float for this\n private float _currentYVelocity;\n\n // EVENTS we expose so other classes can react to those\n public UnityEvent OnDeath;\n public UnityEvent<float> OnHealthChanged;\n public UnityEvent<float> OnStaminaChanged;\n\n // Provide public read-only access to the settings so your visuals can access those for their setup\n public float MaxHealth => _maxHealth;\n public float MaxStamina => _maxStamina;\n\n // And then use properties for your runtime values\n // whenever you set the value you do additional stuff like cleaning the value and invoke according events\n public float currentHealth\n {\n get => _currentHealt;\n private set\n {\n _currentHealt = Mathf.Clamp(value, 0, _maxHealth);\n\n OnHealthChanged.Invoke(_currentHealt);\n\n if (value <= 0f)\n {\n OnDeath.Invoke();\n }\n }\n }\n\n public float currentStamina\n {\n get => _currentStamina;\n private set\n {\n _currentStamina = Mathf.Clamp(value, 0, _maxStamina);\n\n OnStaminaChanged.Invoke(_currentStamina);\n }\n }\n\n private void Awake()\n {\n // As a thumb rule to avoid issues with order I usually initialize everything I an in Awake\n if (!_controller) _controller = GetComponent<CharacterController>();\n\n currentHealth = MaxHealth;\n currentStamina = MaxStamina;\n }\n\n private void Start()\n {\n // in start do the things were you depend on others already being initialized\n if (!_inputManager) _inputManager = InputManager.Instance;\n if (!_cameraTransform) _cameraTransform = Camera.main.transform;\n }\n\n private void Update()\n {\n UpdateStamina();\n\n UpdateHorizontalMovement();\n\n UpdateVerticalMovement();\n }\n\n private void UpdateStamina()\n {\n if (_inputManager.IsRunning)\n {\n // drain your stamina -> also informs all listeners\n currentStamina -= _staminaDrainPerSecond * Time.deltaTime;\n\n // reset the regen timer\n _staminaRegenDelayTimer = _secondsDelayBeforeStaminaRegen;\n }\n else\n {\n // only if not pressing run start the regen timer\n if (_staminaRegenDelayTimer > 0)\n {\n _staminaRegenDelayTimer -= Time.deltaTime;\n }\n else\n {\n // once timer is finished start regen\n currentStamina += _staminaRegenPerSecond * Time.deltaTime;\n }\n }\n }\n\n private void UpdateHorizontalMovement()\n {\n var movement = _inputManager.PlayerMovement;\n var move = _cameraTransform.forward * movement.y + _cameraTransform.right * movement.x;\n move.y = 0f;\n move *= _inputManager.IsRunning && currentStamina > 0 ? _playerRunSpeed : _playerSpeed;\n _controller.Move(move * Time.deltaTime);\n }\n\n private void UpdateVerticalMovement()\n {\n if (_controller.isGrounded)\n {\n if (_inputManager.JumpedThisFrame)\n {\n _currentYVelocity += Mathf.Sqrt(_jumpHeight * -3.0f * _gravityValue);\n }\n else if (_currentYVelocity < 0)\n {\n _currentYVelocity = 0f;\n }\n }\n else\n {\n _currentYVelocity += _gravityValue * Time.deltaTime;\n }\n\n _controller.Move(Vector3.up * _currentYVelocity * Time.deltaTime);\n }\n}\n StaminaBar PlayerController public class StaminaBar : MonoBehaviour\n{\n [SerializeField] private Slider _staminaSlider;\n [SerializeField] private PlayerController _playerController;\n\n private void Awake()\n {\n // or wherever you get the reference from\n if (!_playerController) _playerController = FindObjectOfType<PlayerController>();\n\n // poll the setting from the player\n _staminaSlider.maxValue = _playerController.MaxStamina;\n\n // attach a callback to the event \n _playerController.OnStaminaChanged.AddListener(OnStaminaChanged);\n\n // just to be sure invoke the callback once immediately with the current value\n // so we don't have to wait for the first actual event invocation\n OnStaminaChanged(_playerController.currentStamina);\n }\n\n private void OnDestroy() \n {\n if(_playerController) _playerController.OnStaminaChanged.RemoveListener(OnStaminaChanged);\n }\n\n // This will now be called whenever the stamina has changed\n private void OnStaminaChanged(float stamina)\n {\n _staminaSlider.value = stamina;\n }\n}\n InputManager public class InputManager : MonoBehaviour\n{\n [Header(\"Own references\")]\n [SerializeField] private Transform _bulletParent;\n [SerializeField] private Transform _barrelTransform;\n\n [Header(\"Scene references\")]\n [SerializeField] private Transform _cameraTransform;\n\n // By using the correct component right away you can later skip \"GetComponent\"\n [Header(\"Assets\")]\n [SerializeField] private BulletController _bulletPrefab;\n\n [Header(\"Settings\")]\n [SerializeField] private float _bulletHitMissDistance = 25f;\n [SerializeField] private float _damage = 100;\n [SerializeField] private float _impactForce = 30;\n [SerializeField] private float _fireRate = 8f;\n\n public static InputManager Instance { get; private set; }\n\n // Again I would use properties here\n // You don't want anything else to set the \"isRunning\" flag\n // And the others don't need to be methods either\n public bool IsRunning { get; private set; }\n public Vector2 PlayerMovement => _playerControls.Player.Movement.ReadValue<Vector2>();\n public Vector2 MouseDelta => _playerControls.Player.Look.ReadValue<Vector2>();\n public bool JumpedThisFrame => _playerControls.Player.Jump.triggered;\n\n private Coroutine _fireCoroutine;\n private PlayerControls _playerControls;\n private WaitForSeconds _rapidFireWait;\n\n private void Awake()\n {\n if (Instance != null && Instance != this)\n {\n Destroy(gameObject);\n }\n else\n {\n Instance = this;\n }\n\n _playerControls = new PlayerControls();\n\n //Cursor.visible = false;\n\n _rapidFireWait = new WaitForSeconds(1 / _fireRate);\n _cameraTransform = Camera.main.transform;\n\n _playerControls.Player.RunStart.performed += _ => Running();\n _playerControls.Player.RunEnd.performed += _ => RunningStop();\n _playerControls.Player.Shoot.started += _ => StartFiring();\n _playerControls.Player.Shoot.canceled += _ => StopFiring();\n }\n\n private void OnEnable()\n {\n _playerControls.Enable();\n }\n\n private void OnDisable()\n {\n _playerControls.Disable();\n }\n\n private void StartFiring()\n {\n _fireCoroutine = StartCoroutine(RapidFire());\n }\n\n private void StopFiring()\n {\n if (_fireCoroutine != null)\n {\n StopCoroutine(_fireCoroutine);\n _fireCoroutine = null;\n }\n }\n\n private void Shooting()\n {\n var bulletController = Instantiate(_bulletPrefab, _barrelTransform.position, Quaternion.identity, _bulletParent);\n\n if (Physics.Raycast(_cameraTransform.position, _cameraTransform.forward, out var hit, Mathf.Infinity))\n {\n bulletController.target = hit.point;\n bulletController.hit = true;\n\n if (hit.transform.TryGetComponent<Enemy>(out var enemy))\n {\n enemy.TakeDamage(_damage);\n }\n\n if (hit.rigidbody != null)\n {\n hit.rigidbody.AddForce(-hit.normal * _impactForce);\n }\n }\n else\n {\n bulletController.target = _cameraTransform.position + _cameraTransform.forward * _bulletHitMissDistance;\n bulletController.hit = false;\n }\n }\n\n private IEnumerator RapidFire()\n {\n while (true)\n {\n Shooting();\n yield return _rapidFireWait;\n }\n }\n\n private void Running()\n {\n IsRunning = true;\n }\n\n private void RunningStop()\n {\n IsRunning = false;\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20578847/"
] |
74,542,630
|
<p>I want to get the country code of the products form this website: <a href="https://www.skincarisma.com/products/olay/fresh-effects-s-wipe-out-refreshing-make-up-removal-cloths" rel="nofollow noreferrer">https://www.skincarisma.com/products/olay/fresh-effects-s-wipe-out-refreshing-make-up-removal-cloths</a></p>
<h1><a href="https://i.stack.imgur.com/bu5i7.png" rel="nofollow noreferrer">here is the html</a></h1>
<p>I tried</p>
<pre><code>country = driver.find_element(By.XPATH,'//div[@class="card-subtitle mb-2"]//img[@alt]').text
</code></pre>
<p>and</p>
<pre><code>country = driver.find_element(By.XPATH,'//div[@class="card-subtitle mb-2"]//img').text
</code></pre>
<p>but it failed to fetch (apparently because my code is wrong)</p>
<p>What should be the path?</p>
<p>trying: getting the coutnry code</p>
|
[
{
"answer_id": 74557605,
"author": "derHugo",
"author_id": 7111561,
"author_profile": "https://Stackoverflow.com/users/7111561",
"pm_score": 2,
"selected": true,
"text": "PlayerController StaminaBar PlayerController StaminaBar InputManager PlayerController StaminaBar StaminaBar public class PlayerController : MonoBehaviour\n{\n [Header(\"Own References\")]\n [SerializeField] private CharacterController _controller;\n\n [Header(\"Scene References\")]\n [SerializeField] private Transform _cameraTransform;\n [SerializeField] private InputManager _inputManager;\n\n // In general always make you stuff as encapsulated as possible\n // -> nobody should be able to change these except you via the Inspector\n // (Values you are anyway not gonna change at all you could also convert to \"const\")\n [Header(\"Settings\")]\n [SerializeField] private float _maxHealth = 100f;\n [SerializeField] private float _maxStamina = 100f;\n [SerializeField] private float _staminaDrainPerSecond = 2f;\n [SerializeField] private float _secondsDelayBeforeStaminaRegen = 1f;\n [SerializeField] private float _staminaRegenPerSecond = 2f;\n [SerializeField] private float _playerSpeed = 1f;\n [SerializeField] private float _playerRunSpeed = 2f;\n [SerializeField] private float _jumpHeight = 1f;\n [SerializeField] private float _gravityValue = -9.81f;\n\n // Your runtime valus\n private float _staminaRegenDelayTimer;\n private float _currentHealt;\n private float _currentStamina;\n\n // You only need a single float for this\n private float _currentYVelocity;\n\n // EVENTS we expose so other classes can react to those\n public UnityEvent OnDeath;\n public UnityEvent<float> OnHealthChanged;\n public UnityEvent<float> OnStaminaChanged;\n\n // Provide public read-only access to the settings so your visuals can access those for their setup\n public float MaxHealth => _maxHealth;\n public float MaxStamina => _maxStamina;\n\n // And then use properties for your runtime values\n // whenever you set the value you do additional stuff like cleaning the value and invoke according events\n public float currentHealth\n {\n get => _currentHealt;\n private set\n {\n _currentHealt = Mathf.Clamp(value, 0, _maxHealth);\n\n OnHealthChanged.Invoke(_currentHealt);\n\n if (value <= 0f)\n {\n OnDeath.Invoke();\n }\n }\n }\n\n public float currentStamina\n {\n get => _currentStamina;\n private set\n {\n _currentStamina = Mathf.Clamp(value, 0, _maxStamina);\n\n OnStaminaChanged.Invoke(_currentStamina);\n }\n }\n\n private void Awake()\n {\n // As a thumb rule to avoid issues with order I usually initialize everything I an in Awake\n if (!_controller) _controller = GetComponent<CharacterController>();\n\n currentHealth = MaxHealth;\n currentStamina = MaxStamina;\n }\n\n private void Start()\n {\n // in start do the things were you depend on others already being initialized\n if (!_inputManager) _inputManager = InputManager.Instance;\n if (!_cameraTransform) _cameraTransform = Camera.main.transform;\n }\n\n private void Update()\n {\n UpdateStamina();\n\n UpdateHorizontalMovement();\n\n UpdateVerticalMovement();\n }\n\n private void UpdateStamina()\n {\n if (_inputManager.IsRunning)\n {\n // drain your stamina -> also informs all listeners\n currentStamina -= _staminaDrainPerSecond * Time.deltaTime;\n\n // reset the regen timer\n _staminaRegenDelayTimer = _secondsDelayBeforeStaminaRegen;\n }\n else\n {\n // only if not pressing run start the regen timer\n if (_staminaRegenDelayTimer > 0)\n {\n _staminaRegenDelayTimer -= Time.deltaTime;\n }\n else\n {\n // once timer is finished start regen\n currentStamina += _staminaRegenPerSecond * Time.deltaTime;\n }\n }\n }\n\n private void UpdateHorizontalMovement()\n {\n var movement = _inputManager.PlayerMovement;\n var move = _cameraTransform.forward * movement.y + _cameraTransform.right * movement.x;\n move.y = 0f;\n move *= _inputManager.IsRunning && currentStamina > 0 ? _playerRunSpeed : _playerSpeed;\n _controller.Move(move * Time.deltaTime);\n }\n\n private void UpdateVerticalMovement()\n {\n if (_controller.isGrounded)\n {\n if (_inputManager.JumpedThisFrame)\n {\n _currentYVelocity += Mathf.Sqrt(_jumpHeight * -3.0f * _gravityValue);\n }\n else if (_currentYVelocity < 0)\n {\n _currentYVelocity = 0f;\n }\n }\n else\n {\n _currentYVelocity += _gravityValue * Time.deltaTime;\n }\n\n _controller.Move(Vector3.up * _currentYVelocity * Time.deltaTime);\n }\n}\n StaminaBar PlayerController public class StaminaBar : MonoBehaviour\n{\n [SerializeField] private Slider _staminaSlider;\n [SerializeField] private PlayerController _playerController;\n\n private void Awake()\n {\n // or wherever you get the reference from\n if (!_playerController) _playerController = FindObjectOfType<PlayerController>();\n\n // poll the setting from the player\n _staminaSlider.maxValue = _playerController.MaxStamina;\n\n // attach a callback to the event \n _playerController.OnStaminaChanged.AddListener(OnStaminaChanged);\n\n // just to be sure invoke the callback once immediately with the current value\n // so we don't have to wait for the first actual event invocation\n OnStaminaChanged(_playerController.currentStamina);\n }\n\n private void OnDestroy() \n {\n if(_playerController) _playerController.OnStaminaChanged.RemoveListener(OnStaminaChanged);\n }\n\n // This will now be called whenever the stamina has changed\n private void OnStaminaChanged(float stamina)\n {\n _staminaSlider.value = stamina;\n }\n}\n InputManager public class InputManager : MonoBehaviour\n{\n [Header(\"Own references\")]\n [SerializeField] private Transform _bulletParent;\n [SerializeField] private Transform _barrelTransform;\n\n [Header(\"Scene references\")]\n [SerializeField] private Transform _cameraTransform;\n\n // By using the correct component right away you can later skip \"GetComponent\"\n [Header(\"Assets\")]\n [SerializeField] private BulletController _bulletPrefab;\n\n [Header(\"Settings\")]\n [SerializeField] private float _bulletHitMissDistance = 25f;\n [SerializeField] private float _damage = 100;\n [SerializeField] private float _impactForce = 30;\n [SerializeField] private float _fireRate = 8f;\n\n public static InputManager Instance { get; private set; }\n\n // Again I would use properties here\n // You don't want anything else to set the \"isRunning\" flag\n // And the others don't need to be methods either\n public bool IsRunning { get; private set; }\n public Vector2 PlayerMovement => _playerControls.Player.Movement.ReadValue<Vector2>();\n public Vector2 MouseDelta => _playerControls.Player.Look.ReadValue<Vector2>();\n public bool JumpedThisFrame => _playerControls.Player.Jump.triggered;\n\n private Coroutine _fireCoroutine;\n private PlayerControls _playerControls;\n private WaitForSeconds _rapidFireWait;\n\n private void Awake()\n {\n if (Instance != null && Instance != this)\n {\n Destroy(gameObject);\n }\n else\n {\n Instance = this;\n }\n\n _playerControls = new PlayerControls();\n\n //Cursor.visible = false;\n\n _rapidFireWait = new WaitForSeconds(1 / _fireRate);\n _cameraTransform = Camera.main.transform;\n\n _playerControls.Player.RunStart.performed += _ => Running();\n _playerControls.Player.RunEnd.performed += _ => RunningStop();\n _playerControls.Player.Shoot.started += _ => StartFiring();\n _playerControls.Player.Shoot.canceled += _ => StopFiring();\n }\n\n private void OnEnable()\n {\n _playerControls.Enable();\n }\n\n private void OnDisable()\n {\n _playerControls.Disable();\n }\n\n private void StartFiring()\n {\n _fireCoroutine = StartCoroutine(RapidFire());\n }\n\n private void StopFiring()\n {\n if (_fireCoroutine != null)\n {\n StopCoroutine(_fireCoroutine);\n _fireCoroutine = null;\n }\n }\n\n private void Shooting()\n {\n var bulletController = Instantiate(_bulletPrefab, _barrelTransform.position, Quaternion.identity, _bulletParent);\n\n if (Physics.Raycast(_cameraTransform.position, _cameraTransform.forward, out var hit, Mathf.Infinity))\n {\n bulletController.target = hit.point;\n bulletController.hit = true;\n\n if (hit.transform.TryGetComponent<Enemy>(out var enemy))\n {\n enemy.TakeDamage(_damage);\n }\n\n if (hit.rigidbody != null)\n {\n hit.rigidbody.AddForce(-hit.normal * _impactForce);\n }\n }\n else\n {\n bulletController.target = _cameraTransform.position + _cameraTransform.forward * _bulletHitMissDistance;\n bulletController.hit = false;\n }\n }\n\n private IEnumerator RapidFire()\n {\n while (true)\n {\n Shooting();\n yield return _rapidFireWait;\n }\n }\n\n private void Running()\n {\n IsRunning = true;\n }\n\n private void RunningStop()\n {\n IsRunning = false;\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20576555/"
] |
74,542,683
|
<p>AddBookAction.java</p>
<pre><code> import com.opensymphony.xwork2.ActionSupport;
public class AddBookAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String id, name,aname,badd;
private String msg = "";
int ok = 0;
public String execute() throws Exception {
Main main = new Main();
try {
ok = main.AddBook(id,name);
if (ok > 0) {
msg = "Registration Successfull";
} else {
msg = "error";
}
} catch (Exception e) {
e.printStackTrace();
}
return "SUCCESS";
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAname() {
return aname;
}
public void setAname(String aname) {
this.aname = aname;
}
public String getBadd() {
return badd;
}
public void setBadd(String badd) {
this.badd = badd;
}
}
</code></pre>
<p>Error:</p>
<pre><code>C:\Program Files (x86)\Apache Software Foundation\Tomcat 9.0\webapps\Library\WEB-INF\classes>javac -cp ..\lib\xwork.jar AddBookAction.java
AddBookAction.java:1: error: package com.opensymphony.xwork2 does not exist
import com.opensymphony.xwork2.ActionSupport;
^
AddBookAction.java:3: error: cannot find symbol
public class AddBookAction extends ActionSupport
</code></pre>
<p>jars in my lib</p>
<p><a href="https://i.stack.imgur.com/1LMfg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1LMfg.png" alt="enter image description here" /></a></p>
<p>Path added in system variable</p>
<p><a href="https://i.stack.imgur.com/9vdny.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9vdny.png" alt="enter image description here" /></a></p>
<p>xwork package added in my lib folder, system variable[class path], but while compiling I'm getting the error stating that the package isn't added on my class path. Doing the project only by notepad file not in the eclipse or any other IDE. This is my task need to do. Tried so many ways but unable to fix.</p>
|
[
{
"answer_id": 74557605,
"author": "derHugo",
"author_id": 7111561,
"author_profile": "https://Stackoverflow.com/users/7111561",
"pm_score": 2,
"selected": true,
"text": "PlayerController StaminaBar PlayerController StaminaBar InputManager PlayerController StaminaBar StaminaBar public class PlayerController : MonoBehaviour\n{\n [Header(\"Own References\")]\n [SerializeField] private CharacterController _controller;\n\n [Header(\"Scene References\")]\n [SerializeField] private Transform _cameraTransform;\n [SerializeField] private InputManager _inputManager;\n\n // In general always make you stuff as encapsulated as possible\n // -> nobody should be able to change these except you via the Inspector\n // (Values you are anyway not gonna change at all you could also convert to \"const\")\n [Header(\"Settings\")]\n [SerializeField] private float _maxHealth = 100f;\n [SerializeField] private float _maxStamina = 100f;\n [SerializeField] private float _staminaDrainPerSecond = 2f;\n [SerializeField] private float _secondsDelayBeforeStaminaRegen = 1f;\n [SerializeField] private float _staminaRegenPerSecond = 2f;\n [SerializeField] private float _playerSpeed = 1f;\n [SerializeField] private float _playerRunSpeed = 2f;\n [SerializeField] private float _jumpHeight = 1f;\n [SerializeField] private float _gravityValue = -9.81f;\n\n // Your runtime valus\n private float _staminaRegenDelayTimer;\n private float _currentHealt;\n private float _currentStamina;\n\n // You only need a single float for this\n private float _currentYVelocity;\n\n // EVENTS we expose so other classes can react to those\n public UnityEvent OnDeath;\n public UnityEvent<float> OnHealthChanged;\n public UnityEvent<float> OnStaminaChanged;\n\n // Provide public read-only access to the settings so your visuals can access those for their setup\n public float MaxHealth => _maxHealth;\n public float MaxStamina => _maxStamina;\n\n // And then use properties for your runtime values\n // whenever you set the value you do additional stuff like cleaning the value and invoke according events\n public float currentHealth\n {\n get => _currentHealt;\n private set\n {\n _currentHealt = Mathf.Clamp(value, 0, _maxHealth);\n\n OnHealthChanged.Invoke(_currentHealt);\n\n if (value <= 0f)\n {\n OnDeath.Invoke();\n }\n }\n }\n\n public float currentStamina\n {\n get => _currentStamina;\n private set\n {\n _currentStamina = Mathf.Clamp(value, 0, _maxStamina);\n\n OnStaminaChanged.Invoke(_currentStamina);\n }\n }\n\n private void Awake()\n {\n // As a thumb rule to avoid issues with order I usually initialize everything I an in Awake\n if (!_controller) _controller = GetComponent<CharacterController>();\n\n currentHealth = MaxHealth;\n currentStamina = MaxStamina;\n }\n\n private void Start()\n {\n // in start do the things were you depend on others already being initialized\n if (!_inputManager) _inputManager = InputManager.Instance;\n if (!_cameraTransform) _cameraTransform = Camera.main.transform;\n }\n\n private void Update()\n {\n UpdateStamina();\n\n UpdateHorizontalMovement();\n\n UpdateVerticalMovement();\n }\n\n private void UpdateStamina()\n {\n if (_inputManager.IsRunning)\n {\n // drain your stamina -> also informs all listeners\n currentStamina -= _staminaDrainPerSecond * Time.deltaTime;\n\n // reset the regen timer\n _staminaRegenDelayTimer = _secondsDelayBeforeStaminaRegen;\n }\n else\n {\n // only if not pressing run start the regen timer\n if (_staminaRegenDelayTimer > 0)\n {\n _staminaRegenDelayTimer -= Time.deltaTime;\n }\n else\n {\n // once timer is finished start regen\n currentStamina += _staminaRegenPerSecond * Time.deltaTime;\n }\n }\n }\n\n private void UpdateHorizontalMovement()\n {\n var movement = _inputManager.PlayerMovement;\n var move = _cameraTransform.forward * movement.y + _cameraTransform.right * movement.x;\n move.y = 0f;\n move *= _inputManager.IsRunning && currentStamina > 0 ? _playerRunSpeed : _playerSpeed;\n _controller.Move(move * Time.deltaTime);\n }\n\n private void UpdateVerticalMovement()\n {\n if (_controller.isGrounded)\n {\n if (_inputManager.JumpedThisFrame)\n {\n _currentYVelocity += Mathf.Sqrt(_jumpHeight * -3.0f * _gravityValue);\n }\n else if (_currentYVelocity < 0)\n {\n _currentYVelocity = 0f;\n }\n }\n else\n {\n _currentYVelocity += _gravityValue * Time.deltaTime;\n }\n\n _controller.Move(Vector3.up * _currentYVelocity * Time.deltaTime);\n }\n}\n StaminaBar PlayerController public class StaminaBar : MonoBehaviour\n{\n [SerializeField] private Slider _staminaSlider;\n [SerializeField] private PlayerController _playerController;\n\n private void Awake()\n {\n // or wherever you get the reference from\n if (!_playerController) _playerController = FindObjectOfType<PlayerController>();\n\n // poll the setting from the player\n _staminaSlider.maxValue = _playerController.MaxStamina;\n\n // attach a callback to the event \n _playerController.OnStaminaChanged.AddListener(OnStaminaChanged);\n\n // just to be sure invoke the callback once immediately with the current value\n // so we don't have to wait for the first actual event invocation\n OnStaminaChanged(_playerController.currentStamina);\n }\n\n private void OnDestroy() \n {\n if(_playerController) _playerController.OnStaminaChanged.RemoveListener(OnStaminaChanged);\n }\n\n // This will now be called whenever the stamina has changed\n private void OnStaminaChanged(float stamina)\n {\n _staminaSlider.value = stamina;\n }\n}\n InputManager public class InputManager : MonoBehaviour\n{\n [Header(\"Own references\")]\n [SerializeField] private Transform _bulletParent;\n [SerializeField] private Transform _barrelTransform;\n\n [Header(\"Scene references\")]\n [SerializeField] private Transform _cameraTransform;\n\n // By using the correct component right away you can later skip \"GetComponent\"\n [Header(\"Assets\")]\n [SerializeField] private BulletController _bulletPrefab;\n\n [Header(\"Settings\")]\n [SerializeField] private float _bulletHitMissDistance = 25f;\n [SerializeField] private float _damage = 100;\n [SerializeField] private float _impactForce = 30;\n [SerializeField] private float _fireRate = 8f;\n\n public static InputManager Instance { get; private set; }\n\n // Again I would use properties here\n // You don't want anything else to set the \"isRunning\" flag\n // And the others don't need to be methods either\n public bool IsRunning { get; private set; }\n public Vector2 PlayerMovement => _playerControls.Player.Movement.ReadValue<Vector2>();\n public Vector2 MouseDelta => _playerControls.Player.Look.ReadValue<Vector2>();\n public bool JumpedThisFrame => _playerControls.Player.Jump.triggered;\n\n private Coroutine _fireCoroutine;\n private PlayerControls _playerControls;\n private WaitForSeconds _rapidFireWait;\n\n private void Awake()\n {\n if (Instance != null && Instance != this)\n {\n Destroy(gameObject);\n }\n else\n {\n Instance = this;\n }\n\n _playerControls = new PlayerControls();\n\n //Cursor.visible = false;\n\n _rapidFireWait = new WaitForSeconds(1 / _fireRate);\n _cameraTransform = Camera.main.transform;\n\n _playerControls.Player.RunStart.performed += _ => Running();\n _playerControls.Player.RunEnd.performed += _ => RunningStop();\n _playerControls.Player.Shoot.started += _ => StartFiring();\n _playerControls.Player.Shoot.canceled += _ => StopFiring();\n }\n\n private void OnEnable()\n {\n _playerControls.Enable();\n }\n\n private void OnDisable()\n {\n _playerControls.Disable();\n }\n\n private void StartFiring()\n {\n _fireCoroutine = StartCoroutine(RapidFire());\n }\n\n private void StopFiring()\n {\n if (_fireCoroutine != null)\n {\n StopCoroutine(_fireCoroutine);\n _fireCoroutine = null;\n }\n }\n\n private void Shooting()\n {\n var bulletController = Instantiate(_bulletPrefab, _barrelTransform.position, Quaternion.identity, _bulletParent);\n\n if (Physics.Raycast(_cameraTransform.position, _cameraTransform.forward, out var hit, Mathf.Infinity))\n {\n bulletController.target = hit.point;\n bulletController.hit = true;\n\n if (hit.transform.TryGetComponent<Enemy>(out var enemy))\n {\n enemy.TakeDamage(_damage);\n }\n\n if (hit.rigidbody != null)\n {\n hit.rigidbody.AddForce(-hit.normal * _impactForce);\n }\n }\n else\n {\n bulletController.target = _cameraTransform.position + _cameraTransform.forward * _bulletHitMissDistance;\n bulletController.hit = false;\n }\n }\n\n private IEnumerator RapidFire()\n {\n while (true)\n {\n Shooting();\n yield return _rapidFireWait;\n }\n }\n\n private void Running()\n {\n IsRunning = true;\n }\n\n private void RunningStop()\n {\n IsRunning = false;\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20578845/"
] |
74,542,704
|
<p>I have a shell script inside Jenkins job where I need that only one command inside the script will run only once a year every year. Something like:</p>
<pre><code>if [today is 1st of Nov in any Year]; then
do this command....
fi
</code></pre>
<p>Is it possible?</p>
|
[
{
"answer_id": 74543024,
"author": "M B",
"author_id": 3730626,
"author_profile": "https://Stackoverflow.com/users/3730626",
"pm_score": 0,
"selected": false,
"text": "if @yearly Would last have run at Sunday, September 11, 2022 10:21:52 PM CEST; would next run at Monday, September 11, 2023 10:21:52 PM CEST.\n"
},
{
"answer_id": 74546373,
"author": "Jens",
"author_id": 648658,
"author_profile": "https://Stackoverflow.com/users/648658",
"pm_score": 1,
"selected": false,
"text": "date case $(date +%m%d) in\n (1101) run this command\nesac\n"
},
{
"answer_id": 74579734,
"author": "Ian W",
"author_id": 598141,
"author_profile": "https://Stackoverflow.com/users/598141",
"pm_score": 1,
"selected": false,
"text": "@yearly triggers {\n cron('H * 1 11 *')\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1508682/"
] |
74,542,710
|
<p>Due to <code>minikube</code> issues <a href="https://github.com/kubernetes/minikube/issues/13841" rel="nofollow noreferrer">13841</a> and <a href="https://github.com/kubernetes/minikube/issues/13872" rel="nofollow noreferrer">13872</a> (which I believe to be the same), I have to use <code>minikube</code> 1.23.2. I try using <code>minikube start --kubernetes-version v...</code> with version 1.24+ but none works (not sure why). Thus, I cannot use the convenient command <code>kubectl -n ... create token ...</code>. Seba's answer to this <a href="https://stackoverflow.com/questions/40720979/how-to-access-kubernetes-api-when-using-minkube">question</a> shows how to generate the token with this older <code>kubectl</code> version:</p>
<pre><code>$ export secret=$(kubectl get serviceaccount default -o jsonpath='{.secrets[0].name}')
$ kubectl get secret $secret -o jsonpath='{.data.token}' | base64 --decode
</code></pre>
<p>Apparently, the command is only good for service account <code>default</code>. How can I rewrite that script so it can be used for other users as follows?</p>
<pre><code>$ export my_script=....
$ my_script another_account
</code></pre>
|
[
{
"answer_id": 74543413,
"author": "tripleee",
"author_id": 874188,
"author_profile": "https://Stackoverflow.com/users/874188",
"pm_score": 2,
"selected": true,
"text": "#!/bin/sh\nsecret=$(kubectl get serviceaccount \"${1-default}\" -o jsonpath='{.secrets[0].name}')\nkubectl get secret \"$secret\" -o jsonpath='{.data.token}' | base64 --decode\n serviceaccount default ktoken chmod +x PATH ktoken\n default ktoken otheraccount\n otheraccount export"
},
{
"answer_id": 74555726,
"author": "CaTx",
"author_id": 1336427,
"author_profile": "https://Stackoverflow.com/users/1336427",
"pm_score": 0,
"selected": false,
"text": "get_token.sh #!/bin/bash\nuser_account=$1\nfunction get_token() {\n secret=$(kubectl get serviceaccount \"$1\" -o jsonpath='{.secrets[0].name}')\n kubectl get secret \"$secret\" -o jsonpath='{.data.token}' | base64 --decode\n}\n\nget_token $user_account\n $ bash get_token.sh another_account\n get_token $ function get_token() { secret=$(kubectl get serviceaccount \"$1\" -o jsonpath='{.secrets[0].name}') && kubectl get secret \"$secret\" -o jsonpath='{.data.token}' | base64 --decode; }\n$ get_token another_account\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1336427/"
] |
74,542,720
|
<p>I need to do next behavior on my webssite: until first breakpoint (for tablets) it should just scale without changing of elements positions etc. For example: Website should look similar on 1920x1280 screen and on 1600x900 screen, but on tablets and mobiles i want to use media queries for reform my elements position.</p>
<p>So question is how to allow my website to scale on laptop \ PC screens with different sizes until first breakpoint is reached.</p>
|
[
{
"answer_id": 74543413,
"author": "tripleee",
"author_id": 874188,
"author_profile": "https://Stackoverflow.com/users/874188",
"pm_score": 2,
"selected": true,
"text": "#!/bin/sh\nsecret=$(kubectl get serviceaccount \"${1-default}\" -o jsonpath='{.secrets[0].name}')\nkubectl get secret \"$secret\" -o jsonpath='{.data.token}' | base64 --decode\n serviceaccount default ktoken chmod +x PATH ktoken\n default ktoken otheraccount\n otheraccount export"
},
{
"answer_id": 74555726,
"author": "CaTx",
"author_id": 1336427,
"author_profile": "https://Stackoverflow.com/users/1336427",
"pm_score": 0,
"selected": false,
"text": "get_token.sh #!/bin/bash\nuser_account=$1\nfunction get_token() {\n secret=$(kubectl get serviceaccount \"$1\" -o jsonpath='{.secrets[0].name}')\n kubectl get secret \"$secret\" -o jsonpath='{.data.token}' | base64 --decode\n}\n\nget_token $user_account\n $ bash get_token.sh another_account\n get_token $ function get_token() { secret=$(kubectl get serviceaccount \"$1\" -o jsonpath='{.secrets[0].name}') && kubectl get secret \"$secret\" -o jsonpath='{.data.token}' | base64 --decode; }\n$ get_token another_account\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20454723/"
] |
74,542,734
|
<p>One existing example of this is <code>open</code> which can be used in these two ways:</p>
<pre class="lang-py prettyprint-override"><code>f = open("File")
print(f.readline())
f.close()
# ...and...
with open("File") as f:
print(f.readline())
</code></pre>
<p>I intend to create a version of the asyncio.Lock class which allows you to not only acquire and release the lock manually but also to use a <code>with</code> block to wrap the code that requires the lock and release it automatically.</p>
|
[
{
"answer_id": 74543413,
"author": "tripleee",
"author_id": 874188,
"author_profile": "https://Stackoverflow.com/users/874188",
"pm_score": 2,
"selected": true,
"text": "#!/bin/sh\nsecret=$(kubectl get serviceaccount \"${1-default}\" -o jsonpath='{.secrets[0].name}')\nkubectl get secret \"$secret\" -o jsonpath='{.data.token}' | base64 --decode\n serviceaccount default ktoken chmod +x PATH ktoken\n default ktoken otheraccount\n otheraccount export"
},
{
"answer_id": 74555726,
"author": "CaTx",
"author_id": 1336427,
"author_profile": "https://Stackoverflow.com/users/1336427",
"pm_score": 0,
"selected": false,
"text": "get_token.sh #!/bin/bash\nuser_account=$1\nfunction get_token() {\n secret=$(kubectl get serviceaccount \"$1\" -o jsonpath='{.secrets[0].name}')\n kubectl get secret \"$secret\" -o jsonpath='{.data.token}' | base64 --decode\n}\n\nget_token $user_account\n $ bash get_token.sh another_account\n get_token $ function get_token() { secret=$(kubectl get serviceaccount \"$1\" -o jsonpath='{.secrets[0].name}') && kubectl get secret \"$secret\" -o jsonpath='{.data.token}' | base64 --decode; }\n$ get_token another_account\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10251041/"
] |
74,542,755
|
<p>Getting a NullPointerException Error when trying to run my app, I will link code and Logcat error below, help would be greatly appreciated.</p>
<p>In my XML class with the DrawerLayout I have the ID for the drawer set to drawer_layout (renamed using android:id).</p>
<p><strong>Logcat Error</strong></p>
<pre><code>2022-11-23 01:35:49.526 4976-4976/com.example.appdev2finalproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.appdev2finalproject, PID: 4976
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.appdev2finalproject/com.example.appdev2finalproject.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.drawerlayout.widget.DrawerLayout.addDrawerListener(androidx.drawerlayout.widget.DrawerLayout$DrawerListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.drawerlayout.widget.DrawerLayout.addDrawerListener(androidx.drawerlayout.widget.DrawerLayout$DrawerListener)' on a null object reference
at com.example.appdev2finalproject.MainActivity.onCreate(MainActivity.java:21)
at android.app.Activity.performCreate(Activity.java:7994)
at android.app.Activity.performCreate(Activity.java:7978)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
</code></pre>
<p><strong>Code From Main</strong></p>
<pre><code>package com.example.appdev2finalproject;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.nav_open,
R.string.nav_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
</code></pre>
<p><strong>Edit: Adding Activity Main Code</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/drawer_layout"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/navigation_menu"/>
</androidx.drawerlayout.widget.DrawerLayout>
</code></pre>
|
[
{
"answer_id": 74543413,
"author": "tripleee",
"author_id": 874188,
"author_profile": "https://Stackoverflow.com/users/874188",
"pm_score": 2,
"selected": true,
"text": "#!/bin/sh\nsecret=$(kubectl get serviceaccount \"${1-default}\" -o jsonpath='{.secrets[0].name}')\nkubectl get secret \"$secret\" -o jsonpath='{.data.token}' | base64 --decode\n serviceaccount default ktoken chmod +x PATH ktoken\n default ktoken otheraccount\n otheraccount export"
},
{
"answer_id": 74555726,
"author": "CaTx",
"author_id": 1336427,
"author_profile": "https://Stackoverflow.com/users/1336427",
"pm_score": 0,
"selected": false,
"text": "get_token.sh #!/bin/bash\nuser_account=$1\nfunction get_token() {\n secret=$(kubectl get serviceaccount \"$1\" -o jsonpath='{.secrets[0].name}')\n kubectl get secret \"$secret\" -o jsonpath='{.data.token}' | base64 --decode\n}\n\nget_token $user_account\n $ bash get_token.sh another_account\n get_token $ function get_token() { secret=$(kubectl get serviceaccount \"$1\" -o jsonpath='{.secrets[0].name}') && kubectl get secret \"$secret\" -o jsonpath='{.data.token}' | base64 --decode; }\n$ get_token another_account\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17698173/"
] |
74,542,761
|
<p>I have setup a ToastContainer in my main App.js</p>
<pre><code>return (
<div className='wrapper' style={{height: '100%'}}>
<ToastContainer
limit={1}
containerId={'error'}
position='bottom-left'
autoClose={5000}
hideProgressBar={false}
newestOnTop={false}
closeOnClick
rtl={false}
pauseOnFocusLoss={false}
draggable
pauseOnHover
theme='light'/>
<BrowserRouter>
<Switch>
<Route exact path='/' component={() => (renderComponent(view.type))} />
</Switch>
</BrowserRouter>
</div>
</code></pre>
<p>And I have an errorHandler function as well</p>
<pre><code>const errorHandler = () => {
toast.error(<ErrorToast
errorUUID={localStorage.getItem('errorUUID')}/>, {containerId: 'error', toastId: 'error'});
}
</code></pre>
<p>I have about 1000+ components in my application and almost all of them have a renderData async function that does component-specific fetch calls.</p>
<p>What I want to do, is use this error handler function as the primary error function that is used to handle all async fetch calls that are made in all these different classes.</p>
<p><strong>My options as I see them: -</strong></p>
<p><strong>1) Create a ToastContainer for every component that needs it -</strong></p>
<p><strong>Problem -</strong></p>
<p>a) messy code</p>
<p>b) changing the errorHandler from ToastContainer to something else in the future would be a big pain</p>
<p>c) one page could have multiple error toasts that show up in a situation where the fetch call is from the same backend service in separate containers.</p>
<p><strong>2) Pass the errorHandler as a prop to all children, and do a callback</strong></p>
<p><strong>Problem -</strong></p>
<p>a) messy code</p>
<p>b) Ensuring that I pass this errorHandler to every component wherever it is used is bound to fail at some point</p>
<p>c) Will have to maintain this practice of passing errorHandler to all future components</p>
<p><strong>What I want to know is -</strong></p>
<p>Am I doomed to use one of these two methods, or is there a method that I have not yet considered? And if so, what is it, and what are the pros/cons of it?</p>
|
[
{
"answer_id": 74543413,
"author": "tripleee",
"author_id": 874188,
"author_profile": "https://Stackoverflow.com/users/874188",
"pm_score": 2,
"selected": true,
"text": "#!/bin/sh\nsecret=$(kubectl get serviceaccount \"${1-default}\" -o jsonpath='{.secrets[0].name}')\nkubectl get secret \"$secret\" -o jsonpath='{.data.token}' | base64 --decode\n serviceaccount default ktoken chmod +x PATH ktoken\n default ktoken otheraccount\n otheraccount export"
},
{
"answer_id": 74555726,
"author": "CaTx",
"author_id": 1336427,
"author_profile": "https://Stackoverflow.com/users/1336427",
"pm_score": 0,
"selected": false,
"text": "get_token.sh #!/bin/bash\nuser_account=$1\nfunction get_token() {\n secret=$(kubectl get serviceaccount \"$1\" -o jsonpath='{.secrets[0].name}')\n kubectl get secret \"$secret\" -o jsonpath='{.data.token}' | base64 --decode\n}\n\nget_token $user_account\n $ bash get_token.sh another_account\n get_token $ function get_token() { secret=$(kubectl get serviceaccount \"$1\" -o jsonpath='{.secrets[0].name}') && kubectl get secret \"$secret\" -o jsonpath='{.data.token}' | base64 --decode; }\n$ get_token another_account\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7215355/"
] |
74,542,762
|
<p>I want to apply a filter to every 5th column in a file by using <code>awk</code> and print the entire line if all conditions are met on the specified columns. How can I shorten this code?</p>
<pre><code>awk -F "\t" '{if ($5>=10 && $10>=10 && $15>=10 && $20>=10 && $25>=10 && $30>=10 && $35>=10 && $40>=10 && $45>=10 && $50>=10 && $55>=10 && $60>=10 && $65>=10 && $70>=10 && $75>=10 && $80>=10 && $85>=10 && $90>=10 && $95>=10 && $100>=10 && $105>=10 && $110>=10 && $115>=10 && $120>=10 && $125>=10 && $130>=10 && $135>=10 && $140>=10 && $145>=10 && $150>=10 && $155>=10 && $160>=10 && $165>=10 && $170>=10 && $175>=10 && $180>=10 && $185>=10 && $190>=10 && $195>=10 && $200>=10 && $205>=10 && $210>=10 && $215>=10 && $220>=10 && $225>=10 && $230>=10 && $235>=10 && $240>=10 && $245>=10 && $250>=10 && $255>=10 && $260>=10 && $265>=10 && $270>=10 && $275>=10 && $280>=10 && $285>=10 && $290>=10 && $295>=10 && $300>=10 && $305>=10 && $310>=10 && $315>=10 && $320>=10 && $325>=10 && $330>=10 && $335>=10 && $340>=10 && $345>=10 && $350>=10 && $355>=10 && $360>=10 && $365>=10 && $370>=10 && $375>=10 && $380>=10 && $385>=10 && $390>=10) print}' file
</code></pre>
|
[
{
"answer_id": 74542928,
"author": "WeDBA",
"author_id": 8514862,
"author_profile": "https://Stackoverflow.com/users/8514862",
"pm_score": 0,
"selected": false,
"text": "awk '{a=1; for (i =1 ; i<= NF ; ++i) if ( i%5==0 ) a=a&&$i>10; if (a) print file\n"
},
{
"answer_id": 74542966,
"author": "blhsing",
"author_id": 6890912,
"author_profile": "https://Stackoverflow.com/users/6890912",
"pm_score": 1,
"selected": false,
"text": "for awk -F \"\\t\" '{for(i=5;i<=NF;i+=5)if($i<10)next;print}' file\n"
},
{
"answer_id": 74546343,
"author": "Dave Pritlove",
"author_id": 2005666,
"author_profile": "https://Stackoverflow.com/users/2005666",
"pm_score": 1,
"selected": false,
"text": "fail break awk '{for(i=5;i<=NF;i+=5)if($i<10){fail=\"fail\";break;} if (fail != \"fail\") print }' file.txt\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4564320/"
] |
74,542,772
|
<pre><code> void deletenode(string key) {
if (last == NULL) {
cout << "your circular linked list is an empty one" << endl;
}
else {
node* p = last->next;
node* prev = last;
do {
if (p->title == key) {
node* temp = p;
prev->next = p->next;
delete(temp);
}
else {
p = p->next;
prev = prev->next;
}
} while (p != last->next);
}}
</code></pre>
<p>I was trying to delete a node with key value. For instance, if node <code>p->title</code> is my key then I want to delete that node. However, I implemented it with other values but the code doesn't seem to work or delete a node with key value from my circular linked list. What is the mistake in the function?</p>
<p>circular linked list value <code>"cat", "dog", "rat", "horse"</code>, the key to be deleted was <code>"dog"</code>. When I traverse throughout the linked list after the deletion it still printed everything including <code>"dog"</code>, which means deletion didn't work.</p>
|
[
{
"answer_id": 74542963,
"author": "brmRush",
"author_id": 9483598,
"author_profile": "https://Stackoverflow.com/users/9483598",
"pm_score": 0,
"selected": false,
"text": "void deleteNodeWithKey(node* head, string key)\n{\n node *curr = head;\n node *last , *temp;\n //Search for last node\n while (curr->next != head)\n {\n curr = curr->next;\n }\n last = curr;\n\n //If head is the desired key, make head's next new head\n //and connect last node to new head\n if (head->key == key) \n {\n temp = head->next;\n delete head;\n head = temp;\n last->next = head;\n return;\n }\n\n temp = head->next;\n //Search for node with the given key\n node *prev = head;\n while (temp != head)\n {\n if (temp->key == key)\n {\n prev->next = temp->next;\n delete temp;\n return;\n }\n temp = temp->next;\n prev = prev->next;\n }\n //If function gets here, key was not found\n\n}\n"
},
{
"answer_id": 74543070,
"author": "selbie",
"author_id": 104458,
"author_profile": "https://Stackoverflow.com/users/104458",
"pm_score": 1,
"selected": false,
"text": "Node* deletenode(Node* head, const string& key) {\n\n // empty list\n if (head == nullptr) {\n return nullptr;\n }\n \n // single item list\n if (head->next == nullptr || head->next == head) {\n if (head->title == key) {\n delete head;\n head = nullptr;\n }\n return head;\n }\n \n // two or more item list, possibly circular\n Node* prev = head;\n Node* current = head->next;\n Node* first = current;\n while (current && current->title != key) {\n prev = current;\n current = current->next;\n if (current == first) {\n break;\n }\n }\n \n if (current == nullptr || current->title != key) {\n return head; // not found\n }\n\n prev->next = current->next;\n if (current == head) {\n head = current->next;\n }\n delete current;\n return head;\n}\n"
},
{
"answer_id": 74543150,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "void deletenode(string key) {\n if (last == NULL) {\n cout << \"your circular linked list is an empty one\" << endl;\n }\n else {\n node* prev = last;\n // If head is to be deleted\n if (last->title == key) {\n while (prev->next != last)\n prev = (prev)->next;\n prev->next = last->next;\n free(last);\n last = prev->next;\n return;\n }\n\n node* p = last->next;\n\n do {\n if (p->next->title == key) {\n node* temp = p->next;\n p->next = temp->next;\n delete(temp);\n }\n else {\n p = p->next;\n prev = prev->next;\n }\n } while (p != last->next);\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20550190/"
] |
74,542,802
|
<p>I've written a code about a program where a word gets encrypted as a number dependent on a fixed parameter such as "Software" turning into 76389273. However the for loop is not returning different values for every letter, and returns the same value (value of the first letter) for all letters.</p>
<pre><code>import java.util.Scanner;
public class StringtoNumber {
public static int getNumber(String word) {
int value = 0;
int intArray[] = new int[word.length()];
for (int i = 0; i < word.length(); i++) {
switch (word.charAt(i)) {
case 'A':
case 'B':
case 'C':
case 'a':
case 'b':
case 'c':
value = 2;
break;
case 'D':
case 'E':
case 'F':
case 'd':
case 'e':
case 'f':
value = 3;
break;
case 'G':
case 'H':
case 'I':
case 'g':
case 'h':
case 'i':
value = 4;
break;
case 'J':
case 'K':
case 'L':
case 'j':
case 'k':
case 'l':
value = 5;
break;
case 'M':
case 'N':
case 'O':
case 'm':
case 'n':
case 'o':
value = 6;
break;
case 'P':
case 'Q':
case 'R':
case 'S':
case 'p':
case 'q':
case 'r':
case 's':
value = 7;
break;
case 'T':
case 'U':
case 'V':
case 't':
case 'u':
case 'v':
value = 8;
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
case 'w':
case 'x':
case 'y':
case 'z':
value = 9;
break;
}
intArray[i] = value;
return intArray[i];
}
int result = 0;
for (int i = 0; i < intArray.length; i++) {
result += Math.pow(10, i) * intArray[intArray.length - i - 1];
}
return result;
}
public static void main (String[]arg){
Scanner input = new Scanner(System.in);
System.out.println("what word do you want to encrypt");
String word = input.nextLine();
int counter = 0;
while (counter < word.length()) {
System.out.print(getNumber(word));
counter++;
}
}
}
</code></pre>
<p>I've tried finding mistake but I haven't seen anything, is there something I am not taking into account?</p>
|
[
{
"answer_id": 74542963,
"author": "brmRush",
"author_id": 9483598,
"author_profile": "https://Stackoverflow.com/users/9483598",
"pm_score": 0,
"selected": false,
"text": "void deleteNodeWithKey(node* head, string key)\n{\n node *curr = head;\n node *last , *temp;\n //Search for last node\n while (curr->next != head)\n {\n curr = curr->next;\n }\n last = curr;\n\n //If head is the desired key, make head's next new head\n //and connect last node to new head\n if (head->key == key) \n {\n temp = head->next;\n delete head;\n head = temp;\n last->next = head;\n return;\n }\n\n temp = head->next;\n //Search for node with the given key\n node *prev = head;\n while (temp != head)\n {\n if (temp->key == key)\n {\n prev->next = temp->next;\n delete temp;\n return;\n }\n temp = temp->next;\n prev = prev->next;\n }\n //If function gets here, key was not found\n\n}\n"
},
{
"answer_id": 74543070,
"author": "selbie",
"author_id": 104458,
"author_profile": "https://Stackoverflow.com/users/104458",
"pm_score": 1,
"selected": false,
"text": "Node* deletenode(Node* head, const string& key) {\n\n // empty list\n if (head == nullptr) {\n return nullptr;\n }\n \n // single item list\n if (head->next == nullptr || head->next == head) {\n if (head->title == key) {\n delete head;\n head = nullptr;\n }\n return head;\n }\n \n // two or more item list, possibly circular\n Node* prev = head;\n Node* current = head->next;\n Node* first = current;\n while (current && current->title != key) {\n prev = current;\n current = current->next;\n if (current == first) {\n break;\n }\n }\n \n if (current == nullptr || current->title != key) {\n return head; // not found\n }\n\n prev->next = current->next;\n if (current == head) {\n head = current->next;\n }\n delete current;\n return head;\n}\n"
},
{
"answer_id": 74543150,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "void deletenode(string key) {\n if (last == NULL) {\n cout << \"your circular linked list is an empty one\" << endl;\n }\n else {\n node* prev = last;\n // If head is to be deleted\n if (last->title == key) {\n while (prev->next != last)\n prev = (prev)->next;\n prev->next = last->next;\n free(last);\n last = prev->next;\n return;\n }\n\n node* p = last->next;\n\n do {\n if (p->next->title == key) {\n node* temp = p->next;\n p->next = temp->next;\n delete(temp);\n }\n else {\n p = p->next;\n prev = prev->next;\n }\n } while (p != last->next);\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17650958/"
] |
74,542,872
|
<p>It seems that it is impossible to use <code>typedef</code> and incorporate a malloc function in my program: More specifically:</p>
<p>groups.h</p>
<pre><code>#include "headers.h"
#include "info.h"
#include "sub_list.h"
typedef struct group_entity *group;
group new_group(int id);
void free_group(group group);
</code></pre>
<p>groups.c</p>
<pre><code>#include "groups.h"
struct group_entity {
int gId;
info gFirst;
info gLast;
subinfo gSub;
};
group new_group(int id) {
group new_group = malloc(sizeof(group));
if (!new_group) {
return NULL;
}
new_group->gId = id;
new_group->gFirst = NULL;
new_group->gLast = NULL;
new_group->gSub = NULL;
return new_group;
}
void free_group(group group) {
free(group);
}
</code></pre>
<p>header.h</p>
<pre><code>#pragma once
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#define MG 5 /* Length of Groups Array. */
</code></pre>
<p>main.c</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stddef.h>
#include "headers.h"
#include "groups.h"
#include "info.h"
#include "sub_list.h"
int main() {
group new_object = new_group(5);
return 0;
}
</code></pre>
<p>Whenever I run this piece of code, I get halted with a breakpoint</p>
<p>exe_common.inl - ln 297.</p>
<pre><code> if (!has_cctor)
_cexit();
</code></pre>
<p>I've tried using a <code>free_group(group group)</code> function in my main.c - but it seems that I hit a breakpoint.
By using the VS 2019 debugger, I tried to find out which line causes the error. It seems that the breakpoint is caused AFTER my main is executed.
Quite curious behavior, since main won't even <code>return 0</code>.</p>
|
[
{
"answer_id": 74542951,
"author": "KamilCuk",
"author_id": 9072753,
"author_profile": "https://Stackoverflow.com/users/9072753",
"pm_score": 3,
"selected": false,
"text": "sizeof(group) * typedef struct group_entity group;\ngroup *new_group(int id);\nvoid free_group(group *group);\n\ngroup *new_group(int id) {\n group *new_group = malloc(sizeof(group));\n sizeof(*new_group) sizeof(struct group_entity)"
},
{
"answer_id": 74568551,
"author": "GGLinnk",
"author_id": 12876357,
"author_profile": "https://Stackoverflow.com/users/12876357",
"pm_score": 0,
"selected": false,
"text": "define groups.h * typedef struct group_entity group;\n#define *group GROUP_PTR\nGROUP_PTR new_group(int id);\n groups.c GROUP_PTR new_group(int id) {\n GROUP_PTR new_group = malloc(sizeof(group));\n [...]\n return new_group;\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18750577/"
] |
74,542,873
|
<p>I am calling one Microsoft graph API from my PHP application, API is <strong><a href="https://graph.microsoft.com/beta/policies/identitySecurityDefaultsEnforcementPolicy" rel="nofollow noreferrer">https://graph.microsoft.com/beta/policies/identitySecurityDefaultsEnforcementPolicy</a></strong></p>
<p>my code is like below</p>
<pre><code>$graph = new Graph();
$graph->setAccessToken(session('my_token'));
try{
$response = $graph->createRequest("GET", "/policies/identitySecurityDefaultsEnforcementPolicy")->execute();
}
catch(Exception $e){
dd($e);
}
$arr = $response->getBody();
dd($arr);
</code></pre>
<p>but it always catches exception and displays the below error</p>
<pre><code>Client error: `GET https://graph.microsoft.com/v1.0/policies/identitySecurityDefaultsEnforcementPolicy` resulted in a `403 Forbidden` response:
{"error":{"code":"AccessDenied","message":"You cannot perform the requested operation, required scopes are missing in the token.","innerError":{"date":"2022-11-23T06:47:39","request-id":"9a4573c7-fd72-44ae-8ac6-8e4589cf1497","client-request-id":"9a4573c7-fd72-44ae-8ac6-8e4589cf1497"}}}
</code></pre>
<p>all the other Microsoft graph APIs are working well</p>
<p>I have also given permission to <strong>Policy.Read.All</strong> and granted admin consent to the Microsoft app I am using here for auth.</p>
<p>Update: when I open Microsoft's online token parser <a href="https://jwt.ms/" rel="nofollow noreferrer">https://jwt.ms/</a> and parsed my token, I see the roles like</p>
<pre><code>"roles": [
"Mail.ReadWrite",
"User.ReadWrite.All",
"SecurityEvents.Read.All",
"Mail.ReadBasic.All",
"Group.Read.All",
"MailboxSettings.Read",
"Group.ReadWrite.All",
"SecurityEvents.ReadWrite.All",
"User.Invite.All",
"Directory.Read.All",
"User.Read.All",
"Domain.Read.All",
"GroupMember.Read.All",
"Mail.Read",
"User.Export.All",
"IdentityRiskyUser.Read.All",
"Mail.Send",
"User.ManageIdentities.All",
"MailboxSettings.ReadWrite",
"Organization.Read.All",
"GroupMember.ReadWrite.All",
"IdentityRiskEvent.Read.All",
"Mail.ReadBasic",
"Reports.Read.All"
]
</code></pre>
<p>but not the <strong>Policy.Read.All</strong></p>
<p>Update: Getting auth token code is</p>
<pre><code>$guzzle = new \GuzzleHttp\Client();
$url = 'https://login.microsoftonline.com/'.env("TANANT_ID").'/oauth2/token?api-version=beta';
$token = json_decode($guzzle->post($url, [
'form_params' => [
'client_id' => env("CLIENT_ID"),
'client_secret' => env("CLIENT_SECRET"),
'resource' => 'https://graph.microsoft.com/',
'grant_type' => 'client_credentials',
],
])->getBody()->getContents());
// echo $token->access_token;
Session::put('my_token', $token->access_token);
</code></pre>
|
[
{
"answer_id": 74627992,
"author": "Barkermn01",
"author_id": 493804,
"author_profile": "https://Stackoverflow.com/users/493804",
"pm_score": 1,
"selected": false,
"text": "$guzzle = new \\GuzzleHttp\\Client();\n$url = 'https://login.microsoftonline.com/'.env(\"TANANT_ID\").'/oauth2/token?api-version=beta';\n$token = json_decode($guzzle->post($url, [\n 'form_params' => [\n 'client_id' => env(\"CLIENT_ID\"),\n 'client_secret' => env(\"CLIENT_SECRET\"),\n 'resource' => 'https://graph.microsoft.com/',\n 'scope' => 'https://graph.microsoft.com/.default',\n 'grant_type' => 'client_credentials',\n ],\n])->getBody()->getContents());\n// echo $token->access_token;\nSession::put('my_token', $token->access_token);\n 'scope' => 'https://graph.microsoft.com/.default',"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4710899/"
] |
74,542,884
|
<p>I want to get current select value without modeling on data.
in other words , I want get this select value in second method argument.
pay attention that this select placed in a v-for loop
how can i do this?</p>
<pre><code><select v-if="user.client_groups.length > 0" class="small"
@change="clientGroupChanged(user.id,???)">
<option v-for="group in groups" :key="group.id" :value="group.id"
:selected="user.client_groups[0].id">{{ group.title }}</option>
</select>
</code></pre>
<p>and my clientGroupChanged method body is :</p>
<pre><code>clientGroupChanged: function(uid,value){
alert(value);
},
</code></pre>
|
[
{
"answer_id": 74627992,
"author": "Barkermn01",
"author_id": 493804,
"author_profile": "https://Stackoverflow.com/users/493804",
"pm_score": 1,
"selected": false,
"text": "$guzzle = new \\GuzzleHttp\\Client();\n$url = 'https://login.microsoftonline.com/'.env(\"TANANT_ID\").'/oauth2/token?api-version=beta';\n$token = json_decode($guzzle->post($url, [\n 'form_params' => [\n 'client_id' => env(\"CLIENT_ID\"),\n 'client_secret' => env(\"CLIENT_SECRET\"),\n 'resource' => 'https://graph.microsoft.com/',\n 'scope' => 'https://graph.microsoft.com/.default',\n 'grant_type' => 'client_credentials',\n ],\n])->getBody()->getContents());\n// echo $token->access_token;\nSession::put('my_token', $token->access_token);\n 'scope' => 'https://graph.microsoft.com/.default',"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8327515/"
] |
74,542,896
|
<p>I've a csv file which i'm reading as a dict using Ansible <code>read_csv</code></p>
<pre><code>id,name,quantity,type
1,apple,10,fruit
2,orange,20,fruit
3,carrot,5,veg
4,beetroot,2,veg
5,onion,3,veg
6,tomato,4,both
7,pear,4,fruit
8,banana,6,fruit
9,persimon,4,fruit
10,guava,4,fruit
11,pepper,4,veg
12,potato,5,veg
13,cherry,5,fruit
</code></pre>
<p>The equivalent dict becomes</p>
<pre><code>"{'1': {'id': '1', 'name': 'apple', 'quantity': '10', 'type': 'fruit'}, '2': {'id': '2', 'name': 'orange', 'quantity': '20', 'type': 'fruit'}, '3': {'id': '3', 'name': 'carrot', 'quantity': '5', 'type': 'veg'}, '4': {'id': '4', 'name': 'beetroot', 'quantity': '2', 'type': 'veg'}, '5': {'id': '5', 'name': 'onion', 'quantity': '3', 'type': 'veg'}, '6': {'id': '6', 'name': 'tomato', 'quantity': '4', 'type': 'both'}, '7': {'id': '7', 'name': 'pear', 'quantity': '4', 'type': 'fruit'}, '8': {'id': '8', 'name': 'banana', 'quantity': '6', 'type': 'fruit'}, '9': {'id': '9', 'name': 'persimon', 'quantity': '4', 'type': 'fruit'}, '10': {'id': '10', 'name': 'guava', 'quantity': '4', 'type': 'fruit'}, '11': {'id': '11', 'name': 'pepper', 'quantity': '4', 'type': 'veg'}, '12': {'id': '12', 'name': 'potato', 'quantity': '5', 'type': 'veg'}, '13': {'id': '13', 'name': 'cherry', 'quantity': '5', 'type': 'fruit'}}"
</code></pre>
<p>My logic was to split the list into batches of 2 name per type at a time
So output I was looking for is <code>["carrot", "beetroot"], ["onion", "pepper"]</code> and so on</p>
<p>The below logic works perfectly when i hardcode the <code>[0:2]</code> range in the jinja expression</p>
<pre><code>{% set my_fruit_list = [] %}
{%- for item in (fruits_dict.dict| dict2items | selectattr("value.type", "match", "^veg$"))[0:2] -%}
{{ my_fruit_list.append(item.value.name) }}
{%- endfor -%}
my_list=["{{ my_fruit_list|join('", "') }}"]
</code></pre>
<p>But when i try changing it to a dynamic variable, it doesn't work. I tried below</p>
<pre><code>{% set input_range = "[0:2]" %}
{%- for item in (fruits_dict.dict| dict2items | selectattr("value.type", "match", "^veg$"))input_range -%}
</code></pre>
<p>Is there any way we can pass the "input_range" as a dynamic parameter into the expression?</p>
<p>Also is there a better way of getting the <code>selectattr</code> without converting the csv to <code>dict</code> and <code>dict2items</code> ?</p>
|
[
{
"answer_id": 74627992,
"author": "Barkermn01",
"author_id": 493804,
"author_profile": "https://Stackoverflow.com/users/493804",
"pm_score": 1,
"selected": false,
"text": "$guzzle = new \\GuzzleHttp\\Client();\n$url = 'https://login.microsoftonline.com/'.env(\"TANANT_ID\").'/oauth2/token?api-version=beta';\n$token = json_decode($guzzle->post($url, [\n 'form_params' => [\n 'client_id' => env(\"CLIENT_ID\"),\n 'client_secret' => env(\"CLIENT_SECRET\"),\n 'resource' => 'https://graph.microsoft.com/',\n 'scope' => 'https://graph.microsoft.com/.default',\n 'grant_type' => 'client_credentials',\n ],\n])->getBody()->getContents());\n// echo $token->access_token;\nSession::put('my_token', $token->access_token);\n 'scope' => 'https://graph.microsoft.com/.default',"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1221358/"
] |
74,542,903
|
<p>I want to find all the hidden files inside a directory in linux terminal.</p>
<p>I have found out that we have a grep command to search for the file but I need to search for hidden files.</p>
<p><code>grep -r search *</code></p>
<p>Any help would be appreciated. Thanks.</p>
|
[
{
"answer_id": 74542995,
"author": "Dan Bonachea",
"author_id": 3528321,
"author_profile": "https://Stackoverflow.com/users/3528321",
"pm_score": 1,
"selected": false,
"text": ". . find . -print | grep '/\\.'\n"
},
{
"answer_id": 74545137,
"author": "Pasha Abdul Khalid",
"author_id": 11774456,
"author_profile": "https://Stackoverflow.com/users/11774456",
"pm_score": 1,
"selected": false,
"text": "find / -name \".*\" 2> /dev/null\n"
},
{
"answer_id": 74550295,
"author": "M. Nejat Aydin",
"author_id": 13809001,
"author_profile": "https://Stackoverflow.com/users/13809001",
"pm_score": 0,
"selected": false,
"text": "grep -r search .\n"
},
{
"answer_id": 74550602,
"author": "Gilles Quenot",
"author_id": 465183,
"author_profile": "https://Stackoverflow.com/users/465183",
"pm_score": 0,
"selected": false,
"text": "find /dir -name '.*' -type f\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6682406/"
] |
74,542,915
|
<p>I want to count the number of "domains" for which "adminLock" is equal to 1.</p>
<p>This is my json data structure:</p>
<pre><code>{
"code": 0,
"message": "成功",
"data": {
"recordCount": "128",
"pageSize": 100,
"page": 1,
"pageCount": 2,
"data": [
{
"domainsID": "173652434",
"nsGroupID": "199",
"groupID": "78987",
"domains": "dome1.com",
"state": 3,
"userLock": 0,
"adminLock": 0,
"view_type": "1"
},
{
"domainsID": "173205836",
"nsGroupID": "199",
"groupID": "78987",
"domains": "dome2.com",
"state": 3,
"userLock": 0,
"adminLock": 1,
"view_type": "1"
},
{
"domainsID": "173205812",
"nsGroupID": "199",
"groupID": "78987",
"domains": "dome3.com",
"state": 3,
"userLock": 0,
"adminLock": 0,
"view_type": "1"
},
{
"domainsID": "173203610",
"nsGroupID": "199",
"groupID": "78987",
"domains": "dome4.com",
"state": 3,
"userLock": 0,
"adminLock": 1,
"view_type": "1"
},
{
"domainsID": "173203210",
"nsGroupID": "199",
"groupID": "78987",
"domains": "dome5.com",
"state": 3,
"userLock": 0,
"adminLock": 1,
"view_type": "1"
},
{
"domainsID": "173203131",
"nsGroupID": "199",
"groupID": "78987",
"domains": "dome6.com",
"state": 3,
"userLock": 0,
"adminLock": 1,
"view_type": "1"
},
{
"domainsID": "173203074",
"nsGroupID": "199",
"groupID": "78987",
"domains": "dome7.com",
"state": 3,
"userLock": 0,
"adminLock": 1,
"view_type": "1"
}
],
"nextPage": 2
}
}
</code></pre>
<p>Here's what I have so far:</p>
<pre><code>'.data.data[] | select(.adminLock == 1) | .domains'
</code></pre>
<p>I can get the value of .domains, but how can I count how many times it occurs?</p>
<h1>Replenish</h1>
<p>The script I am using is the bash shell
This command gets the value, I want to count the domains value in the case of adminLock=1, and count the number of domains
————————
Judging that adminLock=1 is getting the domains value, and counting how many in total</p>
|
[
{
"answer_id": 74542973,
"author": "pmf",
"author_id": 2158479,
"author_profile": "https://Stackoverflow.com/users/2158479",
"pm_score": 1,
"selected": false,
"text": "length .data.data | map(select(.adminLock == 1)) | length\n 5\n reduce reduce (.data.data[] | select(.adminLock == 1)) as $i (0; .+1)\n 5\n .domains group_by .data.data | map(select(.adminLock == 1)) | group_by(.domains)\n| map(\"\\(first.domains): \\(length)\") # create your desired format\n [\n \"dome2.com: 1\",\n \"dome4.com: 1\",\n \"dome5.com: 1\",\n \"dome6.com: 1\",\n \"dome7.com: 1\"\n]\n reduce (.data.data[] | select(.adminLock == 1)) as $i (\n {}; .[$i.domains] += 1 # create your desired format\n)\n {\n \"dome2.com\": 1,\n \"dome4.com\": 1,\n \"dome5.com\": 1,\n \"dome6.com\": 1,\n \"dome7.com\": 1\n}\n"
},
{
"answer_id": 74542986,
"author": "peak",
"author_id": 997358,
"author_profile": "https://Stackoverflow.com/users/997358",
"pm_score": 0,
"selected": false,
"text": "def count(s): reduce s as $x (0;.+1);\n count(.data.data[] | select(.adminLock == 1))\n domains count(.data.data[] | select(.adminLock == 1 and has(\"domains\") ))\n unique [.data.data[] | select(.adminLock == 1) | .domains] | unique | length\n unique unique/0"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20438305/"
] |
74,542,916
|
<p>I have created MERN application a little bit ago and deployed it on local server with pm2 package and run API and React App as separate services. As I wanted to dockerize everything, I created <code>Dockerfile</code> in React App and in API and then created <code>docker-compose.yaml</code>:</p>
<pre><code>version: "3.9"
services:
mongo:
image: mongo:latest
ports:
- 27017:27017
volumes:
- ./mongo-db:/var/lib/mongo/data
networks:
- project-network
api:
container_name: project_api
restart: unless-stopped
image: project_api:1.0.0
build:
context: back-end
dockerfile: Dockerfile
ports:
- 4001:4001
networks:
- project-network
depends_on:
- mongo
client:
container_name: project_client
restart: unless-stopped
image: project_client:1.0.0
build:
context: front-end
dockerfile: Dockerfile
ports:
- 3000:3000
networks:
- project-network
depends_on:
- api
networks:
project-network:
</code></pre>
<p>Everything works perfectly OK and there are no errors in execution of this. The problem is that I already have in my local mongodb too many collected data that of course are not presented in the dockerized application (as mongodb is running its own container service). How I can have my data in the application? I see 3 options:</p>
<ol>
<li>Somehow copy the data inside the container</li>
<li>Run the mongodb service outside of the composed image</li>
<li>Manually to re-enter all data (it is very big so for me it is not very good option)</li>
</ol>
<p>For every option there are some questions. If the best option is 1. how I can save the data in container? Also am I going to loose all the data when I re-create some part of the application and use docker compose build again?</p>
<p>If option is 2., how I can access local mongodb inside containers(mongodb://localhost:27017/db_name)? Probably with shared network?</p>
<p>I would appreciate any kind of best advices how should proceed in this situation when I decided to dockerize application some time after it is already in use and have already collected big amount of data.</p>
|
[
{
"answer_id": 74571141,
"author": "sai reddy",
"author_id": 18832149,
"author_profile": "https://Stackoverflow.com/users/18832149",
"pm_score": 0,
"selected": false,
"text": "mongodump --db database_name --collection collection_name docker cp dump_files_path container_id:/tmp/. docker exec -it container_id bash mongorestore --db database_name /tmp/dumped_files"
},
{
"answer_id": 74649726,
"author": "Aurast",
"author_id": 3298338,
"author_profile": "https://Stackoverflow.com/users/3298338",
"pm_score": 0,
"selected": false,
"text": "mongodump /data/db ./mongo-db - ./mongo-db:/data/db"
},
{
"answer_id": 74653112,
"author": "Sahaj Raj Malla",
"author_id": 11773575,
"author_profile": "https://Stackoverflow.com/users/11773575",
"pm_score": 1,
"selected": false,
"text": "version: \"3.9\"\n\nservices:\n mongo:\n image: mongo:latest\n ports:\n - 27017:27017\n volumes:\n - mongo-db:/var/lib/mongo/data\n networks:\n - project-network\n api:\n container_name: project_api\n restart: unless-stopped\n image: project_api:1.0.0\n build:\n context: back-end\n dockerfile: Dockerfile\n ports:\n - 4001:4001\n networks:\n - project-network\n depends_on:\n - mongo\n client:\n container_name: project_client\n restart: unless-stopped\n image: project_client:1.0.0\n build:\n context: front-end\n dockerfile: Dockerfile\n ports:\n - 3000:3000\n networks:\n - project-network\n depends_on:\n - api\n\nnetworks:\n project-network:\n\nvolumes:\n mongo-db:\n $ docker volume create mongo-db $ mongoimport --host localhost --db db_name --collection collection_name --file data.json"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12879474/"
] |
74,542,939
|
<p>I am trying to call an external Rest API endpoints in my Spring Boot application. I have an API key that I generated before using it in my rest application. Whenever I am trying to hit GET request, showing me <strong>missing API Key 403 forbidden error</strong>.</p>
<pre><code>org.springframework.web.client.HttpClientErrorException$Forbidden: 403 Forbidden: "{"error":"Missing API key"}"
at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:109)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:168)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:122)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:819)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:777)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:711)
at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:361)
at com.rakhi.restapidemo.controller.CloudHealthAccessController.getCloudHealthReports(CloudHealthAccessController.java:43)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1071)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:964)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:670)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:779)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:750)
</code></pre>
<p>I tried writing this code to get desired output. Unfortunately not able to do so.</p>
<pre><code>@RequestMapping(value = {"/reports"}, method = {RequestMethod.GET, RequestMethod.POST}, produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<Object> getCloudHealthReports(){
logger.info("Inside get cloud health reporting function..!!!!");
try {
String apiKey = "abc-xyz-example-apikey-e215d82537ba";
final String uri = "https://chapi.cloudhealthtech.com/olap_reports";
RestTemplate restTemplate = new RestTemplate();
URL url = new URL(uri);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestProperty("Accept", "application/json");
http.setRequestProperty(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", apiKey));
ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
return new ResponseEntity<>(response.getHeaders(), HttpStatus.OK);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
return new ResponseEntity<>("Error! Please try again later", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
</code></pre>
|
[
{
"answer_id": 74571141,
"author": "sai reddy",
"author_id": 18832149,
"author_profile": "https://Stackoverflow.com/users/18832149",
"pm_score": 0,
"selected": false,
"text": "mongodump --db database_name --collection collection_name docker cp dump_files_path container_id:/tmp/. docker exec -it container_id bash mongorestore --db database_name /tmp/dumped_files"
},
{
"answer_id": 74649726,
"author": "Aurast",
"author_id": 3298338,
"author_profile": "https://Stackoverflow.com/users/3298338",
"pm_score": 0,
"selected": false,
"text": "mongodump /data/db ./mongo-db - ./mongo-db:/data/db"
},
{
"answer_id": 74653112,
"author": "Sahaj Raj Malla",
"author_id": 11773575,
"author_profile": "https://Stackoverflow.com/users/11773575",
"pm_score": 1,
"selected": false,
"text": "version: \"3.9\"\n\nservices:\n mongo:\n image: mongo:latest\n ports:\n - 27017:27017\n volumes:\n - mongo-db:/var/lib/mongo/data\n networks:\n - project-network\n api:\n container_name: project_api\n restart: unless-stopped\n image: project_api:1.0.0\n build:\n context: back-end\n dockerfile: Dockerfile\n ports:\n - 4001:4001\n networks:\n - project-network\n depends_on:\n - mongo\n client:\n container_name: project_client\n restart: unless-stopped\n image: project_client:1.0.0\n build:\n context: front-end\n dockerfile: Dockerfile\n ports:\n - 3000:3000\n networks:\n - project-network\n depends_on:\n - api\n\nnetworks:\n project-network:\n\nvolumes:\n mongo-db:\n $ docker volume create mongo-db $ mongoimport --host localhost --db db_name --collection collection_name --file data.json"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20274796/"
] |
74,542,974
|
<p>hey guys i have a problem with my flutter web project</p>
<p>it is, if user accesses the project with in-app-browser(ex. instagram, twitter)
it displays crashed UI</p>
<p>so i need to make an Dialog that shows, the link needs to open with other kinds of browser besides in-app-browser</p>
<p>so the first thing what I need to find out is what kind of browser user access from
but I don't know how to debug it from</p>
<p>is there anyone who ever tried this kind of work??</p>
|
[
{
"answer_id": 74571141,
"author": "sai reddy",
"author_id": 18832149,
"author_profile": "https://Stackoverflow.com/users/18832149",
"pm_score": 0,
"selected": false,
"text": "mongodump --db database_name --collection collection_name docker cp dump_files_path container_id:/tmp/. docker exec -it container_id bash mongorestore --db database_name /tmp/dumped_files"
},
{
"answer_id": 74649726,
"author": "Aurast",
"author_id": 3298338,
"author_profile": "https://Stackoverflow.com/users/3298338",
"pm_score": 0,
"selected": false,
"text": "mongodump /data/db ./mongo-db - ./mongo-db:/data/db"
},
{
"answer_id": 74653112,
"author": "Sahaj Raj Malla",
"author_id": 11773575,
"author_profile": "https://Stackoverflow.com/users/11773575",
"pm_score": 1,
"selected": false,
"text": "version: \"3.9\"\n\nservices:\n mongo:\n image: mongo:latest\n ports:\n - 27017:27017\n volumes:\n - mongo-db:/var/lib/mongo/data\n networks:\n - project-network\n api:\n container_name: project_api\n restart: unless-stopped\n image: project_api:1.0.0\n build:\n context: back-end\n dockerfile: Dockerfile\n ports:\n - 4001:4001\n networks:\n - project-network\n depends_on:\n - mongo\n client:\n container_name: project_client\n restart: unless-stopped\n image: project_client:1.0.0\n build:\n context: front-end\n dockerfile: Dockerfile\n ports:\n - 3000:3000\n networks:\n - project-network\n depends_on:\n - api\n\nnetworks:\n project-network:\n\nvolumes:\n mongo-db:\n $ docker volume create mongo-db $ mongoimport --host localhost --db db_name --collection collection_name --file data.json"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16630737/"
] |
74,542,978
|
<p>I have a spreadsheet and have some data in it.</p>
<p>Here I want to trigger a function on Cell <strong>Script!A2 value change.</strong></p>
<p>I will not change it's value directly.</p>
<p>It will be dependent <strong>by it's formula on below conditions</strong></p>
<p><strong>1.</strong> On the Edit of a Cell in <code>SheetA!A10:A300</code></p>
<p><strong>2.</strong> On the value changes of <code>SheetB!A1:A5</code> (which will be changed by formulas like <code>TODAY</code>, <code>NOW</code> )</p>
<p>Of course it's value will be changed <strong>3 times in a day</strong></p>
<p><strong>1</strong> <code>00:05</code> <strong>2</strong> <code>20:25</code> <strong>3</strong> <code>20:49</code></p>
<p>So I have setup the <strong>Installable trigger</strong> on my Spreadsheet instead of <strong>onEdit</strong> simple Trigger.</p>
<p><strong>Code.gs</strong></p>
<pre><code>function ChangeValue() {
console.log("The Value of the Cell was Changed") ;
}
function onChange(e) {
range = e.range;
ss = e.source;
sheetName = ss.getSheetByName("SCRIPT");
if (e.range.getA1Notation() === 'SCRIPT!A2') {
ChangeValue();
}
}
</code></pre>
<p>But I'm getting the below error.</p>
<pre><code>TypeError: Cannot read property 'range' of undefined
</code></pre>
|
[
{
"answer_id": 74571141,
"author": "sai reddy",
"author_id": 18832149,
"author_profile": "https://Stackoverflow.com/users/18832149",
"pm_score": 0,
"selected": false,
"text": "mongodump --db database_name --collection collection_name docker cp dump_files_path container_id:/tmp/. docker exec -it container_id bash mongorestore --db database_name /tmp/dumped_files"
},
{
"answer_id": 74649726,
"author": "Aurast",
"author_id": 3298338,
"author_profile": "https://Stackoverflow.com/users/3298338",
"pm_score": 0,
"selected": false,
"text": "mongodump /data/db ./mongo-db - ./mongo-db:/data/db"
},
{
"answer_id": 74653112,
"author": "Sahaj Raj Malla",
"author_id": 11773575,
"author_profile": "https://Stackoverflow.com/users/11773575",
"pm_score": 1,
"selected": false,
"text": "version: \"3.9\"\n\nservices:\n mongo:\n image: mongo:latest\n ports:\n - 27017:27017\n volumes:\n - mongo-db:/var/lib/mongo/data\n networks:\n - project-network\n api:\n container_name: project_api\n restart: unless-stopped\n image: project_api:1.0.0\n build:\n context: back-end\n dockerfile: Dockerfile\n ports:\n - 4001:4001\n networks:\n - project-network\n depends_on:\n - mongo\n client:\n container_name: project_client\n restart: unless-stopped\n image: project_client:1.0.0\n build:\n context: front-end\n dockerfile: Dockerfile\n ports:\n - 3000:3000\n networks:\n - project-network\n depends_on:\n - api\n\nnetworks:\n project-network:\n\nvolumes:\n mongo-db:\n $ docker volume create mongo-db $ mongoimport --host localhost --db db_name --collection collection_name --file data.json"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74542978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20018193/"
] |
74,543,010
|
<p>Write a program to accept 5 integer elements of an array and copy them to another array, but all tasks must be performed using pointers.</p>
<pre><code>// Here is my program
#include <stdio.h>
#include <conio.h>
void main() {
int arr[5], brr[5], *p, *q, i;
p = arr;
q = brr;
for (i = 0; i < 5; i++) {
printf("Enter any 5 element=");
scanf("%d", (p + i));
}
for (i = 0; i < 5; i++) {
brr[i] = arr[i];
}
for (i = 0; i < 5; i++) {
printf("Copied array elements are=%d", brr);
}
getch();
}
</code></pre>
|
[
{
"answer_id": 74571141,
"author": "sai reddy",
"author_id": 18832149,
"author_profile": "https://Stackoverflow.com/users/18832149",
"pm_score": 0,
"selected": false,
"text": "mongodump --db database_name --collection collection_name docker cp dump_files_path container_id:/tmp/. docker exec -it container_id bash mongorestore --db database_name /tmp/dumped_files"
},
{
"answer_id": 74649726,
"author": "Aurast",
"author_id": 3298338,
"author_profile": "https://Stackoverflow.com/users/3298338",
"pm_score": 0,
"selected": false,
"text": "mongodump /data/db ./mongo-db - ./mongo-db:/data/db"
},
{
"answer_id": 74653112,
"author": "Sahaj Raj Malla",
"author_id": 11773575,
"author_profile": "https://Stackoverflow.com/users/11773575",
"pm_score": 1,
"selected": false,
"text": "version: \"3.9\"\n\nservices:\n mongo:\n image: mongo:latest\n ports:\n - 27017:27017\n volumes:\n - mongo-db:/var/lib/mongo/data\n networks:\n - project-network\n api:\n container_name: project_api\n restart: unless-stopped\n image: project_api:1.0.0\n build:\n context: back-end\n dockerfile: Dockerfile\n ports:\n - 4001:4001\n networks:\n - project-network\n depends_on:\n - mongo\n client:\n container_name: project_client\n restart: unless-stopped\n image: project_client:1.0.0\n build:\n context: front-end\n dockerfile: Dockerfile\n ports:\n - 3000:3000\n networks:\n - project-network\n depends_on:\n - api\n\nnetworks:\n project-network:\n\nvolumes:\n mongo-db:\n $ docker volume create mongo-db $ mongoimport --host localhost --db db_name --collection collection_name --file data.json"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17139447/"
] |
74,543,012
|
<p>Since <code>std::remove()</code> does not resize <code>std::string</code>, I've came up with an idea how to solve this:</p>
<pre><code>std::string s{"aabcdef"};
std::remove_if(s.begin(), s.end(), [&s](char a)
{
if (a == 'a')
{
s.pop_back();
return true;
}
return false;
});
</code></pre>
<p>Excepted output:</p>
<blockquote>
<p>bcdef</p>
</blockquote>
<p>Actual output:</p>
<blockquote>
<p>bcd</p>
</blockquote>
<p>For some reason, it erases 4 characters instead of expected 2. If I try to pass an <code>int</code> instead and count <strong>true</strong> calls in lambda, it works as expected:</p>
<pre><code>int removes{};
std::remove_if(s.begin(), s.end(), [&removes](char a)
{
if (a == 'a')
{
++removes;
return true;
}
return false;
});
for (int i{}; i < removes; ++i) s.pop_back(); //s = "bcdef"
</code></pre>
|
[
{
"answer_id": 74543118,
"author": "Stack Danny",
"author_id": 6039995,
"author_profile": "https://Stackoverflow.com/users/6039995",
"pm_score": 2,
"selected": false,
"text": "std::remove() string::erase() std::string s{ \"aabcdef\" };\n\nauto it = std::remove(s.begin(), s.end(), 'a');\ns.erase(it, s.end());\n\nstd::cout << s << '\\n';\n std::erase() std::string s{ \"aabcdef\" };\nstd::erase(s, 'a');\n\nstd::cout << s << '\\n';\n bcdef\n"
},
{
"answer_id": 74543868,
"author": "Ranoiaetep",
"author_id": 12861639,
"author_profile": "https://Stackoverflow.com/users/12861639",
"pm_score": 2,
"selected": true,
"text": "std::remove_if std::remove_if pop_back() remove_if std::remove pop_back() remove_if(begin_it, end_it, some_predicate) some_predicate begin_it end_it some_predicate pop_back() remove_if remove_if s.size() s.erase(std::remove_if(s.begin(), s.end(), [](char c){ return c == 'a'; }));\n// or\ns.erase(std::remove(s.begin(), s.end(), 'a');\n std::erase_if(s, [](char c){ return c == 'a'; });\n// or\nstd::erase(s, 'a');\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14662740/"
] |
74,543,025
|
<p>I'm using the excellent exifr library to read the create date from pngs. I'm looping through an array and adding data to a created marker on a map... but I'm stuck on promises!</p>
<p>This is what I want to do in each iteration of the loop.</p>
<pre><code>exifr.parse(bottlefullurl, {xmp: true, tiff:false})
.then(output => bottledate = output.CreateDate);
jmarker.jmarkerdatedata = bottledate;
</code></pre>
<p>Which of course returns undefined as the promise isn't complete. I can console log it so I know the library works.</p>
<pre><code>exifr.parse(bottlefullurl, {xmp: true, tiff:false})
.then(output => console.log(output.CreateDate));
</code></pre>
<p>The documentation is great but the examples all only console.log<br />
<a href="https://github.com/MikeKovarik/exifr/blob/master/README.md" rel="nofollow noreferrer">https://github.com/MikeKovarik/exifr/blob/master/README.md</a></p>
<p>I've read some great answers on Stack Overflow like this one...<br />
<a href="https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call">How do I return the response from an asynchronous call?</a></p>
<p>... and some articles and MDN docs but it's about three steps ahead of my current Javascript understanding (I can't write arrow functions).</p>
<p>Please help!</p>
|
[
{
"answer_id": 74543079,
"author": "Ray",
"author_id": 19808086,
"author_profile": "https://Stackoverflow.com/users/19808086",
"pm_score": 1,
"selected": false,
"text": "jmarker.jmarkerdatedata = exifr.parse(bottlefullurl, {xmp: true, tiff:false})\n .then(output => output.CreateDate);\n"
},
{
"answer_id": 74596652,
"author": "Cmeet",
"author_id": 9006881,
"author_profile": "https://Stackoverflow.com/users/9006881",
"pm_score": 1,
"selected": true,
"text": "jmarker.jmarkerdatedata = await exifr.parse(bottlefullurl, {xmp: true, tiff:false})\n.then(output => output.CreateDate);\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9006881/"
] |
74,543,041
|
<p>Input:</p>
<pre><code>["-5", "-12", "0", "20", "9", "-20", "37"]
</code></pre>
<p>Output:</p>
<pre><code>["0", "-5", "9", "-12", "-20", "20", "37"]
</code></pre>
<p>What logic should I use in order to get minimum of function result?</p>
<p>I have a class with function which compares 2 items (int) and returns min of them:</p>
<pre><code>class ListComparator implements Comparator<String> {
@Override
public int compare(String a, String b) {
int intA = Integer.parseInt(a);
int intB = Integer.parseInt(b);
int calculatedA = calc(intA);
int calculatedB = calc(intB);
return (calculatedA < calculatedB) ? intA : intB;
}
private int calc(int x) {
double form = Math.pow(5*x, 2) + 3;
int result = (int) form;
return result;
}
}
</code></pre>
<pre><code></code></pre>
|
[
{
"answer_id": 74543079,
"author": "Ray",
"author_id": 19808086,
"author_profile": "https://Stackoverflow.com/users/19808086",
"pm_score": 1,
"selected": false,
"text": "jmarker.jmarkerdatedata = exifr.parse(bottlefullurl, {xmp: true, tiff:false})\n .then(output => output.CreateDate);\n"
},
{
"answer_id": 74596652,
"author": "Cmeet",
"author_id": 9006881,
"author_profile": "https://Stackoverflow.com/users/9006881",
"pm_score": 1,
"selected": true,
"text": "jmarker.jmarkerdatedata = await exifr.parse(bottlefullurl, {xmp: true, tiff:false})\n.then(output => output.CreateDate);\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17587281/"
] |
74,543,049
|
<p>I've raw data like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
</tr>
</thead>
<tbody>
<tr>
<td>"A:1, B:2, C:3"</td>
<td>XXX</td>
</tr>
</tbody>
</table>
</div>
<p>The result I want is like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Column A</th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>Column B</th>
</tr>
</thead>
<tbody>
<tr>
<td>"A:1, B:2, C:3"</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>XXX</td>
</tr>
</tbody>
</table>
</div>
<p>Can anyone help with pyspark code?</p>
|
[
{
"answer_id": 74543079,
"author": "Ray",
"author_id": 19808086,
"author_profile": "https://Stackoverflow.com/users/19808086",
"pm_score": 1,
"selected": false,
"text": "jmarker.jmarkerdatedata = exifr.parse(bottlefullurl, {xmp: true, tiff:false})\n .then(output => output.CreateDate);\n"
},
{
"answer_id": 74596652,
"author": "Cmeet",
"author_id": 9006881,
"author_profile": "https://Stackoverflow.com/users/9006881",
"pm_score": 1,
"selected": true,
"text": "jmarker.jmarkerdatedata = await exifr.parse(bottlefullurl, {xmp: true, tiff:false})\n.then(output => output.CreateDate);\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16868429/"
] |
74,543,069
|
<p>I have having a bit of a problem:</p>
<p>I am trying to convert these numbers:</p>
<p>-0.2179,
-8.742.754.508,
1.698.516.678,</p>
<p>to</p>
<p>-0.22,
-8.74,
1.70,</p>
<p>But I am really not sure how I do this, when the number of decimal points is different?</p>
<p>I have tried .split('.') but its difficult with changing decimal points.</p>
<p>I was wondering if you guys had any pointers for this small problem? Kind regard.</p>
<pre><code>for number in data.fundreturn:
new_number = number.split('.')[0]
fund.append(new_number)
for number in data.bitcoinreturn:
new_number = number.split('.')[0]
bitcoin.append(new_number)
</code></pre>
<p>but then I get 0, 8, and 1</p>
<p>The code snippet basically is me going through each column and trying to covert the values.</p>
|
[
{
"answer_id": 74543213,
"author": "Mehrdad Saberi",
"author_id": 12534890,
"author_profile": "https://Stackoverflow.com/users/12534890",
"pm_score": 1,
"selected": false,
"text": "data = [\"-0.2179\", \"-8.742.754.508\", \"1.698.516.678\"]\nfund = []\nfor number in data:\n split = number.split('.')\n integer_part = split[0]\n fractional_part = ''.join([split[i] for i in range(1, len(split))])\n new_number = float('.'.join((integer_part, fractional_part)))\n # rounding to two decimal points\n new_number = round(new_number, 2)\n fund.append(new_number)\n\nprint(fund)\n"
},
{
"answer_id": 74543244,
"author": "0x0fba",
"author_id": 20339407,
"author_profile": "https://Stackoverflow.com/users/20339407",
"pm_score": 1,
"selected": true,
"text": "def convert(number: str) -> float:\n n = number.split(\".\")\n return float(n[0]) if len(n)<2 else float(f\"{n[0]}.{n[1]}\")\n\nconvert(\"32\") # 32.0\nconvert(\"-8.742.754.508\") # -8.742\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17507865/"
] |
74,543,072
|
<p>Here's the code can anyone help?</p>
<pre><code>using System;
namespace Mathhero
{
class MainClass
{
public static void Main(string[] args)
{
int i;
for (i = 0; i <= 10; i++)
{
Random numgen = new Random();
int num1 = numgen.Next(1, 11);
int num2 = numgen.Next(1, 11);
Console.WriteLine("What is " + num1 + " * " + num2 + " equal to ???");
int Answer = Convert.ToInt32(Console.ReadLine());
if (Answer == num1 * num2)
{
int ran = numgen.Next(1, 4);
switch (ran)
{
case 1:
Console.WriteLine("Good work!!");
break;
case 2:
Console.WriteLine("Nice!!!");
break;
default:
Console.WriteLine("Excellent!!");
break;
}
Console.WriteLine();
}
else
{
int ran = numgen.Next(1, 4);
switch (ran)
{
case 1:
Console.WriteLine("Wrong!!");
break;
case 2:
Console.WriteLine("Try hard!!!");
break;
default:
Console.WriteLine("DO homework!!");
break;
}
Console.WriteLine();
}
i=i+ 1;
}
Console.WriteLine("Test Ended!!!");
}
}
}
</code></pre>
<p>The for loop is exiting after 6 questions while it should after 10.</p>
|
[
{
"answer_id": 74543091,
"author": "tomerpacific",
"author_id": 10632369,
"author_profile": "https://Stackoverflow.com/users/10632369",
"pm_score": 1,
"selected": false,
"text": " else\n {\n int ran = numgen.Next(1, 4);\n switch (ran)\n {\n case 1:\n Console.WriteLine(\"Wrong!!\");\n break;\n case 2:\n Console.WriteLine(\"Try hard!!!\");\n break;\n default:\n Console.WriteLine(\"DO homework!!\");\n break;\n }\n Console.WriteLine();\n }\n i=i+ 1; //// <------- HERE\n }\n"
},
{
"answer_id": 74543100,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "for i for (i = 0; i <= 10; i++)\n i i=i+ 1;\n i for (i = 0; i < 10; i++)\n < <= i = i + 1; for (int i = 0; i < 10; i++)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19325373/"
] |
74,543,085
|
<p>I have a string I would like to split and access the elements as strings. Here is code:</p>
<pre><code>x <- "b0.5,0.5"
y <- strsplit(x,',')
str(y)
y[[1]][1]
str(y[[1]][1])
length(y[[1]][1])
z <- y[[1]][1]
length(z)
substr(z,1,1)
substr(z,1,2)
substr(z,1,3)
substr(z,1,4)
</code></pre>
<p>The length of z is 1, but I can access at least 4 substrings of length 1. Can someone explain this to me? Thanks!</p>
|
[
{
"answer_id": 74543091,
"author": "tomerpacific",
"author_id": 10632369,
"author_profile": "https://Stackoverflow.com/users/10632369",
"pm_score": 1,
"selected": false,
"text": " else\n {\n int ran = numgen.Next(1, 4);\n switch (ran)\n {\n case 1:\n Console.WriteLine(\"Wrong!!\");\n break;\n case 2:\n Console.WriteLine(\"Try hard!!!\");\n break;\n default:\n Console.WriteLine(\"DO homework!!\");\n break;\n }\n Console.WriteLine();\n }\n i=i+ 1; //// <------- HERE\n }\n"
},
{
"answer_id": 74543100,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "for i for (i = 0; i <= 10; i++)\n i i=i+ 1;\n i for (i = 0; i < 10; i++)\n < <= i = i + 1; for (int i = 0; i < 10; i++)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20579317/"
] |
74,543,089
|
<p>I found my command line tool gets stuck in between and needs a enter to process and I found that it’s because of "QUICKEDIT" mode in cmd and we want to disable it to avoid that. So I searched for Java options to disable quick edit mode on my app launch but I got only bat file from here <a href="https://github.com/npocmaka/batch.scripts/blob/master/hybrids/.net/c/quickEdit.bat" rel="nofollow noreferrer">quickedit.bat</a>.</p>
<p>And this bat file works perfect when I run from my command prompt it disable quick edit mode in the current session itself which is the same I want. So I kept that bat file in my folder via installer and run it first on every launch but it’s not turning off the quick edit mode for current session.</p>
<p>I have tried using both process builder and runtime.exec.</p>
<p>Below is my code</p>
<pre><code>ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "quickedit.bat");
File dir = new File(System.getProperty("user.home")+File.separator+"AppData"+File.separator+"Local"+File.separator);
pb.directory(dir);
Process p=null;
try {
p = pb.start();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
try {
while ((line = in.readLine()) != null) {
System.out.println(line); // ----Here i get the same output i get when i run the bat file
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader inerr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
try {
while ((line = inerr.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
</code></pre>
<p>It gives me this:</p>
<p><img src="https://i.stack.imgur.com/PBu1J.png" alt="output of my java program" /></p>
<p>When I run my bat file directly like this:</p>
<p><img src="https://i.stack.imgur.com/8FkfV.png" alt="output of bat file" /></p>
<p>But through Java it didn't disable quick edit in my current command prompt whereas it disables at once I run the actual bat file. So can anyone say the reason or how to fix it or any other way to disable it for ever from Java?</p>
|
[
{
"answer_id": 74543091,
"author": "tomerpacific",
"author_id": 10632369,
"author_profile": "https://Stackoverflow.com/users/10632369",
"pm_score": 1,
"selected": false,
"text": " else\n {\n int ran = numgen.Next(1, 4);\n switch (ran)\n {\n case 1:\n Console.WriteLine(\"Wrong!!\");\n break;\n case 2:\n Console.WriteLine(\"Try hard!!!\");\n break;\n default:\n Console.WriteLine(\"DO homework!!\");\n break;\n }\n Console.WriteLine();\n }\n i=i+ 1; //// <------- HERE\n }\n"
},
{
"answer_id": 74543100,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "for i for (i = 0; i <= 10; i++)\n i i=i+ 1;\n i for (i = 0; i < 10; i++)\n < <= i = i + 1; for (int i = 0; i < 10; i++)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20579178/"
] |
74,543,125
|
<p>I want to make the user to access firestore data in my flutter app only when they are online.</p>
<p>I am expecting that firestore data can't stored in cache memory, so tha tthe user only gets the data when they are online.</p>
|
[
{
"answer_id": 74543395,
"author": "Irfan Ganatra",
"author_id": 18817235,
"author_profile": "https://Stackoverflow.com/users/18817235",
"pm_score": 1,
"selected": false,
"text": "connectivity_plus: ^3.0.2"
},
{
"answer_id": 74543719,
"author": "Abdullatif Eida",
"author_id": 20570798,
"author_profile": "https://Stackoverflow.com/users/20570798",
"pm_score": 1,
"selected": false,
"text": "YourAppState{\n ConnectivityResult _connectionStatus = ConnectivityResult.none;\n final Connectivity _connectivity = Connectivity();\n late StreamSubscription<ConnectivityResult> _connectivitySubscription;\n\n @override\n void initState() {\n super.initState();\n _connectivitySubscription_connectivity.onConnectivityChanged.listen(_updateConnectionStatus);\n }\n\n Future<void> _updateConnectionStatus(ConnectivityResult result) async {\n setState(() {\n _connectionStatus = result;\n });\n if (_connectionStatus.toString() == \"ConnectivityResult.none\") {\n navigatorKey.currentState!.popUntil((route) => route.isFirst);\n }\n }\n if(_connectionStatus.toString() != \"ConnectivityResult.none\") \n"
},
{
"answer_id": 74543793,
"author": "ColdLogic",
"author_id": 217774,
"author_profile": "https://Stackoverflow.com/users/217774",
"pm_score": 2,
"selected": false,
"text": "// Apple and Android\ndb.settings = const Settings(persistenceEnabled: true);\n\n// Web\nawait db\n .enablePersistence(const PersistenceSettings(synchronizeTabs: true));\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20579354/"
] |
74,543,140
|
<p><a href="https://i.stack.imgur.com/4ILik.png" rel="nofollow noreferrer">desired_output_sample</a>
I have following data:</p>
<pre><code>#1. dates of 15 day frequency:
dates = seq(as.Date("2016-09-01"), as.Date("2020-07-30"), by=15) #96 times observation
#2. water content in crops corresponding to the times given.
water <- c(0.5702722, 0.5631781, 0.5560839, 0.5555985, 0.5519783, 0.5463459,
0.5511598, 0.546652, 0.5361545, 0.530012, 0.5360571, 0.5396569,
0.5683526, 0.6031535, 0.6417821, 0.671358, 0.7015542, 0.7177007,
0.7103561, 0.7036985, 0.6958607, 0.6775161, 0.6545367, 0.6380155,
0.6113306, 0.5846186, 0.5561815, 0.5251135, 0.5085149, 0.495352,
0.485819, 0.4730029, 0.4686458, 0.4616468, 0.4613918, 0.4615532,
0.4827496, 0.5149105, 0.5447824, 0.5776764, 0.6090217, 0.6297454,
0.6399422, 0.6428941, 0.6586344, 0.6507473, 0.6290631, 0.6011123,
0.5744375, 0.5313527, 0.5008027, 0.4770338, 0.4564025, 0.4464508,
0.4309046, 0.4351668, 0.4490393, 0.4701232, 0.4911582, 0.5162941,
0.5490387, 0.5737573, 0.6031149, 0.6400073, 0.6770058, 0.7048311,
0.7255012, 0.739107, 0.7338938, 0.7265202, 0.6940718, 0.6757214,
0.6460862, 0.6163091, 0.5743775, 0.5450822, 0.5057753, 0.4715266,
0.4469859, 0.4303232, 0.4187793, 0.4119401, 0.4201316, 0.426369,
0.4419331, 0.4757525, 0.5070846, 0.5248457, 0.5607567, 0.5859825,
0.6107531, 0.6201754, 0.6356589, 0.6336177, 0.6275579, 0.6214981)
</code></pre>
<p>I want to compute trend of the water content or moisture data corresponding to different subperiods. Lets say: one trend from 2016 - 09-01 to 2019-11-30.
and other trend from 2019-12-15 to the last date (in this case 2020-07-27).</p>
<p>And I want to make a plot like the one attached.
Appreciate your help. Can be in R or in python.</p>
|
[
{
"answer_id": 74543395,
"author": "Irfan Ganatra",
"author_id": 18817235,
"author_profile": "https://Stackoverflow.com/users/18817235",
"pm_score": 1,
"selected": false,
"text": "connectivity_plus: ^3.0.2"
},
{
"answer_id": 74543719,
"author": "Abdullatif Eida",
"author_id": 20570798,
"author_profile": "https://Stackoverflow.com/users/20570798",
"pm_score": 1,
"selected": false,
"text": "YourAppState{\n ConnectivityResult _connectionStatus = ConnectivityResult.none;\n final Connectivity _connectivity = Connectivity();\n late StreamSubscription<ConnectivityResult> _connectivitySubscription;\n\n @override\n void initState() {\n super.initState();\n _connectivitySubscription_connectivity.onConnectivityChanged.listen(_updateConnectionStatus);\n }\n\n Future<void> _updateConnectionStatus(ConnectivityResult result) async {\n setState(() {\n _connectionStatus = result;\n });\n if (_connectionStatus.toString() == \"ConnectivityResult.none\") {\n navigatorKey.currentState!.popUntil((route) => route.isFirst);\n }\n }\n if(_connectionStatus.toString() != \"ConnectivityResult.none\") \n"
},
{
"answer_id": 74543793,
"author": "ColdLogic",
"author_id": 217774,
"author_profile": "https://Stackoverflow.com/users/217774",
"pm_score": 2,
"selected": false,
"text": "// Apple and Android\ndb.settings = const Settings(persistenceEnabled: true);\n\n// Web\nawait db\n .enablePersistence(const PersistenceSettings(synchronizeTabs: true));\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20473161/"
] |
74,543,171
|
<p>I have a T-SQL Query that show Sum(TotalAmount) Sum(Discount) Sum(PayableAmount) from Table1 named p1 and show the Sum(PaidAmount) from Table2 named p2,</p>
<p>the tables p1 and p2 do not have any relationship with Forenkay and the primary key,</p>
<p>so I was not able to use the .net core method syntax _context.Table1.include(a=>a.table2) to join 2 tables because there is no relationship between these 2 tables,</p>
<p>So I have written the below code as T-SQL query and got the exact result that I wanted, but now I want to write the same T-SQL query as a LING query and use it inside my C#.net Core Controller code as query syntax or method syntax,</p>
<p>Here is my T-SQL Code that show Sum(TotalAmount) Sum(Discount) Sum(PayableAmount) from Table1 named p1 and show the Sum(PaidAmount) from Table2 named p2,</p>
<pre><code>SELECT p1.PatientId,
SUM(p1.TotalAmount) as TotalTreatmentAmount,
SUM(p1.Discount) As TotalTreatmentDiscount,
SUM(p1.Payable) as TotalTreatmentPayable,
SUM(p1.Balance) as TotalTreatmentBalancce,
p2.TotalTreatmentPaidAmount
FROM PatientPayments as p1
join (SELECT p2.PatientId, SUM(p2.PaidAmount) as TotalTreatmentPaidAmount
FROM PatientPaymentHistories p2
where p2.PaymentType != 'Refund'
group by p2.PatientId) as p2
ON p2.PatientId = p1.PatientId
group by p1.PatientId, p2.TotalTreatmentPaidAmount
</code></pre>
<p>Here is my C# Code but this code does not work its wrong only the SQL code is working fine</p>
<pre><code> public IActionResult ExportPatientPaymentDataToExcel()
{
var PatientPayments =
from p1 in _context.PatientPayments
join p2 in _context.PatientPaymentHistories on p1.PatientId equals p2.PatientId
select new
{
p1.PatientId,
p1.TotalAmount,
p1.Discount,
p1.Payable,
p2.PaidAmount
};
DataTable PatientPaymentTable = new DataTable("PatientPayment");
PatientPaymentTable.Columns.AddRange(new DataColumn[5]
{
new DataColumn("Patient ID"),
new DataColumn("Total Amount"),
new DataColumn("Total Discount"),
new DataColumn("Total Payable"),
new DataColumn("Total Paid"),
});
foreach (var PatientPayment in PatientPayments)
{
PatientPaymentTable.Rows.Add(
PatientPayment.PatientId,
PatientPayment.TotalAmount,
PatientPayment.Discount,
PatientPayment.Payable,
PatientPayment.PaidAmount
);
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(PatientPaymentTable);
using (MemoryStream stream = new MemoryStream())
{
wb.SaveAs(stream);
return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", GetLocalDateTime().Date.ToShortDateString() + " " + "PatientPayment_Data.xlsx");
}
}
}
</code></pre>
<p>Please help me to change the above T-SQL Code to C# Ling query</p>
|
[
{
"answer_id": 74543395,
"author": "Irfan Ganatra",
"author_id": 18817235,
"author_profile": "https://Stackoverflow.com/users/18817235",
"pm_score": 1,
"selected": false,
"text": "connectivity_plus: ^3.0.2"
},
{
"answer_id": 74543719,
"author": "Abdullatif Eida",
"author_id": 20570798,
"author_profile": "https://Stackoverflow.com/users/20570798",
"pm_score": 1,
"selected": false,
"text": "YourAppState{\n ConnectivityResult _connectionStatus = ConnectivityResult.none;\n final Connectivity _connectivity = Connectivity();\n late StreamSubscription<ConnectivityResult> _connectivitySubscription;\n\n @override\n void initState() {\n super.initState();\n _connectivitySubscription_connectivity.onConnectivityChanged.listen(_updateConnectionStatus);\n }\n\n Future<void> _updateConnectionStatus(ConnectivityResult result) async {\n setState(() {\n _connectionStatus = result;\n });\n if (_connectionStatus.toString() == \"ConnectivityResult.none\") {\n navigatorKey.currentState!.popUntil((route) => route.isFirst);\n }\n }\n if(_connectionStatus.toString() != \"ConnectivityResult.none\") \n"
},
{
"answer_id": 74543793,
"author": "ColdLogic",
"author_id": 217774,
"author_profile": "https://Stackoverflow.com/users/217774",
"pm_score": 2,
"selected": false,
"text": "// Apple and Android\ndb.settings = const Settings(persistenceEnabled: true);\n\n// Web\nawait db\n .enablePersistence(const PersistenceSettings(synchronizeTabs: true));\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7422109/"
] |
74,543,173
|
<pre><code>ERROR NullInjectorError: R3InjectorError(PaceGeneratorLibraryComponentLoader)[HttpClient -> HttpClient -> HttpClient -> HttpClient]:
NullInjectorError: No provider for HttpClient!
at NullInjector.get (core.mjs:6367:27)
at R3Injector.get (core.mjs:6794:33)
at R3Injector.get (core.mjs:6794:33)
at R3Injector.get (core.mjs:6794:33)
at R3Injector.get (core.mjs:6794:33)
at ChainedInjector.get (core.mjs:13824:36)
at lookupTokenUsingModuleInjector (core.mjs:3293:39)
at getOrCreateInjectable (core.mjs:3338:12)
at ɵɵdirectiveInject (core.mjs:10879:12)
at NodeInjectorFactory.DetailsComponent_Factory [as factory] (ɵfac.js? [sm]:1:1)
</code></pre>
<p>I faced error above when I was using HttpClient to acquire backend data. I have included HttpModule in my NgModule but it does not seems to be working.</p>
<pre><code>@NgModule({
declarations: [
AppComponent,
WidgetContainerComponent
],
exports: [],
imports: [
AppRoutingModule,
BrowserAnimationsModule,
HttpClientModule,
BrowserModule,
ToastrModule.forRoot(),
ModalModule.forRoot(),
PlatformCoreBaseModule,
MsalModule.forRoot(getMsalConfig(environment).msalInstanceConfig, getMsalConfig(environment).msalGuardConfig, undefined),
],
providers: [
AppStateService,
ClientSettingsService,
DisplayStateService,
Title,
HttpClientModule,
WebPlatformApiService,
DynamicComponentLoader,
</code></pre>
<p>I have been trying for hours and doesn't have an idea on it.</p>
|
[
{
"answer_id": 74543395,
"author": "Irfan Ganatra",
"author_id": 18817235,
"author_profile": "https://Stackoverflow.com/users/18817235",
"pm_score": 1,
"selected": false,
"text": "connectivity_plus: ^3.0.2"
},
{
"answer_id": 74543719,
"author": "Abdullatif Eida",
"author_id": 20570798,
"author_profile": "https://Stackoverflow.com/users/20570798",
"pm_score": 1,
"selected": false,
"text": "YourAppState{\n ConnectivityResult _connectionStatus = ConnectivityResult.none;\n final Connectivity _connectivity = Connectivity();\n late StreamSubscription<ConnectivityResult> _connectivitySubscription;\n\n @override\n void initState() {\n super.initState();\n _connectivitySubscription_connectivity.onConnectivityChanged.listen(_updateConnectionStatus);\n }\n\n Future<void> _updateConnectionStatus(ConnectivityResult result) async {\n setState(() {\n _connectionStatus = result;\n });\n if (_connectionStatus.toString() == \"ConnectivityResult.none\") {\n navigatorKey.currentState!.popUntil((route) => route.isFirst);\n }\n }\n if(_connectionStatus.toString() != \"ConnectivityResult.none\") \n"
},
{
"answer_id": 74543793,
"author": "ColdLogic",
"author_id": 217774,
"author_profile": "https://Stackoverflow.com/users/217774",
"pm_score": 2,
"selected": false,
"text": "// Apple and Android\ndb.settings = const Settings(persistenceEnabled: true);\n\n// Web\nawait db\n .enablePersistence(const PersistenceSettings(synchronizeTabs: true));\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20256600/"
] |
74,543,206
|
<p>I want each values of df have different decimal point like this</p>
<pre><code> year month day
count 1234 5678 9101
mean 12.12 34.34 2.3456
std 12.12 3.456 7.789
</code></pre>
<p>I searched to find a way to change specific value's decimal point
but couldn't find the way. So this is what I've got</p>
<pre><code> year month day
count 1234.0000 5678.0000 9101.0000
mean 12.1200 34.3400 2.3456
std 12.1200 3.4560 7.7890
</code></pre>
<p>I know the round() method but I don't know how to assign it to each values not the whole row or columns.
Is it possible to change values separately?</p>
|
[
{
"answer_id": 74543395,
"author": "Irfan Ganatra",
"author_id": 18817235,
"author_profile": "https://Stackoverflow.com/users/18817235",
"pm_score": 1,
"selected": false,
"text": "connectivity_plus: ^3.0.2"
},
{
"answer_id": 74543719,
"author": "Abdullatif Eida",
"author_id": 20570798,
"author_profile": "https://Stackoverflow.com/users/20570798",
"pm_score": 1,
"selected": false,
"text": "YourAppState{\n ConnectivityResult _connectionStatus = ConnectivityResult.none;\n final Connectivity _connectivity = Connectivity();\n late StreamSubscription<ConnectivityResult> _connectivitySubscription;\n\n @override\n void initState() {\n super.initState();\n _connectivitySubscription_connectivity.onConnectivityChanged.listen(_updateConnectionStatus);\n }\n\n Future<void> _updateConnectionStatus(ConnectivityResult result) async {\n setState(() {\n _connectionStatus = result;\n });\n if (_connectionStatus.toString() == \"ConnectivityResult.none\") {\n navigatorKey.currentState!.popUntil((route) => route.isFirst);\n }\n }\n if(_connectionStatus.toString() != \"ConnectivityResult.none\") \n"
},
{
"answer_id": 74543793,
"author": "ColdLogic",
"author_id": 217774,
"author_profile": "https://Stackoverflow.com/users/217774",
"pm_score": 2,
"selected": false,
"text": "// Apple and Android\ndb.settings = const Settings(persistenceEnabled: true);\n\n// Web\nawait db\n .enablePersistence(const PersistenceSettings(synchronizeTabs: true));\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20423918/"
] |
74,543,221
|
<p>I have the following the following columns,</p>
<pre><code>column_1 = ["Northern Rockies, British Columbia [9A87]", "Northwest Territories [2H89]", "Canada [00052A]", "Division No. 1, Newfoundland and Labrador [52A]"]
column_2 = ["aa", "bb", "cc", "dd"]
column_3 = [4, 4.5, 23, 1]
zipped = list(zip(column_1 , column_2, column_3))
df = pd.DataFrame(zipped, columns=['column_1' , 'column_2', 'column_3'])
</code></pre>
<p>I want to extract the text between the square brackets from the first column as a separate column. Below is the output I am looking for,</p>
<pre><code>column_1 = ["Northern Rockies, British Columbia", "Northwest Territories", "Canada", "Division No. 1, Newfoundland and Labrador"]
column_2 = ["aa", "bb", "cc", "dd"]
column_3 = [4, 4.5, 23, 1]
column_4 = ["9A87", "2H89", "00052A", "52A"]
zipped = list(zip(column_1 , column_2, column_3, column_4))
df = pd.DataFrame(zipped, columns=['column_1' , 'column_2', 'column_3', 'column_4'])
</code></pre>
<p>I am using square bracket here but I think the solution should apply to any type of bracket.</p>
|
[
{
"answer_id": 74543269,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 2,
"selected": true,
"text": "str.extract str.repalce df[\"column_4\"] = df[\"column_1\"].str.extract(r'\\[(.*?)\\]')\ndf[\"column_1\"] = df[\"column_1\"].str.replace(r'\\s*\\[.*?\\]$', '', regex=True)\n"
},
{
"answer_id": 74543881,
"author": "Bhavesh Rathod",
"author_id": 19997160,
"author_profile": "https://Stackoverflow.com/users/19997160",
"pm_score": 2,
"selected": false,
"text": "df[['column_1','column_4']] = df['column_1'].str.extract(r'(.*)[\\[\\{\\(](.*)[\\]\\}\\)]',flags=re.IGNORECASE)\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13928846/"
] |
74,543,258
|
<p>I have a dataframe which returns the output as</p>
<p><a href="https://i.stack.imgur.com/5g4eB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5g4eB.png" alt="enter image description here" /></a></p>
<p>I would like to transpose this into</p>
<p><a href="https://i.stack.imgur.com/r1G34.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r1G34.png" alt="enter image description here" /></a></p>
<p>Can someone help to understand how to prepare the pyspark code to achieve this result dynamically. I have tried Unpivot in sql but no luck.</p>
|
[
{
"answer_id": 74543427,
"author": "wwnde",
"author_id": 8986975,
"author_profile": "https://Stackoverflow.com/users/8986975",
"pm_score": 3,
"selected": true,
"text": "df =spark.createDataFrame([\n(78,20,19,90),\n],\n('Machines', 'Books', 'Vehicles', 'Plants'))\n df.withColumn('tab', F.array(*[F.struct(lit(x).alias('Fields'), col(x).alias('Count')).alias(x) for x in df.columns])).selectExpr('inline(tab)').show()\n\n\n+--------+-----+\n| Fields|Count|\n+--------+-----+\n|Machines| 78|\n| Books| 20|\n|Vehicles| 19|\n| Plants| 90|\n+--------+-----+\n"
},
{
"answer_id": 74547962,
"author": "Azhar Khan",
"author_id": 2847330,
"author_profile": "https://Stackoverflow.com/users/2847330",
"pm_score": 0,
"selected": false,
"text": "df = df.selectExpr(\"\"\"stack(4, \"Machines\", Machines, \"Books\", Books, \"Vehicles\", Vehicles, \"Plants\", Plants) as (Fields, Count)\"\"\")\n cols = [f'\"{c}\", {c}' for c in df.columns]\nexprs = f\"stack({len(cols)}, {', '.join(str(c) for c in cols)}) as (Fields, Count)\"\ndf = df.selectExpr(exprs)\n df = spark.createDataFrame(data=[[78,20,19,90]], schema=['Machines','Books','Vehicles','Plants'])\n\n# Hard coded\n# df = df.selectExpr(\"\"\"stack(4, \"Machines\", Machines, \"Books\", Books, \"Vehicles\", Vehicles, \"Plants\", Plants) as (Fields, Count)\"\"\")\n\n# Generalised\ncols = [f'\"{c}\", {c}' for c in df.columns]\nexprs = f\"stack({len(cols)}, {', '.join(str(c) for c in cols)}) as (Fields, Count)\"\ndf = df.selectExpr(exprs)\n\n[Out]:\n+--------+-----+\n|Fields |Count|\n+--------+-----+\n|Machines|78 |\n|Books |20 |\n|Vehicles|19 |\n|Plants |90 |\n+--------+-----+\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1211072/"
] |
74,543,261
|
<p>I have the following string</p>
<pre class="lang-none prettyprint-override"><code>Date: 20/8/2020 Duration: 0.33 IP: 110.1.x.x Server:01
</code></pre>
<p>I'm applying <code>findall</code> as a way to split my string when I apply <code>findall</code> it split I & P how can I change expression to get this output</p>
<pre><code>['Date: 20/8/2020 ', 'Duration: 0.33 ', 'IP: 110.1.x.x ', 'Server:01']
</code></pre>
<pre><code>text = "Date: 20/8/2020 Duration: 0.33 IP: 110.1.x.x Server:01"
my_list = re.findall('[a-zA-Z][^A-Z]*', text)
my_list
['Date: 20/8/2020 ', 'Duration: 0.33 ', 'I', 'P: 110.1.x.x ', 'Server:01']
</code></pre>
|
[
{
"answer_id": 74543400,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": ">>> re.findall(r'([A-Z][a-zA-Z].*?)\\s*(?=[A-Z][a-zA-Z]|$)', text)\n['Date: 20/8/2020', 'Duration: 0.33', 'IP: 110.1.x.x', 'Server:01']\n >>> dict(re.split(r'\\s*:\\s*', m, 1) for m in re.findall(r'([A-Z][a-zA\n-Z].*?)\\s*(?=[A-Z][a-zA-Z]|$)', text))\n{'Date': '20/8/2020', 'Duration': '0.33', 'IP': '110.1.x.x', 'Server': '01'}\n"
},
{
"answer_id": 74546805,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 0,
"selected": false,
"text": "(?<!\\S)[A-Z][a-zA-Z]*:\\s*\\S+\n (?<!\\S) [A-Z][a-zA-Z]*: : \\s*\\S import re\n\npattern = r\"(?<!\\S)[A-Z][a-zA-Z]*:\\s*\\S+\"\ns = \"Date: 20/8/2020 Duration: 0.33 IP: 110.1.x.x Server:01\"\nprint(re.findall(pattern, s))\n ['Date: 20/8/2020', 'Duration: 0.33', 'IP: 110.1.x.x', 'Server:01']\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20527442/"
] |
74,543,285
|
<p>I am trying to find the way to test RichFilter function just like RichMappFunction like present here : <a href="https://flink.apache.org/news/2020/02/07/a-guide-for-unit-testing-in-apache-flink.html" rel="nofollow noreferrer">RichMapFunction Testing is present here...</a>...Searched through internet and find nothing...Please help...</p>
<pre><code>public class Person{
public String name;
public Int age;
}
public class OCRKafkaFilter extends RichFilterFunction<Person> {
@Override
public boolean filter(Person person) {
return person.age>21;
}
}
</code></pre>
<p>How can we write a test case for this rich filter function for stateful operators ...</p>
|
[
{
"answer_id": 74543400,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": ">>> re.findall(r'([A-Z][a-zA-Z].*?)\\s*(?=[A-Z][a-zA-Z]|$)', text)\n['Date: 20/8/2020', 'Duration: 0.33', 'IP: 110.1.x.x', 'Server:01']\n >>> dict(re.split(r'\\s*:\\s*', m, 1) for m in re.findall(r'([A-Z][a-zA\n-Z].*?)\\s*(?=[A-Z][a-zA-Z]|$)', text))\n{'Date': '20/8/2020', 'Duration': '0.33', 'IP': '110.1.x.x', 'Server': '01'}\n"
},
{
"answer_id": 74546805,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 0,
"selected": false,
"text": "(?<!\\S)[A-Z][a-zA-Z]*:\\s*\\S+\n (?<!\\S) [A-Z][a-zA-Z]*: : \\s*\\S import re\n\npattern = r\"(?<!\\S)[A-Z][a-zA-Z]*:\\s*\\S+\"\ns = \"Date: 20/8/2020 Duration: 0.33 IP: 110.1.x.x Server:01\"\nprint(re.findall(pattern, s))\n ['Date: 20/8/2020', 'Duration: 0.33', 'IP: 110.1.x.x', 'Server:01']\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20579522/"
] |
74,543,329
|
<p>I'm working on a Ingestion Flow where we ingest the data from csv file to Oracle database. This is a truncate and load. So we should truncate the table before it is loaded. Trying to execute the below SP in the Lookup activity of ADF</p>
<pre><code>BEGIN
execute oracle.cml_trunc_table('SCHEMA','TABLE_NAME')";
END;
</code></pre>
<p>Throws the below Error</p>
<pre><code>PLS-00103: Encountered the symbol "ORACLE" when expecting one of the following:
:= . ( @ % ; immediate
The symbol ":=" was substituted for "ORACLE" to continue.
</code></pre>
<p>Also tried removing the "ORACLE" keyword and it failed with Invalid SQL/
Is there any other approach to execute the truncate table statement</p>
<p>Thanks in advance</p>
|
[
{
"answer_id": 74543400,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": ">>> re.findall(r'([A-Z][a-zA-Z].*?)\\s*(?=[A-Z][a-zA-Z]|$)', text)\n['Date: 20/8/2020', 'Duration: 0.33', 'IP: 110.1.x.x', 'Server:01']\n >>> dict(re.split(r'\\s*:\\s*', m, 1) for m in re.findall(r'([A-Z][a-zA\n-Z].*?)\\s*(?=[A-Z][a-zA-Z]|$)', text))\n{'Date': '20/8/2020', 'Duration': '0.33', 'IP': '110.1.x.x', 'Server': '01'}\n"
},
{
"answer_id": 74546805,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 0,
"selected": false,
"text": "(?<!\\S)[A-Z][a-zA-Z]*:\\s*\\S+\n (?<!\\S) [A-Z][a-zA-Z]*: : \\s*\\S import re\n\npattern = r\"(?<!\\S)[A-Z][a-zA-Z]*:\\s*\\S+\"\ns = \"Date: 20/8/2020 Duration: 0.33 IP: 110.1.x.x Server:01\"\nprint(re.findall(pattern, s))\n ['Date: 20/8/2020', 'Duration: 0.33', 'IP: 110.1.x.x', 'Server:01']\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14125039/"
] |
74,543,330
|
<p>I am trying to retrieve the code from an HTML file in PHP.</p>
<p>And display it in a textarea.</p>
<p>Example: if I have a file with a div and a foo h1 in it I want my textarea to appear like this.</p>
<p>After a few hours of research, I can't find a good result.</p>
<p><a href="https://i.stack.imgur.com/jnjeS.png" rel="nofollow noreferrer">Here is my sample html file</a></p>
<p>And I want this html file to be readable in a textara that I styled.</p>
<p><a href="https://i.stack.imgur.com/vyyfi.png" rel="nofollow noreferrer">Example right here of stylized file</a></p>
<p>Thank you in advance for your lights !</p>
<p><a href="https://i.stack.imgur.com/y6Cy9.png" rel="nofollow noreferrer">Exemple result display</a></p>
<p>I tried to use fopen in order to be able to open the file and read it but I cannot convert my string into an html tag.</p>
|
[
{
"answer_id": 74543400,
"author": "Chris",
"author_id": 15261315,
"author_profile": "https://Stackoverflow.com/users/15261315",
"pm_score": 3,
"selected": true,
"text": ">>> re.findall(r'([A-Z][a-zA-Z].*?)\\s*(?=[A-Z][a-zA-Z]|$)', text)\n['Date: 20/8/2020', 'Duration: 0.33', 'IP: 110.1.x.x', 'Server:01']\n >>> dict(re.split(r'\\s*:\\s*', m, 1) for m in re.findall(r'([A-Z][a-zA\n-Z].*?)\\s*(?=[A-Z][a-zA-Z]|$)', text))\n{'Date': '20/8/2020', 'Duration': '0.33', 'IP': '110.1.x.x', 'Server': '01'}\n"
},
{
"answer_id": 74546805,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 0,
"selected": false,
"text": "(?<!\\S)[A-Z][a-zA-Z]*:\\s*\\S+\n (?<!\\S) [A-Z][a-zA-Z]*: : \\s*\\S import re\n\npattern = r\"(?<!\\S)[A-Z][a-zA-Z]*:\\s*\\S+\"\ns = \"Date: 20/8/2020 Duration: 0.33 IP: 110.1.x.x Server:01\"\nprint(re.findall(pattern, s))\n ['Date: 20/8/2020', 'Duration: 0.33', 'IP: 110.1.x.x', 'Server:01']\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20579566/"
] |
74,543,332
|
<p>I have a Databricks workspace through Azure, and I use the Databricks Job API to run some python scripts that create files.</p>
<p>I want to know if I can retrieve these files created after the job is finished running.</p>
<ul>
<li>In Azure, I see a storage account that is associated with the databricks workspace, in the containers, there's a 'job' entry. When I try to access this, I get a <code>DenyAssignmentAuthorizationFailed</code> error. I am organisation admin, so getting the right permissions shouldn't be a problem, although I wouldn't know why I don't have access already and presume it's a databricks thing.</li>
<li>I tried googling and looking through Azure's docs, but there's surprisingly little documentation on Databricks Jobs or its data storage.</li>
</ul>
<p>Below you find our Job code. This is called over the Jobs API.</p>
<pre class="lang-py prettyprint-override"><code># Parse job info
info = dbutils.notebook.entry_point.getDbutils().notebook().getContext().toJson()
info = json.loads(info)
RUN_ID = info.get("tags").get("multitaskParentRunId", "no_run_id")
# Create directory
run_directory = f"/databricks/driver/training_runs/{RUN_ID}"
dbutils.fs.mkdirs(f"file:{run_directory}")
with open(f"{run_directory}/file.txt", "w") as file_:
file_.write("Hello world :)")
</code></pre>
|
[
{
"answer_id": 74544845,
"author": "Saideep Arikontham",
"author_id": 18844585,
"author_profile": "https://Stackoverflow.com/users/18844585",
"pm_score": 2,
"selected": true,
"text": "file:/databricks/driver/training_runs dbutils.fs.ls(\"file:/databricks/driver/training_runs/<your_run_id>/\")\n\n#OR\n\n#import os\n#print(os.listdir(\"/databricks/driver/training_runs/demo\"))\n Admin Console ->Workspace settings -> DBFS File Browser file:/databricks/driver/training_runs run_directory = f\"/FileStore/training_runs/demo\"\ndbutils.fs.mkdirs(f\"dbfs:{run_directory}\")\n\nwith open(f\"/dbfs{run_directory}/file.txt\", \"w\") as file_:\n file_.write(\"Hello world :)\")\n Data -> browse DBFS -> FileStore"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11360794/"
] |
74,543,334
|
<p>I have a matrix:</p>
<pre><code>contingency.table.1 <- structure(c(40, 5, 1, 0, 24, 8, 0, 1, 2, 1, 1, 0, 0, 1, 0, 1), .Dim = c(4L,
4L), .Dimnames = list(col1 = c("0", "1", "2", "3"), col2 = c("0",
"1", "2", "3")), class = "table")
</code></pre>
<p>Then, if I meet 0 on the diagonal of the matrix, then I replace it with 1</p>
<pre><code>contingency.table.1[row(contingency.table.1) ==
col(contingency.table.1) & contingency.table.1 == 0] <- 1
</code></pre>
<p>I would like to get a matrix, if there are 0 on the symmetric position, then replace them both with 1</p>
<p>What I want to get:</p>
<pre><code>contingency.table.1 <- structure(c(40, 5, 1, 1, 24, 8, 0, 1, 2, 1, 1, 0, 1, 1, 0, 1), .Dim = c(4L,
4L), .Dimnames = list(col1 = c("0", "1", "2", "3"), col2 = c("0",
"1", "2", "3")), class = "table")
</code></pre>
<p>if both zeros are in symmetrical positions, then replace them with 1</p>
|
[
{
"answer_id": 74543689,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 1,
"selected": false,
"text": "for rp <- \\(m) {\n stopifnot(diff(dim(m)) == 0L) ## symmetricity check\n for (i in seq_len(ncol(m)) - 1L) {\n c1 <- n - i\n c2 <- i + 1L\n if (all(c(m[c1, c2], m[c2, c1]) == 0))\n m[c1, c2] <- m[c2, c1] <- 1\n }\n m\n}\n\nrp(contingency.table.1)\n# col2\n# col1 0 1 2 3\n# 0 40 24 2 1\n# 1 5 8 1 1\n# 2 1 0 1 0\n# 3 1 1 0 1\n"
},
{
"answer_id": 74543750,
"author": "Allan Cameron",
"author_id": 12500315,
"author_profile": "https://Stackoverflow.com/users/12500315",
"pm_score": 1,
"selected": true,
"text": "m <- contingency.table.1 \ncontingency.table.1[m == t(m) & m == 0] <- 1\n contingency.table.1\n#> col2\n#> col1 0 1 2 3\n#> 0 40 24 2 1\n#> 1 5 8 1 1\n#> 2 1 0 1 1\n#> 3 1 1 1 1\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16160487/"
] |
74,543,339
|
<p>I know, there's <a href="https://stackoverflow.com/questions/30179272/fixed-div-overflow-is-off-screen">Fixed Div Overflow is Off Screen</a>, I have a similar but still different problem: my DIV isn't always 100% of the page's height, so <code>bottom:0px</code> won't work for me.<br />
I have a DIV fixed to the top right corner of the page which has some contents, one of them is another div with a variable amount of content. Sometimes the content gets too much and both DIVs expand to contain it - it goes over the edge of the page and doesn't scroll. Here's my code (there's only JS code because the JavaScript generates the HTML and CSS as a widget):</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// The plain text in this function (except error messages) is in German because it's for my German website.
function nachrichtenwidgetAnzeigen() {
const nw = document.createElement('div');
nw.id = 'nachrichtenwidget';
nw.hidden = true;
nw.style = 'position:fixed;top:0px;right:0px;max-height:calc(100%-3px);max-width:33%;border-left:1px solid blue;border-bottom:1px solid blue;border-bottom-left-radius:6px;background-color:rgba(0,255,0,0.3);color:rgba(0,0,0,0);/*pointer-events:none;opacity:80%;*/';
nw.nachrichten = document.createElement('div');
nw.nachrichten.id = 'nachrichten';
nw.nachrichten.style = 'color:white;background-color:rgba(0,0,0,0);overflow-x: clip;overflow-y:auto;';
nw.nachrichten.addMsg = nw.addMsg = function(msg, iconURL=undefined, msgTimeout=10_000, options={color:'white',bgColor:'blue',onclickaction:''}) { // Einfach msgTimeout=-1 setzen, um eine permanente Nachricht zu erstellen.
const msgElmnt = document.createElement('div');
try {
if (typeof options.onclickaction === 'function') {
msgElmnt.addEventListener('click', (e) => {
msgElmnt.close();
options.onclickaction();
});
} else if (typeof options.onclickaction === 'string') {
msgElmnt.addEventListener('click', (e) => {
msgElmnt.close();
Function(options.onclickaction)();
});
} else {
throw new TypeError(`options.onclickaction isn\'t of type "function" or "string" (is of type "${typeof options.onclickaction}")!`);
}
} catch (e) {
console.warn('Couldn\'t assign onclickaction to message, ignoring that.');
console.warn(e);
}
// msgElmnt.style = 'pointer-events:auto;';
if (iconURL!==undefined) {
msgElmnt.msgImg = document.createElement('img');
msgElmnt.msgImg.style = 'max-width:33px;max-height:33px;padding-right:3px;';
msgElmnt.msgImg.src = iconURL;
msgElmnt.appendChild(msgElmnt.msgImg);
} else {
msgElmnt.msgImg = undefined;
}
msgElmnt.innerHTML += msg;
msgElmnt.id = `msg-${msg.replace(/[^a-z0-9]/gi, '-').toLowerCase()}`;
msgElmnt.style = 'background-color:blue;color:white;padding:3px;margin:3px;border:0px solid blue;border-radius:3px;display:flex;flex-direction:row;';
if (msgTimeout >= 0) {
msgElmnt.style.flexWrap = 'wrap'; // Nur wenn eine Nachrichtenanzeigedauer existiert: flex-wrap auf 'wrap' stellen.
}
msgElmnt.timeout = document.createElement('div');
msgElmnt.timeout.style = 'width:100%;height:3px;border:0px solid blue;border-radius:3px;color:rgba(0,0,0,0);background-color:grey;flex:0 0 100%;';
msgElmnt.timeout.bar = document.createElement('div');
msgElmnt.timeout.bar.style = 'width:100%;height:3px;border:0px solid blue;border-radius:3px;color:rgba(0,0,0,0);background-color:lightblue;';
async function animTimeout(e) {
msgElmnt.timeout.bar.animate([
{ width: '100%' },
{ width: '0%' }
], msgTimeout);
msgElmnt.timeoutAnimation = msgElmnt.timeout.bar.getAnimations()[0];
msgElmnt.timeoutAnimation.addEventListener('finish', (e) => {
msgElmnt.remove();
nw.countElmnt.innerText = nw.nachrichten.getElementsByTagName('div').length/3;
}); // Nachricht nach Ablauf der Animation entfernen
}
msgElmnt.addEventListener('mouseover', (e) => {
if (msgElmnt.timeoutAnimation) {
msgElmnt.timeoutAnimation.pause();
}
msgElmnt.style.border = '1px solid white';
msgElmnt.style.padding = '2px';
});
msgElmnt.addEventListener('mouseout', (e) => {
if (msgElmnt.timeoutAnimation) {
msgElmnt.timeoutAnimation.play();
}
msgElmnt.style.border = '0px solid blue';
msgElmnt.style.padding = '3px';
});
if (msgTimeout>=0) { msgElmnt.timeout.bar.addEventListener('click', animTimeout); } else { msgElmnt.timeout.hidden = true; }
msgElmnt.close = function() { /* Unscharf und durchsichtig animieren */msgElmnt.remove(); nw.countElmnt.innerText = nw.nachrichten.getElementsByTagName('div').length/3; };
msgElmnt.timeout.appendChild(msgElmnt.timeout.bar);
msgElmnt.timeout.bar.click();
msgElmnt.timeout.bar.removeEventListener('click', animTimeout);
msgElmnt.appendChild(msgElmnt.timeout);
nw.nachrichten.appendChild(msgElmnt);
nw.countElmnt.innerText = nw.nachrichten.getElementsByTagName('div').length/3; // Durch drei, weil jede Nachricht ein DIV-Element mit zwei DIV-Elementen ineinander darin ist.
return msgElmnt;
}
const nwClose = document.createElement('button');
const nwOpen = document.createElement('button');
nwClose.id = 'nwClose';
nwClose.hidden = true;
nwClose.innerText = '\xa0X\xa0'; // \xa0 entspricht der HTML-Entität &nbsp;
nwClose.title = 'Nachrichtenwidget ausblenden';
nwClose.style = 'background-color:red;border-radius:10px;';
nwClose.addEventListener('click', (e) => {
nwClose.hidden = true;
nw.hidden = true;
nwOpen.hidden = false;
});
nwOpen.id = 'nwOpen';
nwOpen.hidden = false;
nwOpen.title = 'Nachrichtenwidget einblenden';
nwOpen.style = 'position:fixed;top:0px;right:33px;background-color:green;';
nwOpen.addEventListener('click', (e) => {
nwOpen.hidden = true;
nw.hidden = false;
nwClose.hidden = false;
});
const nwTitle = document.createElement('span');
nwTitle.style = 'color:white;background-color:rgba(0,0,0,0);padding-left:3px;user-select:none;';
nwTitle.innerText = 'Seitennachrichten';
nw.countElmnt = document.createElement('span');
nw.countElmnt.style = 'color:white;background-color:rgba(0,0,0,0);padding:3px;user-select:none;';
document.body.appendChild(nw);
nwOpen.appendChild(nw.countElmnt);
document.body.appendChild(nwOpen);
nw.appendChild(nwClose);
nw.appendChild(nwTitle);
nw.appendChild(nw.nachrichten);
nwOpen.click();
return nw;
}
// Spawn the widget:
notifWidg = nachrichtenwidgetAnzeigen();
notifWidg.addMsg('This is a notification widget. You can close any notification by clicking on it.', 'https://www.lampe2020.de/favicon.ico', -1);
// Just to spawn some messages to show what happens:
setInterval(() => {
notifWidg.addMsg('Test notification', undefined, 10_000)
}, 1_000);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*
The main div:
div#nachrichtenwidget {
position:fixed;
top:0px;
right:0px;
max-width:33%;
max-height: calc(100%-3px);
...
}
The div with the variable content:
div#nachrichten {
overflow-x:clip;
overflow-y:auto;
...
*/</code></pre>
</div>
</div>
</p>
<p><a href="https://i.stack.imgur.com/dFUoc.png" rel="nofollow noreferrer">image of what I get with my old code vs. what I want (photoshopped because it doesn't work in its current state)</a></p>
|
[
{
"answer_id": 74543546,
"author": "Alex Dimitrov",
"author_id": 3945290,
"author_profile": "https://Stackoverflow.com/users/3945290",
"pm_score": 2,
"selected": false,
"text": ".sticky {\n width: 200px;\n height: 100vh;\n position: fixed;\n top: 0;\n right: 0;\n overflow: auto;\n}\n\n.sticky div {\n background: red;\n margin-bottom: 5px;\n height: 100px;\n} <p>Scroll the right boxes.</p>\n\n<div class=\"sticky\">\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n</div> .sticky {\n width: 200px;\n height: 100vh;\n position: fixed;\n top: 0;\n right: 0;\n \n display: flex;\n flex-direction: column;\n}\n\n.overflow {\n overflow: auto;\n flex: 1 1 auto;\n}\n\n.overflow div {\n background: red;\n margin-bottom: 5px;\n height: 100px;\n} <div class=\"sticky\">\n <h2>Heading</h2>\n <div class=\"overflow\">\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n </div>\n</div>"
},
{
"answer_id": 74543656,
"author": "Anas Mohammad Sheikh",
"author_id": 18045679,
"author_profile": "https://Stackoverflow.com/users/18045679",
"pm_score": 2,
"selected": true,
"text": "// The plain text in this function (except error messages) is in German because it's for my German website. \nfunction nachrichtenwidgetAnzeigen() {\n const nw = document.createElement('div');\n nw.id = 'nachrichtenwidget';\n nw.hidden = true;\n nw.style = 'position:fixed;top:0px;right:0px;max-height:calc(100%-3px);max-width:33%;border-left:1px solid blue;border-bottom:1px solid blue;border-bottom-left-radius:6px;background-color:rgba(0,255,0,0.3);color:rgba(0,0,0,0);/*pointer-events:none;opacity:80%;*/';\n nw.nachrichten = document.createElement('div');\n nw.nachrichten.id = 'nachrichten';\n nw.nachrichten.style = 'color:white;background-color:rgba(0,0,0,0);overflow-x: clip;overflow-y:auto;max-height:90vh';\n nw.nachrichten.addMsg = nw.addMsg = function(msg, iconURL=undefined, msgTimeout=10_000, options={color:'white',bgColor:'blue',onclickaction:''}) { // Einfach msgTimeout=-1 setzen, um eine permanente Nachricht zu erstellen.\n const msgElmnt = document.createElement('div');\n try {\n if (typeof options.onclickaction === 'function') {\n msgElmnt.addEventListener('click', (e) => {\n msgElmnt.close();\n options.onclickaction();\n });\n } else if (typeof options.onclickaction === 'string') {\n msgElmnt.addEventListener('click', (e) => {\n msgElmnt.close();\n Function(options.onclickaction)();\n });\n } else {\n throw new TypeError(`options.onclickaction isn\\'t of type \"function\" or \"string\" (is of type \"${typeof options.onclickaction}\")!`);\n }\n } catch (e) {\n console.warn('Couldn\\'t assign onclickaction to message, ignoring that.');\n console.warn(e);\n }\n // msgElmnt.style = 'pointer-events:auto;';\n if (iconURL!==undefined) {\n msgElmnt.msgImg = document.createElement('img');\n msgElmnt.msgImg.style = 'max-width:33px;max-height:33px;padding-right:3px;';\n msgElmnt.msgImg.src = iconURL;\n msgElmnt.appendChild(msgElmnt.msgImg);\n } else {\n msgElmnt.msgImg = undefined;\n }\n msgElmnt.innerHTML += msg;\n msgElmnt.id = `msg-${msg.replace(/[^a-z0-9]/gi, '-').toLowerCase()}`;\n msgElmnt.style = 'background-color:blue;color:white;padding:3px;margin:3px;border:0px solid blue;border-radius:3px;display:flex;flex-direction:row;';\n if (msgTimeout >= 0) {\n msgElmnt.style.flexWrap = 'wrap'; // Nur wenn eine Nachrichtenanzeigedauer existiert: flex-wrap auf 'wrap' stellen.\n }\n msgElmnt.timeout = document.createElement('div');\n msgElmnt.timeout.style = 'width:100%;height:3px;border:0px solid blue;border-radius:3px;color:rgba(0,0,0,0);background-color:grey;flex:0 0 100%;';\n msgElmnt.timeout.bar = document.createElement('div');\n msgElmnt.timeout.bar.style = 'width:100%;height:3px;border:0px solid blue;border-radius:3px;color:rgba(0,0,0,0);background-color:lightblue;';\n async function animTimeout(e) {\n msgElmnt.timeout.bar.animate([\n { width: '100%' },\n { width: '0%' }\n ], msgTimeout);\n msgElmnt.timeoutAnimation = msgElmnt.timeout.bar.getAnimations()[0];\n msgElmnt.timeoutAnimation.addEventListener('finish', (e) => {\n msgElmnt.remove();\n nw.countElmnt.innerText = nw.nachrichten.getElementsByTagName('div').length/3;\n }); // Nachricht nach Ablauf der Animation entfernen\n }\n msgElmnt.addEventListener('mouseover', (e) => {\n if (msgElmnt.timeoutAnimation) {\n msgElmnt.timeoutAnimation.pause();\n }\n msgElmnt.style.border = '1px solid white';\n msgElmnt.style.padding = '2px';\n });\n msgElmnt.addEventListener('mouseout', (e) => {\n if (msgElmnt.timeoutAnimation) {\n msgElmnt.timeoutAnimation.play();\n }\n msgElmnt.style.border = '0px solid blue';\n msgElmnt.style.padding = '3px';\n });\n if (msgTimeout>=0) { msgElmnt.timeout.bar.addEventListener('click', animTimeout); } else { msgElmnt.timeout.hidden = true; }\n msgElmnt.close = function() { /* Unscharf und durchsichtig animieren */msgElmnt.remove(); nw.countElmnt.innerText = nw.nachrichten.getElementsByTagName('div').length/3; };\n msgElmnt.timeout.appendChild(msgElmnt.timeout.bar);\n msgElmnt.timeout.bar.click();\n msgElmnt.timeout.bar.removeEventListener('click', animTimeout);\n msgElmnt.appendChild(msgElmnt.timeout);\n nw.nachrichten.appendChild(msgElmnt);\n nw.countElmnt.innerText = nw.nachrichten.getElementsByTagName('div').length/3; // Durch drei, weil jede Nachricht ein DIV-Element mit zwei DIV-Elementen ineinander darin ist.\n return msgElmnt;\n }\n const nwClose = document.createElement('button');\n const nwOpen = document.createElement('button');\n nwClose.id = 'nwClose';\n nwClose.hidden = true;\n nwClose.innerText = '\\xa0X\\xa0'; // \\xa0 entspricht der HTML-Entität \n nwClose.title = 'Nachrichtenwidget ausblenden';\n nwClose.style = 'background-color:red;border-radius:10px;';\n nwClose.addEventListener('click', (e) => {\n nwClose.hidden = true;\n nw.hidden = true;\n nwOpen.hidden = false;\n });\n nwOpen.id = 'nwOpen';\n nwOpen.hidden = false;\n nwOpen.title = 'Nachrichtenwidget einblenden';\n nwOpen.style = 'position:fixed;top:0px;right:33px;background-color:green;';\n nwOpen.addEventListener('click', (e) => {\n nwOpen.hidden = true;\n nw.hidden = false;\n nwClose.hidden = false;\n });\n const nwTitle = document.createElement('span');\n nwTitle.style = 'color:white;background-color:rgba(0,0,0,0);padding-left:3px;user-select:none;';\n nwTitle.innerText = 'Seitennachrichten';\n nw.countElmnt = document.createElement('span');\n nw.countElmnt.style = 'color:white;background-color:rgba(0,0,0,0);padding:3px;user-select:none;';\n document.body.appendChild(nw);\n nwOpen.appendChild(nw.countElmnt);\n document.body.appendChild(nwOpen);\n nw.appendChild(nwClose);\n nw.appendChild(nwTitle);\n nw.appendChild(nw.nachrichten);\n nwOpen.click();\n return nw;\n}\n\n// Spawn the widget: \nnotifWidg = nachrichtenwidgetAnzeigen();\nnotifWidg.addMsg('This is a notification widget. You can close any notification by clicking on it.', 'https://www.lampe2020.de/favicon.ico', -1);\n\n// Just to spawn some messages to show what happens: \nsetInterval(() => {\n notifWidg.addMsg('Test notification', undefined, 10_000)\n}, 500);"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17865928/"
] |
74,543,346
|
<p>I am trying multithreading in java for the first time. My problem statement is to fetch the data from an api for multiple months together. Therefor I tried 2-3 things and stuck with the below code. I am getting null value while printing f.get(). Anyone who can explain why it is printing null value for all?</p>
<pre><code>class StyleThreadDemo implements Callable<String>{
private Integer n;
public StyleThreadDemo(int a){
this.setN(a);
}
public String callApi() throws Exception {
String output=null;
try {
URL url = new URL("https://api.publicapis.org/entries");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
System.out.println("Data starting coming .... \n");
while ((output = br.readLine()) != null) {
System.out.println("result "+ n );
}
conn.disconnect();
}catch(Exception e) {
e.printStackTrace();
}
return output;
}
@Override
public String call() throws Exception {
String s=callApi();
return s;
}
public Integer getN() {
return n;
}
public void setN(Integer n) {
this.n = n;
}
}
public class StyleThread {
public static void shutdownAndAwaitTermination(ExecutorService executorService) {
executorService.shutdown();
try {
if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException ie) {
executorService.shutdownNow();
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws Exception
{
StyleThread styleThread = new StyleThread();
ExecutorService pool = Executors.newFixedThreadPool(30);
int n = 5; // Number of threads
List<StyleThreadDemo> tasks= new ArrayList<StyleThreadDemo>();
// List<Future<String>> futures = new ArrayList<>();
for (int i = 0; i < n; i++) {
// Future<String> result= pool.submit(new StyleThreadDemo(i));
// futures.add(result);
tasks.add(new StyleThreadDemo(i));
System.out.println("task added "+i);
}
List<Future<String>> futures=pool.invokeAll(tasks);
shutdownAndAwaitTermination(pool);
for (Future<String> f : futures) {
System.out.println("printing :+f.get());
}
}
}
</code></pre>
|
[
{
"answer_id": 74543546,
"author": "Alex Dimitrov",
"author_id": 3945290,
"author_profile": "https://Stackoverflow.com/users/3945290",
"pm_score": 2,
"selected": false,
"text": ".sticky {\n width: 200px;\n height: 100vh;\n position: fixed;\n top: 0;\n right: 0;\n overflow: auto;\n}\n\n.sticky div {\n background: red;\n margin-bottom: 5px;\n height: 100px;\n} <p>Scroll the right boxes.</p>\n\n<div class=\"sticky\">\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n</div> .sticky {\n width: 200px;\n height: 100vh;\n position: fixed;\n top: 0;\n right: 0;\n \n display: flex;\n flex-direction: column;\n}\n\n.overflow {\n overflow: auto;\n flex: 1 1 auto;\n}\n\n.overflow div {\n background: red;\n margin-bottom: 5px;\n height: 100px;\n} <div class=\"sticky\">\n <h2>Heading</h2>\n <div class=\"overflow\">\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n </div>\n</div>"
},
{
"answer_id": 74543656,
"author": "Anas Mohammad Sheikh",
"author_id": 18045679,
"author_profile": "https://Stackoverflow.com/users/18045679",
"pm_score": 2,
"selected": true,
"text": "// The plain text in this function (except error messages) is in German because it's for my German website. \nfunction nachrichtenwidgetAnzeigen() {\n const nw = document.createElement('div');\n nw.id = 'nachrichtenwidget';\n nw.hidden = true;\n nw.style = 'position:fixed;top:0px;right:0px;max-height:calc(100%-3px);max-width:33%;border-left:1px solid blue;border-bottom:1px solid blue;border-bottom-left-radius:6px;background-color:rgba(0,255,0,0.3);color:rgba(0,0,0,0);/*pointer-events:none;opacity:80%;*/';\n nw.nachrichten = document.createElement('div');\n nw.nachrichten.id = 'nachrichten';\n nw.nachrichten.style = 'color:white;background-color:rgba(0,0,0,0);overflow-x: clip;overflow-y:auto;max-height:90vh';\n nw.nachrichten.addMsg = nw.addMsg = function(msg, iconURL=undefined, msgTimeout=10_000, options={color:'white',bgColor:'blue',onclickaction:''}) { // Einfach msgTimeout=-1 setzen, um eine permanente Nachricht zu erstellen.\n const msgElmnt = document.createElement('div');\n try {\n if (typeof options.onclickaction === 'function') {\n msgElmnt.addEventListener('click', (e) => {\n msgElmnt.close();\n options.onclickaction();\n });\n } else if (typeof options.onclickaction === 'string') {\n msgElmnt.addEventListener('click', (e) => {\n msgElmnt.close();\n Function(options.onclickaction)();\n });\n } else {\n throw new TypeError(`options.onclickaction isn\\'t of type \"function\" or \"string\" (is of type \"${typeof options.onclickaction}\")!`);\n }\n } catch (e) {\n console.warn('Couldn\\'t assign onclickaction to message, ignoring that.');\n console.warn(e);\n }\n // msgElmnt.style = 'pointer-events:auto;';\n if (iconURL!==undefined) {\n msgElmnt.msgImg = document.createElement('img');\n msgElmnt.msgImg.style = 'max-width:33px;max-height:33px;padding-right:3px;';\n msgElmnt.msgImg.src = iconURL;\n msgElmnt.appendChild(msgElmnt.msgImg);\n } else {\n msgElmnt.msgImg = undefined;\n }\n msgElmnt.innerHTML += msg;\n msgElmnt.id = `msg-${msg.replace(/[^a-z0-9]/gi, '-').toLowerCase()}`;\n msgElmnt.style = 'background-color:blue;color:white;padding:3px;margin:3px;border:0px solid blue;border-radius:3px;display:flex;flex-direction:row;';\n if (msgTimeout >= 0) {\n msgElmnt.style.flexWrap = 'wrap'; // Nur wenn eine Nachrichtenanzeigedauer existiert: flex-wrap auf 'wrap' stellen.\n }\n msgElmnt.timeout = document.createElement('div');\n msgElmnt.timeout.style = 'width:100%;height:3px;border:0px solid blue;border-radius:3px;color:rgba(0,0,0,0);background-color:grey;flex:0 0 100%;';\n msgElmnt.timeout.bar = document.createElement('div');\n msgElmnt.timeout.bar.style = 'width:100%;height:3px;border:0px solid blue;border-radius:3px;color:rgba(0,0,0,0);background-color:lightblue;';\n async function animTimeout(e) {\n msgElmnt.timeout.bar.animate([\n { width: '100%' },\n { width: '0%' }\n ], msgTimeout);\n msgElmnt.timeoutAnimation = msgElmnt.timeout.bar.getAnimations()[0];\n msgElmnt.timeoutAnimation.addEventListener('finish', (e) => {\n msgElmnt.remove();\n nw.countElmnt.innerText = nw.nachrichten.getElementsByTagName('div').length/3;\n }); // Nachricht nach Ablauf der Animation entfernen\n }\n msgElmnt.addEventListener('mouseover', (e) => {\n if (msgElmnt.timeoutAnimation) {\n msgElmnt.timeoutAnimation.pause();\n }\n msgElmnt.style.border = '1px solid white';\n msgElmnt.style.padding = '2px';\n });\n msgElmnt.addEventListener('mouseout', (e) => {\n if (msgElmnt.timeoutAnimation) {\n msgElmnt.timeoutAnimation.play();\n }\n msgElmnt.style.border = '0px solid blue';\n msgElmnt.style.padding = '3px';\n });\n if (msgTimeout>=0) { msgElmnt.timeout.bar.addEventListener('click', animTimeout); } else { msgElmnt.timeout.hidden = true; }\n msgElmnt.close = function() { /* Unscharf und durchsichtig animieren */msgElmnt.remove(); nw.countElmnt.innerText = nw.nachrichten.getElementsByTagName('div').length/3; };\n msgElmnt.timeout.appendChild(msgElmnt.timeout.bar);\n msgElmnt.timeout.bar.click();\n msgElmnt.timeout.bar.removeEventListener('click', animTimeout);\n msgElmnt.appendChild(msgElmnt.timeout);\n nw.nachrichten.appendChild(msgElmnt);\n nw.countElmnt.innerText = nw.nachrichten.getElementsByTagName('div').length/3; // Durch drei, weil jede Nachricht ein DIV-Element mit zwei DIV-Elementen ineinander darin ist.\n return msgElmnt;\n }\n const nwClose = document.createElement('button');\n const nwOpen = document.createElement('button');\n nwClose.id = 'nwClose';\n nwClose.hidden = true;\n nwClose.innerText = '\\xa0X\\xa0'; // \\xa0 entspricht der HTML-Entität \n nwClose.title = 'Nachrichtenwidget ausblenden';\n nwClose.style = 'background-color:red;border-radius:10px;';\n nwClose.addEventListener('click', (e) => {\n nwClose.hidden = true;\n nw.hidden = true;\n nwOpen.hidden = false;\n });\n nwOpen.id = 'nwOpen';\n nwOpen.hidden = false;\n nwOpen.title = 'Nachrichtenwidget einblenden';\n nwOpen.style = 'position:fixed;top:0px;right:33px;background-color:green;';\n nwOpen.addEventListener('click', (e) => {\n nwOpen.hidden = true;\n nw.hidden = false;\n nwClose.hidden = false;\n });\n const nwTitle = document.createElement('span');\n nwTitle.style = 'color:white;background-color:rgba(0,0,0,0);padding-left:3px;user-select:none;';\n nwTitle.innerText = 'Seitennachrichten';\n nw.countElmnt = document.createElement('span');\n nw.countElmnt.style = 'color:white;background-color:rgba(0,0,0,0);padding:3px;user-select:none;';\n document.body.appendChild(nw);\n nwOpen.appendChild(nw.countElmnt);\n document.body.appendChild(nwOpen);\n nw.appendChild(nwClose);\n nw.appendChild(nwTitle);\n nw.appendChild(nw.nachrichten);\n nwOpen.click();\n return nw;\n}\n\n// Spawn the widget: \nnotifWidg = nachrichtenwidgetAnzeigen();\nnotifWidg.addMsg('This is a notification widget. You can close any notification by clicking on it.', 'https://www.lampe2020.de/favicon.ico', -1);\n\n// Just to spawn some messages to show what happens: \nsetInterval(() => {\n notifWidg.addMsg('Test notification', undefined, 10_000)\n}, 500);"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20579549/"
] |
74,543,352
|
<p>So I have a table with columns:</p>
<p>UID_person, UID_personHead, Firstname, LastName</p>
<p>The value of UID_personhead is equivalent to UID_person. UID_personHead is the UID_person of managers
So I want to query it and return something like</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>UID_person</th>
<th>FirstName</th>
<th>LastName</th>
<th>Name of manager using the UID_personHead</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Sarah</td>
<td>Smith</td>
<td>Jack</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Smith</td>
<td>David</td>
</tr>
</tbody>
</table>
</div>
<p>I tried this query</p>
<pre><code>SELECT UID_Person, FirstName, LastName
(SELECT FirstName
from person WHERE UID_person IN (SELECT UID_PersonHead From person)) AS Name of the manager
</code></pre>
|
[
{
"answer_id": 74543546,
"author": "Alex Dimitrov",
"author_id": 3945290,
"author_profile": "https://Stackoverflow.com/users/3945290",
"pm_score": 2,
"selected": false,
"text": ".sticky {\n width: 200px;\n height: 100vh;\n position: fixed;\n top: 0;\n right: 0;\n overflow: auto;\n}\n\n.sticky div {\n background: red;\n margin-bottom: 5px;\n height: 100px;\n} <p>Scroll the right boxes.</p>\n\n<div class=\"sticky\">\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n</div> .sticky {\n width: 200px;\n height: 100vh;\n position: fixed;\n top: 0;\n right: 0;\n \n display: flex;\n flex-direction: column;\n}\n\n.overflow {\n overflow: auto;\n flex: 1 1 auto;\n}\n\n.overflow div {\n background: red;\n margin-bottom: 5px;\n height: 100px;\n} <div class=\"sticky\">\n <h2>Heading</h2>\n <div class=\"overflow\">\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n <div></div>\n </div>\n</div>"
},
{
"answer_id": 74543656,
"author": "Anas Mohammad Sheikh",
"author_id": 18045679,
"author_profile": "https://Stackoverflow.com/users/18045679",
"pm_score": 2,
"selected": true,
"text": "// The plain text in this function (except error messages) is in German because it's for my German website. \nfunction nachrichtenwidgetAnzeigen() {\n const nw = document.createElement('div');\n nw.id = 'nachrichtenwidget';\n nw.hidden = true;\n nw.style = 'position:fixed;top:0px;right:0px;max-height:calc(100%-3px);max-width:33%;border-left:1px solid blue;border-bottom:1px solid blue;border-bottom-left-radius:6px;background-color:rgba(0,255,0,0.3);color:rgba(0,0,0,0);/*pointer-events:none;opacity:80%;*/';\n nw.nachrichten = document.createElement('div');\n nw.nachrichten.id = 'nachrichten';\n nw.nachrichten.style = 'color:white;background-color:rgba(0,0,0,0);overflow-x: clip;overflow-y:auto;max-height:90vh';\n nw.nachrichten.addMsg = nw.addMsg = function(msg, iconURL=undefined, msgTimeout=10_000, options={color:'white',bgColor:'blue',onclickaction:''}) { // Einfach msgTimeout=-1 setzen, um eine permanente Nachricht zu erstellen.\n const msgElmnt = document.createElement('div');\n try {\n if (typeof options.onclickaction === 'function') {\n msgElmnt.addEventListener('click', (e) => {\n msgElmnt.close();\n options.onclickaction();\n });\n } else if (typeof options.onclickaction === 'string') {\n msgElmnt.addEventListener('click', (e) => {\n msgElmnt.close();\n Function(options.onclickaction)();\n });\n } else {\n throw new TypeError(`options.onclickaction isn\\'t of type \"function\" or \"string\" (is of type \"${typeof options.onclickaction}\")!`);\n }\n } catch (e) {\n console.warn('Couldn\\'t assign onclickaction to message, ignoring that.');\n console.warn(e);\n }\n // msgElmnt.style = 'pointer-events:auto;';\n if (iconURL!==undefined) {\n msgElmnt.msgImg = document.createElement('img');\n msgElmnt.msgImg.style = 'max-width:33px;max-height:33px;padding-right:3px;';\n msgElmnt.msgImg.src = iconURL;\n msgElmnt.appendChild(msgElmnt.msgImg);\n } else {\n msgElmnt.msgImg = undefined;\n }\n msgElmnt.innerHTML += msg;\n msgElmnt.id = `msg-${msg.replace(/[^a-z0-9]/gi, '-').toLowerCase()}`;\n msgElmnt.style = 'background-color:blue;color:white;padding:3px;margin:3px;border:0px solid blue;border-radius:3px;display:flex;flex-direction:row;';\n if (msgTimeout >= 0) {\n msgElmnt.style.flexWrap = 'wrap'; // Nur wenn eine Nachrichtenanzeigedauer existiert: flex-wrap auf 'wrap' stellen.\n }\n msgElmnt.timeout = document.createElement('div');\n msgElmnt.timeout.style = 'width:100%;height:3px;border:0px solid blue;border-radius:3px;color:rgba(0,0,0,0);background-color:grey;flex:0 0 100%;';\n msgElmnt.timeout.bar = document.createElement('div');\n msgElmnt.timeout.bar.style = 'width:100%;height:3px;border:0px solid blue;border-radius:3px;color:rgba(0,0,0,0);background-color:lightblue;';\n async function animTimeout(e) {\n msgElmnt.timeout.bar.animate([\n { width: '100%' },\n { width: '0%' }\n ], msgTimeout);\n msgElmnt.timeoutAnimation = msgElmnt.timeout.bar.getAnimations()[0];\n msgElmnt.timeoutAnimation.addEventListener('finish', (e) => {\n msgElmnt.remove();\n nw.countElmnt.innerText = nw.nachrichten.getElementsByTagName('div').length/3;\n }); // Nachricht nach Ablauf der Animation entfernen\n }\n msgElmnt.addEventListener('mouseover', (e) => {\n if (msgElmnt.timeoutAnimation) {\n msgElmnt.timeoutAnimation.pause();\n }\n msgElmnt.style.border = '1px solid white';\n msgElmnt.style.padding = '2px';\n });\n msgElmnt.addEventListener('mouseout', (e) => {\n if (msgElmnt.timeoutAnimation) {\n msgElmnt.timeoutAnimation.play();\n }\n msgElmnt.style.border = '0px solid blue';\n msgElmnt.style.padding = '3px';\n });\n if (msgTimeout>=0) { msgElmnt.timeout.bar.addEventListener('click', animTimeout); } else { msgElmnt.timeout.hidden = true; }\n msgElmnt.close = function() { /* Unscharf und durchsichtig animieren */msgElmnt.remove(); nw.countElmnt.innerText = nw.nachrichten.getElementsByTagName('div').length/3; };\n msgElmnt.timeout.appendChild(msgElmnt.timeout.bar);\n msgElmnt.timeout.bar.click();\n msgElmnt.timeout.bar.removeEventListener('click', animTimeout);\n msgElmnt.appendChild(msgElmnt.timeout);\n nw.nachrichten.appendChild(msgElmnt);\n nw.countElmnt.innerText = nw.nachrichten.getElementsByTagName('div').length/3; // Durch drei, weil jede Nachricht ein DIV-Element mit zwei DIV-Elementen ineinander darin ist.\n return msgElmnt;\n }\n const nwClose = document.createElement('button');\n const nwOpen = document.createElement('button');\n nwClose.id = 'nwClose';\n nwClose.hidden = true;\n nwClose.innerText = '\\xa0X\\xa0'; // \\xa0 entspricht der HTML-Entität \n nwClose.title = 'Nachrichtenwidget ausblenden';\n nwClose.style = 'background-color:red;border-radius:10px;';\n nwClose.addEventListener('click', (e) => {\n nwClose.hidden = true;\n nw.hidden = true;\n nwOpen.hidden = false;\n });\n nwOpen.id = 'nwOpen';\n nwOpen.hidden = false;\n nwOpen.title = 'Nachrichtenwidget einblenden';\n nwOpen.style = 'position:fixed;top:0px;right:33px;background-color:green;';\n nwOpen.addEventListener('click', (e) => {\n nwOpen.hidden = true;\n nw.hidden = false;\n nwClose.hidden = false;\n });\n const nwTitle = document.createElement('span');\n nwTitle.style = 'color:white;background-color:rgba(0,0,0,0);padding-left:3px;user-select:none;';\n nwTitle.innerText = 'Seitennachrichten';\n nw.countElmnt = document.createElement('span');\n nw.countElmnt.style = 'color:white;background-color:rgba(0,0,0,0);padding:3px;user-select:none;';\n document.body.appendChild(nw);\n nwOpen.appendChild(nw.countElmnt);\n document.body.appendChild(nwOpen);\n nw.appendChild(nwClose);\n nw.appendChild(nwTitle);\n nw.appendChild(nw.nachrichten);\n nwOpen.click();\n return nw;\n}\n\n// Spawn the widget: \nnotifWidg = nachrichtenwidgetAnzeigen();\nnotifWidg.addMsg('This is a notification widget. You can close any notification by clicking on it.', 'https://www.lampe2020.de/favicon.ico', -1);\n\n// Just to spawn some messages to show what happens: \nsetInterval(() => {\n notifWidg.addMsg('Test notification', undefined, 10_000)\n}, 500);"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16302625/"
] |
74,543,375
|
<p>I have a container with a lighter background color (light green with opacity of 50%) and the container shadow color is dark black (opacity 100%). Because of darker shadow color my container color got disrupt.</p>
<p>Means my shadow color is much darker then the continer color...Please do help. Thanks in advance.</p>
<p><a href="https://i.stack.imgur.com/cgNSK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cgNSK.png" alt="enter image description here" /></a></p>
<p>this is what I have done.</p>
<p><a href="https://i.stack.imgur.com/cINBq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cINBq.png" alt="enter image description here" /></a></p>
<p>the output I want.</p>
<pre><code>child: Container(
height: 100.0,
decoration: BoxDecoration(
border: Border.all(
width: 1.0,
color: const Color.fromRGBO(3, 60, 9, 0.5),
),
boxShadow: const [
BoxShadow(
spreadRadius: 0,
blurRadius: 9,
color: Colors.black,
),
],
color: const Color.fromRGBO(167, 212, 172, 0.2),
borderRadius: BorderRadius.circular(5),
),
child: Center(
child: ListTile(
leading: Icon(
Icons.person_pin,
size: 60,
color: pColor,
),
title: Text(
'My Profile',
style: TextStyle(
color: pColor,
fontFamily: robotoBold,
fontWeight: FontWeight.w700,
fontSize: 20,
),
),
subtitle: Text(
'Tap to See your Profile',
style: TextStyle(
color: pColor,
fontFamily: robotoReg,
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
trailing: const Icon(
Icons.navigate_next_outlined,
size: 40,
color: Color.fromRGBO(153, 153, 153, 1),
),
),
),
),
</code></pre>
<pre><code></code></pre>
|
[
{
"answer_id": 74543495,
"author": "VincentDR",
"author_id": 19540575,
"author_profile": "https://Stackoverflow.com/users/19540575",
"pm_score": 2,
"selected": false,
"text": "boxShadow: const [\n BoxShadow(\n blurStyle: BlurStyle.outer,\n spreadRadius: 0,\n blurRadius: 15,\n color: Colors.black,\n ),\n],\n"
},
{
"answer_id": 74543725,
"author": "Amr Bakr",
"author_id": 11780811,
"author_profile": "https://Stackoverflow.com/users/11780811",
"pm_score": 1,
"selected": false,
"text": " **blurStyle: BlurStyle.outer,**\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10086039/"
] |
74,543,383
|
<p>Existing Dataframe :</p>
<pre><code>Id event time_spent_in_sec
A in 0
A step_1 2.2
A step_2 3
A done 3
B in 0
B step_1 5
B step_2 8
B step_3 15
B done 7
</code></pre>
<p>Expected Dataframe :</p>
<pre><code>Id event time_spent_in_sec
A in 2.2
A step_1 3
A step_2 3
A done 0
B in 5
B step_1 8
B step_2 15
B step_3 7
B done 0
</code></pre>
<p>I am looking to shift the value in a column <strong>time_spent_in_sec</strong> and fill last row of each unique Id by 0.</p>
<p>I tried using <code>shift(1)</code> but stuck with filling the last row with 0</p>
|
[
{
"answer_id": 74543507,
"author": "T C Molenaar",
"author_id": 8814131,
"author_profile": "https://Stackoverflow.com/users/8814131",
"pm_score": 1,
"selected": false,
"text": ".fillna() df.time_spent_in_sec.shift(-1).fillna(df.time_spent_in_sec[0])\n df.time_spent_in_sec.shift(-1, fill_value = df.time_spent_in_sec[0])\n"
},
{
"answer_id": 74543533,
"author": "Guy",
"author_id": 5168011,
"author_profile": "https://Stackoverflow.com/users/5168011",
"pm_score": 3,
"selected": true,
"text": "df['time_spent_in_sec'] = np.roll(df['time_spent_in_sec'], -1)\n"
},
{
"answer_id": 74543608,
"author": "Enrique Benito Casado",
"author_id": 3844270,
"author_profile": "https://Stackoverflow.com/users/3844270",
"pm_score": 1,
"selected": false,
"text": "list_col = list(df[\"time_spent_in_sec\"])\nlist_col.append(list_col.pop(0))\ndf[\"time_spent_in_sec\"] = list_col.copy()\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19303365/"
] |
74,543,384
|
<p>I want to Request a Calendar of a user using the Golang Graph SDK, but i just get random Odata Values as Response instead of Json or some other format.</p>
<p>First i made the Connection and Request using the official Docs and Issues on Github:</p>
<pre><code>package main
import (
"context"
"fmt"
azidentity "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
a "github.com/microsoft/kiota-authentication-azure-go"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
cv "github.com/microsoftgraph/msgraph-sdk-go/users/item/calendarview"
)
func main() {
cred, err := azidentity.NewClientSecretCredential(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
nil,
)
auth, err := a.NewAzureIdentityAuthenticationProviderWithScopes(cred, []string{"https://graph.microsoft.com/.default"})
adapter, err := msgraphsdk.NewGraphRequestAdapter(auth)
client := msgraphsdk.NewGraphServiceClient(adapter)
if err != nil {
fmt.Println("Fehler: ", err)
}
requestStartDateTime := "2022-11-01T00:00:00"
requestEndDateTime := "2022-11-17T00:00:00"
query := cv.CalendarViewRequestBuilderGetQueryParameters{
// Orderby: []string{"start/dateTime"},
StartDateTime: &requestStartDateTime,
EndDateTime: &requestEndDateTime,
Select: []string{
"subject",
"start",
"end",
},
}
options := cv.CalendarViewRequestBuilderGetRequestConfiguration{
QueryParameters: &query,
}
_ = options
result, err := client.UsersById("redacted@domain.com").CalendarView().Get(context.Background(), &options)
if err != nil {
// const colorRed = "\033[0;31m"
fmt.Println(err)
}
fmt.Println(result)
}
</code></pre>
<p>And i just get a response like that:</p>
<pre><code>&{{map[@odata.context:0xc0002310d0] <nil> 0xc00043c030} [0xc0003da310 0xc0003da120 0xc0001daa11 0xc0001dad20 0xc0003dbf01 0xc0003db110 0xc0003da401 0xc0003db681 0xc0003da901 0xc0003daa81]}
</code></pre>
<p>I was expecting a Json output, not Random odata Context Values. is there something obvious that i have missed? The count of the Oxc.... Values changes, if i alter the StartDateTime and EndDateTime.</p>
|
[
{
"answer_id": 74543507,
"author": "T C Molenaar",
"author_id": 8814131,
"author_profile": "https://Stackoverflow.com/users/8814131",
"pm_score": 1,
"selected": false,
"text": ".fillna() df.time_spent_in_sec.shift(-1).fillna(df.time_spent_in_sec[0])\n df.time_spent_in_sec.shift(-1, fill_value = df.time_spent_in_sec[0])\n"
},
{
"answer_id": 74543533,
"author": "Guy",
"author_id": 5168011,
"author_profile": "https://Stackoverflow.com/users/5168011",
"pm_score": 3,
"selected": true,
"text": "df['time_spent_in_sec'] = np.roll(df['time_spent_in_sec'], -1)\n"
},
{
"answer_id": 74543608,
"author": "Enrique Benito Casado",
"author_id": 3844270,
"author_profile": "https://Stackoverflow.com/users/3844270",
"pm_score": 1,
"selected": false,
"text": "list_col = list(df[\"time_spent_in_sec\"])\nlist_col.append(list_col.pop(0))\ndf[\"time_spent_in_sec\"] = list_col.copy()\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20532115/"
] |
74,543,455
|
<p>I am seeing some weird behaviour in Java stream API. Here's my code:</p>
<pre><code>public static void main( String[] args ) {
final List<String> list = Arrays.asList( "string1", "string2" );
final Map<String, List<String>> map = new HashMap<>();
map.put( "string1", Arrays.asList( "1" ) );
//map.put( "string2", Arrays.asList( "1" ) );
Stream<String> stream = list.stream().map( map::get ).flatMap( List::stream );
System.out.println( "Stream=" + stream );
long count = stream.count();
System.out.println( "Stream count=" + count );
}
</code></pre>
<p>The second last line (<code>long count = stream.count();</code>) is resulting in a NPE. The exception does not occur if I add another entry to map for key "string2" (commented code). Can somebody please point-out why it results in a NPE instead of just returning the count as 1?</p>
<p>The same behaviour is observed if I try to collect the stream's result in a list instead of calling <code>count()</code></p>
|
[
{
"answer_id": 74543529,
"author": "Eran",
"author_id": 1221571,
"author_profile": "https://Stackoverflow.com/users/1221571",
"pm_score": 1,
"selected": false,
"text": ".map( map::get ) null .flatMap( List::stream ) null NullPointerException stream() null Stream<String> stream = list.stream()\n .map( map::get )\n .filter(Objects::nonNull)\n .flatMap( List::stream );\n"
},
{
"answer_id": 74543534,
"author": "Mark Rotteveel",
"author_id": 466862,
"author_profile": "https://Stackoverflow.com/users/466862",
"pm_score": 3,
"selected": true,
"text": "List#stream flatMap list.stream()\n .map(map::get)\n .filter(Objects::nonNull)\n .flatMap(List::stream)\n"
},
{
"answer_id": 74543538,
"author": "Antoniossss",
"author_id": 1527544,
"author_profile": "https://Stackoverflow.com/users/1527544",
"pm_score": 0,
"selected": false,
"text": "map.get(\"string2\") null map.get(\"string2\").stream()"
},
{
"answer_id": 74543561,
"author": "Not A Number",
"author_id": 20175711,
"author_profile": "https://Stackoverflow.com/users/20175711",
"pm_score": 0,
"selected": false,
"text": ".map( map::get )\n \"1\" \"string1\" map null \"string2\""
},
{
"answer_id": 74543583,
"author": "Chaosfire",
"author_id": 17795888,
"author_profile": "https://Stackoverflow.com/users/17795888",
"pm_score": 1,
"selected": false,
"text": "null Stream<String> stream = list.stream()\n .map(map::get)\n .filter(Objects::nonNull)\n .flatMap(Collection::stream);\n Stream<String> stream = list.stream()\n .map(str -> map.getOrDefault(str, Collections.emptyList()))\n .flatMap(Collection::stream);\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/521347/"
] |
74,543,468
|
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ID</th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>Orderd</th>
</tr>
</thead>
<tbody>
<tr>
<td>No1</td>
<td>8</td>
<td>9</td>
<td>5</td>
<td>2</td>
<td>D:2 C:5 A:8 B:9</td>
</tr>
<tr>
<td>No2</td>
<td>3</td>
<td>1</td>
<td>7</td>
<td>9</td>
<td>B:1 A:3 C:7 D:9</td>
</tr>
<tr>
<td>No3</td>
<td>29</td>
<td>34</td>
<td>5</td>
<td>294</td>
<td>C:5 A:29 B:34 D:294</td>
</tr>
</tbody>
</table>
</div>
<p>I would like to add "Orderd" column with column of A, B, C and D.</p>
<p>If I use <em>for loop</em>, I can do it as like</p>
<pre><code>for n in range(len(df)):
df['Orderd'][n] = df.T.sort_values(by=n,ascending=True)[n].to_string()
</code></pre>
<p>However, this method is too slow. I would like to do like this with "<strong>df.apply</strong>" method for doing speedy.</p>
|
[
{
"answer_id": 74543529,
"author": "Eran",
"author_id": 1221571,
"author_profile": "https://Stackoverflow.com/users/1221571",
"pm_score": 1,
"selected": false,
"text": ".map( map::get ) null .flatMap( List::stream ) null NullPointerException stream() null Stream<String> stream = list.stream()\n .map( map::get )\n .filter(Objects::nonNull)\n .flatMap( List::stream );\n"
},
{
"answer_id": 74543534,
"author": "Mark Rotteveel",
"author_id": 466862,
"author_profile": "https://Stackoverflow.com/users/466862",
"pm_score": 3,
"selected": true,
"text": "List#stream flatMap list.stream()\n .map(map::get)\n .filter(Objects::nonNull)\n .flatMap(List::stream)\n"
},
{
"answer_id": 74543538,
"author": "Antoniossss",
"author_id": 1527544,
"author_profile": "https://Stackoverflow.com/users/1527544",
"pm_score": 0,
"selected": false,
"text": "map.get(\"string2\") null map.get(\"string2\").stream()"
},
{
"answer_id": 74543561,
"author": "Not A Number",
"author_id": 20175711,
"author_profile": "https://Stackoverflow.com/users/20175711",
"pm_score": 0,
"selected": false,
"text": ".map( map::get )\n \"1\" \"string1\" map null \"string2\""
},
{
"answer_id": 74543583,
"author": "Chaosfire",
"author_id": 17795888,
"author_profile": "https://Stackoverflow.com/users/17795888",
"pm_score": 1,
"selected": false,
"text": "null Stream<String> stream = list.stream()\n .map(map::get)\n .filter(Objects::nonNull)\n .flatMap(Collection::stream);\n Stream<String> stream = list.stream()\n .map(str -> map.getOrDefault(str, Collections.emptyList()))\n .flatMap(Collection::stream);\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1835703/"
] |
74,543,480
|
<p>I want to be able to keep track on the order of selected options in multiple mat-select. How can I implement this use case?</p>
<p>Let's say first I select 'Onion' then 'Mushroom' and then 'Pepperoni'. I want to be able to get from mat-select the selected options in this order ['Onion', 'Mushroom', 'Pepperoni'].
And if I then deselect 'Mushroom' and select 'Extra cheese', I want to get the selected options in an array like ['Onion', 'Pepperoni', 'Extra cheese'].</p>
<p><a href="https://i.stack.imgur.com/pyZh1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pyZh1.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74543643,
"author": "Stacks Queue",
"author_id": 14820590,
"author_profile": "https://Stackoverflow.com/users/14820590",
"pm_score": 0,
"selected": false,
"text": "FormControl FormControl toppings = new FormControl('');\ntoppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];\n <mat-form-field appearance=\"fill\">\n <mat-label>Toppings</mat-label>\n <mat-select [formControl]=\"toppings\" multiple>\n <mat-option *ngFor=\"let topping of toppingList\" [value]=\"topping\">{{topping}}</mat-option>\n </mat-select>\n</mat-form-field>\n (selectionChange)=selectionChanged($event) mat-select <mat-select [formControl]=\"toppings\" (selectionChange)=selectionChanged($event) multiple>\n"
},
{
"answer_id": 74544043,
"author": "MoxxiManagarm",
"author_id": 11011793,
"author_profile": "https://Stackoverflow.com/users/11011793",
"pm_score": 2,
"selected": true,
"text": "optionSelectionChanges MatOptionSelectionChange scan <mat-form-field appearance=\"fill\">\n <mat-label>Toppings</mat-label>\n <mat-select multiple #toppingSelection>\n <mat-option *ngFor=\"let topping of toppingList\" [value]=\"topping\"\n >{{topping}}</mat-option\n >\n </mat-select>\n</mat-form-field>\n export class SelectMultipleExample implements AfterViewInit {\n @ViewChild('toppingSelection')\n toppingSelection: MatSelect;\n\n toppingList: string[] = [\n 'Extra cheese',\n 'Mushroom',\n 'Onion',\n 'Pepperoni',\n 'Sausage',\n 'Tomato',\n ];\n\n ngAfterViewInit() {\n // TODO: unsubscribe\n this.toppingSelection.optionSelectionChanges\n .pipe(\n scan((acc: string[], change: MatOptionSelectionChange) => {\n if (change.source.selected) {\n return [...acc, change.source.value];\n } else {\n return acc.filter((entry) => entry !== change.source.value);\n }\n }, [])\n )\n .subscribe((selectedValues: string[]) => console.log(selectedValues));\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3776697/"
] |
74,543,500
|
<p>How can I add a suffix to <code>TextField</code> input that flows (moves) with the user input text?</p>
|
[
{
"answer_id": 74543501,
"author": "Mahozad",
"author_id": 8583692,
"author_profile": "https://Stackoverflow.com/users/8583692",
"pm_score": 0,
"selected": false,
"text": "const val SUFFIX = \" $\"\n@Composable\nfun SuffixedText() {\n var text by remember { mutableStateOf(\"\") }\n TextField(\n text,\n singleLine = true,\n visualTransformation = SuffixTransformer(SUFFIX),\n onValueChange = { text = it }\n )\n}\n class SuffixTransformer(val suffix: String) : VisualTransformation {\n override fun filter(text: AnnotatedString): TransformedText {\n val result = text + AnnotatedString(suffix)\n return TransformedText(result, OffsetMapping.Identity)\n }\n}\n TextField"
},
{
"answer_id": 74544199,
"author": "Gabriele Mariotti",
"author_id": 2016562,
"author_profile": "https://Stackoverflow.com/users/2016562",
"pm_score": 2,
"selected": false,
"text": "visualTransformation TextField(\n value = text,\n onValueChange = { text = it },\n singleLine = true,\n visualTransformation = SuffixTransformation(\" €\"),\n)\n\nclass SuffixTransformation(val suffix: String) : VisualTransformation {\n override fun filter(text: AnnotatedString): TransformedText {\n\n val result = text + AnnotatedString(suffix)\n val suffixOffset = suffix.length\n\n val textWithSuffixMapping = object : OffsetMapping {\n override fun originalToTransformed(offset: Int): Int {\n return offset\n }\n\n override fun transformedToOriginal(offset: Int): Int {\n if (text.isEmpty()) return 0\n if (offset >= text.length + suffixOffset) return text.length\n return offset\n }\n }\n\n return TransformedText(result, textWithSuffixMapping )\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8583692/"
] |
74,543,525
|
<p>I have a parent class called Snack with subclasses Drink and Sweets. I want to store my Snacks in a "VendingMachine" Class where there is a list for each of the Products. However, I don't want to write the same method for each type of Snack. How would you write this as a generic method ?</p>
<pre><code>
// DRINKS LIST
List<Drink> drinks = new List<Drink>();
public List<Drink> Drinks { get => drinks; set => drinks = value; }
private void FillWithProducts <Product> (params Product[] products) where Product : Snack
{
Type typeParameter = typeof(Product);
Type drink = typeof(Drink);
foreach (Product p in products)
{
if (typeParameter.Equals(drink))
{
Drinks.Add(p);
}
}
}
</code></pre>
|
[
{
"answer_id": 74543501,
"author": "Mahozad",
"author_id": 8583692,
"author_profile": "https://Stackoverflow.com/users/8583692",
"pm_score": 0,
"selected": false,
"text": "const val SUFFIX = \" $\"\n@Composable\nfun SuffixedText() {\n var text by remember { mutableStateOf(\"\") }\n TextField(\n text,\n singleLine = true,\n visualTransformation = SuffixTransformer(SUFFIX),\n onValueChange = { text = it }\n )\n}\n class SuffixTransformer(val suffix: String) : VisualTransformation {\n override fun filter(text: AnnotatedString): TransformedText {\n val result = text + AnnotatedString(suffix)\n return TransformedText(result, OffsetMapping.Identity)\n }\n}\n TextField"
},
{
"answer_id": 74544199,
"author": "Gabriele Mariotti",
"author_id": 2016562,
"author_profile": "https://Stackoverflow.com/users/2016562",
"pm_score": 2,
"selected": false,
"text": "visualTransformation TextField(\n value = text,\n onValueChange = { text = it },\n singleLine = true,\n visualTransformation = SuffixTransformation(\" €\"),\n)\n\nclass SuffixTransformation(val suffix: String) : VisualTransformation {\n override fun filter(text: AnnotatedString): TransformedText {\n\n val result = text + AnnotatedString(suffix)\n val suffixOffset = suffix.length\n\n val textWithSuffixMapping = object : OffsetMapping {\n override fun originalToTransformed(offset: Int): Int {\n return offset\n }\n\n override fun transformedToOriginal(offset: Int): Int {\n if (text.isEmpty()) return 0\n if (offset >= text.length + suffixOffset) return text.length\n return offset\n }\n }\n\n return TransformedText(result, textWithSuffixMapping )\n }\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19319604/"
] |
74,543,539
|
<p>I have a file <code>config.yaml</code> that looks like this:</p>
<pre><code>myenv1:
abc: efg
host: ( ENV["HOST1"] )
db: ( ENV["DB1"] )
user: <%= ENV["USER1"] %>
pass: <%= ENV["VE_PASS1"] %>
time: 00
myenv2:
abc: efg
host: ( ENV["HOST2"] )
db: ( ENV["DB2"] )
user: <%= ENV["USER2"] %>
pass: <%= ENV["VE_PASS2"] %>
time: 800
</code></pre>
<p>And another file <code>values.yaml</code> that looks like this:</p>
<pre><code>secrets:
- MY_PASS_1
- MY_PASS_2
abc:
- pqr
psp:
- jdfhs
</code></pre>
<p>I need to update/replace the value (it is a list) of a particular key <code>secret</code> in the file <code>values.yaml</code> with a list of words like <code>VE_PASS1</code> and <code>VE_PASS2</code> present in the file <code>config.yaml</code>.</p>
<p>After running the commands, the <code>values.yaml</code> should look like this:</p>
<pre><code>secrets:
- VE_PASS1
- VE_PASS2
abc:
- pqr
psp:
- jdfhs
</code></pre>
<p>What would be the Linux command or script to do that?</p>
|
[
{
"answer_id": 74544078,
"author": "AnjanaAK",
"author_id": 10259516,
"author_profile": "https://Stackoverflow.com/users/10259516",
"pm_score": 0,
"selected": false,
"text": "temp secrets values.yaml yq #!/bin/bash\n\nsource_file=config.yaml\ndestination_file=values.yaml\ntemp_file=temp\n\nreadarray -t my_array < <(grep -E '\\bVE_' $source_file | awk -v RS=[ -v FS=] 'NR>1{print $1}' | sed 's/\"//g')\n\n# yq version 4\ntouch $temp_file\nfor i in \"${my_array[@]}\"; do\n printf '\\055 %s\\n' $i >> $temp_file\ndone\n\nyq eval '.secrets |= load(\"temp\")' $destination_file --inplace\n values.yaml secrets: \n - VE_PASS1\n - VE_PASS2\nabc:\n - pqr\npsp:\n - jdfhs\n"
},
{
"answer_id": 74544776,
"author": "pmf",
"author_id": 2158479,
"author_profile": "https://Stackoverflow.com/users/2158479",
"pm_score": 0,
"selected": false,
"text": "readarray awk sed sub yq -i '\n .secrets = (\n load(\"config.yaml\")\n | map(.pass | sub(\"^.*\\[\\\"(.*)\\\"\\].*$\"; \"$1\"))\n )\n' values.yaml\n values.yaml secrets:\n - VE_PASS1\n - VE_PASS2\nabc:\n - pqr\npsp:\n - jdfhs\n"
},
{
"answer_id": 74547883,
"author": "Christy Jose",
"author_id": 19915563,
"author_profile": "https://Stackoverflow.com/users/19915563",
"pm_score": 1,
"selected": false,
"text": "secrets: \n - MY_PASS_1\n - MY_PASS_2\nabc:\n - pqr\npsp:\n - jdfhs\n yq -i \".secrets = [\"foo\",\"bar\"]\" yqtest.yaml values.yml secrets: \n - foo\n - bar\nabc:\n - pqr\npsp:\n - jdfhs\n insert_array=() (grep -E '\\bVE_' $source_file | awk -v RS=[ -v FS=] 'NR>1{print $1}' | sed 's/\"//g') insert_array #!/bin/bash\n \ninsert_array=()\nfor i in $(grep -E '\\bKV_' $source_file | awk -v RS=[ -v FS=] 'NR>1{print $1}' | sed 's/\"//g')\n do \n insert_array+=(\\\"$i\\\"); insert_array+=(\",\") \n done\n list #echo ${insert_array[*]}\nfoo , bar\n # yq -i \".secret = [${insert_array[*]}]\" destination.yaml \nError: bad expression, please check expression syntax\n # yq -i \".secret = [\"foo\" \"bar\"]\" destination.yaml \n Error: bad expression, please check expression syntax\n unset insert_array[-1] for i in $(grep -E '\\bKV_' $source_file | awk -v RS=[ -v FS=] 'NR>1{print $1}' | sed 's/\"//g')\n do \n insert_array+=(\\\"$i\\\")\n insert_array+=(\",\") \n done\n #!/bin/bash\n\ninsert_array=()\nfor i in $(grep -E '\\bKV_' $source_file | awk -v RS=[ -v FS=] 'NR>1{print $1}' | sed 's/\"//g')\n do \n insert_array+=(\\\"$i\\\")\n insert_array+=(\",\")\n done\nunset insert_array[-1] \nyq -i \".secret = [${insert_array[*]}]\" destination.yaml\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10259516/"
] |
74,543,569
|
<p>I have a simple problem. For example sometimes I need to call <code>Auth::user()->id</code> in conditional but if I'm not logged in, it triggers an error. For example
<code>@if(isset(Auth::user()->id)) //do something @endif</code>
How can I do that in a simple way to make it work?</p>
<p>I want to make only one conditional instruction that works</p>
|
[
{
"answer_id": 74543667,
"author": "N69S",
"author_id": 4369919,
"author_profile": "https://Stackoverflow.com/users/4369919",
"pm_score": 1,
"selected": false,
"text": "id() null @if(Auth::id())\n check() true false ! is_null(Auth::user()) @if(Auth::check())\n"
},
{
"answer_id": 74543703,
"author": "Mahmud hasan",
"author_id": 5215027,
"author_profile": "https://Stackoverflow.com/users/5215027",
"pm_score": 0,
"selected": false,
"text": "Auth::check() web Auth::guard('guard_name')->check()"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20321593/"
] |
74,543,570
|
<p>I'm trying to count unique values in one column only when the value meets a certain condition based on another column. For example, the data looks like this:</p>
<pre><code>GroupID ID Value
ABC TX123 0
ABC TX678 1
ABC TX678 2
DEF AG123 1
DEF AG123 1
DEF AG123 1
GHI TE203 0
GHI TE203 0
</code></pre>
<p>I want to count the number of unique ID by Group ID but only when the value column >0. When all values for a group ID =0, it will simply have 0. For example, the result dataset would look like this:</p>
<pre><code>GroupID UniqueNum
ABC 1
DEF 1
GHI 0
</code></pre>
<p>I've tried the following but it simply returns the uique number of IDs regardless of its value. How do I add the condition of when value >0?</p>
<pre><code>count_df = df.groupby(['GroupID'])['ID'].nunique()
</code></pre>
|
[
{
"answer_id": 74543745,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "loc groupby.agg('nunique') (df.loc[df['Value'].gt(0), 'ID']\n .groupby(df['GroupID'])\n .agg(UniqueNum='nunique')\n .reset_index()\n)\n GroupID UniqueNum\n0 ABC 1\n1 DEF 1\n reindex (df.loc[df['Value'].gt(0), 'ID']\n .groupby(df['GroupID'])\n .agg(UniqueNum='nunique')\n .reindex(df['GroupID'].unique(), fill_value=0)\n .reset_index()\n)\n mask (df['ID'].where(df['Value'].gt(0))\n .groupby(df['GroupID'])\n .agg(UniqueNum='nunique')\n .reset_index()\n)\n GroupID UniqueNum\n0 ABC 1\n1 DEF 1\n2 GHI 0\n GroupID ID Value\nABC TX123 0\nABC TX678 1\nABC TX678 2\nDEF AG123 1\nDEF AG123 1\nDEF AG123 1\nGHI AB123 0\n"
},
{
"answer_id": 74543808,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 0,
"selected": false,
"text": "0 Series.where NaN DataFrameGroupBy.nunique df = pd.DataFrame({ 'GroupID': ['ABC', 'ABC', 'ABC', 'DEF', 'DEF', 'NEW'],\n 'ID': ['TX123', 'TX678', 'TX678', 'AG123', 'AG123', 'AG123'],\n 'Value': [0, 1, 2, 1, 1, 0]})\n\ndf = (df['ID'].where(df[\"Value\"].gt(0)).groupby(df['GroupID'])\n .nunique()\n .reset_index(name='nunique'))\n\nprint (df)\n GroupID nunique\n0 ABC 1\n1 DEF 1\n2 NEW 0\n print (df.assign(new=df['ID'].where(df[\"Value\"].gt(0))))\n GroupID ID Value new\n0 ABC TX123 0 NaN\n1 ABC TX678 1 TX678\n2 ABC TX678 2 TX678\n3 DEF AG123 1 AG123\n4 DEF AG123 1 AG123\n5 NEW AG123 0 NaN <- set NaN for non matched condition\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17670715/"
] |
74,543,613
|
<p>Repository implementation where a suspend function of uploading and getting back the urls. the await() function said that it should be "suspend". so i added a Coroutine Scope block . inside the block have added urls to a list. the log statement inside the scope has required downloaded urls in the arraylist . but outside the block the list is empty. how to make the list updated outside the coroutine block and can anyone help me to understand how to work with Coroutine thanks</p>
<p>my code</p>
<pre><code>override suspend fun addProductImagesToFirebaseStorage(
productImages: List<Uri>
): AddProductImagesResponse {
return try {
val downloadUrls = mutableListOf<Uri>()
val tasks = mutableListOf<UploadTask>()
productImages.forEach { downloadUrl ->
val task = categoryImageStorage.reference
.child("Home").child("PP")
.child("images")
.putFile(downloadUrl)
tasks.add(task)
}
Tasks.whenAllSuccess<UploadTask.TaskSnapshot>(tasks).addOnSuccessListener { uploadTask ->
uploadTask.forEach {
// downloadUrls.add(it.storage.downloadUrl.await()) Error: Suspension functions can be called only within coroutine body
CoroutineScope(Dispatchers.Default).launch {
downloadUrls.add(it.storage.downloadUrl.await())
Log.i(TAG,"Inside the block : $downloadUrls")
}
Log.i(TAG,"Outside the block : $downloadUrls")
}
}
Success(downloadUrls)
} catch(e:Exception) {
Failure(e)
}
}
</code></pre>
|
[
{
"answer_id": 74543745,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "loc groupby.agg('nunique') (df.loc[df['Value'].gt(0), 'ID']\n .groupby(df['GroupID'])\n .agg(UniqueNum='nunique')\n .reset_index()\n)\n GroupID UniqueNum\n0 ABC 1\n1 DEF 1\n reindex (df.loc[df['Value'].gt(0), 'ID']\n .groupby(df['GroupID'])\n .agg(UniqueNum='nunique')\n .reindex(df['GroupID'].unique(), fill_value=0)\n .reset_index()\n)\n mask (df['ID'].where(df['Value'].gt(0))\n .groupby(df['GroupID'])\n .agg(UniqueNum='nunique')\n .reset_index()\n)\n GroupID UniqueNum\n0 ABC 1\n1 DEF 1\n2 GHI 0\n GroupID ID Value\nABC TX123 0\nABC TX678 1\nABC TX678 2\nDEF AG123 1\nDEF AG123 1\nDEF AG123 1\nGHI AB123 0\n"
},
{
"answer_id": 74543808,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 0,
"selected": false,
"text": "0 Series.where NaN DataFrameGroupBy.nunique df = pd.DataFrame({ 'GroupID': ['ABC', 'ABC', 'ABC', 'DEF', 'DEF', 'NEW'],\n 'ID': ['TX123', 'TX678', 'TX678', 'AG123', 'AG123', 'AG123'],\n 'Value': [0, 1, 2, 1, 1, 0]})\n\ndf = (df['ID'].where(df[\"Value\"].gt(0)).groupby(df['GroupID'])\n .nunique()\n .reset_index(name='nunique'))\n\nprint (df)\n GroupID nunique\n0 ABC 1\n1 DEF 1\n2 NEW 0\n print (df.assign(new=df['ID'].where(df[\"Value\"].gt(0))))\n GroupID ID Value new\n0 ABC TX123 0 NaN\n1 ABC TX678 1 TX678\n2 ABC TX678 2 TX678\n3 DEF AG123 1 AG123\n4 DEF AG123 1 AG123\n5 NEW AG123 0 NaN <- set NaN for non matched condition\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13075886/"
] |
74,543,650
|
<p>this is my code I want to convert this query in to a common query</p>
<pre><code> if ($limit == 0) {
$response = WebhookErrorNotification::where('is_error', true)->orderByDesc('id')->get();
} else {
$response = WebhookErrorNotification::where('is_error', true)->orderByDesc('id')->limit($limit)->get();
}
</code></pre>
|
[
{
"answer_id": 74543745,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "loc groupby.agg('nunique') (df.loc[df['Value'].gt(0), 'ID']\n .groupby(df['GroupID'])\n .agg(UniqueNum='nunique')\n .reset_index()\n)\n GroupID UniqueNum\n0 ABC 1\n1 DEF 1\n reindex (df.loc[df['Value'].gt(0), 'ID']\n .groupby(df['GroupID'])\n .agg(UniqueNum='nunique')\n .reindex(df['GroupID'].unique(), fill_value=0)\n .reset_index()\n)\n mask (df['ID'].where(df['Value'].gt(0))\n .groupby(df['GroupID'])\n .agg(UniqueNum='nunique')\n .reset_index()\n)\n GroupID UniqueNum\n0 ABC 1\n1 DEF 1\n2 GHI 0\n GroupID ID Value\nABC TX123 0\nABC TX678 1\nABC TX678 2\nDEF AG123 1\nDEF AG123 1\nDEF AG123 1\nGHI AB123 0\n"
},
{
"answer_id": 74543808,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 0,
"selected": false,
"text": "0 Series.where NaN DataFrameGroupBy.nunique df = pd.DataFrame({ 'GroupID': ['ABC', 'ABC', 'ABC', 'DEF', 'DEF', 'NEW'],\n 'ID': ['TX123', 'TX678', 'TX678', 'AG123', 'AG123', 'AG123'],\n 'Value': [0, 1, 2, 1, 1, 0]})\n\ndf = (df['ID'].where(df[\"Value\"].gt(0)).groupby(df['GroupID'])\n .nunique()\n .reset_index(name='nunique'))\n\nprint (df)\n GroupID nunique\n0 ABC 1\n1 DEF 1\n2 NEW 0\n print (df.assign(new=df['ID'].where(df[\"Value\"].gt(0))))\n GroupID ID Value new\n0 ABC TX123 0 NaN\n1 ABC TX678 1 TX678\n2 ABC TX678 2 TX678\n3 DEF AG123 1 AG123\n4 DEF AG123 1 AG123\n5 NEW AG123 0 NaN <- set NaN for non matched condition\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18698442/"
] |
74,543,671
|
<p>I have a page for playing songs in my project. When I go back to the previous page after playing a song (without pausing it), it will continue to play in the background, and users can pause it at any time from the notification bar. I am using Plugin.MediaManager (Version: 1.1.1) for the integration of songs.</p>
<p><strong>Current song screens on my App</strong></p>
<p><a href="https://i.stack.imgur.com/cx3fI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cx3fI.jpg" alt="enter image description here" /></a></p>
<p>But we have a new suggestion, like playing the songs in the app itself on top or bottom on all the other pages (like WhatsApp). Our application has more than 100 pages, so adding the audio player on all these pages is a tedious task. So any other tricky way to implement it on all the pages by reusing it or any other better solution for this feature?</p>
<p><strong>The expected feature is like the below one, like WhatsApp</strong></p>
<p><a href="https://i.stack.imgur.com/awvZN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/awvZN.jpg" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74543745,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 2,
"selected": true,
"text": "loc groupby.agg('nunique') (df.loc[df['Value'].gt(0), 'ID']\n .groupby(df['GroupID'])\n .agg(UniqueNum='nunique')\n .reset_index()\n)\n GroupID UniqueNum\n0 ABC 1\n1 DEF 1\n reindex (df.loc[df['Value'].gt(0), 'ID']\n .groupby(df['GroupID'])\n .agg(UniqueNum='nunique')\n .reindex(df['GroupID'].unique(), fill_value=0)\n .reset_index()\n)\n mask (df['ID'].where(df['Value'].gt(0))\n .groupby(df['GroupID'])\n .agg(UniqueNum='nunique')\n .reset_index()\n)\n GroupID UniqueNum\n0 ABC 1\n1 DEF 1\n2 GHI 0\n GroupID ID Value\nABC TX123 0\nABC TX678 1\nABC TX678 2\nDEF AG123 1\nDEF AG123 1\nDEF AG123 1\nGHI AB123 0\n"
},
{
"answer_id": 74543808,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 0,
"selected": false,
"text": "0 Series.where NaN DataFrameGroupBy.nunique df = pd.DataFrame({ 'GroupID': ['ABC', 'ABC', 'ABC', 'DEF', 'DEF', 'NEW'],\n 'ID': ['TX123', 'TX678', 'TX678', 'AG123', 'AG123', 'AG123'],\n 'Value': [0, 1, 2, 1, 1, 0]})\n\ndf = (df['ID'].where(df[\"Value\"].gt(0)).groupby(df['GroupID'])\n .nunique()\n .reset_index(name='nunique'))\n\nprint (df)\n GroupID nunique\n0 ABC 1\n1 DEF 1\n2 NEW 0\n print (df.assign(new=df['ID'].where(df[\"Value\"].gt(0))))\n GroupID ID Value new\n0 ABC TX123 0 NaN\n1 ABC TX678 1 TX678\n2 ABC TX678 2 TX678\n3 DEF AG123 1 AG123\n4 DEF AG123 1 AG123\n5 NEW AG123 0 NaN <- set NaN for non matched condition\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8783685/"
] |
74,543,673
|
<p>I will try to explain it as simple as I can. I have one entity class, one service, one repository.</p>
<p>User.class</p>
<pre class="lang-java prettyprint-override"><code>@NotNull
@NotEmpty
@UniqueEmail
private String email;
</code></pre>
<p>UserRepo</p>
<pre class="lang-java prettyprint-override"><code>public interface UserRepository extends JpaRepository<User,Long> {
boolean findByEmail(String email);
}
</code></pre>
<p>UserService</p>
<pre class="lang-java prettyprint-override"><code>@Service
public class UserService {
private final UserRepository userRepository;
PasswordEncoder passwordEncoder;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
this.passwordEncoder = new BCryptPasswordEncoder();
}
public UserResponseDTO createUser(UserRequestDTO userRequestDTO){
userRequestDTO.setPassword(passwordEncoder.encode(userRequestDTO.getPassword()));
User u = userRepository.save(UserMapper.INSTANCE.entityToDto(userRequestDTO));
return UserMapper.INSTANCE.toEntity(u);
}
public boolean findUserByUserName(String email){
if(userRepository.findByUsername(email)){
return true;
}
return false;
}
public boolean findUserByUserEmail(String email){
if(userRepository.findByEmail(email)){
return true;
}
return false;
}
}
</code></pre>
<p>UserController</p>
<pre class="lang-java prettyprint-override"><code>@CrossOrigin
@RestController
public class UserController {
private final String endPointName = "api";
@Autowired
private UserService userService;
@ResponseStatus(HttpStatus.CREATED)
@PostMapping(path = endPointName+"/addUser", consumes = "application/json")
public GenericResponseMessage addUser(@Valid @RequestBody UserRequestDTO userRequestDTO){
userService.createUser(userRequestDTO);
return new GenericResponseMessage("ok");
}
}
</code></pre>
<p>Validator Annotation</p>
<pre class="lang-java prettyprint-override"><code>@Constraint(validatedBy = UniqueEmailValidator.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD })
public @interface UniqueEmail {
public String message() default "There is already user with this email!";
public Class<?>[] groups() default {};
public Class<? extends Payload>[] payload() default{};
}
</code></pre>
<p>UniqueEmailValidator class</p>
<pre class="lang-java prettyprint-override"><code>@Component
public class UniqueEmailValidator implements ConstraintValidator<UniqueEmail, String> {
@Autowired
private UserService userService;
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return value != null && !userService.findUserByUserEmail(value);
}
}
</code></pre>
<p><strong><a href="https://i.stack.imgur.com/ue8N1.png" rel="nofollow noreferrer">API ERROR</a></strong></p>
<pre class="lang-json prettyprint-override"><code>{
"timestamp": "2022-11-23T08:51:07.717+00:00",
"status": 500,
"error": "Internal Server Error",
"trace": "javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.\n\tat org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:186)\n\tat org.hibernate.validator.internal.engine.constraintvalidation.SimpleConstraintTree.validateConstraints(SimpleConstraintTree.java:62)\n\tat org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:75)\n\tat org.hibernate.validator.internal.metadata.core.MetaConstraint.doValidateConstraint(MetaConstraint.java:130)\n\tat org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:123)\n\tat org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:555)\n\tat bla bla bla",
"message": "HV000028: Unexpected exception during isValid call.",
"path": "/api/addUser"
}
</code></pre>
<p>INTELLIJ ERROR:</p>
<pre><code>java.lang.NullPointerException: null
at mywebapp.demowebapp.constraint.UniqueEmailValidator.isValid(UniqueEmailValidator.java:22) ~[main/:na]
at mywebapp.demowebapp.constraint.UniqueEmailValidator.isValid(UniqueEmailValidator.java:13) ~[main/:na]
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:180) ~[hibernate-validator-6.2.5.Final.jar:6.2.5.Final]
at org.hibernate.validator.internal.engine.constraintvalidation.SimpleConstraintTree.validateConstraints(SimpleConstraintTree.java:62) ~[hibernate-validator-6.2.5.Final.jar:6.2.5.Final]
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:75) ~[hibernate-validator-6.2.5.Final.jar:6.2.5.Final]
at org.hibernate.validator.internal.metadata.core.MetaConstraint.doValidateConstraint(MetaConstraint.java:130) ~[hibernate-validator-6.2.5.Final.jar:6.2.5.Final]
at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:123) ~[hibernate-validator-6.2.5.Final.jar:6.2.5.Final]
at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:555) ~[hibernate-validator-6.2.5.Final.jar:6.2.5.Final]
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForSingleDefaultGroupElement(ValidatorImpl.java:518) ~[hibernate-validator-6.2.5.Final.jar:6.2.5.Final]
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:488) ~[hibernate-validator-6.2.5.Final.jar:6.2.5.Final]
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:450) ~[hibernate-validator-6.2.5.Final.jar:6.2.5.Final]
at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:400) ~[hibernate-validator-6.2.5.Final.jar:6.2.5.Final]
at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:172) ~[hibernate-validator-6.2.5.Final.jar:6.2.5.Final]
at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:116) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreInsert(BeanValidationEventListener.java:80) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
at org.hibernate.action.internal.EntityIdentityInsertAction.preInsert(EntityIdentityInsertAction.java:188) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:78) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:645) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:317) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:330) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:287) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:123) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:185) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:128) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:55) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:756) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:742) ~[hibernate-core-5.6.12.Final.jar:5.6.12.Final]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:362) ~[spring-orm-5.3.23.jar:5.3.23]
at com.sun.proxy.$Proxy105.persist(Unknown Source) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:311) ~[spring-orm-5.3.23.jar:5.3.23]
at com.sun.proxy.$Proxy105.persist(Unknown Source) ~[na:na]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:666) ~[spring-data-jpa-2.7.5.jar:2.7.5]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289) ~[spring-data-commons-2.7.5.jar:2.7.5]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137) ~[spring-data-commons-2.7.5.jar:2.7.5]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121) ~[spring-data-commons-2.7.5.jar:2.7.5]
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:530) ~[spring-data-commons-2.7.5.jar:2.7.5]
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:286) ~[spring-data-commons-2.7.5.jar:2.7.5]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:640) ~[spring-data-commons-2.7.5.jar:2.7.5]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:164) ~[spring-data-commons-2.7.5.jar:2.7.5]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:139) ~[spring-data-commons-2.7.5.jar:2.7.5]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:81) ~[spring-data-commons-2.7.5.jar:2.7.5]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123) ~[spring-tx-5.3.23.jar:5.3.23]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388) ~[spring-tx-5.3.23.jar:5.3.23]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.23.jar:5.3.23]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.23.jar:5.3.23]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174) ~[spring-data-jpa-2.7.5.jar:2.7.5]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.23.jar:5.3.23]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.23.jar:5.3.23]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.23.jar:5.3.23]
at com.sun.proxy.$Proxy109.save(Unknown Source) ~[na:na]
at mywebapp.demowebapp.service.UserService.createUser(UserService.java:35) ~[main/:na]
at mywebapp.demowebapp.controller.UserController.addUser(UserController.java:32) ~[main/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-5.3.23.jar:5.3.23]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150) ~[spring-web-5.3.23.jar:5.3.23]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) ~[spring-webmvc-5.3.23.jar:5.3.23]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.3.23.jar:5.3.23]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.23.jar:5.3.23]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.23.jar:5.3.23]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1071) ~[spring-webmvc-5.3.23.jar:5.3.23]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:964) ~[spring-webmvc-5.3.23.jar:5.3.23]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.23.jar:5.3.23]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.23.jar:5.3.23]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:696) ~[tomcat-embed-core-9.0.68.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.23.jar:5.3.23]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:779) ~[tomcat-embed-core-9.0.68.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.68.jar:9.0.68]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.23.jar:5.3.23]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.23.jar:5.3.23]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.23.jar:5.3.23]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.23.jar:5.3.23]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.23.jar:5.3.23]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.23.jar:5.3.23]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
</code></pre>
<p>I added <code>@Component</code> annotation <strong>but it did not work.</strong></p>
<p>I edit and try <code>@Valid</code> annotation <code>@Valited</code> <em><strong>but it did not work</strong></em>.</p>
<p>I add</p>
<p>"spring.jpa.properties.javax.persistence.validation.mode = none"</p>
<p>in application.properties file. If I add this, <strong>the error goes away but the "validation" in the whole system is disabled.</strong></p>
<p>If I remove</p>
<p><strong>"spring.jpa.properties.javax.persistence.validation.mode = none"</strong></p>
<p>all validations like @NotNull, @NotEmpty, @Pattern etc are working except the annotation I created.</p>
<p>But if I add</p>
<p><strong>"spring.jpa.properties.javax.persistence.validation.mode = none"</strong></p>
<p>all of them are disabled, and the data is entered into the database without any checks.</p>
|
[
{
"answer_id": 74545283,
"author": "Times",
"author_id": 5151202,
"author_profile": "https://Stackoverflow.com/users/5151202",
"pm_score": 3,
"selected": true,
"text": "UserService findUserByUserEmail UserService @Documented\n@Target(FIELD)\n@Retention(RUNTIME)\n@Constraint(validatedBy = UniqueEmail.Validator.class)\npublic @interface UniqueEmail {\n\n String message() default \"There is already a user with this email!\";\n\n Class<?>[] groups() default {};\n\n Class<? extends Payload>[] payload() default {};\n\n class Validator implements ConstraintValidator<UniqueEmail, String> {\n\n @Autowired\n private UserService userService;\n\n @Override\n public void initialize(UniqueEmail constraintAnnotation) {}\n\n @Override\n public boolean isValid(String email, ConstraintValidatorContext context) {\n return value != null && !userService.findUserByUserEmail(value);\n }\n\n }\n}\n LocalValidatorFactoryBean @Configuration\npublic class ValidationConfiguration {\n\n @Bean\n @Primary\n LocalValidatorFactoryBean localValidatorFactoryBean() {\n return new LocalValidatorFactoryBean();\n }\n\n}\n public interface UserRepository extends JpaRepository<User,Long> {\n\n boolean existsByEmail(String email);\n\n boolean existsByUsername(String email);\n\n}\n"
},
{
"answer_id": 74546085,
"author": "Hantsy",
"author_id": 893898,
"author_profile": "https://Stackoverflow.com/users/893898",
"pm_score": 1,
"selected": false,
"text": "@RequiredArgsConstructor\nclass UniqueEmailValidator implements ConstraintValidator<UniqueEmail, String> {\n private final UserAccountRepository userAccounts;\n\n @Override\n public void initialize(UniqueEmail constraintAnnotation) {\n }\n\n @Override\n public boolean isValid(String value, ConstraintValidatorContext context) {\n if (StringUtils.hasText(value)) {\n return !userAccounts.existsByEmail(value);\n }\n\n // empty or blank text, skip to use @NotBlank @NotEmpty to validate it.\n return true;\n }\n}\n @Test\npublic void testSaveUserAccount() throws Exception {\n when(userAccounts.existsByEmail(anyString())).thenReturn(true);\n\n var body = objectMapper.writeValueAsBytes(new CreateUserAccountCommand(\"foo@bar.com\", \"test\"));\n mockMvc.perform(post(\"/users\").contentType(MediaType.APPLICATION_JSON).content(body))\n .andExpect(status().isBadRequest());\n\n verify(userAccounts, atLeastOnce()).existsByEmail(anyString());\n verifyNoMoreInteractions(userAccounts);\n}\n [Field error in object 'createUserAccountCommand' on field 'email': \nrejected value [foo@bar.com]; \ncodes [UniqueEmail.createUserAccountCommand.email,UniqueEmail.email,UniqueEmail.java.lang.String,UniqueEmail];\n arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [createUserAccountCommand.email,email]; \narguments []; default message [email]]; \ndefault message [There is already user with this email!]] ]\n"
},
{
"answer_id": 74548052,
"author": "smhylc",
"author_id": 14538782,
"author_profile": "https://Stackoverflow.com/users/14538782",
"pm_score": 0,
"selected": false,
"text": "@Entity\n@Getter\n@Setter\n@Table(name = \"users\")\n@NoArgsConstructor\n@AllArgsConstructor\npublic class User {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long userid;\n private String username;\n private String userDisplayName;\n private String email;\n private String password;\n\n}\n @Getter\n@Setter\npublic class UserRequestDTO implements Serializable {\n\n\n @NotNull\n @NotEmpty\n @Size(min = 2,max = 20)\n private String username;\n\n\n @NotNull\n @NotEmpty\n @Size(min = 2,max = 20)\n @UsernameControl\n private String email;\n\n\n\n @NotNull\n @NotEmpty\n private String userDisplayName;\n\n @Column\n @NotNull\n @NotEmpty\n private String password;\n\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14538782/"
] |
74,543,698
|
<p>The font I am using on my HTML page supports <a href="https://practicaltypography.com/alternate-figures.html#tabular-and-proportional-figures" rel="nofollow noreferrer">tabular figures</a>, which is great for presenting rows of currency numbers nicely. They can be activated in CSS by using either:</p>
<pre><code>.table {
font-variant-numeric: tabular-nums;
}
</code></pre>
<p>or the more low-level way with:</p>
<pre><code>.table {
font-feature-settings: "tnum" on;
}
</code></pre>
<p>But how do I activate tabular figures when drawing on a JavaScript Canvas object using the <code>CanvasRenderingContext2D.fillText()</code> method? I tried putting the <code>font-feature-settings</code> line within the <code>@font-face</code> CSS block that defines the font to be loaded, but that did only affect the rendering within HTML, not the Canvas drawing.</p>
|
[
{
"answer_id": 74544067,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 3,
"selected": true,
"text": "measureText()"
},
{
"answer_id": 74560352,
"author": "blerontin",
"author_id": 511016,
"author_profile": "https://Stackoverflow.com/users/511016",
"pm_score": 0,
"selected": false,
"text": "@font-face {\n font-family: \"SomeDefault\";\n /* ... points to regular font variant ... */\n}\n\n@font-face {\n font-family: \"SomeNumbers\";\n /* ... points to monospaced font variant ... */\n unicode-range: U+0030-0039;\n}\n const canvas = document.querySelector('canvas');\nconst ctx = canvas.getContext('2d');\n\n/* TODO: Make sure the fonts are already loaded, either by referencing them in HTML or by using the FontFace API */\nctx.font = '20px SomeNumbers, SomeDefault, sans-serif';\nctx.fillStyle = '#444';\nctx.fillText('Text with numbers: 1.234$', 10, 40);\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/511016/"
] |
74,543,712
|
<p>I am writing R shiny, and I want to make the column name of the renderTable to be center-aligned.</p>
<p>I have tried this, but it only makes the table move to the center to the panel.</p>
<pre><code>#UI
column(12, align = "center", tableOutput("table_of_item")), (XXXWRONG!)
</code></pre>
<p>So</p>
<pre><code> output$table_of_item <- renderTable({ #the table in the middle
if (is.null(rv2$data_batch))return() #to check the file is imported
t <- dataset_preprocess_batch(rv2$data_batch) #data preprocess
head(t,n=20) #show the data with the first 20 row only
})
</code></pre>
<p>table_of_item is one of the example, I want to make all the renderTable 's colname to be center-aligned.</p>
<p>Thanks for your help :)</p>
|
[
{
"answer_id": 74544067,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 3,
"selected": true,
"text": "measureText()"
},
{
"answer_id": 74560352,
"author": "blerontin",
"author_id": 511016,
"author_profile": "https://Stackoverflow.com/users/511016",
"pm_score": 0,
"selected": false,
"text": "@font-face {\n font-family: \"SomeDefault\";\n /* ... points to regular font variant ... */\n}\n\n@font-face {\n font-family: \"SomeNumbers\";\n /* ... points to monospaced font variant ... */\n unicode-range: U+0030-0039;\n}\n const canvas = document.querySelector('canvas');\nconst ctx = canvas.getContext('2d');\n\n/* TODO: Make sure the fonts are already loaded, either by referencing them in HTML or by using the FontFace API */\nctx.font = '20px SomeNumbers, SomeDefault, sans-serif';\nctx.fillStyle = '#444';\nctx.fillText('Text with numbers: 1.234$', 10, 40);\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16469595/"
] |
74,543,715
|
<p>getting this error on <code>flutter run</code> for a linux desktop application</p>
<pre><code>Running "flutter pub get" in proj... 5.3s
Launching lib/main.dart on Linux in debug mode...
CMake Error at /usr/share/cmake-3.22/Modules/CMakeTestCXXCompiler.cmake:62 (message):
The C++ compiler
"/usr/bin/clang++"
is not able to compile a simple test program.
It fails with the following output:
Change Dir: /media/kingbob/Dvolve/EData/proj/build/linux/x64/debug/CMakeFiles/CMakeTmp
Run Build Command(s):/usr/bin/ninja cmTC_5f1b6 && [1/2] Building CXX object CMakeFiles/cmTC_5f1b6.dir/testCXXCompiler.cxx.o
[2/2] Linking CXX executable cmTC_5f1b6
FAILED: cmTC_5f1b6
: && /usr/bin/clang++ CMakeFiles/cmTC_5f1b6.dir/testCXXCompiler.cxx.o -o cmTC_5f1b6 && :
/usr/bin/ld: cannot find -lstdc++: No such file or directory
clang: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.
CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
CMakeLists.txt:2 (project)
Building Linux application...
Exception: Unable to generate build files
</code></pre>
<p>output of flutter doctor</p>
<pre><code>Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.3.8, on Ubuntu 22.04.1 LTS 5.15.0-53-generic, locale en_IN)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
[✓] Chrome - develop for the web
[✓] Linux toolchain - develop for Linux desktop
[✓] Android Studio (version 2021.3)
[✓] Connected device (2 available)
[✓] HTTP Host Availability
• No issues found!
</code></pre>
<p>output of clang++ --version</p>
<pre><code>Ubuntu clang version 14.0.0-1ubuntu1
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
</code></pre>
<p>I noticed that <code>/usr/lib/libstdc++.so</code> was missing, so manually created a symlink
<code>sudo ln -s /usr/lib/x86_64-linux-gnu/libstdc++.so.6 /usr/lib/libstdc++.so</code>.</p>
<p>Then I ended up in this error on <code>flutter run</code></p>
<pre><code>Launching lib/main.dart on Linux in debug mode...
/usr/include/glib-2.0/glib/glib-typeof.h:39:10: fatal error: 'type_traits' file not found
/usr/include/glib-2.0/glib/glib-typeof.h:39:10: fatal error: 'type_traits' file not found
/usr/include/glib-2.0/glib/glib-typeof.h:39:10: fatal error: 'type_traits' file not found
/usr/include/glib-2.0/glib/glib-typeof.h:39:10: fatal error: 'type_traits' file not found
/usr/include/glib-2.0/glib/glib-typeof.h:39:10: fatal error: 'type_traits' file not found
/usr/include/glib-2.0/glib/glib-typeof.h:39:10: fatal error: 'type_traits' file not found
</code></pre>
|
[
{
"answer_id": 74556869,
"author": "legacyO7",
"author_id": 12290785,
"author_profile": "https://Stackoverflow.com/users/12290785",
"pm_score": 1,
"selected": false,
"text": "/usr/lib/libstdc++.so sudo ln -s /usr/lib/x86_64-linux-gnu/libstdc++.so.6 /usr/lib/libstdc++.so fatal error: 'type_traits' file not found flutter run export CPLUS_INCLUDE_PATH=\"${CPLUS_INCLUDE_PATH:+${CPLUS_INCLUDE_PATH}:}/usr/lib/llvm-13/include/c++/v1/\""
},
{
"answer_id": 74605488,
"author": "Kevin",
"author_id": 3068259,
"author_profile": "https://Stackoverflow.com/users/3068259",
"pm_score": 0,
"selected": false,
"text": "nvidia-driver-520-open gcc-12 clang-15 clang-15 libstdc++-11-dev gcc-11 gcc-12 clang++ gcc-11 clang++ --verbose Ubuntu clang version 15.0.6\nTarget: x86_64-pc-linux-gnu\nThread model: posix\nInstalledDir: /usr/local/bin\nFound candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/11\nFound candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/12\nSelected GCC installation: /usr/lib/gcc/x86_64-linux-gnu/12\nCandidate multilib: .;@m64\nSelected multilib: .;@m64\n libstdc++-12-dev sudo apt install libstdc++-12-dev\n nvidia-driver-520-open gcc-13 libstdc++-13-dev clang++ clang-16 --gcc-install-dir $HOME/src/llvm-project/staging/bin/clang++ --gcc-install-dir=/usr/lib/gcc/x86_64-linux-gnu/11 a.cpp\n a.cpp #include <iostream>\nint main() { std::cout << \"Hello World!\" << std::endl; }\n clang --gcc-toolchain sudo mkdir --parents /opt/gcc-root/lib/gcc/x86_64-linux-gnu\nsudo ln --symbolic /usr/lib/gcc/x86_64-linux-gnu/11 /opt/gcc-root/lib/gcc/x86_64-linux-gnu/11\nsudo ln --symbolic /usr/include /opt/gcc-root/\n ln --symbolic /usr/include /opt/gcc-root/ clang++ --gcc-toolchain=/opt/gcc-root a.cpp\n export CCC_OVERRIDE_OPTIONS=^--gcc-toolchain=/opt/gcc-root clang++ #!/usr/bin/env bash\n/usr/local/bin/clang++ --gcc-toolchain=/opt/gcc-root \"$@\"\n export CXX=<PATH_TO_SCRIPT>/clang++ clang-tidy clangd --gcc-toolchain compile_commands.json CMAKE_EXPORT_COMPILE_COMMANDS clang++ fixed-gcc-root-clang++ fixed-gcc-root-clang++.cfg clang-15 /usr/lib/llvm-15/bin --gcc-toolchain=/opt/gcc-root export CXX=fixed-gcc-root-clang++ clang++ fixed-gcc-root-clang++ c++ -> fixed-gcc-root-clang++ nvidia-driver-520-open"
},
{
"answer_id": 74611723,
"author": "Bhikkhu Subhuti",
"author_id": 5980804,
"author_profile": "https://Stackoverflow.com/users/5980804",
"pm_score": 0,
"selected": false,
"text": "sudo apt-get install clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12290785/"
] |
74,543,752
|
<p>I have the following dataframe called df (<code>dput</code> below):</p>
<pre><code> group date indicator value
1 A 2022-11-01 01:00:00 FALSE 2
2 A 2022-11-01 03:00:00 FALSE 1
3 A 2022-11-01 04:00:00 FALSE 2
4 A 2022-11-01 05:00:00 FALSE 1
5 A 2022-11-01 06:00:00 TRUE 1
6 A 2022-11-01 07:00:00 FALSE 1
7 A 2022-11-01 10:00:00 FALSE 2
8 A 2022-11-01 12:00:00 FALSE 1
9 B 2022-11-01 01:00:00 FALSE 1
10 B 2022-11-01 02:00:00 FALSE 2
11 B 2022-11-01 03:00:00 FALSE 1
12 B 2022-11-01 06:00:00 TRUE 1
13 B 2022-11-01 07:00:00 FALSE 1
14 B 2022-11-01 08:00:00 FALSE 1
15 B 2022-11-01 11:00:00 FALSE 2
16 B 2022-11-01 13:00:00 FALSE 2
</code></pre>
<p>I would like to find the first rows that have a value change after with respect to the rows with <code>indicator == TRUE</code> per group. This means that it should find row 7 for group A and row 15 for group B because they are both the first rows that have a value change after and with respect to the conditioned rows. Here is the desired output called df_desired:</p>
<pre><code> group date indicator value
1 A 2022-11-01 06:00:00 TRUE 1
2 A 2022-11-01 10:00:00 FALSE 2
3 B 2022-11-01 06:00:00 TRUE 1
4 B 2022-11-01 11:00:00 FALSE 2
</code></pre>
<p>So I was wondering if anyone knows how to find the desired rows with conditioned rows like in df_desired?</p>
<hr />
<p>Here <code>dput</code> of df and df_desired:</p>
<pre><code>df <- structure(list(group = c("A", "A", "A", "A", "A", "A", "A", "A",
"B", "B", "B", "B", "B", "B", "B", "B"), date = structure(c(1667260800,
1667268000, 1667271600, 1667275200, 1667278800, 1667282400, 1667293200,
1667300400, 1667260800, 1667264400, 1667268000, 1667278800, 1667282400,
1667286000, 1667296800, 1667304000), class = c("POSIXct", "POSIXt"
), tzone = ""), indicator = c(FALSE, FALSE, FALSE, FALSE, TRUE,
FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE,
FALSE, FALSE), value = c(2, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 1,
1, 1, 2, 2)), row.names = c(NA, -16L), class = "data.frame")
df_desired <- structure(list(group = c("A", "A", "B", "B"), date = c("2022-11-01 06:00:00",
"2022-11-01 10:00:00", "2022-11-01 06:00:00", "2022-11-01 11:00:00"
), indicator = c(TRUE, FALSE, TRUE, FALSE), value = c(1, 2, 1,
2)), class = "data.frame", row.names = c(NA, -4L))
</code></pre>
|
[
{
"answer_id": 74543960,
"author": "Sotos",
"author_id": 5635580,
"author_profile": "https://Stackoverflow.com/users/5635580",
"pm_score": 3,
"selected": true,
"text": "library(dplyr)\n\ndf %>% \n group_by(group) %>% \n mutate(val_diff = value - lag(value), \n new = row_number()[indicator], \n new1 = (val_diff == 1) & (row_number() > new)) %>% \n filter(indicator|new1) %>% \n select(-c(val_diff, new, new1))\n\n# A tibble: 4 × 4\n# Groups: group [2]\n group date indicator value\n <chr> <dttm> <lgl> <dbl>\n1 A 2022-11-01 08:00:00 TRUE 1\n2 A 2022-11-01 12:00:00 FALSE 2\n3 B 2022-11-01 08:00:00 TRUE 1\n4 B 2022-11-01 13:00:00 FALSE 2\n group date indicator value\n1 A 2022-11-01 03:00:00 FALSE 2\n2 A 2022-11-01 05:00:00 FALSE 1\n3 A 2022-11-01 06:00:00 FALSE 2\n4 A 2022-11-01 07:00:00 FALSE 1\n5 A 2022-11-01 08:00:00 TRUE 1\n6 A 2022-11-01 09:00:00 FALSE 1\n7 A 2022-11-01 12:00:00 FALSE 2\n8 A 2022-11-01 14:00:00 FALSE 1\n9 B 2022-11-01 03:00:00 FALSE 1\n10 B 2022-11-01 04:00:00 FALSE 2\n11 B 2022-11-01 05:00:00 FALSE 1\n12 B 2022-11-01 08:00:00 TRUE 1\n13 B 2022-11-01 09:00:00 FALSE 1\n14 B 2022-11-01 10:00:00 FALSE 1\n15 B 2022-11-01 13:00:00 FALSE 2\n16 B 2022-11-01 15:00:00 FALSE 2\n"
},
{
"answer_id": 74543968,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 2,
"selected": false,
"text": "by by(df, df$group, \\(x) {\n u <- x[cumsum(x$indicator) > 0, ]\n u[c(1L, which.max(u$value != u$value[1L])), ]\n}) |> do.call(what=rbind)\n# group date indicator value\n# A.5 A 2022-11-01 06:00:00 TRUE 1\n# A.7 A 2022-11-01 10:00:00 FALSE 2\n# B.12 B 2022-11-01 06:00:00 TRUE 1\n# B.15 B 2022-11-01 11:00:00 FALSE 2\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14282714/"
] |
74,543,753
|
<p>I'm trying to create a user registration in Django, but I have an issue with the template: registrazione.html.</p>
<p>My github repo: <a href="https://github.com/Pif50/MobFix" rel="nofollow noreferrer">https://github.com/Pif50/MobFix</a></p>
<p><strong>registrazione.html</strong></p>
<pre><code>{% extends 'base.html' %} {% load crispy_forms_tags %} {% block head_title %} {{
block.super }} - Registrati sul Forum{% endblock head_title %} {% block content
%}
<div class="row justify-content-center mt-4">
<div class="col-6 text-center">
<h2>Registrati sul Sito!</h2>
<form method="POST" novalidate>
{% csrf_token %} {{ form|crispy }}
<input type="submit" class="btn btn-info" value="Crea Account" />
</form>
</div>
</div>
{% endblock %}
</code></pre>
<p><strong>view.py</strong></p>
<pre><code>from django.shortcuts import render, HttpResponseRedirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from accounts.forms import FormRegistrazione
# Create your views here.
def registrazione_view(request):
if request.method == "POST":
form = FormRegistrazione(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
email = form.cleaned_data["email"]
password = form.cleaned_data["password1"]
User.objects.create_user(
username=username,
password=password,
email=email
)
user = authenticate(username=username, password=password)
login(request, user)
return HttpResponseRedirect("/")
else:
form = FormRegistrazione()
context = {'form': form}
return render(request, "accounts/registrazione.html", context)
</code></pre>
<p><strong>urls.py</strong></p>
<pre><code>from django.urls import path
from .views import registrazione_view
urlpatterns = [
path('registrazione/', registrazione_view, name="registration_view")
]
</code></pre>
<p><strong>main/urls.py</strong></p>
<pre><code>from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('accounts.urls')),
path('accounts/', include('django.contrib.auth.urls'))
]
</code></pre>
<p><strong>Error output:</strong></p>
<pre><code>During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/pif/Desktop/Corso Blockchain Developer/Progetti/progetto finale pier francesco tripodi/MobFix/myvenv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/Users/pif/Desktop/Corso Blockchain Developer/Progetti/progetto finale pier francesco tripodi/MobFix/myvenv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/pif/Desktop/Corso Blockchain Developer/Progetti/progetto finale pier francesco tripodi/MobFix/accounts/views.py", line 26, in registrazione_view
return render(request, "accounts/registrazione.html", context)
File "/Users/pif/Desktop/Corso Blockchain Developer/Progetti/progetto finale pier francesco tripodi/MobFix/myvenv/lib/python3.10/site-packages/django/shortcuts.py", line 24, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "/Users/pif/Desktop/Corso Blockchain Developer/Progetti/progetto finale pier francesco tripodi/MobFix/myvenv/lib/python3.10/site-packages/django/template/loader.py", line 61, in render_to_string
template = get_template(template_name, using=using)
File "/Users/pif/Desktop/Corso Blockchain Developer/Progetti/progetto finale pier francesco tripodi/MobFix/myvenv/lib/python3.10/site-packages/django/template/loader.py", line 15, in get_template
return engine.get_template(template_name)
File "/Users/pif/Desktop/Corso Blockchain Developer/Progetti/progetto finale pier francesco tripodi/MobFix/myvenv/lib/python3.10/site-packages/django/template/backends/django.py", line 34, in get_template
return Template(self.engine.get_template(template_name), self)
File "/Users/pif/Desktop/Corso Blockchain Developer/Progetti/progetto finale pier francesco tripodi/MobFix/myvenv/lib/python3.10/site-packages/django/template/engine.py", line 175, in get_template
template, origin = self.find_template(template_name)
File "/Users/pif/Desktop/Corso Blockchain Developer/Progetti/progetto finale pier francesco tripodi/MobFix/myvenv/lib/python3.10/site-packages/django/template/engine.py", line 157, in find_template
template = loader.get_template(name, skip=skip)
File "/Users/pif/Desktop/Corso Blockchain Developer/Progetti/progetto finale pier francesco tripodi/MobFix/myvenv/lib/python3.10/site-packages/django/template/loaders/cached.py", line 57, in get_template
template = super().get_template(template_name, skip)
File "/Users/pif/Desktop/Corso Blockchain Developer/Progetti/progetto finale pier francesco tripodi/MobFix/myvenv/lib/python3.10/site-packages/django/template/loaders/base.py", line 28, in get_template
return Template(
File "/Users/pif/Desktop/Corso Blockchain Developer/Progetti/progetto finale pier francesco tripodi/MobFix/myvenv/lib/python3.10/site-packages/django/template/base.py", line 154, in __init__
self.nodelist = self.compile_nodelist()
File "/Users/pif/Desktop/Corso Blockchain Developer/Progetti/progetto finale pier francesco tripodi/MobFix/myvenv/lib/python3.10/site-packages/django/template/base.py", line 200, in compile_nodelist
return parser.parse()
File "/Users/pif/Desktop/Corso Blockchain Developer/Progetti/progetto finale pier francesco tripodi/MobFix/myvenv/lib/python3.10/site-packages/django/template/base.py", line 513, in parse
raise self.error(token, e)
File "/Users/pif/Desktop/Corso Blockchain Developer/Progetti/progetto finale pier francesco tripodi/MobFix/myvenv/lib/python3.10/site-packages/django/template/base.py", line 511, in parse
compiled_result = compile_func(self, token)
File "/Users/pif/Desktop/Corso Blockchain Developer/Progetti/progetto finale pier francesco tripodi/MobFix/myvenv/lib/python3.10/site-packages/django/template/loader_tags.py", line 293, in do_extends
nodelist = parser.parse()
File "/Users/pif/Desktop/Corso Blockchain Developer/Progetti/progetto finale pier francesco tripodi/MobFix/myvenv/lib/python3.10/site-packages/django/template/base.py", line 507, in parse
self.invalid_block_tag(token, command, parse_until)
File "/Users/pif/Desktop/Corso Blockchain Developer/Progetti/progetto finale pier francesco tripodi/MobFix/myvenv/lib/python3.10/site-packages/django/template/base.py", line 568, in invalid_block_tag
raise self.error(
django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 13: 'endblock'. Did you forget to register or load this tag?
[23/Nov/2022 08:23:12] "GET /accounts/registrazione/ HTTP/1.1" 500 147740
</code></pre>
<h2>Error during template rendering</h2>
<p><a href="https://i.stack.imgur.com/0bcNn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0bcNn.png" alt="enter image description here" /></a></p>
<p>I try to see over StackOverFlow but I see only spelling errors</p>
|
[
{
"answer_id": 74543960,
"author": "Sotos",
"author_id": 5635580,
"author_profile": "https://Stackoverflow.com/users/5635580",
"pm_score": 3,
"selected": true,
"text": "library(dplyr)\n\ndf %>% \n group_by(group) %>% \n mutate(val_diff = value - lag(value), \n new = row_number()[indicator], \n new1 = (val_diff == 1) & (row_number() > new)) %>% \n filter(indicator|new1) %>% \n select(-c(val_diff, new, new1))\n\n# A tibble: 4 × 4\n# Groups: group [2]\n group date indicator value\n <chr> <dttm> <lgl> <dbl>\n1 A 2022-11-01 08:00:00 TRUE 1\n2 A 2022-11-01 12:00:00 FALSE 2\n3 B 2022-11-01 08:00:00 TRUE 1\n4 B 2022-11-01 13:00:00 FALSE 2\n group date indicator value\n1 A 2022-11-01 03:00:00 FALSE 2\n2 A 2022-11-01 05:00:00 FALSE 1\n3 A 2022-11-01 06:00:00 FALSE 2\n4 A 2022-11-01 07:00:00 FALSE 1\n5 A 2022-11-01 08:00:00 TRUE 1\n6 A 2022-11-01 09:00:00 FALSE 1\n7 A 2022-11-01 12:00:00 FALSE 2\n8 A 2022-11-01 14:00:00 FALSE 1\n9 B 2022-11-01 03:00:00 FALSE 1\n10 B 2022-11-01 04:00:00 FALSE 2\n11 B 2022-11-01 05:00:00 FALSE 1\n12 B 2022-11-01 08:00:00 TRUE 1\n13 B 2022-11-01 09:00:00 FALSE 1\n14 B 2022-11-01 10:00:00 FALSE 1\n15 B 2022-11-01 13:00:00 FALSE 2\n16 B 2022-11-01 15:00:00 FALSE 2\n"
},
{
"answer_id": 74543968,
"author": "jay.sf",
"author_id": 6574038,
"author_profile": "https://Stackoverflow.com/users/6574038",
"pm_score": 2,
"selected": false,
"text": "by by(df, df$group, \\(x) {\n u <- x[cumsum(x$indicator) > 0, ]\n u[c(1L, which.max(u$value != u$value[1L])), ]\n}) |> do.call(what=rbind)\n# group date indicator value\n# A.5 A 2022-11-01 06:00:00 TRUE 1\n# A.7 A 2022-11-01 10:00:00 FALSE 2\n# B.12 B 2022-11-01 06:00:00 TRUE 1\n# B.15 B 2022-11-01 11:00:00 FALSE 2\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17830991/"
] |
74,543,785
|
<p>I want to change the value on my select input by clicking on a button, but this button is on an other page.</p>
<p>My button is on the home page and the form with the select input is on contact page.
The select input look like this :</p>
<pre><code><select name="menu-vol" class="wpcf7-form-control wpcf7-select wpcf7-validates-as-required select-field w-select" id="select-vol" aria-required="true" aria-invalid="false">
<option value="">---</option>
<option value="Le marmaille">Le marmaille</option>
<option value="Le Vol découverte">Le Vol découverte</option>
<option value="Le plus">Le plus</option>
<option value="L'infini">L'infini</option>
<option value="Le vol des Hauts">Le vol des Hauts</option>
<option value="Le vol de distance">Le vol de distance</option>
<option value="Le vol du Maïdo">Le vol du Maïdo</option>
</select>
</code></pre>
<p>For exemple i want when i click on the button, the input select value change to "Le Vol découverte"</p>
<p>I'm trying <a href="https://mdbootstrap.com/snippets/standard/neanrakyr/2514494#html-tab-view" rel="nofollow noreferrer">this solution</a> but isn't work because is not a bootstrap template i think and in this exemple the form input and the button is on the same page, not like my case.</p>
|
[
{
"answer_id": 74544114,
"author": "DCodeMania",
"author_id": 8546303,
"author_profile": "https://Stackoverflow.com/users/8546303",
"pm_score": 2,
"selected": true,
"text": "<a href=\"contact.html?param=test\">Goto Contact</a>\n href if (window.location.search.includes('param=test')) {\n document.getElementById('select-vol').value = 'Le Vol découverte';\n}\n param=test"
},
{
"answer_id": 74544240,
"author": "Amirhossein",
"author_id": 11342834,
"author_profile": "https://Stackoverflow.com/users/11342834",
"pm_score": 0,
"selected": false,
"text": "<a href=\"contact.html\">Contact Page</a>\n <a href=\"contact.html?selectedValue=Le marmaille\">Contact Page</a>\n const selectedValue = (new URL(document.location)).searchParams.get(\"selectedValue\");\ndocument.getElementById(\"select-vol\").value = selectedValue;\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20579883/"
] |
74,543,805
|
<p>I have string like <strong>(CAT,A)(DOG,C)(MOUSE,D)</strong></p>
<p>i want to get the DOG value <strong>C</strong> using Regular expression.</p>
<p>i tried following</p>
<pre><code>Match match = Regex.Match(rspData, @"\(DOG,*?\)");
if (match.Success)
Console.WriteLine(match.Value);
</code></pre>
<p>But not working could any one help me to solve this issue.</p>
|
[
{
"answer_id": 74543875,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 2,
"selected": true,
"text": "(?<=\\(DOG,)\\w+(?=\\))?\n(?<=\\(DOG,)[^()]*(?=\\))\n (?<=\\(DOG,) (DOG, \\w+ [^()]* ( ) (?=\\)) )"
},
{
"answer_id": 74546626,
"author": "The fourth bird",
"author_id": 5424988,
"author_profile": "https://Stackoverflow.com/users/5424988",
"pm_score": 0,
"selected": false,
"text": "\\(DOG,([^()]*)\\)\n \\(DOG, (DOG, ([^()]*) ( ) \\) ) String rspData = \"(CAT,A)(DOG,C)(MOUSE,D)\";\nMatch match = Regex.Match(rspData, @\"\\(DOG,([^()]*)\\)\");\nif (match.Success)\n Console.WriteLine(match.Groups[1].Value);\n}\n C\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20579863/"
] |
74,543,838
|
<p><code>Products Array</code> has an array <code>property</code> called <code>subArr</code> and my goal is to return an array with the length of subArr which will include biggest numbers.</p>
<p>Array</p>
<pre><code>const products = [
{
name: "car",
subArr: ["4", "200", "599.4", "4444"]
},
{
name: "tv",
subArr: ["44477", "50", "579.2", "3232"]
},
{
name: "glass",
subArr: ["2121.1", "6347", "8867", "90.01"]
}
];
</code></pre>
<p>My desired array is <code>[44477, 4444, 8867, 6347]</code> <br></p>
<p>I tried to map through the main array and the loop through the second one but can't figure out how to get an array with the length of <code>subArr</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>const products = [
{
name: "car",
numArr: ["4", "200", "599.4", "4444"]
},
{
name: "tv",
numArr: ["44477", "50", "579.2", "3232"]
},
{
name: "glass",
numArr: ["2121.1", "6343", "8867", "90.01"]
}
];
function getMaxFromArr(products) {
if (!products.length) {
return [];
}
return products[0].numArr.map((val, index) => {
return products.map((prod) => parse(prod.numArr[index]));
});
}
const parse = value => parseFloat(value);
const result = getMaxFromArr(products);
console.log("result", result);</code></pre>
</div>
</div>
</p>
<p>Any help will be appreciated</p>
|
[
{
"answer_id": 74544015,
"author": "Asraf",
"author_id": 20361860,
"author_profile": "https://Stackoverflow.com/users/20361860",
"pm_score": 2,
"selected": false,
"text": "subArrs reduce() .map(Number) newArray slice() const products = [ { name: \"car\", subArr: [\"4\", \"200\", \"599.4\", \"4444\"] }, { name: \"tv\", subArr: [\"44477\", \"50\", \"579.2\", \"3232\"] }, { name: \"glass\", subArr: [\"2121.1\", \"6347\", \"8867\", \"90.01\"] } ];\nconst sortNum = (a, b) => b - a; //descending order\nconst findMaxArr = (arr, sArrSize) => products.reduce((a, {subArr}) => [...a, ...subArr.map(Number)],[]).sort(sortNum).slice(0, sArrSize);\nconsole.log(findMaxArr(products, products[0].subArr.length));"
},
{
"answer_id": 74544045,
"author": "adiga",
"author_id": 3082296,
"author_profile": "https://Stackoverflow.com/users/3082296",
"pm_score": 1,
"selected": false,
"text": "flatMap Number sort slice const products = [{name:\"car\",numArr:[\"4\",\"200\",\"599.4\",\"4444\"]},{name:\"tv\",numArr:[\"44477\",\"50\",\"579.2\",\"3232\"]},{name:\"glass\",numArr:[\"2121.1\",\"6343\",\"8867\",\"90.01\"]}],\n \n topN = products\n .flatMap(p => p.numArr.map(Number))\n .sort((a, b) => b - a)\n .slice(0, products[0].numArr.length)\n\nconsole.log(topN)"
},
{
"answer_id": 74544062,
"author": "Peter Lam",
"author_id": 19948640,
"author_profile": "https://Stackoverflow.com/users/19948640",
"pm_score": 0,
"selected": false,
"text": "const products = [{\n name: \"car\",\n numArr: [\"4\", \"200\", \"599.4\", \"4444\"]\n },\n {\n name: \"tv\",\n numArr: [\"44477\", \"50\", \"579.2\", \"3232\"]\n },\n {\n name: \"glass\",\n numArr: [\"2121.1\", \"6343\", \"8867\", \"90.01\"]\n }\n];\n\nfunction getMaxFromArr(products) {\n var BiggestNum = 0;\n var BiggestNumArray = [];\n if (!products.length) {\n return [];\n }\n products.map((value, index) => {\n var Array = value.numArr;\n for (let i = 0; i < Array.length; i++) {\n if (BiggestNum < Number(Array[i])) {\n BiggestNum = Number(Array[i])\n BiggestNumArray = Array\n }\n }\n\n })\n return BiggestNumArray\n\n}\n\nconst parse = value => parseFloat(value);\n\nconst result = getMaxFromArr(products);\nconsole.log(\"result\", result);"
},
{
"answer_id": 74544281,
"author": "Gass",
"author_id": 14895985,
"author_profile": "https://Stackoverflow.com/users/14895985",
"pm_score": 0,
"selected": false,
"text": "numArr numArr const products = [\n {\n name: \"car\",\n numArr: [\"4\", \"200\", \"599.4\", \"4444\"]\n },\n {\n name: \"tv\",\n numArr: [\"44477\", \"50\", \"579.2\", \"3232\"]\n },\n {\n name: \"glass\",\n numArr: [\"2121.1\", \"6343\", \"8867\", \"90.01\"]\n }\n];\n\nfunction getMaxFromArr(products) {\n let allNumbers = []\n \n if (!products.length) {\n return []\n }\n else{\n // get the length of first numArr\n let subArrLength = products[0].numArr.length\n \n // convert all strings in all numArr props to numbers and save them in a new array\n products.forEach((prod) => {\n prod.numArr.forEach((n) => allNumbers.push(Number(n)))\n })\n \n // sort and slice\n console.log(allNumbers.sort((a,b) => a - b).slice(allNumbers.length - subArrLength))\n }\n}\n\ngetMaxFromArr(products)"
},
{
"answer_id": 74544289,
"author": "Nick Parsons",
"author_id": 5648954,
"author_profile": "https://Stackoverflow.com/users/5648954",
"pm_score": 2,
"selected": true,
"text": "Math.max() ... parse() Math.max() ?. ?? const products = [ { name: \"car\", subArr: [\"4\", \"200\", \"599.4\", \"4444\"] }, { name: \"tv\", subArr: [\"44477\", \"50\", \"579.2\", \"3232\"] }, { name: \"glass\", subArr: [\"2121.1\", \"6347\", \"8867\", \"90.01\"] } ];\n\nfunction getMaxFromArr(products) {\n return products[0]?.subArr.map((val, index) =>\n Math.max(...products.map((prod) => prod.subArr[index]))\n ) ?? [];\n}\n\nconst result = getMaxFromArr(products);\nconsole.log(\"result\", result);"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12971921/"
] |
74,543,861
|
<p>I'm trying to setup authentication against Azure DevOps using MSAL. I've followed <a href="https://github.com/microsoft/azure-devops-auth-samples/tree/master/ManagedClientConsoleAppSample" rel="nofollow noreferrer">Microsoft's sample</a> but I can't get it to work with personal Microsoft accounts. Whenever I try to login with a personal account I get the following error:</p>
<blockquote>
<p>This username may be incorrect. Make sure you typed it correctly. Otherwise, contact your admin.</p>
</blockquote>
<p>In the sample I have only changed <code>ida:Tenant</code> to <code>"common"</code> and <code>ida:ClientId</code> to my application id. I've setup my App Registration by following the guide in the sample except for the "Supported account types" which I've set to:</p>
<blockquote>
<p>All users with a work or school, or personal Microsoft account can use your application or API. This includes Office 365 subscribers.</p>
</blockquote>
<p>What am I doing wrong or missing?</p>
|
[
{
"answer_id": 74556711,
"author": "Suki Ji-MSFT",
"author_id": 18349158,
"author_profile": "https://Stackoverflow.com/users/18349158",
"pm_score": 1,
"selected": false,
"text": "ado:OrganizationUrl ado:OrganizationUrl"
},
{
"answer_id": 74651317,
"author": "iDoMnCi",
"author_id": 10850031,
"author_profile": "https://Stackoverflow.com/users/10850031",
"pm_score": -1,
"selected": false,
"text": "const tenant = 'consumers';\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1523238/"
] |
74,543,883
|
<p>I use the SAS key to make a GET request for the table, but I get the error "This request is not authorized to perform this operation.". What values should I fill in on the authorization tab to work this out?</p>
<p><a href="https://i.stack.imgur.com/h8qyM.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>x-ms-blob-type and BlobBlock work for blob storage but I need key and value for table type.</p>
|
[
{
"answer_id": 74556711,
"author": "Suki Ji-MSFT",
"author_id": 18349158,
"author_profile": "https://Stackoverflow.com/users/18349158",
"pm_score": 1,
"selected": false,
"text": "ado:OrganizationUrl ado:OrganizationUrl"
},
{
"answer_id": 74651317,
"author": "iDoMnCi",
"author_id": 10850031,
"author_profile": "https://Stackoverflow.com/users/10850031",
"pm_score": -1,
"selected": false,
"text": "const tenant = 'consumers';\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20579892/"
] |
74,543,907
|
<p>I am trying to append another shape when one of the values satisfy the condition as follows:</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 keys = ["A", "B", "C", "D", "E", "E", "G"]
const colors = ['#1e90ff', '#008000', '#d3d3d3', '#d3d3d3', '#fe0000', '#ffa500', '#800080']
var triangle = d3.symbol().type(d3.symbolTriangle).size(500);
const colorOrdinalScale = d3
.scaleOrdinal()
.domain(keys)
.range(colors);
const svg = d3
.select("#container")
.append("svg")
.attr("class", "svg-area")
.attr("width", 600)
.attr("height", 500)
const legend = svg
.append('g')
.attr('id', 'legend')
.selectAll("symbols")
.data(keys)
.enter()
legend
.each(d => {
if (d === "D") {
console.log("triangle", d)
legend
.append("circle")
.attr("r", 15)
.style("fill", (d) => colorOrdinalScale(d))
.attr("transform", (d, i) => `translate(${100 + i * 70}, 20)`)
}
else {
console.log("circle", d)
legend
.append("path")
.attr("d", triangle)
.attr("fill", (d) => colorOrdinalScale(d))
.attr("transform", (d, i) => `translate(${100 + i * 70}, 20)`);
}
})</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="container"></div></code></pre>
</div>
</div>
</p>
<p>What is supposed to happen is that when the key is equal to <code>D</code> it should print out a triangle and the rest should print out a circle.</p>
<p>As far as I understand, the logic seems to be working. But the result is that both a triangle and a circle are printed for each datum. However, the log shows that the appropriate block of code runs.</p>
<p>Basically, this is the result that I am looking forward to:</p>
<p><a href="https://i.stack.imgur.com/OotaM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OotaM.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74544332,
"author": "Gerardo Furtado",
"author_id": 5768908,
"author_profile": "https://Stackoverflow.com/users/5768908",
"pm_score": 3,
"selected": true,
"text": "d3.symbol symbolCircle .attr(\"d\", d => symbol.type(d === \"D\" ? d3.symbolTriangle : d3.symbolCircle)())\n each const keys = [\"A\", \"B\", \"C\", \"D\", \"E\", \"E\", \"G\"]\nconst colors = ['#1e90ff', '#008000', '#d3d3d3', '#d3d3d3', '#fe0000', '#ffa500', '#800080']\n\nvar symbol = d3.symbol().size(500);\n\nconst colorOrdinalScale = d3.scaleOrdinal()\n .domain(keys)\n .range(colors);\n\nconst svg = d3\n .select(\"#container\")\n .append(\"svg\")\n .attr(\"class\", \"svg-area\")\n .attr(\"width\", 600)\n .attr(\"height\", 500)\n\nconst legend = svg\n .append('g')\n .attr('id', 'legend')\n .selectAll(\"symbols\")\n .data(keys)\n .enter()\n .append(\"path\")\n .attr(\"d\", d => symbol.type(d === \"D\" ? d3.symbolTriangle : d3.symbolCircle)())\n .attr(\"fill\", d => colorOrdinalScale(d))\n .attr(\"transform\", (d, i) => `translate(${100 + i * 70}, 20)`); <script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js\"></script>\n<div id=\"container\"></div>"
},
{
"answer_id": 74544417,
"author": "B Kalra",
"author_id": 1758832,
"author_profile": "https://Stackoverflow.com/users/1758832",
"pm_score": 1,
"selected": false,
"text": "const keys = [\"A\", \"B\", \"C\", \"D\", \"E\", \"E\", \"G\"]\nconst colors = ['#1e90ff', '#008000', '#d3d3d3', '#d3d3d3', '#fe0000', '#ffa500', '#800080']\n\nvar triangle = d3.symbol().type(d3.symbolTriangle).size(500);\n\nconst colorOrdinalScale = d3\n.scaleOrdinal()\n.domain(keys)\n.range(colors);\n\nconst svg = d3\n.select(\"#container\")\n.append(\"svg\")\n.attr(\"class\", \"svg-area\")\n.attr(\"width\", 600)\n.attr(\"height\", 500)\n\nconst legend = svg\n.append('g')\n.attr('id', 'legend')\n.selectAll(\"symbols\")\n.data(keys)\n.enter()\n\nlegend\n.each((d,index) => {\n if (d === \"D\") {\n console.log(\"triangle\", index)\n legend\n .filter(function (d, i) { return i == index;})\n .append(\"circle\")\n .attr(\"r\", 15)\n .style(\"fill\", (d) => colorOrdinalScale(d)) \n .attr(\"transform\", (d, i) => `translate(${100 + index * 70}, 20)`)\n } \n else {\n console.log(\"circle\", index)\n legend\n .filter(function (d, i) { return i == index;})\n .append(\"path\")\n .attr(\"d\", triangle)\n .attr(\"fill\", (d) => colorOrdinalScale(d))\n .attr(\"transform\", (d, i) => `translate(${100 + index * 70}, 20)`);\n }\n}) <script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js\"></script>\n<div id=\"container\"></div>"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12897021/"
] |
74,543,919
|
<p>I'm trying to build an Oauth2.0 Authorization server and I wanted to understand more about the response_type and grant_type parameters.</p>
<p>From what I've read so far,
response_type is a query parameter on the /authorize endpoint and it's values can be either 'token' or 'code' which indicates that the authorization server will respond with an access token or an authorization code.</p>
<p>grant_type is a query parameter on the /token endpoint which indicates which grant type will the authorization server use to either generate a token or a authorization code. Grant types can be 'authorization_code', 'client_credentials', 'implicit' etc.</p>
<p>My question is, how will the authorization server behave if I pick the response_type as 'token' but the grant_type as 'authorization_code' ?
Since the authorization code grant is supposed to return a code and not a token, what is the server going to do in this scenario ?</p>
<p>Similarly, if I choose 'code' response type and 'implicit' grant type, what will be the behaviour ?</p>
|
[
{
"answer_id": 74544332,
"author": "Gerardo Furtado",
"author_id": 5768908,
"author_profile": "https://Stackoverflow.com/users/5768908",
"pm_score": 3,
"selected": true,
"text": "d3.symbol symbolCircle .attr(\"d\", d => symbol.type(d === \"D\" ? d3.symbolTriangle : d3.symbolCircle)())\n each const keys = [\"A\", \"B\", \"C\", \"D\", \"E\", \"E\", \"G\"]\nconst colors = ['#1e90ff', '#008000', '#d3d3d3', '#d3d3d3', '#fe0000', '#ffa500', '#800080']\n\nvar symbol = d3.symbol().size(500);\n\nconst colorOrdinalScale = d3.scaleOrdinal()\n .domain(keys)\n .range(colors);\n\nconst svg = d3\n .select(\"#container\")\n .append(\"svg\")\n .attr(\"class\", \"svg-area\")\n .attr(\"width\", 600)\n .attr(\"height\", 500)\n\nconst legend = svg\n .append('g')\n .attr('id', 'legend')\n .selectAll(\"symbols\")\n .data(keys)\n .enter()\n .append(\"path\")\n .attr(\"d\", d => symbol.type(d === \"D\" ? d3.symbolTriangle : d3.symbolCircle)())\n .attr(\"fill\", d => colorOrdinalScale(d))\n .attr(\"transform\", (d, i) => `translate(${100 + i * 70}, 20)`); <script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js\"></script>\n<div id=\"container\"></div>"
},
{
"answer_id": 74544417,
"author": "B Kalra",
"author_id": 1758832,
"author_profile": "https://Stackoverflow.com/users/1758832",
"pm_score": 1,
"selected": false,
"text": "const keys = [\"A\", \"B\", \"C\", \"D\", \"E\", \"E\", \"G\"]\nconst colors = ['#1e90ff', '#008000', '#d3d3d3', '#d3d3d3', '#fe0000', '#ffa500', '#800080']\n\nvar triangle = d3.symbol().type(d3.symbolTriangle).size(500);\n\nconst colorOrdinalScale = d3\n.scaleOrdinal()\n.domain(keys)\n.range(colors);\n\nconst svg = d3\n.select(\"#container\")\n.append(\"svg\")\n.attr(\"class\", \"svg-area\")\n.attr(\"width\", 600)\n.attr(\"height\", 500)\n\nconst legend = svg\n.append('g')\n.attr('id', 'legend')\n.selectAll(\"symbols\")\n.data(keys)\n.enter()\n\nlegend\n.each((d,index) => {\n if (d === \"D\") {\n console.log(\"triangle\", index)\n legend\n .filter(function (d, i) { return i == index;})\n .append(\"circle\")\n .attr(\"r\", 15)\n .style(\"fill\", (d) => colorOrdinalScale(d)) \n .attr(\"transform\", (d, i) => `translate(${100 + index * 70}, 20)`)\n } \n else {\n console.log(\"circle\", index)\n legend\n .filter(function (d, i) { return i == index;})\n .append(\"path\")\n .attr(\"d\", triangle)\n .attr(\"fill\", (d) => colorOrdinalScale(d))\n .attr(\"transform\", (d, i) => `translate(${100 + index * 70}, 20)`);\n }\n}) <script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js\"></script>\n<div id=\"container\"></div>"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12401995/"
] |
74,543,985
|
<p>I have an odd issue and I am hoping you guys can help me.</p>
<p>The Task:
I want to post json to a API rest call.</p>
<p>And I am sure the rest API works - I have copied the json from print() in Swift and tried it in postman, and the works just fine.</p>
<p>When I try to post via Swift i get 400 Bad request.
The code:</p>
<pre><code> func postMobileContacts(serverURL: String, jsonToPost: String){
// Prepare URL
let url = URL(string: serverURL)
guard let requestUrl = url else { fatalError() }
// Prepare URL Request Object
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
// Set HTTP Request Body
request.httpBody = Data(jsonToPost.utf8);
// Set HTTP Request Header
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Authorization", forHTTPHeaderField: String(data: KeychainHelper.standard.read(service: "access-token", account: "store")!, encoding: .utf8)!)
// Perform HTTP Request
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
// Check for Error
if let error = error {
print("Error took place \(error)")
return
}
// Convert HTTP Response Data to a String
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string:\n \(dataString)")
}
}
task.resume()
}
</code></pre>
|
[
{
"answer_id": 74544596,
"author": "vishnu_146",
"author_id": 6081374,
"author_profile": "https://Stackoverflow.com/users/6081374",
"pm_score": 0,
"selected": false,
"text": " func postMobileContacts(serverURL: String, jsonToPost: Encodable) { //<--here\n \n // Prepare URL\n let url = URL(string: serverURL)\n guard let requestUrl = url else { fatalError() }\n \n let data = try! JSONEncoder().encode(jsonToPost) //<-Changed here\n \n // Prepare URL Request Object\n var request = URLRequest(url: requestUrl)\n request.httpMethod = \"POST\"\n \n // Set HTTP Request Body\n request.httpBody = data; //<-- and here\n \n \n // Set HTTP Request Header\n request.setValue(\"application/json\", forHTTPHeaderField: \"Accept\")\n request.setValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\n request.setValue(\"Authorization\", forHTTPHeaderField: String(data: KeychainHelper.standard.read(service: \"access-token\", account: \"store\")!, encoding: .utf8)!)\n // Perform HTTP Request\n let task = URLSession.shared.dataTask(with: request) { (data, response, error) in\n \n // Check for Error\n if let error = error {\n print(\"Error took place \\(error)\")\n return\n }\n \n // Convert HTTP Response Data to a String\n if let data = data, let dataString = String(data: data, encoding: .utf8) {\n print(\"Response data string:\\n \\(dataString)\")\n }\n }\n task.resume()\n }\n"
},
{
"answer_id": 74545818,
"author": "burnsi",
"author_id": 6950415,
"author_profile": "https://Stackoverflow.com/users/6950415",
"pm_score": 3,
"selected": true,
"text": "request.setValue(\"Authorization\", forHTTPHeaderField: String(data: KeychainHelper.standard.read(service: \"access-token\", account: \"store\")!, encoding: .utf8)!)\n request.setValue(String(data: KeychainHelper.standard.read(service: \"access-token\", account: \"store\")!, encoding: .utf8)!, forHTTPHeaderField: \"Authorization\")\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3453222/"
] |
74,543,989
|
<p>I wonder why we need to use a try-finally when using a the <a href="https://docs.python.org/3/library/contextlib.html" rel="nofollow noreferrer">@contextmanager</a> decorator.</p>
<p>The provided <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" rel="nofollow noreferrer">example</a> suggests:</p>
<pre class="lang-py prettyprint-override"><code>from contextlib import contextmanager
@contextmanager
def managed_resource(*args, **kwds):
resource = acquire_resource(*args, **kwds)
try:
yield resource
finally:
release_resource(resource)
</code></pre>
<p>It seems to me, however, that this will do the exact same thing:</p>
<pre class="lang-py prettyprint-override"><code>@contextmanager
def managed_resource(*args, **kwds):
resource = acquire_resource(*args, **kwds)
yield resource
release_resource(resource)
</code></pre>
<p>I'm sure I must be missing something. What am I missing?</p>
|
[
{
"answer_id": 74544596,
"author": "vishnu_146",
"author_id": 6081374,
"author_profile": "https://Stackoverflow.com/users/6081374",
"pm_score": 0,
"selected": false,
"text": " func postMobileContacts(serverURL: String, jsonToPost: Encodable) { //<--here\n \n // Prepare URL\n let url = URL(string: serverURL)\n guard let requestUrl = url else { fatalError() }\n \n let data = try! JSONEncoder().encode(jsonToPost) //<-Changed here\n \n // Prepare URL Request Object\n var request = URLRequest(url: requestUrl)\n request.httpMethod = \"POST\"\n \n // Set HTTP Request Body\n request.httpBody = data; //<-- and here\n \n \n // Set HTTP Request Header\n request.setValue(\"application/json\", forHTTPHeaderField: \"Accept\")\n request.setValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\n request.setValue(\"Authorization\", forHTTPHeaderField: String(data: KeychainHelper.standard.read(service: \"access-token\", account: \"store\")!, encoding: .utf8)!)\n // Perform HTTP Request\n let task = URLSession.shared.dataTask(with: request) { (data, response, error) in\n \n // Check for Error\n if let error = error {\n print(\"Error took place \\(error)\")\n return\n }\n \n // Convert HTTP Response Data to a String\n if let data = data, let dataString = String(data: data, encoding: .utf8) {\n print(\"Response data string:\\n \\(dataString)\")\n }\n }\n task.resume()\n }\n"
},
{
"answer_id": 74545818,
"author": "burnsi",
"author_id": 6950415,
"author_profile": "https://Stackoverflow.com/users/6950415",
"pm_score": 3,
"selected": true,
"text": "request.setValue(\"Authorization\", forHTTPHeaderField: String(data: KeychainHelper.standard.read(service: \"access-token\", account: \"store\")!, encoding: .utf8)!)\n request.setValue(String(data: KeychainHelper.standard.read(service: \"access-token\", account: \"store\")!, encoding: .utf8)!, forHTTPHeaderField: \"Authorization\")\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2123555/"
] |
74,543,998
|
<p>I'm working on a project and I'm trying to get the footer to stay at the bottom of the page but out of sight until you scroll to the bottom of the page. I tried using a 'position: fixed' in my CSS but it floats above my content, for absolute it stuck to the middle of the page and covered content. Also, for pages without much content when I don't specify the position or I use 'position: absolute', there is whitespace below the footer. Please provide suggestions.</p>
<pre><code>* {
margin: 0;
padding: 0;
}
header {
background-color: gray;
}
footer {
background-color: gray;
bottom: 0;
height: 20px;
position: fixed;
width: 100%;
}
/* when I use the fixed position, the footer is fixed above my content. What I want is for the footer to remain at the bottom of the page but out of sight. */
<html>
<body>
<header>Heading</header>
<main>
<h1>Heading</h1>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Adipisci eos deserunt fugiat doloremque your text`ut.</p>
</main>
<footer>&copy; Copyright, Business</footer>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 74544211,
"author": "ssspuer_ege",
"author_id": 20580063,
"author_profile": "https://Stackoverflow.com/users/20580063",
"pm_score": 1,
"selected": false,
"text": ".footer {\n position: fixed;\n bottom: 0;\n left: 0;\n width: 100vw;\n height: 200px;\n background-color: red;\n}\n.footer-container {\n height: 200px;\n width: 100vw;\n} <div class=\"footer-container\">\n <div class=\"footer\"></div>\n</div>"
},
{
"answer_id": 74544219,
"author": "pier farrugia",
"author_id": 19996700,
"author_profile": "https://Stackoverflow.com/users/19996700",
"pm_score": 1,
"selected": false,
"text": "* {\n margin: 0;\n padding: 0;\n}\n\nheader {\n background-color: gray;\n}\n\nmain {\n min-height: 100vh;\n}\n\nfooter {\n background-color: gray;\n bottom: 0;\n height: 20px;\n width: 100%;\n} <header>Heading</header>\n<main>\n <h1>Heading</h1>\n <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Adipisci eos deserunt fugiat doloremque your text`ut.</p>\n</main>\n<footer>© Copyright, Business</footer>"
},
{
"answer_id": 74544375,
"author": "Abdul Samad",
"author_id": 3143678,
"author_profile": "https://Stackoverflow.com/users/3143678",
"pm_score": 1,
"selected": false,
"text": "html,body{\n width: 100%;\n height: 100%;\n}\nbody{\n display: flex;\n flex-direction: column;\n}\nbody main{\n flex-grow: 1;\n overflow: auto;\n}\n position: fixed\n"
},
{
"answer_id": 74544399,
"author": "Cédric",
"author_id": 17684809,
"author_profile": "https://Stackoverflow.com/users/17684809",
"pm_score": 0,
"selected": false,
"text": "display: table-footer-group display:table body min-height: 100vh * {\n margin: 0;\n padding: 0;\n}\n\nbody {\n display: table;\n min-height: 100vh;\n width: 100%;\n}\n\nheader {\n background-color: gray;\n}\n\nfooter {\n background-color: gray;\n height: 20px;\n width: 100%;\n display: table-footer-group;\n}\n\n#big-content {\n height: 2000px;\n align-items: end;\n display: none;\n}\n\ninput:checked+#big-content {\n display: flex;\n} <header>Heading</header>\n<main>\n <h1>Heading</h1>\n <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Adipisci eos deserunt fugiat doloremque your text`ut.</p>\n <label for=\"more-content\">More content</label>\n <input id=\"more-content\" type=\"checkbox\">\n <div id=\"big-content\">end of big content</div>\n</main>\n<footer>© Copyright, Business</footer>"
},
{
"answer_id": 74544560,
"author": "Anish Dalvi",
"author_id": 17417451,
"author_profile": "https://Stackoverflow.com/users/17417451",
"pm_score": 1,
"selected": false,
"text": " \n <html>\n <style>\n * {\n margin: 0;\n padding: 0;\n }\n \n header {\n background-color: gray;\n }\n \n footer {\n background-color: gray;\n position: absolute;\n bottom: 0;\n height: 20px;\n \n width: 100%;\n }\n .container{\n height: 1000px;\n position: relative;\n }\n \n </style>\n <body>\n <header>Heading</header>\n <main>\n <div class=\"container\">\n <div class=\"content\">\n <h1>Heading</h1>\n <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Adipisci eos deserunt fugiat doloremque your text`ut.</p>\n <h1>Heading</h1>\n <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Adipisci eos deserunt fugiat doloremque your text`ut.</p>\n\n </div>\n\n\n\n <div>\n <footer>© Copyright, Business</footer>\n </div>\n </div>\n \n </main>\n </body>\n </html>"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74543998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20557728/"
] |
74,544,030
|
<p>In a Spring Boot app, I am reading csv file data using OpenCSV and it is possible to use FileReader to BufferedReader with it. However, when I compare both of them, I have a dilemma for the following point:</p>
<blockquote>
<p>BufferedReader is faster than FileReader, but it uses much more memory.</p>
</blockquote>
<p>As I am reading multiple data file (having hundreds of thousands records) in the same method (first I read data from one csv and then use the retrieved id fields to read the second csv), I think I shouldn't use <code>BufferedReader</code> for less memory usage. But I am really not sure what is the most proper way.</p>
<p>So, in this situation, Should I prefer FileReader to BufferedReader?</p>
|
[
{
"answer_id": 74544211,
"author": "ssspuer_ege",
"author_id": 20580063,
"author_profile": "https://Stackoverflow.com/users/20580063",
"pm_score": 1,
"selected": false,
"text": ".footer {\n position: fixed;\n bottom: 0;\n left: 0;\n width: 100vw;\n height: 200px;\n background-color: red;\n}\n.footer-container {\n height: 200px;\n width: 100vw;\n} <div class=\"footer-container\">\n <div class=\"footer\"></div>\n</div>"
},
{
"answer_id": 74544219,
"author": "pier farrugia",
"author_id": 19996700,
"author_profile": "https://Stackoverflow.com/users/19996700",
"pm_score": 1,
"selected": false,
"text": "* {\n margin: 0;\n padding: 0;\n}\n\nheader {\n background-color: gray;\n}\n\nmain {\n min-height: 100vh;\n}\n\nfooter {\n background-color: gray;\n bottom: 0;\n height: 20px;\n width: 100%;\n} <header>Heading</header>\n<main>\n <h1>Heading</h1>\n <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Adipisci eos deserunt fugiat doloremque your text`ut.</p>\n</main>\n<footer>© Copyright, Business</footer>"
},
{
"answer_id": 74544375,
"author": "Abdul Samad",
"author_id": 3143678,
"author_profile": "https://Stackoverflow.com/users/3143678",
"pm_score": 1,
"selected": false,
"text": "html,body{\n width: 100%;\n height: 100%;\n}\nbody{\n display: flex;\n flex-direction: column;\n}\nbody main{\n flex-grow: 1;\n overflow: auto;\n}\n position: fixed\n"
},
{
"answer_id": 74544399,
"author": "Cédric",
"author_id": 17684809,
"author_profile": "https://Stackoverflow.com/users/17684809",
"pm_score": 0,
"selected": false,
"text": "display: table-footer-group display:table body min-height: 100vh * {\n margin: 0;\n padding: 0;\n}\n\nbody {\n display: table;\n min-height: 100vh;\n width: 100%;\n}\n\nheader {\n background-color: gray;\n}\n\nfooter {\n background-color: gray;\n height: 20px;\n width: 100%;\n display: table-footer-group;\n}\n\n#big-content {\n height: 2000px;\n align-items: end;\n display: none;\n}\n\ninput:checked+#big-content {\n display: flex;\n} <header>Heading</header>\n<main>\n <h1>Heading</h1>\n <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Adipisci eos deserunt fugiat doloremque your text`ut.</p>\n <label for=\"more-content\">More content</label>\n <input id=\"more-content\" type=\"checkbox\">\n <div id=\"big-content\">end of big content</div>\n</main>\n<footer>© Copyright, Business</footer>"
},
{
"answer_id": 74544560,
"author": "Anish Dalvi",
"author_id": 17417451,
"author_profile": "https://Stackoverflow.com/users/17417451",
"pm_score": 1,
"selected": false,
"text": " \n <html>\n <style>\n * {\n margin: 0;\n padding: 0;\n }\n \n header {\n background-color: gray;\n }\n \n footer {\n background-color: gray;\n position: absolute;\n bottom: 0;\n height: 20px;\n \n width: 100%;\n }\n .container{\n height: 1000px;\n position: relative;\n }\n \n </style>\n <body>\n <header>Heading</header>\n <main>\n <div class=\"container\">\n <div class=\"content\">\n <h1>Heading</h1>\n <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Adipisci eos deserunt fugiat doloremque your text`ut.</p>\n <h1>Heading</h1>\n <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Adipisci eos deserunt fugiat doloremque your text`ut.</p>\n\n </div>\n\n\n\n <div>\n <footer>© Copyright, Business</footer>\n </div>\n </div>\n \n </main>\n </body>\n </html>"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20562773/"
] |
74,544,037
|
<p>We are developing a software product that needs a very big amount of data and we are trying to find the most efficient way to concatenate 3 strings. We used the most known ways to concatenate the strings, such as the "+" operator or the "CONCAT" function.
My query will look like this, when I use the "+" operator:</p>
<pre><code> declare @S1 varchar(max)
declare @s2 varchar(max)
declare @s varchar(max)
declare @lni int
set @lni = 0
set @s = cast('' as varchar(max))
set @S1 = cast('TEST' as varchar(max))
set @s2 = cast(' OK' as varchar(max))
while (@lni <100000) begin
set @lni = @lni+1
set @S =@s+ @S1+ @s2
end
print len(@S)
print @S
</code></pre>
<p>Using "Concat" function, my query will look like this:</p>
<pre><code> declare @S1 varchar(max)
declare @s2 varchar(max)
declare @s varchar(max)
declare @lni int
set @lni = 0
set @s = cast('' as varchar(max))
set @S1 = cast('TEST' as varchar(max))
set @s2 = cast(' OK' as varchar(max))
while (@lni <100000) begin
set @lni = @lni+1
set @S =concat(@S,@S1,@S2)
end
print len(@S)
print @S
</code></pre>
<p>The query that used the "+" operator was executed by the SSMS in 2 minutes and 30 seconds and the one using "CONCAT" function was exected in a minute and 18 seconds. I also have to mention that I replaced '100000' with '10000000' and it was executed in more than 5 hours. I am curious if we can find a faster way to execute.</p>
|
[
{
"answer_id": 74544241,
"author": "Stu",
"author_id": 15332650,
"author_profile": "https://Stackoverflow.com/users/15332650",
"pm_score": 3,
"selected": true,
"text": " declare @s varchar(max) = '', @s1 varchar(max) = 'TEST', @s2 varchar(max) = ' OK';\n with \n l0 as (select 0 v from (values(0),(0),(0),(0),(0))v(v)), \n l1 as (select 1 v from l0 a cross join l0 b),\n l2 as (select 2 v from l1 a cross join l1 b),\n l3 as (select 3 v from l2 a cross join l2 b),\n l4 as (select 4 v from l3 a cross join l3 b),\n n as (select n = Row_Number() over(order by @@spid) from l4)\n\n select top (100000) \n @s = string_agg(concat(@s1, @s2),'') \n from n;\n\n print @s;\n"
},
{
"answer_id": 74544585,
"author": "Nenad Zivkovic",
"author_id": 612181,
"author_profile": "https://Stackoverflow.com/users/612181",
"pm_score": 1,
"selected": false,
"text": " declare @S1 varchar(max)\n declare @s2 varchar(max)\n declare @s varchar(max)\n declare @lni int \n set @lni = 0 \n\n set @s = cast('' as varchar(max))\n set @S1 = cast('TEST' as varchar(max))\n set @s2 = cast(' OK' as varchar(max))\n ;\n\n WITH CTE AS \n (\n SELECT concat(@S,@S1,@S2) s, @lni as i\n UNION ALL\n SELECT s,i+1 FROM CTE\n WHERE i<99999\n)\nSelect @S = \n( \n SELECT S AS [text()]\n FROM CTE\n FOR XML PATH ('')\n)\nOPTION (MAXRECURSION 0);\n\nprint len(@S)\nprint @S\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10834046/"
] |
74,544,038
|
<p>I want to disable button after one click.
I use this code:</p>
<pre><code>const handleClick = (event) => {
event.currentTarget.disabled = true;
console.log(event);
console.log('button clicked');
};
</code></pre>
<p>When I have only one button it Works.</p>
<pre><code><div className="col-md-1">
<button type="submit" onClick={handleClick} className="btn btn-
success">Filtriraj</button>
</div>
</code></pre>
<p>but when I have multiple same buttons it doesn't work.</p>
<pre><code><div className="showAds" >
{adsList.map((val, key) => {
return <div className="ad" key={key}>
<h4> {val.content}</h4>
<h5><a href=""><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#bb2d3b" className="bi bi-geo-alt-fill" viewBox="0 0 16 16">
<path d="M8 16s6-5.686 6-10A6 6 0 0 0 2 6c0 4.314 6 10 6 10zm0-7a3 3 0 1 1 0-6 3 3 0 0 1 0 6z"></path>
</svg>{val.adress}</a></h5>
<h5>Likes: {val.likes}</h5>
<div>
{""}
<button type="submit" onClick={() => {addLike(val.id, val.likes + 1);handleClick}} className="btn btn-success" > LIKE</button>
</div>
</div>
})}
</div>
</code></pre>
<p>The problem is when I try to call handleClick it shows me the error:</p>
<pre><code> Expected an assignment or function call and instead saw an expression
</code></pre>
|
[
{
"answer_id": 74544241,
"author": "Stu",
"author_id": 15332650,
"author_profile": "https://Stackoverflow.com/users/15332650",
"pm_score": 3,
"selected": true,
"text": " declare @s varchar(max) = '', @s1 varchar(max) = 'TEST', @s2 varchar(max) = ' OK';\n with \n l0 as (select 0 v from (values(0),(0),(0),(0),(0))v(v)), \n l1 as (select 1 v from l0 a cross join l0 b),\n l2 as (select 2 v from l1 a cross join l1 b),\n l3 as (select 3 v from l2 a cross join l2 b),\n l4 as (select 4 v from l3 a cross join l3 b),\n n as (select n = Row_Number() over(order by @@spid) from l4)\n\n select top (100000) \n @s = string_agg(concat(@s1, @s2),'') \n from n;\n\n print @s;\n"
},
{
"answer_id": 74544585,
"author": "Nenad Zivkovic",
"author_id": 612181,
"author_profile": "https://Stackoverflow.com/users/612181",
"pm_score": 1,
"selected": false,
"text": " declare @S1 varchar(max)\n declare @s2 varchar(max)\n declare @s varchar(max)\n declare @lni int \n set @lni = 0 \n\n set @s = cast('' as varchar(max))\n set @S1 = cast('TEST' as varchar(max))\n set @s2 = cast(' OK' as varchar(max))\n ;\n\n WITH CTE AS \n (\n SELECT concat(@S,@S1,@S2) s, @lni as i\n UNION ALL\n SELECT s,i+1 FROM CTE\n WHERE i<99999\n)\nSelect @S = \n( \n SELECT S AS [text()]\n FROM CTE\n FOR XML PATH ('')\n)\nOPTION (MAXRECURSION 0);\n\nprint len(@S)\nprint @S\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,544,052
|
<p>I set state(id) on button click and i want to use that data(id) in that state, it just showing undefined in the first click</p>
<p>[State Initialization]
<code>const [id,setId] = useState("");</code></p>
<p>[Onclick of Button]</p>
<pre><code>`render: (record) => (
<div>
<Button
className="details-btn-approve"
onClick={()=>{
handleApprove(record)
}}
>
Approve
</Button>
)`
</code></pre>
<p>[useEffect and calling on click action]</p>
<p>`</p>
<pre><code>useEffect(()=>{
},[id]);
const handleApprove = async (record) => {
setId(record.ID);
console.log(id);
}
</code></pre>
<p>`</p>
<p>i was expecting the id to be changing every time i click button</p>
<p>here is the complete Code
`</p>
<pre><code>import {useEffect, useState} from "react";
import {Button, Card, Input, Modal, Table} from "antd";
import axios from "axios";
import {endPoints} from "./ApiEndPoints";
function Approval() {
const [isLoading, setIsLoading] = useState(false);
const [dataSource, setDataSource] = useState([]);
const [searchedText,setSearchedText] = useState("");
const [id,setId] = useState("");
useEffect(()=>{
ViewUnApproved();
},[setDataSource])
const ViewUnApproved = async () =>{
setIsLoading(true);
const {data: response} = await axios.get(
endPoints.pendingApprovalAsset
);
if (response["status"] === 100){
setIsLoading(false)
setDataSource(response["pending_approval"]);
} else if(response["status"] === 104){
console.log('no data ')
}
}
useEffect(()=>{
},[id])
const handleApprove = async (record) => {
setId(record.ID);
const data = {
ASSET_ID: id,
}
const {data: response } = await axios.post(
endPoints.approve,
data
);
if((response["status"] = 100)){
setIsLoading(false);
console.log(response.to_be_approved);
}
}
console.log(id);
const columns = [
{
title: "Asset",
dataIndex: "DESCRIPTION",
key: "name",
filteredValue:[searchedText],
onFilter:(value,record)=>{
return String(record.DESCRIPTION)
.toLowerCase()
.includes(value.toLowerCase()) ||
String(record.TAG_NUMBER)
.toLowerCase()
.includes(value.toLowerCase()) ||
String(record.BUILDING_NAME)
.toLowerCase()
.includes(value.toLowerCase()) ||
String(record.STATUS)
.toLowerCase()
.includes(value.toLowerCase()) ||
String(record.CONDITION)
.toLowerCase()
.includes(value.toLowerCase())
}
},
{
title: "Tag",
dataIndex: "TAG_NUMBER",
key: "tag",
},
{
title: "Location",
dataIndex: "BUILDING_NAME",
key: "location",
},
{
title: "Status",
dataIndex: "STATUS",
key: "status",
},
{
title: "Condition",
dataIndex: "CONDITION",
key: "condition",
},
{
title: "Action",
key: "",
render: (record) => (
<div>
<Button
className="details-btn-approve"
onClick={()=>{
handleApprove(record)
}}
>
Approve
</Button>
<Button
className="details-btn-reject"
id={record.ID}
type="danger"
onClick={() => {
//showModal(record);
}}
>
Reject
</Button>
</div>
),
},
];
return (
<>
<Card
title="LIST OF ASSETS TO BE APPROVED"
bordered={false}
className="table-card"
>
<Input.Search className='search-input'
placeholder ="Search here ..."
onSearch={(value)=>{
setSearchedText(value)
}}
onChange = {(e)=>{
setSearchedText(e.target.value)
}}
/>
<Table
loading={isLoading}
columns={columns}
dataSource={dataSource}
pagination={{ pageSize: 10 }}
/>
</Card>
</>
);
}
export default Approval;
</code></pre>
<p>`</p>
|
[
{
"answer_id": 74544241,
"author": "Stu",
"author_id": 15332650,
"author_profile": "https://Stackoverflow.com/users/15332650",
"pm_score": 3,
"selected": true,
"text": " declare @s varchar(max) = '', @s1 varchar(max) = 'TEST', @s2 varchar(max) = ' OK';\n with \n l0 as (select 0 v from (values(0),(0),(0),(0),(0))v(v)), \n l1 as (select 1 v from l0 a cross join l0 b),\n l2 as (select 2 v from l1 a cross join l1 b),\n l3 as (select 3 v from l2 a cross join l2 b),\n l4 as (select 4 v from l3 a cross join l3 b),\n n as (select n = Row_Number() over(order by @@spid) from l4)\n\n select top (100000) \n @s = string_agg(concat(@s1, @s2),'') \n from n;\n\n print @s;\n"
},
{
"answer_id": 74544585,
"author": "Nenad Zivkovic",
"author_id": 612181,
"author_profile": "https://Stackoverflow.com/users/612181",
"pm_score": 1,
"selected": false,
"text": " declare @S1 varchar(max)\n declare @s2 varchar(max)\n declare @s varchar(max)\n declare @lni int \n set @lni = 0 \n\n set @s = cast('' as varchar(max))\n set @S1 = cast('TEST' as varchar(max))\n set @s2 = cast(' OK' as varchar(max))\n ;\n\n WITH CTE AS \n (\n SELECT concat(@S,@S1,@S2) s, @lni as i\n UNION ALL\n SELECT s,i+1 FROM CTE\n WHERE i<99999\n)\nSelect @S = \n( \n SELECT S AS [text()]\n FROM CTE\n FOR XML PATH ('')\n)\nOPTION (MAXRECURSION 0);\n\nprint len(@S)\nprint @S\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19245986/"
] |
74,544,092
|
<p>I'm trying to do the test to learn Allure, and to assure that the test is passed, the button has to be INVISIBLE. It first clicks 1st button to make 2nd button appear. Then click 2nd button - so same (2nd button disappears). Here it is: <a href="http://the-internet.herokuapp.com/add_remove_elements/" rel="nofollow noreferrer">http://the-internet.herokuapp.com/add_remove_elements/</a></p>
<p>My code would look like this (below), it clicks the 1st button, 2nd button - and after it should check that button DELETE is not visible anymore. Instead it interrupts whole code and throws error that element was not found/located.
How do you make it so it will not interrput/cancel whole codeblock when it doesn't find this button?</p>
<pre><code>class TestPage:
def test_button(self):
s=Service('C:\Program Files\chromedriver.exe')
browser = webdriver.Chrome(service=s)
browser.get("http://the-internet.herokuapp.com/")
browser.maximize_window()
time.sleep(1)
add = browser.find_element(By.XPATH, "/html/body/div[2]/div/ul/li[2]/a")
add.click()
time.sleep(1)
button = browser.find_element(By.XPATH, "/html/body/div[2]/div/div/button")
button.click()
time.sleep(1)
deleteButton = browser.find_element(By.XPATH, "/html/body/div[2]/div/div/div/button")
deleteButton.click()
deleteCheck = browser.find_element(By.XPATH, "/html/body/div[2]/div/div/div/button").is_displayed()
if deleteCheck == False:
assert True
else:
assert False
time.sleep(1)
browser.close()
</code></pre>
<p>Here's edited code (with last step trying to go to main page):</p>
<pre><code>def test_button(self):
s=Service('C:\Program Files\chromedriver.exe')
browser = webdriver.Chrome(service=s)
browser.get("http://the-internet.herokuapp.com/")
browser.maximize_window()
wait = WebDriverWait(browser, 3)
time.sleep(1)
add = browser.find_element(By.XPATH, "/html/body/div[2]/div/ul/li[2]/a")
add.click()
time.sleep(1)
button = browser.find_element(By.XPATH, "/html/body/div[2]/div/div/button")
button.click()
time.sleep(1)
browser.save_screenshot('buttons.png')
time.sleep(1)
delete = browser.find_element(By.XPATH, "/html/body/div[2]/div/div/div/button")
delete.click()
time.sleep(1)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[onclick*='delete']"))).click()
time.sleep(0.5)
if not browser.find_elements(By.CSS_SELECTOR, "button[onclick*='delete']"):
assert True
else:
assert False
time.sleep(0.5)
browser.get("http://the-internet.herokuapp.com/")
</code></pre>
|
[
{
"answer_id": 74544241,
"author": "Stu",
"author_id": 15332650,
"author_profile": "https://Stackoverflow.com/users/15332650",
"pm_score": 3,
"selected": true,
"text": " declare @s varchar(max) = '', @s1 varchar(max) = 'TEST', @s2 varchar(max) = ' OK';\n with \n l0 as (select 0 v from (values(0),(0),(0),(0),(0))v(v)), \n l1 as (select 1 v from l0 a cross join l0 b),\n l2 as (select 2 v from l1 a cross join l1 b),\n l3 as (select 3 v from l2 a cross join l2 b),\n l4 as (select 4 v from l3 a cross join l3 b),\n n as (select n = Row_Number() over(order by @@spid) from l4)\n\n select top (100000) \n @s = string_agg(concat(@s1, @s2),'') \n from n;\n\n print @s;\n"
},
{
"answer_id": 74544585,
"author": "Nenad Zivkovic",
"author_id": 612181,
"author_profile": "https://Stackoverflow.com/users/612181",
"pm_score": 1,
"selected": false,
"text": " declare @S1 varchar(max)\n declare @s2 varchar(max)\n declare @s varchar(max)\n declare @lni int \n set @lni = 0 \n\n set @s = cast('' as varchar(max))\n set @S1 = cast('TEST' as varchar(max))\n set @s2 = cast(' OK' as varchar(max))\n ;\n\n WITH CTE AS \n (\n SELECT concat(@S,@S1,@S2) s, @lni as i\n UNION ALL\n SELECT s,i+1 FROM CTE\n WHERE i<99999\n)\nSelect @S = \n( \n SELECT S AS [text()]\n FROM CTE\n FOR XML PATH ('')\n)\nOPTION (MAXRECURSION 0);\n\nprint len(@S)\nprint @S\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20396568/"
] |
74,544,098
|
<p>in my application I'm opening a Window for an Input form. In my App.xaml I have defined the following:</p>
<pre><code> <DataTemplate DataType="{x:Type ViewModels:EditTicketViewModel}">
<Frame>
<Frame.Content>
<Views:EditTicketView></Views:EditTicketView>
</Frame.Content>
</Frame>
</DataTemplate>
</code></pre>
<p>My application also has a Window service for opening windows:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DevPortal.Interfaces
{
public interface IWindowService
{
public void ShowWindow(object viewModel, bool showDialog);
}
}
</code></pre>
<p>the implementation:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using DevPortal.Interfaces;
using Syncfusion.Windows.Shared;
using Syncfusion.SfSkinManager;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace DevPortal.Services
{
public class WindowService : IWindowService
{
public void ShowWindow(object viewModel, bool showDialog)
{
var window = new ChromelessWindow();
window.ResizeMode = ResizeMode.NoResize;
SfSkinManager.SetTheme(window, new Theme("FluentDark"));
window.Content = viewModel;
window.SizeToContent = SizeToContent.WidthAndHeight;
window.Title = viewModel.GetType().GetProperty("Title").GetValue(viewModel).ToString();
window.ShowIcon = false;
if (showDialog)
{
window.ShowDialog();
} else
{
window.Show();
}
}
}
}
</code></pre>
<p>How I open the window (from a viewmodel in the MainView)</p>
<pre><code> [RelayCommand]
private void CreateTicket()
{
App.Current.ServiceProvider.GetService<IWindowService>().ShowWindow(new EditTicketViewModel(), true);
}
</code></pre>
<p>What would be the best way to close this window from the ViewModel? Previously i was used to directly create the view, and in the constructor of the view i would subscribe to a close-event in the viewmodel, but that's not really the MVVM-way I guess. Do I need to implement some kind of service? Thanks!</p>
<p>EDIT: I forgott to mention that the View is a page. So i Am creating a window with the viewmodel as content, and the datatemplate of the viewmodel is a Frame containing the page.</p>
|
[
{
"answer_id": 74545172,
"author": "mm8",
"author_id": 7252182,
"author_profile": "https://Stackoverflow.com/users/7252182",
"pm_score": 1,
"selected": false,
"text": "IWindow public class WindowService : IWindowService\n{\n public IWindow ShowWindow(object viewModel, bool showDialog)\n {\n var window = new ChromelessWindow();\n ...\n return window;\n }\n}\n Close() public interface IWindow\n{\n void Close();\n}\n ChromelessWindow public partial class ChromelessWindow : Window, IWindow { ... }\n IWindow"
},
{
"answer_id": 74545521,
"author": "Peregrine",
"author_id": 967885,
"author_profile": "https://Stackoverflow.com/users/967885",
"pm_score": 0,
"selected": false,
"text": "public static class perWindowHelper\n{\n public static readonly DependencyProperty CloseWindowProperty = DependencyProperty.RegisterAttached(\n \"CloseWindow\",\n typeof(bool?),\n typeof(perWindowHelper),\n new PropertyMetadata(null, OnCloseWindowChanged));\n\n private static void OnCloseWindowChanged(DependencyObject target, DependencyPropertyChangedEventArgs args)\n {\n if (!(target is Window view))\n {\n return;\n }\n\n if (view.IsModal())\n {\n view.DialogResult = args.NewValue as bool?;\n }\n else\n {\n view.Close();\n }\n }\n\n public static void SetCloseWindow(Window target, bool? value)\n {\n target.SetValue(CloseWindowProperty, value);\n }\n\n public static bool IsModal(this Window window)\n {\n var fieldInfo = typeof(Window).GetField(\"_showingAsDialog\", BindingFlags.Instance | BindingFlags.NonPublic);\n return fieldInfo != null && (bool)fieldInfo.GetValue(window);\n }\n}\n private bool? _viewClosed;\n\npublic bool? ViewClosed\n{\n get => _viewClosed;\n set => Set(nameof(ViewClosed), ref _viewClosed, value);\n}\n <Window\n ...\n vhelp:perWindowHelper.CloseWindow=\"{Binding ViewClosed}\" >\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3052148/"
] |
74,544,132
|
<p>I started learning rust from <a href="https://doc.rust-lang.org/rust-by-example/" rel="nofollow noreferrer">https://doc.rust-lang.org/rust-by-example/</a>, and as far as I understand rust uses move on an assignment, and you explicitly have to tell it to copy with <code>clone()</code>.</p>
<pre><code>#[derive(Debug)]
struct Point {
x: f32,
y: f32,
}
impl Point {
fn destroy(self) {
let Point{x, y} = self;
println!("pt is consumed: {}, {}", x, y);
}
}
fn main() {
let pt = Point{x: 2f32, y: 2f32};
let Point{x, y} = pt; //#a
println!("destructured, pt not consumed: {}, {}", x, y);
let pt2 = pt; //#b
//println!("pt is consumed: {:?}", pt);
pt2.destroy(); //#c
//println!("pt2 is consumed: {:?}", pt2);
}
</code></pre>
<p>So pt is consumed on <code>#b</code>, that is clear why. But why is it consumed on <code>#c</code> when it's not consumed on <code>#a</code>?</p>
|
[
{
"answer_id": 74544188,
"author": "Cerberus",
"author_id": 3003401,
"author_profile": "https://Stackoverflow.com/users/3003401",
"pm_score": 2,
"selected": false,
"text": "Copy Copy String error[E0382]: use of partially moved value: `pt`\n --> src/main.rs:18:15\n |\n16 | let Point{x, y} = pt; //#a\n | - value partially moved here\n17 | println!(\"destructured, pt not consumed: {}, {}\", x, y);\n18 | let pt2 = pt; //#b\n | ^^ value used here after partial move\n |\n = note: partial move occurs because `pt.y` has type `String`, which does not implement the `Copy` trait\n"
},
{
"answer_id": 74544207,
"author": "cafce25",
"author_id": 442760,
"author_profile": "https://Stackoverflow.com/users/442760",
"pm_score": 3,
"selected": true,
"text": "f32 Copy let x = pt.x;\nlet y = pt.y;\n pt Point::destroy() Point self &self Point self let Point{ x, y } = self; pt2 pt2.destroy()"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20580001/"
] |
74,544,138
|
<p>The following data is about a person sending an IpHone 14 pro max to his wife. The Iphone 14 pro max
has to travel from America to China, China to Argentina and finally from Argentina to Saudi Arabia since the girl is at Saudi Arabia
watching FIFA.</p>
<pre><code>CREATE TABLE IPhone (Id int, Country NVARCHAR(12), seqNo int, Send datetime2(0), Arrive datetime2(0));
INSERT INTO IPhone VALUES
('1001','America','1', '2022-11-23 18:30:00.000',null),
('1002','China','2', '2022-11-24 08:18:00.000','2022-11-24 05:00:00'),
('1003','Argentina','3', '2022-11-25 18:30:00.000','2022-11-24 18:18:00.000'),
('1004','Saudi Arabia','4',null,'2022-11-25 20:30:00.000');
</code></pre>
<p>What I am trying to achieve is</p>
<ol>
<li>Sent from America on 2022-11-23 18:30:00.000 and reached on China at
2022-11-24 05:00:00</li>
<li>Sent from China on 2022-11-24 08:18:00.000 and<br />
reached on Argentina on 2022-11-24 18:18:00.000</li>
<li>Sent from Argentina
on 2022-11-25 18:30:00.000 and reached on Saudi Arabia on 2022-11-25
20:30:00.000</li>
</ol>
|
[
{
"answer_id": 74544316,
"author": "Anel Hodžić",
"author_id": 4018834,
"author_profile": "https://Stackoverflow.com/users/4018834",
"pm_score": 0,
"selected": false,
"text": "select\nId, Country countryFrom, \n (select top 1 Country from IPhone c where c.seqNo > IPhone.seqNo ) CountryTo, \n Send_date,\n (select top 1 Arrive_date from IPhone c where c.seqNo > IPhone.seqNo ) Arrive\n\nfrom IPhone \n select \n IPhone.Id,\n IPhone.Country,\n c.country,\n IPhone.Send_date,\n c.Arrive_date\nfrom IPhone\nleft join IPhone c on IPhone.seqNo + 1 = c.seqNo\n"
},
{
"answer_id": 74544389,
"author": "Dale K",
"author_id": 1127428,
"author_profile": "https://Stackoverflow.com/users/1127428",
"pm_score": 2,
"selected": true,
"text": "CREATE TABLE IPhone (Id int, Country NVARCHAR(12), seqNo int, Send datetime2(0), Arrive datetime2(0));\n\nINSERT INTO IPhone VALUES \n('1001','America','1', '2022-11-23 18:30:00.000',null),\n('1002','China','2', '2022-11-24 08:18:00.000','2022-11-24 05:00:00'),\n('1003','Argentina','3', '2022-11-25 18:30:00.000','2022-11-24 18:18:00.000'),\n('1004','Saudi Arabia','4',null,'2022-11-25 20:30:00.000');\n\nSELECT f.id, f.Country CountryFrom, t.Country CountryTo\n , convert(varchar(4),f.seqNo) + '-' + convert(varchar(4),t.seqNo) seqNo\n , f.Send, t.Arrive\nFROM IPhone f\nINNER JOIN IPhone t ON t.seqNo = f.seqNo + 1\nORDER BY id;\n"
},
{
"answer_id": 74544996,
"author": "Nenad Zivkovic",
"author_id": 612181,
"author_profile": "https://Stackoverflow.com/users/612181",
"pm_score": 1,
"selected": false,
"text": "SELECT id\n, Country AS CountryFrom\n, LEAD(Country,1) OVER (ORDER BY SeqNo) AS CountryTo\n, CAST(seqNo AS VARCHAR(4)) + '-' + CAST(LEAD(seqNo,1) OVER (ORDER BY SeqNo) AS VARCHAR(4)) AS seqNo\n, Send\n, LEAD (Arrive,1) OVER (ORDER BY SeqNo) AS Arrive\nFROM Iphone\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20319015/"
] |
74,544,164
|
<p>I have a Bicep template where I create an <code>App Service</code> in which I need to link a SSL certificate that exists in Key Vault (both in same resource group).</p>
<p>The Key Vault has Azure RBAC enabled.</p>
<p>I use the following to Bicep template to link the SSL certificate from Key Vault to the App Service:</p>
<pre><code>resource certEncryption 'Microsoft.Web/certificates@2018-02-01' = {
name: '${resourcePrefix}-cert-encryption'
location: location
properties: {
keyVaultId: resourceId('myResourceGroup', 'Microsoft.KeyVault/vaults', keyVaultName)
keyVaultSecretName: '${resourcePrefix}-cert-encryption'
serverFarmId: hostingPlan.id
password: 'SecretPassword'
}
dependsOn: [
webApi
]
}
</code></pre>
<p>But it fails with the following message:</p>
<blockquote>
<p>The service does not have access to '/subscriptions/3449f-xxxx/resourcegroups/rgabptrialt/providers/microsoft.keyvault/vaults/my-test-vault' Key Vault. Please make sure that you have granted necessary permissions to the service to perform the request operation.</p>
</blockquote>
<p>This isn't really telling a lot...</p>
<p>What permission do I need to grant <strong>exactly</strong>? And to what? And where and how do I even grant these permissions?</p>
<p>Do I have to create a Managed Identity and link that in my App Service? And what Permissions/Roles do I need exactly? Or do I need to do something else to make this work?</p>
<p>I couldn't really find any good info on how to do this.</p>
|
[
{
"answer_id": 74590743,
"author": "Pradeep Kumar",
"author_id": 18704952,
"author_profile": "https://Stackoverflow.com/users/18704952",
"pm_score": -1,
"selected": false,
"text": " Ensure that the service principal has all the permissions. The only thing that worked for me though is adding the service principal 24681998-555f-4570-a559-2fced2d7e841 which shows up as Microsoft.Azure.WebSites. You can add this through the portal, by adding an access policy for Microsoft.Azure.WebSites or through arm with the GUID."
},
{
"answer_id": 74654463,
"author": "Jahnavi",
"author_id": 19785512,
"author_profile": "https://Stackoverflow.com/users/19785512",
"pm_score": 0,
"selected": false,
"text": "keyvault -> secrets key vault Access Policies ssl certificate key,secret & certificate management AzureAD -> App registrations App Service -> Web Application -> Certificates keyvault -> secrets .pfx resource certEncryption 'Microsoft.Web/certificates@2018-02-01' = {\nname: 'xcc-cert-encryption'\nlocation: 'EastUS'\nproperties: {\nkeyVaultId: '/subscriptions/<subscriptionID>/resourceGroups/xxxxRG/providers/Microsoft.KeyVault/vaults/xxxxxkeyvaults'\nkeyVaultSecretName: 'jahnss'\npassword: 'xxxxx' //Certificate protected password\nextensionResourceId: '/subscriptions/<subscriptionID>/resourceGroups/xxxxRG/providers/Microsoft.Web/serverfarms/xxxxxappserviceplan'\n}\n}\n"
}
] |
2022/11/23
|
[
"https://Stackoverflow.com/questions/74544164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175327/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.