问:
entity framework Core generate Wrong migrigation
i have model class like below

```<code>public class DIMAuthOffice
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ID { get; set; }
        public string Title { get; set; }
        [StringLength(50)]
        [Required]
        public string UserNameManager { get; set; }
        public int? ParentID { get; set; }
        [ForeignKey(nameof(ParentID))]
        public DIMAuthOffice OfficeParent { get; set; }
        public List<DIMAuthOffice> OfficeChilds { get; set; } = new List<DIMAuthOffice>();

        [ForeignKey(nameof(UserNameManager))]
        public DIMAuthUser UserManager { get; set; }
        public List<DIMAuthRole> DIMAuthRoles { get; set; } = new List<DIMAuthRole>();
        public List<DIMAuthRolePostOffice> DIMAuthRolePostOffices { get; set; } = new List<DIMAuthRolePostOffice>();

    }
</code>```

but when i execute

Add-Migration

the generated File is :

```<code>migrationBuilder.CreateTable(
                name: "DIMAuthOffices",
                columns: table => new
                {
                    ID = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Title = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    UserNameManager = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false),
                    ParentID = table.Column<int>(type: "int", nullable: false),
                    UserManagerUserName = table.Column<string>(type: "nvarchar(50)", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_DIMAuthOffices", x => x.ID);
                    table.ForeignKey(
                        name: "FK_DIMAuthOffices_DIMAuthOffices_ParentID",
                        column: x => x.ParentID,
                        principalTable: "DIMAuthOffices",
                        principalColumn: "ID");
                    table.ForeignKey(
                        name: "FK_DIMAuthOffices_DIMAuthUsers_UserManagerUserName",
                        column: x => x.UserManagerUserName,
                        principalTable: "DIMAuthUsers",
                        principalColumn: "UserName");
                });
</code>```

wrong line is :

ParentID = table.Column(type: "int", nullable: false),

the generated File is Wrong and property ParentID set to nullable:false but this should be true ...
why ???

答:
I use FluentApi and writed this code in modelBuilder and fixed issue</p>
```<code>modelBuilder.Entity<DIMAuthOffice>()
                .HasOne(q => q.OfficeParent)
                .WithMany(q => q.OfficeChilds)
                .IsRequired(false)
                .OnDelete(DeleteBehavior.Restrict);
</code>```

Body:
i have model class like below

public class DIMAuthOffice
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ID { get; set; }
        public string Title { get; set; }
        [StringLength(50)]
        [Required]
        public string UserNameManager { get; set; }
        public int? ParentID { get; set; }
        [ForeignKey(nameof(ParentID))]
        public DIMAuthOffice OfficeParent { get; set; }
        public List<DIMAuthOffice> OfficeChilds { get; set; } = new List<DIMAuthOffice>();

        [ForeignKey(nameof(UserNameManager))]
        public DIMAuthUser UserManager { get; set; }
        public List<DIMAuthRole> DIMAuthRoles { get; set; } = new List<DIMAuthRole>();
        public List<DIMAuthRolePostOffice> DIMAuthRolePostOffices { get; set; } = new List<DIMAuthRolePostOffice>();

    }

but when i execute

Add-Migration

the generated File is :

migrationBuilder.CreateTable(
                name: "DIMAuthOffices",
                columns: table => new
                {
                    ID = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Title = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    UserNameManager = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false),
                    ParentID = table.Column<int>(type: "int", nullable: false),
                    UserManagerUserName = table.Column<string>(type: "nvarchar(50)", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_DIMAuthOffices", x => x.ID);
                    table.ForeignKey(
                        name: "FK_DIMAuthOffices_DIMAuthOffices_ParentID",
                        column: x => x.ParentID,
                        principalTable: "DIMAuthOffices",
                        principalColumn: "ID");
                    table.ForeignKey(
                        name: "FK_DIMAuthOffices_DIMAuthUsers_UserManagerUserName",
                        column: x => x.UserManagerUserName,
                        principalTable: "DIMAuthUsers",
                        principalColumn: "UserName");
                });

wrong line is :

ParentID = table.Column(type: "int", nullable: false),

the generated File is Wrong and property ParentID set to nullable:false but this should be true ...
why ???

Body:
I use FluentApi and writed this code in modelBuilder and fixed issue

modelBuilder.Entity<DIMAuthOffice>()
                .HasOne(q => q.OfficeParent)
                .WithMany(q => q.OfficeChilds)
                .IsRequired(false)
                .OnDelete(DeleteBehavior.Restrict);


来源: stackexchange

问:
Copying Data from 1 table to another , the second table has 2 extra columns with data that must be inserted
Copying data from 1 table to another, the second table has 2 extra columns with data that must be inserted.
I know I must use an insert into statement and possibly make it nested ,also maybe use @ for variables or something my knowledge is limited and I need to do this in a single query.
There can't be nulls

My current code that isn't working:

```<code>INSERT INTO SampleExtraTable_2 (SampleID, SampleName, SampleEmail)
SELECT *
       (
       SELECT Extra1,Extra2
       FROM SampleExtraTable_2
       Values('b','r');
       )
FROM SampleTable_1
WHERE 1 = 1
</code>```

SampleExtraTable_2 has the following fields all defined as char(10), (SampleID, SampleName, SampleEmail,Extra1,Extra2)

SampleTable_1 two has the same fields except the extras and definition amounts are all char(10)

答:
Youre trying to insert NULL values.

```<code>   SELECT Extra1,Extra2
   FROM SampleExtraTable_2
</code>```

Your inner select query is returning NULL.

You can insert 'dta', 'dta2' values as a string to your new table like below. (if they are constant)

```<code>INSERT INTO SampleExtraTable_2 (SampleID, SampleName, SampleEmail, Extra1, Extra2)
SELECT SampleID, SampleName, SampleEmail, 'dta', 'dta2'
FROM SampleTable_1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Copying data from 1 table to another, the second table has 2 extra columns with data that must be inserted.
I know I must use an insert into statement and possibly make it nested ,also maybe use @ for variables or something my knowledge is limited and I need to do this in a single query.
There can't be nulls

My current code that isn't working:

INSERT INTO SampleExtraTable_2 (SampleID, SampleName, SampleEmail)
SELECT *
       (
       SELECT Extra1,Extra2
       FROM SampleExtraTable_2
       Values('b','r');
       )
FROM SampleTable_1
WHERE 1 = 1

SampleExtraTable_2 has the following fields all defined as char(10), (SampleID, SampleName, SampleEmail,Extra1,Extra2)

SampleTable_1 two has the same fields except the extras and definition amounts are all char(10)

Body:
Youre trying to insert NULL values.

   SELECT Extra1,Extra2
   FROM SampleExtraTable_2

Your inner select query is returning NULL.

You can insert 'dta', 'dta2' values as a string to your new table like below. (if they are constant)

INSERT INTO SampleExtraTable_2 (SampleID, SampleName, SampleEmail, Extra1, Extra2)
SELECT SampleID, SampleName, SampleEmail, 'dta', 'dta2'
FROM SampleTable_1


问:
How is WAV data stored in principle?
Each WAV files depends on a Sampling Rate and a Bit Depth. The former governs how many different samples are played per second, and the latter governs how many possibilities there are for each timeslot.

For sampling rate for example 1000 Hz and the bit depth is 8 then each 1/1000 of a second the audio device plays one of a possible $2^8$ different sounds.

Hence the bulk of the WAV file is a sequence of 8-bit numbers.  There is also a header which contains the Sampling Rate and Bit Depth and other specifics of how the data should be read:

The above comes from running xxd on a wav file to view it in binary on the terminal. The first column is just increments of 6 in hexadecimal. The last one seems to say where the header ends. So the data looks like this:

Each of those 8-bit numbers is a sample. So the device reads left-to right and converts the samples in order into sounds. But how in principle can each number correspond to a sound. I would think each bit should somehow encode an amplitude and a pitch, with each coming from a finite range. But I can not find any reference to for example the first half of the bits being a pitch and the second being a frequency.

I have found references to the numbers encoding "signal strength" but I do not know what this means.Can anyone explain in principle how the data is read and converted to audio?

答:
In your example, over the course of a second, 1000 values are sent to a DAC (Digital to Analog converter) where the discrete values are smoothed out into a waveform. The pitch is determined by the rate and pattern by which the stream of values (which get smoothed out to a wave) rise and fall.

Steve W. Smith gives some good diagrams and explanations in his chapter ADC and DCA from his very helpful book The Scientists and Engineers Guide to Digital Signal Processing.

Title: How is WAV data stored in principle?


问:
Connecting tables of two or more databases with each other in android studio
I just wanted to know if there is any way to connect two tables of two different databases under one project.
I have the databases as follow

First database

```<code>private String CREATE_USER_TABLE = "CREATE TABLE  "+ TABLE_USER + "(" +
        COLUMN_USER_ID +" INTEGER PRIMARY KEY AUTOINCREMENT , " + COLUMN_USER_MOBILE + " TEXT," +
        COLUMN_USER_EMAIL + " TEXT, "
        + COLUMN_USER_MOTHERNAME + " TEXT, " + COLUMN_USER_FATHERNAME + " TEXT, " +
        COLUMN_USER_PASSWORD + " TEXT, " + COLUMN_USER_CONFIRM_PASSWORD + " TEXT " + ")";
</code>```

Second database

```<code>        private String CREATE_BABY_TABLE = "CREATE TABLE "+ TABLE_BABY + "(" +
        COLUMN_BABY_ID + " INTEGER  PRIMARY KEY AUTOINCREMENT , " + COLUMN_BABY_NAME + " TEXT, "
        + COLUMN_BABY_DATE + " TEXT, " + COLUMN_BABY_GENDER + " TEXT, " + COLUMN_BABY_AGE +
          " TEXT " + ")";
</code>```

答: The standard solution to this is to query each of the databases separately and then merge or join the results in your application logic.</p>

Body:
I just wanted to know if there is any way to connect two tables of two different databases under one project.
I have the databases as follow

First database

private String CREATE_USER_TABLE = "CREATE TABLE  "+ TABLE_USER + "(" +
        COLUMN_USER_ID +" INTEGER PRIMARY KEY AUTOINCREMENT , " + COLUMN_USER_MOBILE + " TEXT," +
        COLUMN_USER_EMAIL + " TEXT, "
        + COLUMN_USER_MOTHERNAME + " TEXT, " + COLUMN_USER_FATHERNAME + " TEXT, " +
        COLUMN_USER_PASSWORD + " TEXT, " + COLUMN_USER_CONFIRM_PASSWORD + " TEXT " + ")";

Second database

        private String CREATE_BABY_TABLE = "CREATE TABLE "+ TABLE_BABY + "(" +
        COLUMN_BABY_ID + " INTEGER  PRIMARY KEY AUTOINCREMENT , " + COLUMN_BABY_NAME + " TEXT, "
        + COLUMN_BABY_DATE + " TEXT, " + COLUMN_BABY_GENDER + " TEXT, " + COLUMN_BABY_AGE +
          " TEXT " + ")";


问:
How to get only the text part from tweets extracted using Tweepy?
I am doing a research project on something similar to sentiment analysis. I have extracted tweets from twitter using Tweepy.
The data I get is something like this:

```<code>{"created_at":"Sat Apr 22 07:28:47 +0000 2017","id":855684794939842560,"id_str":"855684794939842560","text":"#PL | FIXTURES - 22 April 2017 \nWest Ham v Everton 16:00\nHull v Watford\nSwansea v Stoke \nBournemouth v Middlesbrough #CCFMSport","source":"\u003ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003eTwitter Web Client\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":256051042,"id_str":"256051042","name":"Ayanda Frances Felem","screen_name":"AyandaFelemZA","location":"Cape Town, South Africa","url":"http:\/\/ccfm.org.za","description":"Sports Producer\/Reporter for @RadioCCFm, Views are my own. ayanda@ccfm.org.za","protected":false,"verified":false,"followers_count":446,"friends_count":1648,"listed_count":23,"favourites_count":1625,"statuses_count":16110,"created_at":"Tue Feb 22 15:15:38 +0000 2011","utc_offset":7200,"time_zone":"Pretoria","geo_enabled":true,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"000000","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme11\/bg.gif","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme11\/bg.gif","profile_background_tile":false,"profile_link_color":"DD2E44","profile_sidebar_border_color":"000000","profile_sidebar_fill_color":"000000","profile_text_color":"000000","profile_use_background_image":false,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/850335374446665728\/BvVIo7oB_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/850335374446665728\/BvVIo7oB_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/256051042\/1491570881","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[{"text":"PL","indices":[0,3]},{"text":"CCFMSport","indices":[117,127]}],"urls":[],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"filter_level":"low","lang":"en","timestamp_ms":"1492846127625"}
</code>```

Now I want to extract only the tweet 'text' from this file. I have tried this:

```<code>import json

tweets_data_path = 'twitter_streaming.txt'
tweets_data = []
tweets_file = open(tweets_data_path, "r")

json_load = json.load(tweets_file)
texts = json_load['text']
coded = texts.encode('utf-8')
s = str(coded)
tweets_data.append(s[1:-2))
print tweets_data
</code>```

But I get a error saying:

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Tried looking for the reason of this error but didn't find anything concrete.

What am I doing wrong? Is there a better way?

答:
This code is working as expected -

```<code>import json

tweets_data_path = 'twitter_data.txt'
tweets_data = []
tweets_file = open(tweets_data_path, "r")

json_load = json.load(tweets_file)
texts = json_load['text']
print(texts)
</code>```

The below code part is not needed if the expected output is-

```<code>coded = texts.encode('utf-8')
s = str(coded)
tweets_data.append(s[1:-2))
print tweets_data

#output
'''
#PL | FIXTURES - 22 April 2017
West Ham v Everton 16:00
Hull v Watford
Swansea v Stoke
Bournemouth v Middlesbrough #CCFMSport
None
'''
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am doing a research project on something similar to sentiment analysis. I have extracted tweets from twitter using Tweepy.
The data I get is something like this:

{"created_at":"Sat Apr 22 07:28:47 +0000 2017","id":855684794939842560,"id_str":"855684794939842560","text":"#PL | FIXTURES - 22 April 2017 \nWest Ham v Everton 16:00\nHull v Watford\nSwansea v Stoke \nBournemouth v Middlesbrough #CCFMSport","source":"\u003ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003eTwitter Web Client\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":256051042,"id_str":"256051042","name":"Ayanda Frances Felem","screen_name":"AyandaFelemZA","location":"Cape Town, South Africa","url":"http:\/\/ccfm.org.za","description":"Sports Producer\/Reporter for @RadioCCFm, Views are my own. ayanda@ccfm.org.za","protected":false,"verified":false,"followers_count":446,"friends_count":1648,"listed_count":23,"favourites_count":1625,"statuses_count":16110,"created_at":"Tue Feb 22 15:15:38 +0000 2011","utc_offset":7200,"time_zone":"Pretoria","geo_enabled":true,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"000000","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme11\/bg.gif","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme11\/bg.gif","profile_background_tile":false,"profile_link_color":"DD2E44","profile_sidebar_border_color":"000000","profile_sidebar_fill_color":"000000","profile_text_color":"000000","profile_use_background_image":false,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/850335374446665728\/BvVIo7oB_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/850335374446665728\/BvVIo7oB_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/256051042\/1491570881","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[{"text":"PL","indices":[0,3]},{"text":"CCFMSport","indices":[117,127]}],"urls":[],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"filter_level":"low","lang":"en","timestamp_ms":"1492846127625"}

Now I want to extract only the tweet 'text' from this file. I have tried this:

import json

tweets_data_path = 'twitter_streaming.txt'
tweets_data = []
tweets_file = open(tweets_data_path, "r")

json_load = json.load(tweets_file)
texts = json_load['text']
coded = texts.encode('utf-8')
s = str(coded)
tweets_data.append(s[1:-2))
print tweets_data

But I get a error saying:

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Tried looking for the reason of this error but didn't find anything concrete.

What am I doing wrong? Is there a better way?

Body:
This code is working as expected -

import json

tweets_data_path = 'twitter_data.txt'
tweets_data = []
tweets_file = open(tweets_data_path, "r")

json_load = json.load(tweets_file)
texts = json_load['text']
print(texts)

The below code part is not needed if the expected output is-

coded = texts.encode('utf-8')
s = str(coded)
tweets_data.append(s[1:-2))
print tweets_data

#output
'''
#PL | FIXTURES - 22 April 2017
West Ham v Everton 16:00
Hull v Watford
Swansea v Stoke
Bournemouth v Middlesbrough #CCFMSport
None
'''


问:
BlueZ version in Android Honeycomb
I'd like to know a way to know the version of BlueZ (the bluetooth stack) implemented in Android Honeycomb, without having the source code of this system.
I am pretty interested in the HDP functionalities offered by the last versions of this stack.
Any help would be greatly appreciated.

Thanks a lot!

答:
Android 3.2(Honeycomb) had been released as the following link.
  http://groups.google.com/group/android-building/msg/6410b44798c19d61

I had downloaded bluez source code in Honeycomb. It's the early version bluez-4.69 as Android 2.3.
  So, porting bluez is necessary.

Title: BlueZ version in Android Honeycomb


问:
gym package not identifying ten-armed-bandits-v0 env
Environment:

Python: 3.9

OS: Windows 10

When I try to create the ten armed bandits environment using the following code the error is thrown not sure of the reason.

```<code>import gym
import gym_armed_bandits

env = gym.make('ten-armed-bandits-v0')
</code>```

The error:

```<code>---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File D:\00_PythonEnvironments\01_RL\lib\site-packages\gym\envs\registration.py:158, in EnvRegistry.spec(self, path)
    157 try:
--> 158     return self.env_specs[id]
    159 except KeyError:
    160     # Parse the env name and check to see if it matches the non-version
    161     # part of a valid env (could also check the exact number here)

KeyError: 'ten-armed-bandits-v0'

During handling of the above exception, another exception occurred:

UnregisteredEnv                           Traceback (most recent call last)
Input In [6], in <module>
----> 1 env = gym.make('ten-armed-bandits-v0')

File D:\00_PythonEnvironments\01_RL\lib\site-packages\gym\envs\registration.py:235, in make(id, **kwargs)
    234 def make(id, **kwargs):
--> 235     return registry.make(id, **kwargs)

File D:\00_PythonEnvironments\01_RL\lib\site-packages\gym\envs\registration.py:128, in EnvRegistry.make(self, path, **kwargs)
    126 else:
    127     logger.info("Making new env: %s", path)
--> 128 spec = self.spec(path)
    129 env = spec.make(**kwargs)
    130 return env

File D:\00_PythonEnvironments\01_RL\lib\site-packages\gym\envs\registration.py:203, in EnvRegistry.spec(self, path)
    197     raise error.UnregisteredEnv(
    198         "Toytext environment {} has been moved out of Gym. Install it via `pip install gym-legacy-toytext` and add `import gym_toytext` before using it.".format(
    199             id
    200         )
    201     )
    202 else:
--> 203     raise error.UnregisteredEnv("No registered env with id: {}".format(id))

UnregisteredEnv: No registered env with id: ten-armed-bandits-v0
</code>```

When I check the environments available, I am able to see it there.

```<code>from gym import envs
print(envs.registry.all())

dict_values([EnvSpec(CartPole-v0), EnvSpec(CartPole-v1), EnvSpec(MountainCar-v0), EnvSpec(MountainCarContinuous-v0), EnvSpec(Pendulum-v1), EnvSpec(Acrobot-v1), EnvSpec(LunarLander-v2), EnvSpec(LunarLanderContinuous-v2), EnvSpec(BipedalWalker-v3), EnvSpec(BipedalWalkerHardcore-v3), EnvSpec(CarRacing-v0), EnvSpec(Blackjack-v1), EnvSpec(FrozenLake-v1), EnvSpec(FrozenLake8x8-v1), EnvSpec(CliffWalking-v0), EnvSpec(Taxi-v3), EnvSpec(Reacher-v2), EnvSpec(Pusher-v2), EnvSpec(Thrower-v2), EnvSpec(Striker-v2), EnvSpec(InvertedPendulum-v2), EnvSpec(InvertedDoublePendulum-v2), EnvSpec(HalfCheetah-v2), EnvSpec(HalfCheetah-v3), EnvSpec(Hopper-v2), EnvSpec(Hopper-v3), EnvSpec(Swimmer-v2), EnvSpec(Swimmer-v3), EnvSpec(Walker2d-v2), EnvSpec(Walker2d-v3), EnvSpec(Ant-v2), EnvSpec(Ant-v3), EnvSpec(Humanoid-v2), EnvSpec(Humanoid-v3), EnvSpec(HumanoidStandup-v2), EnvSpec(FetchSlide-v1), EnvSpec(FetchPickAndPlace-v1), EnvSpec(FetchReach-v1), EnvSpec(FetchPush-v1), EnvSpec(HandReach-v0), EnvSpec(HandManipulateBlockRotateZ-v0), EnvSpec(HandManipulateBlockRotateZTouchSensors-v0), EnvSpec(HandManipulateBlockRotateZTouchSensors-v1), EnvSpec(HandManipulateBlockRotateParallel-v0), EnvSpec(HandManipulateBlockRotateParallelTouchSensors-v0), EnvSpec(HandManipulateBlockRotateParallelTouchSensors-v1), EnvSpec(HandManipulateBlockRotateXYZ-v0), EnvSpec(HandManipulateBlockRotateXYZTouchSensors-v0), EnvSpec(HandManipulateBlockRotateXYZTouchSensors-v1), EnvSpec(HandManipulateBlockFull-v0), EnvSpec(HandManipulateBlock-v0), EnvSpec(HandManipulateBlockTouchSensors-v0), EnvSpec(HandManipulateBlockTouchSensors-v1), EnvSpec(HandManipulateEggRotate-v0), EnvSpec(HandManipulateEggRotateTouchSensors-v0), EnvSpec(HandManipulateEggRotateTouchSensors-v1), EnvSpec(HandManipulateEggFull-v0), EnvSpec(HandManipulateEgg-v0), EnvSpec(HandManipulateEggTouchSensors-v0), EnvSpec(HandManipulateEggTouchSensors-v1), EnvSpec(HandManipulatePenRotate-v0), EnvSpec(HandManipulatePenRotateTouchSensors-v0), EnvSpec(HandManipulatePenRotateTouchSensors-v1), EnvSpec(HandManipulatePenFull-v0), EnvSpec(HandManipulatePen-v0), EnvSpec(HandManipulatePenTouchSensors-v0), EnvSpec(HandManipulatePenTouchSensors-v1), EnvSpec(FetchSlideDense-v1), EnvSpec(FetchPickAndPlaceDense-v1), EnvSpec(FetchReachDense-v1), EnvSpec(FetchPushDense-v1), EnvSpec(HandReachDense-v0), EnvSpec(HandManipulateBlockRotateZDense-v0), EnvSpec(HandManipulateBlockRotateZTouchSensorsDense-v0), EnvSpec(HandManipulateBlockRotateZTouchSensorsDense-v1), EnvSpec(HandManipulateBlockRotateParallelDense-v0), EnvSpec(HandManipulateBlockRotateParallelTouchSensorsDense-v0), EnvSpec(HandManipulateBlockRotateParallelTouchSensorsDense-v1), EnvSpec(HandManipulateBlockRotateXYZDense-v0), EnvSpec(HandManipulateBlockRotateXYZTouchSensorsDense-v0), EnvSpec(HandManipulateBlockRotateXYZTouchSensorsDense-v1), EnvSpec(HandManipulateBlockFullDense-v0), EnvSpec(HandManipulateBlockDense-v0), EnvSpec(HandManipulateBlockTouchSensorsDense-v0), EnvSpec(HandManipulateBlockTouchSensorsDense-v1), EnvSpec(HandManipulateEggRotateDense-v0), EnvSpec(HandManipulateEggRotateTouchSensorsDense-v0), EnvSpec(HandManipulateEggRotateTouchSensorsDense-v1), EnvSpec(HandManipulateEggFullDense-v0), EnvSpec(HandManipulateEggDense-v0), EnvSpec(HandManipulateEggTouchSensorsDense-v0), EnvSpec(HandManipulateEggTouchSensorsDense-v1), EnvSpec(HandManipulatePenRotateDense-v0), EnvSpec(HandManipulatePenRotateTouchSensorsDense-v0), EnvSpec(HandManipulatePenRotateTouchSensorsDense-v1), EnvSpec(HandManipulatePenFullDense-v0), EnvSpec(HandManipulatePenDense-v0), EnvSpec(HandManipulatePenTouchSensorsDense-v0), EnvSpec(HandManipulatePenTouchSensorsDense-v1), EnvSpec(CubeCrash-v0), EnvSpec(CubeCrashSparse-v0), EnvSpec(CubeCrashScreenBecomesBlack-v0), EnvSpec(MemorizeDigits-v0), EnvSpec(three-armed-bandits-v0), EnvSpec(five-armed-bandits-v0), EnvSpec(ten-armed-bandits-v0), EnvSpec(MultiarmedBandits-v0)])
</code>```

答:
It could be a problem with your Python version: k-armed-bandits library was made 4 years ago, when Python 3.9 didn't exist. Besides this, the configuration files in the repo indicates that the Python version is 2.7 (not 3.9).

If you create an environment with Python 2.7 and follow the setup instructions it works correctly on Windows:

```<code>git clone gym_armed_bandits
cd gym_armed_bandits
pip install -e .
</code>```

Body:
Environment:

Python: 3.9

OS: Windows 10

When I try to create the ten armed bandits environment using the following code the error is thrown not sure of the reason.

import gym
import gym_armed_bandits

env = gym.make('ten-armed-bandits-v0')

The error:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File D:\00_PythonEnvironments\01_RL\lib\site-packages\gym\envs\registration.py:158, in EnvRegistry.spec(self, path)
    157 try:
--> 158     return self.env_specs[id]
    159 except KeyError:
    160     # Parse the env name and check to see if it matches the non-version
    161     # part of a valid env (could also check the exact number here)

KeyError: 'ten-armed-bandits-v0'

During handling of the above exception, another exception occurred:

UnregisteredEnv                           Traceback (most recent call last)
Input In [6], in <module>
----> 1 env = gym.make('ten-armed-bandits-v0')

File D:\00_PythonEnvironments\01_RL\lib\site-packages\gym\envs\registration.py:235, in make(id, **kwargs)
    234 def make(id, **kwargs):
--> 235     return registry.make(id, **kwargs)

File D:\00_PythonEnvironments\01_RL\lib\site-packages\gym\envs\registration.py:128, in EnvRegistry.make(self, path, **kwargs)
    126 else:
    127     logger.info("Making new env: %s", path)
--> 128 spec = self.spec(path)
    129 env = spec.make(**kwargs)
    130 return env

File D:\00_PythonEnvironments\01_RL\lib\site-packages\gym\envs\registration.py:203, in EnvRegistry.spec(self, path)
    197     raise error.UnregisteredEnv(
    198         "Toytext environment {} has been moved out of Gym. Install it via `pip install gym-legacy-toytext` and add `import gym_toytext` before using it.".format(
    199             id
    200         )
    201     )
    202 else:
--> 203     raise error.UnregisteredEnv("No registered env with id: {}".format(id))

UnregisteredEnv: No registered env with id: ten-armed-bandits-v0

When I check the environments available, I am able to see it there.

from gym import envs
print(envs.registry.all())

dict_values([EnvSpec(CartPole-v0), EnvSpec(CartPole-v1), EnvSpec(MountainCar-v0), EnvSpec(MountainCarContinuous-v0), EnvSpec(Pendulum-v1), EnvSpec(Acrobot-v1), EnvSpec(LunarLander-v2), EnvSpec(LunarLanderContinuous-v2), EnvSpec(BipedalWalker-v3), EnvSpec(BipedalWalkerHardcore-v3), EnvSpec(CarRacing-v0), EnvSpec(Blackjack-v1), EnvSpec(FrozenLake-v1), EnvSpec(FrozenLake8x8-v1), EnvSpec(CliffWalking-v0), EnvSpec(Taxi-v3), EnvSpec(Reacher-v2), EnvSpec(Pusher-v2), EnvSpec(Thrower-v2), EnvSpec(Striker-v2), EnvSpec(InvertedPendulum-v2), EnvSpec(InvertedDoublePendulum-v2), EnvSpec(HalfCheetah-v2), EnvSpec(HalfCheetah-v3), EnvSpec(Hopper-v2), EnvSpec(Hopper-v3), EnvSpec(Swimmer-v2), EnvSpec(Swimmer-v3), EnvSpec(Walker2d-v2), EnvSpec(Walker2d-v3), EnvSpec(Ant-v2), EnvSpec(Ant-v3), EnvSpec(Humanoid-v2), EnvSpec(Humanoid-v3), EnvSpec(HumanoidStandup-v2), EnvSpec(FetchSlide-v1), EnvSpec(FetchPickAndPlace-v1), EnvSpec(FetchReach-v1), EnvSpec(FetchPush-v1), EnvSpec(HandReach-v0), EnvSpec(HandManipulateBlockRotateZ-v0), EnvSpec(HandManipulateBlockRotateZTouchSensors-v0), EnvSpec(HandManipulateBlockRotateZTouchSensors-v1), EnvSpec(HandManipulateBlockRotateParallel-v0), EnvSpec(HandManipulateBlockRotateParallelTouchSensors-v0), EnvSpec(HandManipulateBlockRotateParallelTouchSensors-v1), EnvSpec(HandManipulateBlockRotateXYZ-v0), EnvSpec(HandManipulateBlockRotateXYZTouchSensors-v0), EnvSpec(HandManipulateBlockRotateXYZTouchSensors-v1), EnvSpec(HandManipulateBlockFull-v0), EnvSpec(HandManipulateBlock-v0), EnvSpec(HandManipulateBlockTouchSensors-v0), EnvSpec(HandManipulateBlockTouchSensors-v1), EnvSpec(HandManipulateEggRotate-v0), EnvSpec(HandManipulateEggRotateTouchSensors-v0), EnvSpec(HandManipulateEggRotateTouchSensors-v1), EnvSpec(HandManipulateEggFull-v0), EnvSpec(HandManipulateEgg-v0), EnvSpec(HandManipulateEggTouchSensors-v0), EnvSpec(HandManipulateEggTouchSensors-v1), EnvSpec(HandManipulatePenRotate-v0), EnvSpec(HandManipulatePenRotateTouchSensors-v0), EnvSpec(HandManipulatePenRotateTouchSensors-v1), EnvSpec(HandManipulatePenFull-v0), EnvSpec(HandManipulatePen-v0), EnvSpec(HandManipulatePenTouchSensors-v0), EnvSpec(HandManipulatePenTouchSensors-v1), EnvSpec(FetchSlideDense-v1), EnvSpec(FetchPickAndPlaceDense-v1), EnvSpec(FetchReachDense-v1), EnvSpec(FetchPushDense-v1), EnvSpec(HandReachDense-v0), EnvSpec(HandManipulateBlockRotateZDense-v0), EnvSpec(HandManipulateBlockRotateZTouchSensorsDense-v0), EnvSpec(HandManipulateBlockRotateZTouchSensorsDense-v1), EnvSpec(HandManipulateBlockRotateParallelDense-v0), EnvSpec(HandManipulateBlockRotateParallelTouchSensorsDense-v0), EnvSpec(HandManipulateBlockRotateParallelTouchSensorsDense-v1), EnvSpec(HandManipulateBlockRotateXYZDense-v0), EnvSpec(HandManipulateBlockRotateXYZTouchSensorsDense-v0), EnvSpec(HandManipulateBlockRotateXYZTouchSensorsDense-v1), EnvSpec(HandManipulateBlockFullDense-v0), EnvSpec(HandManipulateBlockDense-v0), EnvSpec(HandManipulateBlockTouchSensorsDense-v0), EnvSpec(HandManipulateBlockTouchSensorsDense-v1), EnvSpec(HandManipulateEggRotateDense-v0), EnvSpec(HandManipulateEggRotateTouchSensorsDense-v0), EnvSpec(HandManipulateEggRotateTouchSensorsDense-v1), EnvSpec(HandManipulateEggFullDense-v0), EnvSpec(HandManipulateEggDense-v0), EnvSpec(HandManipulateEggTouchSensorsDense-v0), EnvSpec(HandManipulateEggTouchSensorsDense-v1), EnvSpec(HandManipulatePenRotateDense-v0), EnvSpec(HandManipulatePenRotateTouchSensorsDense-v0), EnvSpec(HandManipulatePenRotateTouchSensorsDense-v1), EnvSpec(HandManipulatePenFullDense-v0), EnvSpec(HandManipulatePenDense-v0), EnvSpec(HandManipulatePenTouchSensorsDense-v0), EnvSpec(HandManipulatePenTouchSensorsDense-v1), EnvSpec(CubeCrash-v0), EnvSpec(CubeCrashSparse-v0), EnvSpec(CubeCrashScreenBecomesBlack-v0), EnvSpec(MemorizeDigits-v0), EnvSpec(three-armed-bandits-v0), EnvSpec(five-armed-bandits-v0), EnvSpec(ten-armed-bandits-v0), EnvSpec(MultiarmedBandits-v0)])

Body:
It could be a problem with your Python version: k-armed-bandits library was made 4 years ago, when Python 3.9 didn't exist. Besides this, the configuration files in the repo indicates that the Python version is 2.7 (not 3.9).

If you create an environment with Python 2.7 and follow the setup instructions it works correctly on Windows:

git clone gym_armed_bandits
cd gym_armed_bandits
pip install -e .


问:
heading tag won't work in alignment attribute
```<code><html>
    <head>
        <title> my's info </title>
    </head>
    <body>
        <p align="center">
            <h1>ABOUT ME</h1>
        </p>
        <p> this is a paragraph  </p>
        <h3> this is a heading </h3>
        <p> this is a paragraph </p>

    </body>
</html>
</code>```

why does not the ABOUT ME is not align in the center when i used the heading tag?
does heading tag doesn't work in alignments ?

答:
See the difference between inline and block elements.

        <title> my's info </title>

ABOUT ME

ABOUT ME

 this is a paragraph

 this is a heading

 this is a paragraph

```

https://developer.mozilla.org/en-US/docs/Web/HTML/Inline_elements

Body:
        <title> my's info </title>

ABOUT ME

 this is a paragraph

 this is a heading

 this is a paragraph

why does not the ABOUT ME is not align in the center when i used the heading tag?
does heading tag doesn't work in alignments ?

Body:
See the difference between inline and block elements.

<html>
    <head>
        <title> my's info </title>
    </head>
    <body>
         <!-- Inline element -->
        <p align="center">
            <h1>ABOUT ME</h1>
        </p>
        <!-- Block element -->
        <div align="center">
            <h1>ABOUT ME</h1>
        </div>
        <p> this is a paragraph  </p>
        <h3> this is a heading </h3>
        <p> this is a paragraph </p>

    </body>
</html>

https://developer.mozilla.org/en-US/docs/Web/HTML/Inline_elements


问:
Simple array rotation
I'm trying to solve a simple array problem and I have encountered some bug.

I input {1, 2, 3, 4, 5, 6} and rotate left by 2, it should give me {3, 4, 5, 6, 1, 2}

I cannot find a reason why it gives me {0, 0, 0, 0, 1, 2}
I think my code is correct. I do not like looking at answers but I looked it up but then I still don't see why it is giving me this wrong answer.

I've looked it through more than 1 hour and I still cannot figure it out so I joined this community. Please help me out...

```<code>public int[] rotate(int[] arr, int shift, int size) {
    int[] output = new int[size];
    for(int i = 0; i < output.length;i++) {
        int newIndex = (arr.length-shift+i) % arr.length;
        output[newIndex] = arr[i];
        }
    return output;
}
</code>```

My output:

答:
You can find the shifted index by adding the shift value with modulo length of array. Now you can add this value to the current index.</p>
```<code>int newIndex = (shift+i) % arr.length;
output[i] = arr[newIndex];
</code>```

Title: Simple array rotation

Body:
I'm trying to solve a simple array problem and I have encountered some bug.

I input {1, 2, 3, 4, 5, 6} and rotate left by 2, it should give me {3, 4, 5, 6, 1, 2}

I cannot find a reason why it gives me {0, 0, 0, 0, 1, 2}
I think my code is correct. I do not like looking at answers but I looked it up but then I still don't see why it is giving me this wrong answer.

I've looked it through more than 1 hour and I still cannot figure it out so I joined this community. Please help me out...

public int[] rotate(int[] arr, int shift, int size) {
    int[] output = new int[size];
    for(int i = 0; i < output.length;i++) {
        int newIndex = (arr.length-shift+i) % arr.length;
        output[newIndex] = arr[i];
        }
    return output;
}

My output:

Body:
You can find the shifted index by adding the shift value with modulo length of array. Now you can add this value to the current index.

int newIndex = (shift+i) % arr.length;
output[i] = arr[newIndex];


问:
when a file is generated by an executable, what is the file's user and group on linux
I have an executable with user as root and group as ddd

```<code>-rwxr-x--- 1 root ddd 30050496 Jan  1  2021 exed
</code>```

exed will use fd = open(filename, O_CREAT | O_RDWR,0664); and write(fd, buff, size); to write a file to the hard disk. There is no place to change the group of the filename in the source code.

But I found after running the exed, the filename has fff as group. How did this happen? Should the file's group be ddd?

```<code>-rw-rw---- 1 root fff  11236167 Nov 13 04:28 filename
</code>```

答:
The file's owner will be the effective UID of the process that creates it, and the group will be the effective GID of the process.

The exception is if the directory where the file is created has the setgid permission bit set. Then the group will be the group of the directory.

Body:
I have an executable with user as root and group as ddd

-rwxr-x--- 1 root ddd 30050496 Jan  1  2021 exed

exed will use fd = open(filename, O_CREAT | O_RDWR,0664); and write(fd, buff, size); to write a file to the hard disk. There is no place to change the group of the filename in the source code.

But I found after running the exed, the filename has fff as group. How did this happen? Should the file's group be ddd?

-rw-rw---- 1 root fff  11236167 Nov 13 04:28 filename


问:
what is use of self in 'self.window addSubview : view '?
i am new developer of iphone i want to knw what is the difference b/w these 2 statement
statement1:

[self.window addSubview:lscreen.view];

statement2:

[window addSubview:lscreen.view];

答: self key word is used when we useing the property getter/setter instead of accessing the value directly. when it is generated by the synthesize key word you have to use self because the object is retained there instead of simply pointer-assigned.</p>


问:
Why can't I run make xv6 with make qemu, but it works fine with make qemu-nox?
I am using WSL-Ubuntu in Visual Studio Code and I have gcc, gdb, Qemu all installed and the xv6-public git cloned.
I can cd into the xv6 directory and type make, then make qemu-nox and it works just fine.

However make qemu doesn't work. and gives the error below. How do I get the gui for qemu working and so I don't have to use make qemu-nox every time?

```<code>qemu-system-i386 -serial mon:stdio -drive
file=fs.img,index=1,media=disk,format=raw -drive file=xv
Unable to init server: Could not connect: Connection refused
gtk initialization failed
make: *** [Makefile:226: qemu] Error 1
</code>```

答:
I guess you don't have an X server running.

You can use xming.

Once X is running, in bash, just add export DISPLAY=0:0 to help it find it.

Body:
I am using WSL-Ubuntu in Visual Studio Code and I have gcc, gdb, Qemu all installed and the xv6-public git cloned.
I can cd into the xv6 directory and type make, then make qemu-nox and it works just fine.

However make qemu doesn't work. and gives the error below. How do I get the gui for qemu working and so I don't have to use make qemu-nox every time?

qemu-system-i386 -serial mon:stdio -drive
file=fs.img,index=1,media=disk,format=raw -drive file=xv
Unable to init server: Could not connect: Connection refused
gtk initialization failed
make: *** [Makefile:226: qemu] Error 1


问:
How to open password protected pdf- document?
Kubuntu 21.10, Python 3.9.5

I use this code:

```<code>import fitz

doc = fitz.open(file_name) #ERROR!

#idata = open(file_name, "rb").read()  # read the PDF into memory
#ibuffer = BytesIO(idata)  # convert to stream
#doc = fitz.Document(stream=ibuffer, filetype='pdf') #ERROR!

doc.authenticate(my_password)
</code>```

and I always get an error:
RuntimeError: encryption dictionary missing owner password

How to open my pdf- file?

答:
Here is how you can crack the .pdf file password:

Firstly: pip3 install pikepdf tqdm

```<code>import pikepdf
from tqdm import tqdm

# load password list
passwords = [ line.strip() for line in open("wordlist.txt") ]

# iterate over passwords
for password in tqdm(passwords, "Decrypting PDF"):
    try:
        # open PDF file
        with pikepdf.open("foo-protected.pdf", password=password) as pdf:
            # Password decrypted successfully, break out of the loop
            print("[+] Password found:", password)
            break
    except pikepdf._qpdf.PasswordError as e:
        # wrong password, just continue in the loop
        continue
</code>```

Body:
Kubuntu 21.10, Python 3.9.5

I use this code:

import fitz

doc = fitz.open(file_name) #ERROR!

#idata = open(file_name, "rb").read()  # read the PDF into memory
#ibuffer = BytesIO(idata)  # convert to stream
#doc = fitz.Document(stream=ibuffer, filetype='pdf') #ERROR!

doc.authenticate(my_password)

and I always get an error:
RuntimeError: encryption dictionary missing owner password

How to open my pdf- file?

Body:
Here is how you can crack the .pdf file password:

Firstly: pip3 install pikepdf tqdm

import pikepdf
from tqdm import tqdm

# load password list
passwords = [ line.strip() for line in open("wordlist.txt") ]

# iterate over passwords
for password in tqdm(passwords, "Decrypting PDF"):
    try:
        # open PDF file
        with pikepdf.open("foo-protected.pdf", password=password) as pdf:
            # Password decrypted successfully, break out of the loop
            print("[+] Password found:", password)
            break
    except pikepdf._qpdf.PasswordError as e:
        # wrong password, just continue in the loop
        continue


问:
Spring boot write predicate to retrieve user from given role list
I am trying to create a predicate to retrieve users having certain Role list (Role is a separate Table )
I have created predicate for other fields in User entity only unable to create the proper criteria for the above mentioned scenario.
below are the 2 entity classes

User:

```<code>@Entity
@Table(name = "user")
@Data
public class User implements Serializable {
    public User() {
    }

    public User(User user) {
        this.username = user.getUsername();
        this.password = user.getPassword();
        this.email = user.getEmail();
        this.fullName = user.getFullName();
        this.address = user.getAddress();
        this.contactNo = user.getContactNo();
        this.enabled = user.isEnabled();
        this.accountNonExpired = user.isAccountNonExpired();
        this.credentialsNonExpired = user.isCredentialsNonExpired();
        this.accountNonLocked = user.isAccountNonLocked();
        this.roles = user.getRoles();
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "username")
    private String username;
    @Column(name = "fullName")
    private String fullName;
    @Column(name = "contactNo")
    private String contactNo;
    @Column(name = "address")
    private String address;
    @Column(name = "password")
    private String password;
    @Column(name = "email")
    private String email;
    @Column(name = "enabled")
    private boolean enabled;
    @Column(name = "accountNonExpired")
    private boolean accountNonExpired;
    @Column(name = "credentialsNonExpired")
    private boolean credentialsNonExpired;
    @Column(name = "accountNonLocked")
    private boolean accountNonLocked;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "role_user", joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
            inverseJoinColumns = {
                    @JoinColumn(name = "role_id", referencedColumnName = "id")})
    private List<Role> roles;
}
</code>```

Role

```<code>
@Entity
@Table(name = "role")
@Data
public class Role implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    @Column(name = "name")
    private String name;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "permission_role", joinColumns = {
            @JoinColumn(name = "role_id", referencedColumnName = "id")}, inverseJoinColumns = {
            @JoinColumn(name = "permission_id", referencedColumnName = "id")})
    private List<Permission> permissions;

}
</code>```

I have to use predicates No other option.
guide  me how to write a predicate to get users who are having given Role list.

答:
If you refer to Java 8 Predicate class:

```<code>Predicate<User> userPredicate = user -> user.getRoles().equals(roleListArg);
</code>```

If you want a more complex predicate:

```<code>Predicate<User> userPredicate = user -> {
     ... your code here
};
</code>```

Take care while comparing List objects like that. Should be better to check if the user has certains roles (user.getRoles().contains(role))

If you refer to JPA Specification:

```<code>public Specification<User> getUserByRoles(List<Role> roles) {
   return (root, query, criteriaBuilder) => {
      Join<Role, User> join = root.join("role");
      //Return the condition you want to build, this is an example to get by role id
      return criteriaBuilder.in(join.get(id), roles.get(0).getId());
   }
}
</code>```

Body:
I am trying to create a predicate to retrieve users having certain Role list (Role is a separate Table )
I have created predicate for other fields in User entity only unable to create the proper criteria for the above mentioned scenario.
below are the 2 entity classes

User:

@Entity
@Table(name = "user")
@Data
public class User implements Serializable {
    public User() {
    }

    public User(User user) {
        this.username = user.getUsername();
        this.password = user.getPassword();
        this.email = user.getEmail();
        this.fullName = user.getFullName();
        this.address = user.getAddress();
        this.contactNo = user.getContactNo();
        this.enabled = user.isEnabled();
        this.accountNonExpired = user.isAccountNonExpired();
        this.credentialsNonExpired = user.isCredentialsNonExpired();
        this.accountNonLocked = user.isAccountNonLocked();
        this.roles = user.getRoles();
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "username")
    private String username;
    @Column(name = "fullName")
    private String fullName;
    @Column(name = "contactNo")
    private String contactNo;
    @Column(name = "address")
    private String address;
    @Column(name = "password")
    private String password;
    @Column(name = "email")
    private String email;
    @Column(name = "enabled")
    private boolean enabled;
    @Column(name = "accountNonExpired")
    private boolean accountNonExpired;
    @Column(name = "credentialsNonExpired")
    private boolean credentialsNonExpired;
    @Column(name = "accountNonLocked")
    private boolean accountNonLocked;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "role_user", joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
            inverseJoinColumns = {
                    @JoinColumn(name = "role_id", referencedColumnName = "id")})
    private List<Role> roles;
}

Role

@Entity
@Table(name = "role")
@Data
public class Role implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    @Column(name = "name")
    private String name;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "permission_role", joinColumns = {
            @JoinColumn(name = "role_id", referencedColumnName = "id")}, inverseJoinColumns = {
            @JoinColumn(name = "permission_id", referencedColumnName = "id")})
    private List<Permission> permissions;

}

I have to use predicates No other option.
guide  me how to write a predicate to get users who are having given Role list.

Body:
If you refer to Java 8 Predicate class:

Predicate<User> userPredicate = user -> user.getRoles().equals(roleListArg);

If you want a more complex predicate:

Predicate<User> userPredicate = user -> {
     ... your code here
};

Take care while comparing List objects like that. Should be better to check if the user has certains roles (user.getRoles().contains(role))

If you refer to JPA Specification:

public Specification<User> getUserByRoles(List<Role> roles) {
   return (root, query, criteriaBuilder) => {
      Join<Role, User> join = root.join("role");
      //Return the condition you want to build, this is an example to get by role id
      return criteriaBuilder.in(join.get(id), roles.get(0).getId());
   }
}


问:
Writable file location / Communication AutoPlay Media Studio -> Flash AS3
I have an application built with AutoPlay Media Studio which needs to be able to communicate with an embedded .swf, built in Flash CS3 with AS3. The APMS application needs to send a filename to the embedded flash.

I've tried using flashvars but these don't seem to work from the APMS app. I've previously written the info to a text file in the app's folder so that both the APMS and the flash have a set relative path to the file. Now I'm tasked with making this work on a write-protected device, and I'm stumped as to where I could place the file and still be able to find it from the flash.

My first thought was the user's temp folder, but from another question I don't seem able to find that path from the flash. Where else could I put it and still have permission to write to it even if the user is not logged in as an administrator? The path needs also be in the same place on Win XP, Vista and 7.

Any other ideas regarding the communication are also very welcome!

答: Buddy, Just upgrade to AMS 8. You should write some script in order to check the user system if he she had installed Flash Player or not. Notice that flash player is no longer supported by Adobe. I advise you to use material design algorithms if you want to make your projects look attractive.</p>

ContentLicense: CC BY-SA 2.5


问:
JAVA ThreadPoolExecutor workqueue with Callable
Java ExecutorService.newFixedThreadPool() internally using a LinkedBlockingQueue<Runnable>() as below:

```<code>public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}
</code>```

I am wondering when I call ExecutorService.submit(Callable<?>) with callable, how it is pushed into workQueue. As per docs, only Runnable are pushed to workQueue, then what happens to Callable when all threads are busy. Where these are kept for later processing.

As per docs

workQueue - the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.

答:
Callable is packaged as a FutureTask, which implements both Runnable and Future. Therefore, the FutureTask can also be executed or pushed to the queue. The FutureTask holds the Callable object. When the FutureTask is running, the Callable object is called and the future-related attributes are set.
In fact, when a runnable is submitted, it is first packaged as a Callable and then packaged as a FutureTask.</p>

Body:
Java ExecutorService.newFixedThreadPool() internally using a LinkedBlockingQueue<Runnable>() as below:

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

I am wondering when I call ExecutorService.submit(Callable<?>) with callable, how it is pushed into workQueue. As per docs, only Runnable are pushed to workQueue, then what happens to Callable when all threads are busy. Where these are kept for later processing.

As per docs

workQueue - the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.


答:
The
 tag can only contain inline elements. The header tags are block-level elements, and cannot go inside
 tags even when you style them to display inline.

So in this case your
 is not considered in your paragraph.
You can see that by adding border attributes to it.

Title: heading tag won't work in alignment attribute

Body:
The <p> tag can only contain inline elements. The header tags are block-level elements, and cannot go inside <p> tags even when you style them to display inline.

So in this case your <h1> is not considered in your paragraph.
You can see that by adding border attributes to it.


问:
API Exception 10 - Google sign in
I'm making an app and I have implemented the Google sign in withe firebase feature. But for some reason when the onActicityForResult() or ActivityResultLauncher() is being called, i'm getting API EXCEPTION 10. I tried to add the correct SHA1 key to firebase and on my Google cloud console. I read a lot of questions here on SO but none of them helped me.

LoginActivity onActivityForResult() is replaced from Activity Result Launcher:

```<code>public class LoginActivity extends AppCompatActivity {

    LoadingDialog progressDialog;
    public static String TAG = "GoogleActivity: ";
    public static int RC_SIGN_IN = 9001;
    GoogleSignInClient mGoogleSignInClient;
    FirebaseAuth mAuth = FirebaseAuth.getInstance();

    ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == Activity.RESULT_OK || result.getResultCode() == RC_SIGN_IN) {

                        Intent data = result.getData();
                        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);

                        try {
                            // Google Sign In was successful, authenticate with Firebase
                            GoogleSignInAccount account = task.getResult(ApiException.class);
                            Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
                            firebaseAuthWithGoogle(account.getIdToken());
                        } catch (ApiException e) {
                            progressDialog.hide();
                            new AlertDialog.Builder(LoginActivity.this)
                                    .setTitle("Error")
                                    .setMessage(e.getLocalizedMessage())
                                    .setPositiveButton("OK", (dialog, which) -> dialog.dismiss())
                                    .show();
                        }
                    }else {
                        Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_SHORT).show();
                    }
                }
            });

    void googleSignIn() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        someActivityResultLauncher.launch(signInIntent);
        //startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    void singIn(String email, String password) {

        // show progress dialog
        progressDialog.show();

        mAuth.signInWithEmailAndPassword(email, password).addOnSuccessListener(authResult -> {
            progressDialog.hide();
            finish();
            startActivity(new Intent(LoginActivity.this, HomeActivity.class));
            CustomIntent.customType(LoginActivity.this, "left-to-right");
            HomeActivity.anonymous = false;
        }).addOnFailureListener(e -> {
            progressDialog.hide();
            new AlertDialog.Builder(LoginActivity.this)
                    .setTitle("Whoops!")
                    .setMessage(e.getMessage())
                    .setPositiveButton("Okay", (dialog, which) -> dialog.dismiss()).show();
        });

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        CustomIntent.customType(LoginActivity.this, "right-to-left");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        progressDialog = LoadingDialog.Companion.get(LoginActivity.this);

        EditText email = findViewById(R.id.email_login);
        EditText password = findViewById(R.id.password_login);
        Button submit = findViewById(R.id.submit_login);
        TextView resetPasswordTV = findViewById(R.id.textView6);
        TextView register = findViewById(R.id.register_login);
        SignInButton googleSignInBtn = findViewById(R.id.signInButton);

        // Google sign config
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();

        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        googleSignInBtn.setOnClickListener(view -> {
            progressDialog.show();
            googleSignIn();
        });

        resetPasswordTV.setOnClickListener(view -> {

            AlertDialog.Builder dialog = new AlertDialog.Builder(LoginActivity.this)
                    .setTitle("Reset your password");
            final EditText email_et = new EditText(LoginActivity.this);
            email_et.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
            email_et.setHint("Enter your email");
            dialog.setView(email_et);
            dialog.setPositiveButton("OK", (dialogInterface, i) -> {

                if (!email_et.getText().toString().isEmpty()) {
                    sendResetPasswordLink(email_et.getText().toString());
                }

            }).setNegativeButton("Cancel", (dialogInterface, i) -> {
                dialogInterface.dismiss();
            }).show();

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(550, FrameLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(50, 6, 30, 6);
            email_et.setLayoutParams(params);
        });

        register.setOnClickListener(v -> {
            finish();
            startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
            CustomIntent.customType(LoginActivity.this, "fadein-to-fadeout");
        });

        submit.setOnClickListener(v -> {
            if (email.getText().toString().isEmpty() || password.getText().toString().isEmpty()) {
                new AlertDialog.Builder(LoginActivity.this)
                        .setTitle("Whoops!")
                        .setMessage("All fields are required")
                        .setPositiveButton("OK", (dialog, which) -> dialog.dismiss()).show();
            } else {
                singIn(email.getText().toString(), password.getText().toString());
            }
        });

    }

    private void sendResetPasswordLink(String email) {

        progressDialog.show();

        mAuth.sendPasswordResetEmail(email).addOnSuccessListener(task -> {

            progressDialog.hide();

            new AlertDialog.Builder(LoginActivity.this)
                    .setIcon(R.drawable.success_icon)
                    .setTitle("Email send")
                    .setMessage("Reset password link has been send on this email address \n" + email)
                    .setPositiveButton("OK", (dialog, which) -> dialog.dismiss()).show();

        }).addOnFailureListener(e -> {

            progressDialog.hide();

            new AlertDialog.Builder(LoginActivity.this)
                    .setIcon(R.drawable.error_icon)
                    .setTitle("Error")
                    .setMessage(e.getLocalizedMessage())
                    .setPositiveButton("OK", (dialog, which) -> dialog.dismiss()).show();
        });
    }

    private void firebaseAuthWithGoogle(String idToken) {
        AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, task -> {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = mAuth.getCurrentUser();
                        updateUI(user, null);
                    } else {
                        // If sign in fails, display a message to the user.
                        updateUI(null, task.getException());

                    }
                });
    }

    private void updateUI(FirebaseUser user, Exception errorMsg) {
        progressDialog.hide();

        if (user != null) {

            DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("users");

            usersRef.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    if (!snapshot.child(user.getUid()).exists()) {
                        usersRef.child(user.getUid()).child("id").setValue(user.getUid());
                        usersRef.child(user.getUid()).child("name").setValue(user.getDisplayName());
                        usersRef.child(user.getUid()).child("email").setValue(user.getEmail());
                        usersRef.child(user.getUid()).child("profileImgUrl").setValue(user.getPhotoUrl());
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {
                    Toast.makeText(LoginActivity.this, "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });

            finish();
            startActivity(new Intent(LoginActivity.this, HomeActivity.class));
            CustomIntent.customType(LoginActivity.this, "left-to-right");

            Toast.makeText(LoginActivity.this, "Signed in as " + user.getDisplayName(), Toast.LENGTH_SHORT).show();

        } else {
            new AlertDialog.Builder(LoginActivity.this)
                    .setTitle("Error")
                    .setMessage(errorMsg.getLocalizedMessage())
                    .setPositiveButton("OK", (dialog, which) -> dialog.dismiss())
                    .show();
        }
        progressDialog.hide();
    }

}
</code>```

答: The problem was fixed by going Google play console -> MyApp -> Set-up -> Signing and adding the SHA1 key to firebase console</p>

Title: API Exception 10 - Google sign in

Body:
I'm making an app and I have implemented the Google sign in withe firebase feature. But for some reason when the onActicityForResult() or ActivityResultLauncher() is being called, i'm getting API EXCEPTION 10. I tried to add the correct SHA1 key to firebase and on my Google cloud console. I read a lot of questions here on SO but none of them helped me.

LoginActivity onActivityForResult() is replaced from Activity Result Launcher:

public class LoginActivity extends AppCompatActivity {

    LoadingDialog progressDialog;
    public static String TAG = "GoogleActivity: ";
    public static int RC_SIGN_IN = 9001;
    GoogleSignInClient mGoogleSignInClient;
    FirebaseAuth mAuth = FirebaseAuth.getInstance();

    ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == Activity.RESULT_OK || result.getResultCode() == RC_SIGN_IN) {

                        Intent data = result.getData();
                        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);

                        try {
                            // Google Sign In was successful, authenticate with Firebase
                            GoogleSignInAccount account = task.getResult(ApiException.class);
                            Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
                            firebaseAuthWithGoogle(account.getIdToken());
                        } catch (ApiException e) {
                            progressDialog.hide();
                            new AlertDialog.Builder(LoginActivity.this)
                                    .setTitle("Error")
                                    .setMessage(e.getLocalizedMessage())
                                    .setPositiveButton("OK", (dialog, which) -> dialog.dismiss())
                                    .show();
                        }
                    }else {
                        Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_SHORT).show();
                    }
                }
            });

    void googleSignIn() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        someActivityResultLauncher.launch(signInIntent);
        //startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    void singIn(String email, String password) {

        // show progress dialog
        progressDialog.show();

        mAuth.signInWithEmailAndPassword(email, password).addOnSuccessListener(authResult -> {
            progressDialog.hide();
            finish();
            startActivity(new Intent(LoginActivity.this, HomeActivity.class));
            CustomIntent.customType(LoginActivity.this, "left-to-right");
            HomeActivity.anonymous = false;
        }).addOnFailureListener(e -> {
            progressDialog.hide();
            new AlertDialog.Builder(LoginActivity.this)
                    .setTitle("Whoops!")
                    .setMessage(e.getMessage())
                    .setPositiveButton("Okay", (dialog, which) -> dialog.dismiss()).show();
        });

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        CustomIntent.customType(LoginActivity.this, "right-to-left");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        progressDialog = LoadingDialog.Companion.get(LoginActivity.this);

        EditText email = findViewById(R.id.email_login);
        EditText password = findViewById(R.id.password_login);
        Button submit = findViewById(R.id.submit_login);
        TextView resetPasswordTV = findViewById(R.id.textView6);
        TextView register = findViewById(R.id.register_login);
        SignInButton googleSignInBtn = findViewById(R.id.signInButton);

        // Google sign config
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();

        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        googleSignInBtn.setOnClickListener(view -> {
            progressDialog.show();
            googleSignIn();
        });

        resetPasswordTV.setOnClickListener(view -> {

            AlertDialog.Builder dialog = new AlertDialog.Builder(LoginActivity.this)
                    .setTitle("Reset your password");
            final EditText email_et = new EditText(LoginActivity.this);
            email_et.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
            email_et.setHint("Enter your email");
            dialog.setView(email_et);
            dialog.setPositiveButton("OK", (dialogInterface, i) -> {

                if (!email_et.getText().toString().isEmpty()) {
                    sendResetPasswordLink(email_et.getText().toString());
                }

            }).setNegativeButton("Cancel", (dialogInterface, i) -> {
                dialogInterface.dismiss();
            }).show();

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(550, FrameLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(50, 6, 30, 6);
            email_et.setLayoutParams(params);
        });

        register.setOnClickListener(v -> {
            finish();
            startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
            CustomIntent.customType(LoginActivity.this, "fadein-to-fadeout");
        });

        submit.setOnClickListener(v -> {
            if (email.getText().toString().isEmpty() || password.getText().toString().isEmpty()) {
                new AlertDialog.Builder(LoginActivity.this)
                        .setTitle("Whoops!")
                        .setMessage("All fields are required")
                        .setPositiveButton("OK", (dialog, which) -> dialog.dismiss()).show();
            } else {
                singIn(email.getText().toString(), password.getText().toString());
            }
        });

    }

    private void sendResetPasswordLink(String email) {

        progressDialog.show();

        mAuth.sendPasswordResetEmail(email).addOnSuccessListener(task -> {

            progressDialog.hide();

            new AlertDialog.Builder(LoginActivity.this)
                    .setIcon(R.drawable.success_icon)
                    .setTitle("Email send")
                    .setMessage("Reset password link has been send on this email address \n" + email)
                    .setPositiveButton("OK", (dialog, which) -> dialog.dismiss()).show();

        }).addOnFailureListener(e -> {

            progressDialog.hide();

            new AlertDialog.Builder(LoginActivity.this)
                    .setIcon(R.drawable.error_icon)
                    .setTitle("Error")
                    .setMessage(e.getLocalizedMessage())
                    .setPositiveButton("OK", (dialog, which) -> dialog.dismiss()).show();
        });
    }

    private void firebaseAuthWithGoogle(String idToken) {
        AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, task -> {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = mAuth.getCurrentUser();
                        updateUI(user, null);
                    } else {
                        // If sign in fails, display a message to the user.
                        updateUI(null, task.getException());

                    }
                });
    }

    private void updateUI(FirebaseUser user, Exception errorMsg) {
        progressDialog.hide();

        if (user != null) {

            DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("users");

            usersRef.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    if (!snapshot.child(user.getUid()).exists()) {
                        usersRef.child(user.getUid()).child("id").setValue(user.getUid());
                        usersRef.child(user.getUid()).child("name").setValue(user.getDisplayName());
                        usersRef.child(user.getUid()).child("email").setValue(user.getEmail());
                        usersRef.child(user.getUid()).child("profileImgUrl").setValue(user.getPhotoUrl());
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {
                    Toast.makeText(LoginActivity.this, "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });

            finish();
            startActivity(new Intent(LoginActivity.this, HomeActivity.class));
            CustomIntent.customType(LoginActivity.this, "left-to-right");

            Toast.makeText(LoginActivity.this, "Signed in as " + user.getDisplayName(), Toast.LENGTH_SHORT).show();

        } else {
            new AlertDialog.Builder(LoginActivity.this)
                    .setTitle("Error")
                    .setMessage(errorMsg.getLocalizedMessage())
                    .setPositiveButton("OK", (dialog, which) -> dialog.dismiss())
                    .show();
        }
        progressDialog.hide();
    }

}


问:
Consume external web service in Magento/PHP
Are there any tutorials or good examples of how I can utilize (consume?) an external web service via SOAP from within Magento? (Magento is a PHP based software system)

I see TONS of tutorials on accessing Magento data externally using SOAP and Magento's API, but I want to access an external web service from within Magento.

I've done a bit of research and I have to imagine I can use the SoapClient class to do this, but I'm not sure how the required keys and method calls translate to setting up/using the SoapClient class.  If someone can point me in the right direction I'd greatly appreciate it!

Here's an example

Let's say I need to send the following SOAP request to http://someurl.somewhere.com:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://api.channeladvisor.com/webservices/">
    <soapenv:Header>
        <web:APICredentials>
            <web:DeveloperKey>DeveloperKey</web:DeveloperKey>
            <web:Password>Password</web:Password>
        </web:APICredentials>
    </soapenv:Header>
    <soapenv:Body>
        <web:RequestAccess>
            <web:localID>99999999</web:localID>
        </web:RequestAccess>
    </soapenv:Body>
</soapenv:Envelope>
</code>```

How would I go about doing this in Magento?

答: Magento is a php application based on  zend framework so any tutorial that is about zend and soap will also do. You can do any php related stuff in any magento file (exept from config files) although the best place to do such request are models.</p>

Body:
Are there any tutorials or good examples of how I can utilize (consume?) an external web service via SOAP from within Magento? (Magento is a PHP based software system)

I see TONS of tutorials on accessing Magento data externally using SOAP and Magento's API, but I want to access an external web service from within Magento.

I've done a bit of research and I have to imagine I can use the SoapClient class to do this, but I'm not sure how the required keys and method calls translate to setting up/using the SoapClient class.  If someone can point me in the right direction I'd greatly appreciate it!

Here's an example

Let's say I need to send the following SOAP request to http://someurl.somewhere.com:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://api.channeladvisor.com/webservices/">
    <soapenv:Header>
        <web:APICredentials>
            <web:DeveloperKey>DeveloperKey</web:DeveloperKey>
            <web:Password>Password</web:Password>
        </web:APICredentials>
    </soapenv:Header>
    <soapenv:Body>
        <web:RequestAccess>
            <web:localID>99999999</web:localID>
        </web:RequestAccess>
    </soapenv:Body>
</soapenv:Envelope>

How would I go about doing this in Magento?


问:
Typescript : Check for words in a string
There are many options in javascript, but are there any options in typescript to do the find words in a given string:

Eg:

For the list: ['Mr', 'Mrs', 'FM.', 'Sir'] and a string called 'Sir FM. Sam Manekshaw'. I have the words 'Sir' and 'FM.' present, hence needs to be assigned to a string and the remaining parts of the string assigned to another string. i.e:

```<code>a = Sir FM.
b = Sam Manekshaw
</code>```

NOTE: It should validate only full words and not a substring.

UPDATE:
What I tried:

```<code>var tempPrefixList = ['Mr', 'Mrs', 'FM.', 'Sir'];
var firstName = "Sir FM. Sam Manekshaw";

var prefixSearchExp = new RegExp(tempPrefixList.join("|"),"gi");
if(firstName && prefixSearchExp.test(firstName)) {
    console.log("Caught");
    var requestFirstNameSplit = firstName?.split(" ");
    console.log("Prefix: " + requestFirstNameSplit[0]);
    console.log("First name: " + requestFirstNameSplit[1]);
}
</code>```

But this considers only if the name has one Prefix. And also, has only one name in firstName. Eg: Sir Sam. But doesn't work for the example I mentioned earlier.

答:
You can solve it like this:

class PersonDetails {
  formOfAddress: string;
  name: string;

  constructor(formOfAddress: string, name: string) {
    this.formOfAddress = formOfAddress;
    this.name = name;
  }

  get fullName(): string {
    return [this.formOfAddress, this.name].join(' ');
  }
}

function extractPersonDetailsFromFullName(fullName: string): PersonDetails {
  const formOfAddresses = ['Mr', 'Mrs', 'FM.', 'Sir'];

  let usedFormOfAddresses = [];

  const wordsInName = fullName.split(' ').filter((x) => x);
  for (const word of wordsInName ?? []) {
    if (formOfAddresses.filter((foa) => foa == word).length == 1) {
      usedFormOfAddresses.push(word);
    }
  }

  const formOfAddress = usedFormOfAddresses.join(' ');

  return new PersonDetails(
    formOfAddress,
    fullName.substr(formOfAddress.length).trim()
  );
}

const testNames = ['Sir FM. Sam Manekshaw', 'Mr Tom'];

for (const testName of testNames) {
  const personDetails = extractPersonDetailsFromFullName(testName);
  appDiv.innerHTML +=
    testName +
    ' =>
  ' +
    JSON.stringify(personDetails) +
    '

';
}
```
<p>Code: https://stackblitz.com/edit/typescript-iyk3ul?file=index.ts</p>
<p>If you don't want to use the implementation with the separate function and object, you can use the following code:</p>
<pre class="lang-js prettyprint-override"><code>const fullName = 'Sir FM. Sam Manekshaw';

const formOfAddresses = ['Mr', 'Mrs', 'FM.', 'Sir'];

let formOfAddressParts = [];
let nameParts = [];

const wordsInName = fullName.split(' ').filter((x) => x);
for (const word of wordsInName ?? []) {
  if (formOfAddresses.filter((foa) => foa == word).length == 1) {
    formOfAddressParts.push(word);
  } else {
    nameParts.push(word);
  }
}

let formOfAddress = formOfAddressParts.join(' ');
let name = nameParts.join(' ');

console.log('formOfAddress: ', formOfAddress);
console.log('name: ', name);
</code>```

Body:
There are many options in javascript, but are there any options in typescript to do the find words in a given string:

Eg:

For the list: ['Mr', 'Mrs', 'FM.', 'Sir'] and a string called 'Sir FM. Sam Manekshaw'. I have the words 'Sir' and 'FM.' present, hence needs to be assigned to a string and the remaining parts of the string assigned to another string. i.e:

a = Sir FM.
b = Sam Manekshaw

NOTE: It should validate only full words and not a substring.

UPDATE:
What I tried:

var tempPrefixList = ['Mr', 'Mrs', 'FM.', 'Sir'];
var firstName = "Sir FM. Sam Manekshaw";

var prefixSearchExp = new RegExp(tempPrefixList.join("|"),"gi");
if(firstName && prefixSearchExp.test(firstName)) {
    console.log("Caught");
    var requestFirstNameSplit = firstName?.split(" ");
    console.log("Prefix: " + requestFirstNameSplit[0]);
    console.log("First name: " + requestFirstNameSplit[1]);
}

But this considers only if the name has one Prefix. And also, has only one name in firstName. Eg: Sir Sam. But doesn't work for the example I mentioned earlier.

Body:
You can solve it like this:

class PersonDetails {
  formOfAddress: string;
  name: string;

  constructor(formOfAddress: string, name: string) {
    this.formOfAddress = formOfAddress;
    this.name = name;
  }

  get fullName(): string {
    return [this.formOfAddress, this.name].join(' ');
  }
}

function extractPersonDetailsFromFullName(fullName: string): PersonDetails {
  const formOfAddresses = ['Mr', 'Mrs', 'FM.', 'Sir'];

  let usedFormOfAddresses = [];

  const wordsInName = fullName.split(' ').filter((x) => x);
  for (const word of wordsInName ?? []) {
    if (formOfAddresses.filter((foa) => foa == word).length == 1) {
      usedFormOfAddresses.push(word);
    }
  }

  const formOfAddress = usedFormOfAddresses.join(' ');

  return new PersonDetails(
    formOfAddress,
    fullName.substr(formOfAddress.length).trim()
  );
}

const testNames = ['Sir FM. Sam Manekshaw', 'Mr Tom'];

for (const testName of testNames) {
  const personDetails = extractPersonDetailsFromFullName(testName);
  appDiv.innerHTML +=
    testName +
    ' => <br>&nbsp;&nbsp;' +
    JSON.stringify(personDetails) +
    '<br><br>';
}

Code: https://stackblitz.com/edit/typescript-iyk3ul?file=index.ts

If you don't want to use the implementation with the separate function and object, you can use the following code:

const fullName = 'Sir FM. Sam Manekshaw';

const formOfAddresses = ['Mr', 'Mrs', 'FM.', 'Sir'];

let formOfAddressParts = [];
let nameParts = [];

const wordsInName = fullName.split(' ').filter((x) => x);
for (const word of wordsInName ?? []) {
  if (formOfAddresses.filter((foa) => foa == word).length == 1) {
    formOfAddressParts.push(word);
  } else {
    nameParts.push(word);
  }
}

let formOfAddress = formOfAddressParts.join(' ');
let name = nameParts.join(' ');

console.log('formOfAddress: ', formOfAddress);
console.log('name: ', name);


问:
Assign a TimeZone to Dataframe Datetime Column
I cannot figure out how to assign a timezone to a dataframe. I have a df called 'df' that looks like this:

```<code>df
Out[67]:
           date  daily_flow
0    2002-02-13    144000.0
1    2002-02-14    184000.0
2    2002-02-15    159000.0
3    2002-02-16    126000.0
4    2002-02-17    114000.0
        ...         ...
7277 2022-02-02    152000.0
7278 2022-02-03    159000.0
7279 2022-02-04    150000.0
7280 2022-02-05    165000.0
7281 2022-02-06    148000.0

[7282 rows x 2 columns]

df.dtypes
Out[68]:
date          datetime64[ns]
daily_flow           float64
dtype: object
</code>```

I have read the documentation and other posts and it is not clear how to assign the "date" column to a timezone such as 'US/Pacific'. thank you!

Here is an example of an error I keep getting when I try and assign a timezone (UTC) to the datetime column in the index position ('date').

```<code>df.date.tz_localize('UTC')
Traceback (most recent call last):

  Input In [10] in <module>
    df.tz_localize('UTC')

  File ~\Anaconda3\envs\ARIMA\lib\site-packages\pandas\core\generic.py:9977 in tz_localize
    ax = _tz_localize(ax, tz, ambiguous, nonexistent)

  File ~\Anaconda3\envs\ARIMA\lib\site-packages\pandas\core\generic.py:9959 in _tz_localize
    raise TypeError(

TypeError: index is not a valid DatetimeIndex or PeriodIndex
</code>```

答:
To set a time zone for a column, parse to_datetime and use the dt accessor of the Series to tz_localize. EX:

```<code>df
Out[3]:
         date  daily_flow
0  2002-02-13    144000.0
1  2002-02-14    184000.0
2  2002-02-15    159000.0

df['date'] = pd.to_datetime(df['date']).dt.tz_localize('UTC')

df['date']
Out[5]:
0   2002-02-13 00:00:00+00:00
1   2002-02-14 00:00:00+00:00
2   2002-02-15 00:00:00+00:00
Name: date, dtype: datetime64[ns, UTC]
</code>```

In the example, you can replace 'UTC' with the appropriate time zone. You can also convert to another time zone using the same approach (.dt.tz_convert('your-time-zone')).

Body:
I cannot figure out how to assign a timezone to a dataframe. I have a df called 'df' that looks like this:

df
Out[67]:
           date  daily_flow
0    2002-02-13    144000.0
1    2002-02-14    184000.0
2    2002-02-15    159000.0
3    2002-02-16    126000.0
4    2002-02-17    114000.0
        ...         ...
7277 2022-02-02    152000.0
7278 2022-02-03    159000.0
7279 2022-02-04    150000.0
7280 2022-02-05    165000.0
7281 2022-02-06    148000.0

[7282 rows x 2 columns]

df.dtypes
Out[68]:
date          datetime64[ns]
daily_flow           float64
dtype: object

I have read the documentation and other posts and it is not clear how to assign the "date" column to a timezone such as 'US/Pacific'. thank you!

Here is an example of an error I keep getting when I try and assign a timezone (UTC) to the datetime column in the index position ('date').

df.date.tz_localize('UTC')
Traceback (most recent call last):

  Input In [10] in <module>
    df.tz_localize('UTC')

  File ~\Anaconda3\envs\ARIMA\lib\site-packages\pandas\core\generic.py:9977 in tz_localize
    ax = _tz_localize(ax, tz, ambiguous, nonexistent)

  File ~\Anaconda3\envs\ARIMA\lib\site-packages\pandas\core\generic.py:9959 in _tz_localize
    raise TypeError(

TypeError: index is not a valid DatetimeIndex or PeriodIndex

Body:
To set a time zone for a column, parse to_datetime and use the dt accessor of the Series to tz_localize. EX:

df
Out[3]:
         date  daily_flow
0  2002-02-13    144000.0
1  2002-02-14    184000.0
2  2002-02-15    159000.0

df['date'] = pd.to_datetime(df['date']).dt.tz_localize('UTC')

df['date']
Out[5]:
0   2002-02-13 00:00:00+00:00
1   2002-02-14 00:00:00+00:00
2   2002-02-15 00:00:00+00:00
Name: date, dtype: datetime64[ns, UTC]

In the example, you can replace 'UTC' with the appropriate time zone. You can also convert to another time zone using the same approach (.dt.tz_convert('your-time-zone')).


问:
is it possible to remote debugging java program in kubernetes using service name
Now I am remote debugging my java program in kubernetes(v1.15.2) using kubectl proxy forward like this:

```<code>kubectl port-forward soa-report-analysis 5018:5018 -n dabai-fat
</code>```

I could using intellij idea to remote connect my localhost port 5018 to remote debugging my pod in kubernetes cluster in remote datacenter,but now I am facing a problem is every time I must change the pod name to redebug after pod upgrade,any way to keep a stable channel for debugging?

答:
I could suggest for anyone who looks for ways to debug Java(and Go, NodeJS, Python, .NET Core) applications in Kubernetes to look at skaffold.

It simple CLI tool that uses already existing build and deploy configuration that you used to work with.
There is no need for additional installation in the cluster, modification for existing deployment configuration, etc.

Install CLI: https://skaffold.dev/docs/install/

Open your project, and try:

```<code>skaffold init
</code>```

This will make skaffold create

skaffold.yaml

(the only needed config file for skaffold)

And then

```<code>skaffold debug
</code>```

Which will use your existing build and deploy config, to build a container and deploy it. If needed necessary arguments will be injected into the container, and port forwarding will start automatically.

For more info look at:
https://skaffold.dev/docs/workflows/debug/

This can provide a consistent way to debug your application without having to be aware all time about the current pod or deployment state.

Body:
Now I am remote debugging my java program in kubernetes(v1.15.2) using kubectl proxy forward like this:

kubectl port-forward soa-report-analysis 5018:5018 -n dabai-fat

I could using intellij idea to remote connect my localhost port 5018 to remote debugging my pod in kubernetes cluster in remote datacenter,but now I am facing a problem is every time I must change the pod name to redebug after pod upgrade,any way to keep a stable channel for debugging?

Body:
I could suggest for anyone who looks for ways to debug Java(and Go, NodeJS, Python, .NET Core) applications in Kubernetes to look at skaffold.

It simple CLI tool that uses already existing build and deploy configuration that you used to work with.
There is no need for additional installation in the cluster, modification for existing deployment configuration, etc.

Install CLI: https://skaffold.dev/docs/install/

Open your project, and try:

skaffold init

This will make skaffold create

skaffold.yaml

(the only needed config file for skaffold)

And then

skaffold debug

Which will use your existing build and deploy config, to build a container and deploy it. If needed necessary arguments will be injected into the container, and port forwarding will start automatically.

For more info look at:
https://skaffold.dev/docs/workflows/debug/

This can provide a consistent way to debug your application without having to be aware all time about the current pod or deployment state.


问:
How to make a fill parent+wrap_content (in that order) Android
I'll try to simplify the problem for avoiding long code pieces: I want to do something like that in my layout

The structure should be easy with something like:

```<code> LinearLayoutA (vertical)
      LinearLayoutB (vertical)
           LinearLayoutC    (horizontal)
           LinearLayoutC'   (horizontal)
      LinearLayoutB' (vertical)
           LinearLayoutC''  (horizontal)
           LinearLayoutC''' (horizontal)
  All with weight=1
</code>```

the problem for me is define what to put within the LinearLayoutC. So focusing now the elements inside LinearLayoutC:

My first option was another LinearLayout (vertical) the problem is that if the image is taller than the LinearLayoutC the TextView is not visible.

So I used that RelativeLayout:

```<code><RelativeLayout
    android:id="@+id/RelativeLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Eiffel"
        android:textSize="45sp"
        android:id="@+id/text"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
    ></TextView>
    <ImageView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:src="@drawable/eiffel2"
        android:id="@+id/image"
        android:layout_above="@id/text"
    android:layout_centerHorizontal="true"></ImageView>

</RelativeLayout>
</code>```

Nice it works! But not for long =(. (We will call it from now RelativeLayout1) When the screen is smaller than the views the layout seems perfect but when going into a larger screen the block is aligned to the bottom of the parent and I'd like it to be centered in the screen (or the sublayout). Like shows that screen:

That is because of the android:layout_alignParentBottom="true" at the TextView.

Trying to solve that I used a RelativeLayout2 for wrap the RelativeLayout1 with a code like:

```<code><RelativeLayout2
android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>

     <RelativeLayout1
      android:layout_centerInParent="true"
      .....
     ></RelativeLayout1>

 </RelativeLayout2>
</code>```

But even with that the layout RelativeLayout1 still aligned to the bottom of the image (and filling all the screen vertically as it had a height= fill_parent and I don't understand why is that happening and how can I solve it. Please can you help me? I've tried for hours. Thanks in advance

答: use  android:layout_height="wrap_content" for your second RelativeLayout

Body:
I'll try to simplify the problem for avoiding long code pieces: I want to do something like that in my layout

The structure should be easy with something like:

 LinearLayoutA (vertical)
      LinearLayoutB (vertical)
           LinearLayoutC    (horizontal)
           LinearLayoutC'   (horizontal)
      LinearLayoutB' (vertical)
           LinearLayoutC''  (horizontal)
           LinearLayoutC''' (horizontal)
  All with weight=1

the problem for me is define what to put within the LinearLayoutC. So focusing now the elements inside LinearLayoutC:

My first option was another LinearLayout (vertical) the problem is that if the image is taller than the LinearLayoutC the TextView is not visible.

So I used that RelativeLayout:

<RelativeLayout
    android:id="@+id/RelativeLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Eiffel"
        android:textSize="45sp"
        android:id="@+id/text"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
    ></TextView>
    <ImageView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:src="@drawable/eiffel2"
        android:id="@+id/image"
        android:layout_above="@id/text"
    android:layout_centerHorizontal="true"></ImageView>

</RelativeLayout>

Nice it works! But not for long =(. (We will call it from now RelativeLayout1) When the screen is smaller than the views the layout seems perfect but when going into a larger screen the block is aligned to the bottom of the parent and I'd like it to be centered in the screen (or the sublayout). Like shows that screen:

That is because of the android:layout_alignParentBottom="true" at the TextView.

Trying to solve that I used a RelativeLayout2 for wrap the RelativeLayout1 with a code like:

<RelativeLayout2
android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>

     <RelativeLayout1
      android:layout_centerInParent="true"
      .....
     ></RelativeLayout1>

 </RelativeLayout2>

But even with that the layout RelativeLayout1 still aligned to the bottom of the image (and filling all the screen vertically as it had a height= fill_parent and I don't understand why is that happening and how can I solve it. Please can you help me? I've tried for hours. Thanks in advance


问:
Cannot get Username / given_name when using angular-oauth2-oidc and Identity Server 4
I am following the Implicit Workflow example from the angular-oauth2-oidc documentation.

Everything works well in my Angular app, and I can login (during which I am redirected to Identity Server), get my token and use this token to access my Web Api.

However, I have noticed that the "given_name" claim is null, and therefore, the username is not displayed on the login page. Specifically, the following method from the sample code appears to return null:

```<code>public get name() {
    let claims = this.oauthService.getIdentityClaims();
    if (!claims) return null;
    return claims.given_name;
}
</code>```

I thought perhaps this was a problem with permissions, but my scope is set to:

```<code>scope: 'openid profile email api1',
</code>```

Any idea what I need to change to get this "given_name" claim?

答:
I had the same issue, in my case with an error displayed on the browser console, saying that Request was blocked by Security Policy.
even having the AllowAnyOrigin() method called in startup, I lacked to get the header allowed. So when in my angular aap i call the loadUserProfile  method via the
token_received event, it sends some headers that were not allowed.
Finaly this fix my issue:
app.UseCors(options => options.AllowAnyOrigin().AllowAnyHeader());
Don't forget calling that before usemvc</p>

Body:
I am following the Implicit Workflow example from the angular-oauth2-oidc documentation.

Everything works well in my Angular app, and I can login (during which I am redirected to Identity Server), get my token and use this token to access my Web Api.

However, I have noticed that the "given_name" claim is null, and therefore, the username is not displayed on the login page. Specifically, the following method from the sample code appears to return null:

public get name() {
    let claims = this.oauthService.getIdentityClaims();
    if (!claims) return null;
    return claims.given_name;
}

I thought perhaps this was a problem with permissions, but my scope is set to:

scope: 'openid profile email api1',

Any idea what I need to change to get this "given_name" claim?


问:
python code time difference with cut-off time and start time in all columns
I want to find diffence of cut-off time and list of end time in pandas columns and append new time in df</p>
```<code>from datetime import datetime, date

out = datetime.combine(date.today(), datetime.strptime('00:15', '%H:%M').time())
print(out)

# output : datetime.datetime(2020,2,8,0,15)

reception time

2022-02-07 18:01:58
2022-02-07 05:05:05
2022-02-07 08:07:34
2022-02-07 09:05:33

find difference of all time and append in new column in df
</code>```

Body:
I want to find diffence of cut-off time and list of end time in pandas columns and append new time in df

from datetime import datetime, date

out = datetime.combine(date.today(), datetime.strptime('00:15', '%H:%M').time())
print(out)

# output : datetime.datetime(2020,2,8,0,15)

reception time

2022-02-07 18:01:58
2022-02-07 05:05:05
2022-02-07 08:07:34
2022-02-07 09:05:33

find difference of all time and append in new column in df

Body:
If your reception time is a column of a dataframe, use:

df['diff'] = out - pd.to_datetime(df['reception time'])
print(df)

# Output
        reception time            diff
0  2022-02-07 18:01:58 0 days 06:13:02
1  2022-02-07 05:05:05 0 days 19:09:55
2  2022-02-07 08:07:34 0 days 16:07:26
3  2022-02-07 09:05:33 0 days 15:09:27

Setup:

data = {'reception time': ['2022-02-07 18:01:58', '2022-02-07 05:05:05',
                           '2022-02-07 08:07:34', '2022-02-07 09:05:33']}
df = pd.DataFrame(data)
print(df)

# Output
        reception time
0  2022-02-07 18:01:58
1  2022-02-07 05:05:05
2  2022-02-07 08:07:34
3  2022-02-07 09:05:33