问:
MySQL Sub Queries With WHERE condition outside
Is this possible in sub queries?

```<code>SELECT (SELECT count(*) FROM employee WHERE age is not null) as NAME,
       (SELECT count(*) FROM employee WHERE age is null) as NamewithoutAge FROM table WHERE name in('List of name')
</code>```

instead of

```<code>SELECT (SELECT count(*) FROM employee WHERE age is not null and name in('List of name')) as NAME,
       (SELECT count(*) FROM employee WHERE age is null and name in('List of name')) as NamewithoutAge
</code>```

答:
Yes

You can use the results of a query in the select part of the query

```<code>SELECT (SELECT name FROM t2 WHERE t2.age is not null and t1.id = t2.t1_id ) as NAME
        FROM t1 WHERE name in('List of name')
</code>```

Body:
Is this possible in sub queries?

SELECT (SELECT count(*) FROM employee WHERE age is not null) as NAME,
       (SELECT count(*) FROM employee WHERE age is null) as NamewithoutAge FROM table WHERE name in('List of name')

instead of

SELECT (SELECT count(*) FROM employee WHERE age is not null and name in('List of name')) as NAME,
       (SELECT count(*) FROM employee WHERE age is null and name in('List of name')) as NamewithoutAge

Body:
Yes

You can use the results of a query in the select part of the query

SELECT (SELECT name FROM t2 WHERE t2.age is not null and t1.id = t2.t1_id ) as NAME
        FROM t1 WHERE name in('List of name')


来源: stackexchange

问:
cloud computing with Python 3
I wanted to try cloud computing.

I went to PythonInfo Wiki and found links to Google App Engine and PiCloud (which uses Amazon Web Services). However, it turns out that neither of them supports Python 3 (at least at first glance). I would hate to port my code back to Python 2.7.

Does anyone know if there's an easy way to use cloud computing in Python 3 (I don't care who the provider of computing power is)?

答:
With apologies for the self-promotion, my company are working on a cloud-based python environment.  We should be able to support all flavours of Python.  More info here:

http://www.pythonanywhere.com/

ContentLicense: CC BY-SA 3.0

Title: cloud computing with Python 3


问:
How to implement role authorization with custom database?
I have an application which requires role authorization using custom database. The database is set up with a tblUsers table that has a reference to a tblRoles table. The users are also already assigned to their roles.

I also want to use the [Authorize(Role = "RoleName")] attribute on each action to check if an authenticated user is assigned to "RoleName" in the database. I'm having a lot of trouble figuring out where I need to make a modification to the [Authorize] attribute so it behaves that way. I just want to see if a username has a role, I won't have a page to manage roles in the database.

I have tried implementing custom storage providers for ASP.NET Core Identity, but it's starting to look like this is not what I need because I'm not gonna be managing roles within the application, and I can't tell how it affects the behavior of [Authorize] attribute.

Also, it's likely that I have a false assumption in my understanding on how the [Authorize] attribute even works. If you notice it, I would appreciate if you could point it out.

答:
I had a similar problem when my client asked for granular permissions for each role. I couldn't find a way to modify the Authorize attribute but was able to implement the solution with a custom attribute. But it depends on one thing i.e can you get the userId of the calling user? I used cookie authentication so I just include the userId in my claims when someone logs in so when a request comes I can always get it from there. I think the built-in Session logic in asp.net might get the job done too, I can't say for sure though. Anyways the logic for custom authorization goes like this:

Load users and roles from database to cache on startup. If you haven't set up a cache in your program (and don't want to) you can simply make your own for this purpose by making a UserRoleCache class with 2 static lists in it. Also there are several ways of loading data from db on startup but I found it easy to do that directly in Program.cs as you'll see below.

Define your custom attribute to check if the calling user has the required role by iterating over lists in cache and return 403 if not.

Modify your Program class like:

```<code>    public class Program
    {
        public static async Task Main(string[] args)
        {
            IWebHost webHost = CreateWebHostBuilder(args).Build();

            using (var scope = webHost.Services.CreateScope())
            {
                //Get the DbContext instance. Replace MyDbContext with the
                //actual name of the context in your program
                var context = scope.ServiceProvider.GetRequiredService<MyDbContext>();

                List<User> users = await context.User.ToListAsync();
                List<Role> roles = await context.Role.ToListAsync();

                //You may make getters and setters, this is just to give you an idea
                UserRoleCache.users = users;
                UserRoleCache.roles = roles;

            }

            webHost.Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();

    }
</code>```

Then comes the logic for checking if user has a role. Notice I've used an array of roles because sometimes you'll want to allow access to multiple roles.

```<code>    public class RoleRequirementFilter : IAuthorizationFilter
    {
        private readonly string[] _roles;

        public PermissionRequirementFilter(string[] roles)
        {
            _roles = roles;
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            bool hasRole = false;

            //Assuming there's a way you can get the userId
            var userId = GetUserId();

            User user = UserRoleCache.users.FirstOrDefault(x => x.Id == userId);
            //Where roleType is the name of the role like Admin, Manager etc
            List<Role> roles = UserRoleCache.roles.FindAll(x => _roles.Contains(x.RoleType))

            foreach(var role in roles)
            {
                if(user.RoleId == role.Id)
                {
                    hasRole = true;
                    break;
                }
            }

            if (!hasRole)
                context.Result = new StatusCodeResult(403);
        }
    }
</code>```

Finally make the Role attribute

```<code>    public class RoleAttribute : TypeFilterAttribute
    {
        public RoleAttribute(params string[] roles) : base(typeof(RoleRequirementFilter))
        {
            Arguments = new object[] { roles };
        }
    }
</code>```

Now you can use the Role attribute in your controllers:

```<code>public class SampleController : ControllerBase
    {

        [HttpGet]
        [Role("Admin", "Manager")]
        public async Task<ActionResult> Get()
        {

        }

        [HttpPost]
        [Role("Admin")]
        public async Task<ActionResult> Post()
        {

        }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I had a similar problem when my client asked for granular permissions for each role. I couldn't find a way to modify the Authorize attribute but was able to implement the solution with a custom attribute. But it depends on one thing i.e can you get the userId of the calling user? I used cookie authentication so I just include the userId in my claims when someone logs in so when a request comes I can always get it from there. I think the built-in Session logic in asp.net might get the job done too, I can't say for sure though. Anyways the logic for custom authorization goes like this:

Load users and roles from database to cache on startup. If you haven't set up a cache in your program (and don't want to) you can simply make your own for this purpose by making a UserRoleCache class with 2 static lists in it. Also there are several ways of loading data from db on startup but I found it easy to do that directly in Program.cs as you'll see below.

Define your custom attribute to check if the calling user has the required role by iterating over lists in cache and return 403 if not.

Modify your Program class like:

    public class Program
    {
        public static async Task Main(string[] args)
        {
            IWebHost webHost = CreateWebHostBuilder(args).Build();

            using (var scope = webHost.Services.CreateScope())
            {
                //Get the DbContext instance. Replace MyDbContext with the
                //actual name of the context in your program
                var context = scope.ServiceProvider.GetRequiredService<MyDbContext>();

                List<User> users = await context.User.ToListAsync();
                List<Role> roles = await context.Role.ToListAsync();

                //You may make getters and setters, this is just to give you an idea
                UserRoleCache.users = users;
                UserRoleCache.roles = roles;

            }

            webHost.Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();

    }

Then comes the logic for checking if user has a role. Notice I've used an array of roles because sometimes you'll want to allow access to multiple roles.

    public class RoleRequirementFilter : IAuthorizationFilter
    {
        private readonly string[] _roles;

        public PermissionRequirementFilter(string[] roles)
        {
            _roles = roles;
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            bool hasRole = false;

            //Assuming there's a way you can get the userId
            var userId = GetUserId();

            User user = UserRoleCache.users.FirstOrDefault(x => x.Id == userId);
            //Where roleType is the name of the role like Admin, Manager etc
            List<Role> roles = UserRoleCache.roles.FindAll(x => _roles.Contains(x.RoleType))

            foreach(var role in roles)
            {
                if(user.RoleId == role.Id)
                {
                    hasRole = true;
                    break;
                }
            }

            if (!hasRole)
                context.Result = new StatusCodeResult(403);
        }
    }

Finally make the Role attribute

    public class RoleAttribute : TypeFilterAttribute
    {
        public RoleAttribute(params string[] roles) : base(typeof(RoleRequirementFilter))
        {
            Arguments = new object[] { roles };
        }
    }

Now you can use the Role attribute in your controllers:

public class SampleController : ControllerBase
    {

        [HttpGet]
        [Role("Admin", "Manager")]
        public async Task<ActionResult> Get()
        {

        }

        [HttpPost]
        [Role("Admin")]
        public async Task<ActionResult> Post()
        {

        }
    }


问:
VSCode extension to modify the files.exclude configuration
Currently I am trying to write an extension that allows me to dynamically change the workspace filter by adding/removing/modifying entries in the files.exclude configuration element and storing it in the workspace settings.

Running a command like this, e.g. to modify a string or array based configuration works as intended:

```<code>const config = vscode.workspace.getConfiguration();
config.update('editor.fontSize', 14, false); -> works
</code>```

But I just can't wrap my head around how to modify an object based configuration like files.exclude.
I tried different approaches but always got an error saying that I am accessing an element that does not exist.

```<code>config.update('files.exclude.TestXYZ', false, false); -> doesn't work
config.update('TestXYZ', false, false); -> doesn't work
</code>```

Hardcoding an object in advance and using this as new value for the configuration works

```<code>let settings = { "*.html": true, "*.css": true };
config.update('files.exclude', settings, false); -> works, but isn't what I need
</code>```

but in order to write a configurable workspace filter I need to add/remove values from the filter list dynamically.

In addition to that (but not as important): I also can't manage to "read" the current values of files.exclude in a way that I can work with them. I always get a Proxy object and I'm not that of a pro in typescript tbh.

The initial idea was to read the configuration, make my modifications and save it back but after trying for hours I would be OK to overwrite them entirely as long as it works.

答:
With the helpful links by @Gama11 I was able to achieve the result I wanted:

```<code>const config = vscode.workspace.getConfiguration();
var excludeList: {[k: string]: boolean} = {};
excludeList[*.html] = true;
excludeList[*.css] = true;
config.update('files.exclude', excludeList, false);
</code>```

With this I can dynamically change the excludeList and update the config accordingly.

Body:
Currently I am trying to write an extension that allows me to dynamically change the workspace filter by adding/removing/modifying entries in the files.exclude configuration element and storing it in the workspace settings.

Running a command like this, e.g. to modify a string or array based configuration works as intended:

const config = vscode.workspace.getConfiguration();
config.update('editor.fontSize', 14, false); -> works

But I just can't wrap my head around how to modify an object based configuration like files.exclude.
I tried different approaches but always got an error saying that I am accessing an element that does not exist.

config.update('files.exclude.TestXYZ', false, false); -> doesn't work
config.update('TestXYZ', false, false); -> doesn't work

Hardcoding an object in advance and using this as new value for the configuration works

let settings = { "*.html": true, "*.css": true };
config.update('files.exclude', settings, false); -> works, but isn't what I need

but in order to write a configurable workspace filter I need to add/remove values from the filter list dynamically.

In addition to that (but not as important): I also can't manage to "read" the current values of files.exclude in a way that I can work with them. I always get a Proxy object and I'm not that of a pro in typescript tbh.

The initial idea was to read the configuration, make my modifications and save it back but after trying for hours I would be OK to overwrite them entirely as long as it works.

Body:
With the helpful links by @Gama11 I was able to achieve the result I wanted:

const config = vscode.workspace.getConfiguration();
var excludeList: {[k: string]: boolean} = {};
excludeList[*.html] = true;
excludeList[*.css] = true;
config.update('files.exclude', excludeList, false);

With this I can dynamically change the excludeList and update the config accordingly.


问:
How to hide a column in output result in Mysql?
```<code>select historic_betfair_win_prices.sf_name,historic_runners.finish_position,historic_runners.official_rating,historic_betfair_win_prices.date, historic_betfair_win_prices.bsp,
         if(finish_position = 1 , @b:=@b+1,@b:=@b) opening_position,
         if(finish_position = 1 , @last_op:=official_rating,@last_op:=@last_op)last_opening_position,
         cast(if(@b = 0 or finish_position = 1,0,@last_op - official_rating) as decimal(10,2)) diff
from historic_runners
inner join historic_betfair_win_prices on historic_betfair_win_prices.runner_id = historic_runners.runner_id and historic_betfair_win_prices.sf_race_id = historic_runners.race_id
cross join (select @b:=0, @last_op :=0) b
where historic_betfair_win_prices.sf_name = "Camanche Grey"
limit 50
</code>```

I want to hide

opening_position, last_opening_position

columns from the output result. My Mysql version 8.0.18

答:
Use a subquery </p>

```<code>select sf_name,finish_position,official_rating,date,bsp,diff from
(
select historic_betfair_win_prices.sf_name,historic_runners.finish_position,historic_runners.official_rating,historic_betfair_win_prices.date, historic_betfair_win_prices.bsp,
         if(finish_position = 1 , @b:=@b+1,@b:=@b) opening_position,
         if(finish_position = 1 , @last_op:=official_rating,@last_op:=@last_op)last_opening_position,
         cast(if(@b = 0 or finish_position = 1,0,@last_op - official_rating) as decimal(10,2)) diff
from historic_runners
inner join historic_betfair_win_prices on historic_betfair_win_prices.runner_id = historic_runners.runner_id and historic_betfair_win_prices.sf_race_id = historic_runners.race_id
cross join (select @b:=0, @last_op :=0) b
where historic_betfair_win_prices.sf_name = "Camanche Grey"
limit 50
)A
</code>```

Body:
select historic_betfair_win_prices.sf_name,historic_runners.finish_position,historic_runners.official_rating,historic_betfair_win_prices.date, historic_betfair_win_prices.bsp,
         if(finish_position = 1 , @b:=@b+1,@b:=@b) opening_position,
         if(finish_position = 1 , @last_op:=official_rating,@last_op:=@last_op)last_opening_position,
         cast(if(@b = 0 or finish_position = 1,0,@last_op - official_rating) as decimal(10,2)) diff
from historic_runners
inner join historic_betfair_win_prices on historic_betfair_win_prices.runner_id = historic_runners.runner_id and historic_betfair_win_prices.sf_race_id = historic_runners.race_id
cross join (select @b:=0, @last_op :=0) b
where historic_betfair_win_prices.sf_name = "Camanche Grey"
limit 50

I want to hide

opening_position, last_opening_position

columns from the output result. My Mysql version 8.0.18

Body:
Use a subquery

select sf_name,finish_position,official_rating,date,bsp,diff from
(
select historic_betfair_win_prices.sf_name,historic_runners.finish_position,historic_runners.official_rating,historic_betfair_win_prices.date, historic_betfair_win_prices.bsp,
         if(finish_position = 1 , @b:=@b+1,@b:=@b) opening_position,
         if(finish_position = 1 , @last_op:=official_rating,@last_op:=@last_op)last_opening_position,
         cast(if(@b = 0 or finish_position = 1,0,@last_op - official_rating) as decimal(10,2)) diff
from historic_runners
inner join historic_betfair_win_prices on historic_betfair_win_prices.runner_id = historic_runners.runner_id and historic_betfair_win_prices.sf_race_id = historic_runners.race_id
cross join (select @b:=0, @last_op :=0) b
where historic_betfair_win_prices.sf_name = "Camanche Grey"
limit 50
)A


问:
Play WAV file in Browser from WebAPI
I have a challenge. I need to provide an audio to an user to listen it in a web browser.

So, i was trying to begin the solution. What is the best way to provide an audio file (WAV) to an html audio tag play it?

The thing is that when i send it as an url, i believe that the client should need first download all the content, and then start to play. I was thinking something which will run while the data are downloaded, something like a stream.

Do you have an ideia from where to start?

I was thinking something near from Google Drive:

https://docs.google.com/uc?export=download&id={GUIDFromFileFromGoogleDrive}

答:
The thing is that when i send it as an url, i believe that the client should need first download all the content, and then start to play.

No, this is incorrect.

I was thinking something which will run while the data are downloaded, something like a stream.

That's how it works.

```<code><audio src="https://example.com/your-stream.wav" controls />
</code>```

Title: Play WAV file in Browser from WebAPI

Body:
The thing is that when i send it as an url, i believe that the client should need first download all the content, and then start to play.

No, this is incorrect.

I was thinking something which will run while the data are downloaded, something like a stream.

That's how it works.

<audio src="https://example.com/your-stream.wav" controls />


问:
Lookahead regex failing to find the same overlapping matches
Is it possible to find overlapping matches using regular expressions when searching again for the same pattern? I want to be able to find matches that occurs three times. For example babab occurs three times in babababab:

babababab

babababab

babababab

This is my current Python implementation:

```<code>import re
matches = re.findall(r'(?=(\w+).*\1).*\1', "babababab")
print(matches)
</code>```

My program find only baba instead of babab. Thanks!

答:
One trick you may use here is to actually just match on ba(?=bab), which would only consume ba, allowing the regex engine to shift forward logically by just one match:

```<code>matches = re.findall(r'ba(?=bab)', "babababab")
matches = [i + 'bab' for i in matches]
print(matches)
</code>```

This prints:

```<code>['babab', 'babab', 'babab']
</code>```

Note that I concatenate the tail bab to each match, which is fine, because we know the actual logic match was babab.

Body:
Is it possible to find overlapping matches using regular expressions when searching again for the same pattern? I want to be able to find matches that occurs three times. For example babab occurs three times in babababab:

babababab

babababab

babababab

This is my current Python implementation:

import re
matches = re.findall(r'(?=(\w+).*\1).*\1', "babababab")
print(matches)

My program find only baba instead of babab. Thanks!

Body:
One trick you may use here is to actually just match on ba(?=bab), which would only consume ba, allowing the regex engine to shift forward logically by just one match:

matches = re.findall(r'ba(?=bab)', "babababab")
matches = [i + 'bab' for i in matches]
print(matches)

This prints:

['babab', 'babab', 'babab']

Note that I concatenate the tail bab to each match, which is fine, because we know the actual logic match was babab.


问:
Docker cannot mount any folder under /var on Mac OS
After I upgrade to the latest version of docker on Mac os 10.15.3. I get Mounts denied error again.

Here are the versions:

```<code>Docker desktop: 2.2.0.3(42716)
Engine: 19.03.5
Mac osx: Catalina(10.15.3)
Docker compose: 1.25.4
</code>```

I try to mount /var/data/test:/var/data/test in the docker-compose file. And I choose the folder in the File Sharing menu, it turns out to be /private/var/data/test and can't edit anymore.

If I try to run docker-compose up, always get Mounts denied error.

```<code>ERROR: for c9430ce45017_xxx-SNAPSHOT  Cannot start service xxx: Mounts denied:
The path /var/data/test
is not shared from OS X and is not known to Docker.
You can configure shared paths from Docker -> Preferences... -> File Sharing.
See https://docs.docker.com/docker-for-mac/osxfs/#namespaces for more info.
</code>```

Update:
As @tripleee suggest, I edit the compose file to /private/var/data/test:/var/data/test, it works. But it won't work on the server which is Linux.

答:
Thanks for @GordonDavisson sharing your two cents.

Even I can't put the /var/data/test through the docker desktop GUI, I set the sharing file directories from the command line finally.

The shared folders list displayed in the GUI can also be edited in ~/Library/Group Containers/group.com.docker/settings.json.

If the user has already modified shared folders, the "filesharingDirectories" array will already exist in settings.json, you can just add the path in the json array. If not modified, the array is not present in settings.json, but you can add it with your path in addition to the default ones :

```<code>"filesharingDirectories" : [
    "/Users",
    "/Volumes",
    "/private",
    "/tmp",
    "/usr/local/share/dotnet/sdk/NuGetFallbackFolder"
  ]
</code>```

Eventually, the app needs restarting so that folders are visible in the VM.

Credits to this link

At last, I put /var/data/test in the settings.json, after restarting the docker it works.

Body:
After I upgrade to the latest version of docker on Mac os 10.15.3. I get Mounts denied error again.

Here are the versions:

Docker desktop: 2.2.0.3(42716)
Engine: 19.03.5
Mac osx: Catalina(10.15.3)
Docker compose: 1.25.4

I try to mount /var/data/test:/var/data/test in the docker-compose file. And I choose the folder in the File Sharing menu, it turns out to be /private/var/data/test and can't edit anymore.

If I try to run docker-compose up, always get Mounts denied error.

ERROR: for c9430ce45017_xxx-SNAPSHOT  Cannot start service xxx: Mounts denied:
The path /var/data/test
is not shared from OS X and is not known to Docker.
You can configure shared paths from Docker -> Preferences... -> File Sharing.
See https://docs.docker.com/docker-for-mac/osxfs/#namespaces for more info.

Update:
As @tripleee suggest, I edit the compose file to /private/var/data/test:/var/data/test, it works. But it won't work on the server which is Linux.

Body:
Thanks for @GordonDavisson sharing your two cents.

Even I can't put the /var/data/test through the docker desktop GUI, I set the sharing file directories from the command line finally.

The shared folders list displayed in the GUI can also be edited in ~/Library/Group Containers/group.com.docker/settings.json.

If the user has already modified shared folders, the "filesharingDirectories" array will already exist in settings.json, you can just add the path in the json array. If not modified, the array is not present in settings.json, but you can add it with your path in addition to the default ones :

"filesharingDirectories" : [
    "/Users",
    "/Volumes",
    "/private",
    "/tmp",
    "/usr/local/share/dotnet/sdk/NuGetFallbackFolder"
  ]

Eventually, the app needs restarting so that folders are visible in the VM.

Credits to this link

At last, I put /var/data/test in the settings.json, after restarting the docker it works.


问:
Kentico CMS - open URL in specific browser
I am new to Kentico CMS and expect that my question can be answered easily by somebody in the know!

Basically the default web browser we use at work is IE but we have a web app that only supports Chrome, we have linked the web page but I am not sure how to force it to open in Chrome.

Thanks for any assistance!

Chris

答: There is no way to force user to open your link in a particular browser. How open a web links is a OS setting. For example, in Window 10 you can see/change it in Settings->Apps->Default apps-> Web browser</p>


答:
You can do it with conditional aggregation:</p>

```<code>SELECT
  SUM(age is not null) as NameWithAge,
  SUM(age is null) as NamewithoutAge
FROM table
WHERE name in('List of name')
</code>```

Title: MySQL Sub Queries With WHERE condition outside

Body:
You can do it with conditional aggregation:

SELECT
  SUM(age is not null) as NameWithAge,
  SUM(age is null) as NamewithoutAge
FROM table
WHERE name in('List of name')


问:
Playing songs from iPod Library
I'm trying to play couple of songs from iPod library. I can play one song using this code:

```<code>MPMusicPlayerController *musicPlayer = [MPMusicPlayerController applicationMusicPlayer];
MPMediaPropertyPredicate *artist = [MPMediaPropertyPredicate predicateWithValue:@"Poker Face" forProperty:MPMediaItemPropertyTitle];

MPMediaQuery *myArtistQuery = [[MPMediaQuery alloc] init];
[myArtistQuery addFilterPredicate:artist];

[musicPlayer setQueueWithQuery:myArtistQuery];
[musicPlayer play];
</code>```

It plays one songs "Poker Face", when I added to previous code

```<code>MPMediaPropertyPredicate *artist1 = [MPMediaPropertyPredicate predicateWithValue:@"Born This Way" forProperty:MPMediaItemPropertyTitle]

[myArtistQuery addFilterPredicate:artist1];
</code>```

It plays nothing. I have array of song titles, and I want to play them if they exists.

How can I do that?

Thank you.

答:
Here is solution. Playing two songs from iPod library of an artist
```</p>

<code>MPMusicPlayerController *musicPlayer = [MPMusicPlayerController applicationMusicPlayer];
MPMediaQuery *everything = [[MPMediaQuery alloc] init];

MPMediaPropertyPredicate *artist = [MPMediaPropertyPredicate predicateWithValue:@"AC/DC" forProperty:MPMediaItemPropertyArtist];
[everything addFilterPredicate:artist];
NSArray *itemsFromGenericQuery = [everything items];

NSMutableArray *array = [[NSMutableArray alloc] init];
for (MPMediaItem *song in itemsFromGenericQuery) {
    NSString *songTitle = [song valueForProperty: MPMediaItemPropertyTitle];
    if ([songTitle isEqualToString:@"Highway to Hell"]) {
        NSLog (@"%@", songTitle);
        [array addObject:song];
    }
    if ([songTitle isEqualToString:@"Thunderstruck"]) {
        NSLog (@"%@", songTitle);
        [array addObject:song];
    }

}

MPMediaItemCollection *collection = [[MPMediaItemCollection alloc] initWithItems:array];
[musicPlayer setQueueWithItemCollection:collection];
//    NSLog(@"%@", [[MPMediaQuery songsQuery].items );
[musicPlayer play];
</code>```

Title: Playing songs from iPod Library

Body:
I'm trying to play couple of songs from iPod library. I can play one song using this code:

MPMusicPlayerController *musicPlayer = [MPMusicPlayerController applicationMusicPlayer];
MPMediaPropertyPredicate *artist = [MPMediaPropertyPredicate predicateWithValue:@"Poker Face" forProperty:MPMediaItemPropertyTitle];

MPMediaQuery *myArtistQuery = [[MPMediaQuery alloc] init];
[myArtistQuery addFilterPredicate:artist];

[musicPlayer setQueueWithQuery:myArtistQuery];
[musicPlayer play];

It plays one songs "Poker Face", when I added to previous code

MPMediaPropertyPredicate *artist1 = [MPMediaPropertyPredicate predicateWithValue:@"Born This Way" forProperty:MPMediaItemPropertyTitle]

[myArtistQuery addFilterPredicate:artist1];

It plays nothing. I have array of song titles, and I want to play them if they exists.

How can I do that?

Thank you.

Body:
Here is solution. Playing two songs from iPod library of an artist

MPMusicPlayerController *musicPlayer = [MPMusicPlayerController applicationMusicPlayer];
MPMediaQuery *everything = [[MPMediaQuery alloc] init];

MPMediaPropertyPredicate *artist = [MPMediaPropertyPredicate predicateWithValue:@"AC/DC" forProperty:MPMediaItemPropertyArtist];
[everything addFilterPredicate:artist];
NSArray *itemsFromGenericQuery = [everything items];

NSMutableArray *array = [[NSMutableArray alloc] init];
for (MPMediaItem *song in itemsFromGenericQuery) {
    NSString *songTitle = [song valueForProperty: MPMediaItemPropertyTitle];
    if ([songTitle isEqualToString:@"Highway to Hell"]) {
        NSLog (@"%@", songTitle);
        [array addObject:song];
    }
    if ([songTitle isEqualToString:@"Thunderstruck"]) {
        NSLog (@"%@", songTitle);
        [array addObject:song];
    }

}

MPMediaItemCollection *collection = [[MPMediaItemCollection alloc] initWithItems:array];
[musicPlayer setQueueWithItemCollection:collection];
//    NSLog(@"%@", [[MPMediaQuery songsQuery].items );
[musicPlayer play];


问:
Matching file path using awk from a report
Despite many attempts, I'm not able to get a proper way to extract file names from a report using awk.

I have an output like this.

```<code>found in file /home/cloudst/homes/james/Maildir/cur/1580910042.2931_0.s3.mydomain.com:2,Sa/PURCHASE ORDER KALI-1374Wpdf.gz/PURCHASE ORDER KALI-1374Wpdf.exe/FILE:0000
found in file /home/cloudst/homes/james/Maildir/cur/1580910052.2932_0.s3.mydomain.com:2,Sa/PURCHASE ORDER KALI-1374Bpdf.gz/PURCHASE ORDER KALI-1374Bpdf.exe
found in file /home/cloudst/homes/james/Maildir/.afolder/cur/1580910152.2935_0.s3.mydomain.com:2,Sa/PURCHASE ORDER KALI-1364Cpdf.gz/PURCHASE ORDER KALI-1374Dpdf.exe
</code>```

I need to extract the actual file path. Here, the actual file path is

```<code>/home/cloudst/homes/james/Maildir/.afolder/cur/1580910152.2935_0.s3.mydomain.com:2,Sa
</code>```

for the first line. How can I extract the actual file path from this result using awk, sed or any command using regex?

The expected output will be

```<code>/home/cloudst/homes/james/Maildir/cur/1580910042.2931_0.s3.mydomain.com:2,Sa
/home/cloudst/homes/james/Maildir/cur/1580910052.2932_0.s3.mydomain.com:2,Sa
/home/cloudst/homes/james/Maildir/.afolder/cur/1580910152.2935_0.s3.mydomain.com:2,Sa
</code>```

答:
sed also offer a fairly easy solution by using a capture group to capture the text between the first '/' and the ",Sa", e.g.

```<code>$ sed 's|^[^/]*\(/.*,Sa\)/.*$|\1|' file
/home/cloudst/homes/james/Maildir/cur/1580910042.2931_0.s3.mydomain.com:2,Sa
/home/cloudst/homes/james/Maildir/cur/1580910052.2932_0.s3.mydomain.com:2,Sa
/home/cloudst/homes/james/Maildir/.afolder/cur/1580910152.2935_0.s3.mydomain.com:2,Sa
</code>```

Alternate delimiters of '|' are used instead of '/' to avoid the picket-fence effect of \/..\/.

Body:
Despite many attempts, I'm not able to get a proper way to extract file names from a report using awk.

I have an output like this.

found in file /home/cloudst/homes/james/Maildir/cur/1580910042.2931_0.s3.mydomain.com:2,Sa/PURCHASE ORDER KALI-1374Wpdf.gz/PURCHASE ORDER KALI-1374Wpdf.exe/FILE:0000
found in file /home/cloudst/homes/james/Maildir/cur/1580910052.2932_0.s3.mydomain.com:2,Sa/PURCHASE ORDER KALI-1374Bpdf.gz/PURCHASE ORDER KALI-1374Bpdf.exe
found in file /home/cloudst/homes/james/Maildir/.afolder/cur/1580910152.2935_0.s3.mydomain.com:2,Sa/PURCHASE ORDER KALI-1364Cpdf.gz/PURCHASE ORDER KALI-1374Dpdf.exe

I need to extract the actual file path. Here, the actual file path is

/home/cloudst/homes/james/Maildir/.afolder/cur/1580910152.2935_0.s3.mydomain.com:2,Sa

for the first line. How can I extract the actual file path from this result using awk, sed or any command using regex?

The expected output will be

/home/cloudst/homes/james/Maildir/cur/1580910042.2931_0.s3.mydomain.com:2,Sa
/home/cloudst/homes/james/Maildir/cur/1580910052.2932_0.s3.mydomain.com:2,Sa
/home/cloudst/homes/james/Maildir/.afolder/cur/1580910152.2935_0.s3.mydomain.com:2,Sa

Body:
sed also offer a fairly easy solution by using a capture group to capture the text between the first '/' and the ",Sa", e.g.

$ sed 's|^[^/]*\(/.*,Sa\)/.*$|\1|' file
/home/cloudst/homes/james/Maildir/cur/1580910042.2931_0.s3.mydomain.com:2,Sa
/home/cloudst/homes/james/Maildir/cur/1580910052.2932_0.s3.mydomain.com:2,Sa
/home/cloudst/homes/james/Maildir/.afolder/cur/1580910152.2935_0.s3.mydomain.com:2,Sa

Alternate delimiters of '|' are used instead of '/' to avoid the picket-fence effect of \/..\/.


问:
What is the colon (:) expression in verilog structure assignment pattern?
For example,

```<code>typedef struct packed {
  logic foo_1;
  logic foo_2;
} my_type

my_type foo_out;

assign foo_out = ‘{
  foo_1 : sig_1,
  foo_2 : sig_2
};
</code>```

It looks like that, just same as

```<code>assign foo_out = {sig_1, sig_2};
</code>```

I can’t find any structure assignment pattern using colon (:) in LRM.
Anybody please leave comment where this kind of expression is describled.

答:
This is a SystemVerilog expression, which isn't part of plain Verilog so you won't find it if you're searching in the Verilog LRM.

From the SystemVerilog LRM:

It can sometimes be useful to set structure members to a value without having to keep track of how many
  members there are, or what the names are. This can be done with the default keyword:

```<code>initial s1 = {default:2}; // sets x and y to 2
</code>```

The {member:value} or {data_type: default_value} syntax can also be used:

```<code>ab abkey[1:0] = {{a:1, b:1.0}, {int:2, shortreal:2.0}};
</code>```

Body:
For example,

typedef struct packed {
  logic foo_1;
  logic foo_2;
} my_type

my_type foo_out;

assign foo_out = ‘{
  foo_1 : sig_1,
  foo_2 : sig_2
};

It looks like that, just same as

assign foo_out = {sig_1, sig_2};

I can’t find any structure assignment pattern using colon (:) in LRM.
Anybody please leave comment where this kind of expression is describled.

Body:
This is a SystemVerilog expression, which isn't part of plain Verilog so you won't find it if you're searching in the Verilog LRM.

From the SystemVerilog LRM:

It can sometimes be useful to set structure members to a value without having to keep track of how many
  members there are, or what the names are. This can be done with the default keyword:

initial s1 = {default:2}; // sets x and y to 2

The {member:value} or {data_type: default_value} syntax can also be used:

ab abkey[1:0] = {{a:1, b:1.0}, {int:2, shortreal:2.0}};


问:
How to get a list of video URLs from a specific YouTube channel
I want to get a list of video URLs from a specific YouTube channel with Python.

First, I wrote the following code.

```<code>import os
import time
import requests
import pandas as pd

API_KEY = os.environ['API_KEY']
CHANNEL_ID = 'your_searching_channel_id'

base_url = 'https://www.googleapis.com/youtube/v3'
url = base_url + '/search?key=%s&channelId=%s&part=snippet,id&order=date&maxResults=50'
infos = []
</code>```

But I don't know the next step.

I read YouTube API HELP, but I couldn't understand how to structure the program.

答:
Logic ->

Import Necessary libraries.

```<code>import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
</code>```

Use Selenium.
I'm picking up Chrome driver.Make sure your chromedriver is in same directory in which you are running the script.

```<code>driver = webdriver.Chrome()
</code>```

Supply the Youtube Channel's url.

```<code>url = input("Enter Youtube Channel URL : ")
</code>```

Go to the videos section.

```<code>driver.get(url+"/videos")
</code>```

Scroll down till the end of the page.
Because the page loads when scrolled down,we need to take care of this.

```<code>ht=driver.execute_script("return document.documentElement.scrollHeight;")
while True:
    prev_ht=driver.execute_script("return document.documentElement.scrollHeight;")
    driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight);")
    time.sleep(2)
    ht=driver.execute_script("return document.documentElement.scrollHeight;")
    if prev_ht==ht:
        break
</code>```

Find links of all the videos.

```<code>links=driver.find_elements_by_xpath('//*[@id="video-title"]')
for link in links:
    print(link.get_attribute("href"))
</code>```

That's it.

Cons- Requires a webdriver. Slower than getting results directly from Youtube API.

Body:
I want to get a list of video URLs from a specific YouTube channel with Python.

First, I wrote the following code.

import os
import time
import requests
import pandas as pd

API_KEY = os.environ['API_KEY']
CHANNEL_ID = 'your_searching_channel_id'

base_url = 'https://www.googleapis.com/youtube/v3'
url = base_url + '/search?key=%s&channelId=%s&part=snippet,id&order=date&maxResults=50'
infos = []

But I don't know the next step.

I read YouTube API HELP, but I couldn't understand how to structure the program.

Body:
Logic ->

Import Necessary libraries.

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

Use Selenium.
I'm picking up Chrome driver.Make sure your chromedriver is in same directory in which you are running the script.

driver = webdriver.Chrome()

Supply the Youtube Channel's url.

url = input("Enter Youtube Channel URL : ")

Go to the videos section.

driver.get(url+"/videos")

Scroll down till the end of the page.
Because the page loads when scrolled down,we need to take care of this.

ht=driver.execute_script("return document.documentElement.scrollHeight;")
while True:
    prev_ht=driver.execute_script("return document.documentElement.scrollHeight;")
    driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight);")
    time.sleep(2)
    ht=driver.execute_script("return document.documentElement.scrollHeight;")
    if prev_ht==ht:
        break

Find links of all the videos.

links=driver.find_elements_by_xpath('//*[@id="video-title"]')
for link in links:
    print(link.get_attribute("href"))

That's it.

Cons- Requires a webdriver. Slower than getting results directly from Youtube API.


问:
No next button when importing Maven projects in IntelliJ
I am trying to follow a tutorial on spring boot, first step is to import a maven project in intelliJ, generated by spring initializer, but when I try to do so, I have no next button in the import window, only "finish". And when I click on finish, it does not seem to detect packages. Any idea ?

答:
Indeed all dependencies were resolved with maven build :)
Thanks guys !</p>


问:
Unable to read xlsb file using pandas
I am trying to read an xlsb file from local using pandas' read_excel but I am getting error.
My code:

```<code>import pandas as pd
df3 = pd.read_excel('a.xlsb', engine = 'pyxlsb')
</code>```

Error:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-06db88cb2446> in <module>
----> 1 pd.read_excel('a.xlsb', engine='pyxlsb')

/usr/local/lib/python3.5/dist-packages/pandas/util/_decorators.py in wrapper(*args, **kwargs)
    186                 else:
    187                     kwargs[new_arg_name] = new_arg_value
--> 188             return func(*args, **kwargs)
    189         return wrapper
    190     return _deprecate_kwarg

/usr/local/lib/python3.5/dist-packages/pandas/util/_decorators.py in wrapper(*args, **kwargs)
    186                 else:
    187                     kwargs[new_arg_name] = new_arg_value
--> 188             return func(*args, **kwargs)
    189         return wrapper
    190     return _deprecate_kwarg

/usr/local/lib/python3.5/dist-packages/pandas/io/excel.py in read_excel(io, sheet_name, header, names, index_col, parse_cols, usecols, squeeze, dtype, engine, converters, true_values, false_values, skiprows, nrows, na_values, keep_default_na, verbose, parse_dates, date_parser, thousands, comment, skip_footer, skipfooter, convert_float, mangle_dupe_cols, **kwds)
    348
    349     if not isinstance(io, ExcelFile):
--> 350         io = ExcelFile(io, engine=engine)
    351
    352     return io.parse(

/usr/local/lib/python3.5/dist-packages/pandas/io/excel.py in __init__(self, io, engine)
    644             engine = 'xlrd'
    645         if engine not in self._engines:
--> 646             raise ValueError("Unknown engine: {engine}".format(engine=engine))
    647
    648         # could be a str, ExcelFile, Book, etc.

ValueError: Unknown engine: pyxlsb
</code>```

It works fine for csv and xlsx files.

python version: 3.5.2

pandas version: 0.24.2

答:
After looking into the problem a bit more and referring to @Datanovice 's comment, it works for me if I update to pandas v1.0.
I am using ubuntu 16.04 which can automatically update my python to 3.5, not any further and pandas v1.0 is supported from python 3.6. Hence, even after updating with the latest versions, I was not able to run the code.
We can install python 3.6 and install pandas v1.0 for that.

```<code>sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt-get install python3.6
</code>```

Using pandas 3.6, we can simply pass the engine as pyxlsb to read_excel to read the file.

```<code>import pandas as pd
df3 = pd.read_excel('a.xlsb', engine = 'pyxlsb')
</code>```

Reference to install python3.6 on Ubuntu 16.04: https://askubuntu.com/questions/865554/how-do-i-install-python-3-6-using-apt-get

Title: Unable to read xlsb file using pandas

Body:
I am trying to read an xlsb file from local using pandas' read_excel but I am getting error.
My code:

import pandas as pd
df3 = pd.read_excel('a.xlsb', engine = 'pyxlsb')

Error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-06db88cb2446> in <module>
----> 1 pd.read_excel('a.xlsb', engine='pyxlsb')

/usr/local/lib/python3.5/dist-packages/pandas/util/_decorators.py in wrapper(*args, **kwargs)
    186                 else:
    187                     kwargs[new_arg_name] = new_arg_value
--> 188             return func(*args, **kwargs)
    189         return wrapper
    190     return _deprecate_kwarg

/usr/local/lib/python3.5/dist-packages/pandas/util/_decorators.py in wrapper(*args, **kwargs)
    186                 else:
    187                     kwargs[new_arg_name] = new_arg_value
--> 188             return func(*args, **kwargs)
    189         return wrapper
    190     return _deprecate_kwarg

/usr/local/lib/python3.5/dist-packages/pandas/io/excel.py in read_excel(io, sheet_name, header, names, index_col, parse_cols, usecols, squeeze, dtype, engine, converters, true_values, false_values, skiprows, nrows, na_values, keep_default_na, verbose, parse_dates, date_parser, thousands, comment, skip_footer, skipfooter, convert_float, mangle_dupe_cols, **kwds)
    348
    349     if not isinstance(io, ExcelFile):
--> 350         io = ExcelFile(io, engine=engine)
    351
    352     return io.parse(

/usr/local/lib/python3.5/dist-packages/pandas/io/excel.py in __init__(self, io, engine)
    644             engine = 'xlrd'
    645         if engine not in self._engines:
--> 646             raise ValueError("Unknown engine: {engine}".format(engine=engine))
    647
    648         # could be a str, ExcelFile, Book, etc.

ValueError: Unknown engine: pyxlsb

It works fine for csv and xlsx files.

python version: 3.5.2

pandas version: 0.24.2

Body:
After looking into the problem a bit more and referring to @Datanovice 's comment, it works for me if I update to pandas v1.0.
I am using ubuntu 16.04 which can automatically update my python to 3.5, not any further and pandas v1.0 is supported from python 3.6. Hence, even after updating with the latest versions, I was not able to run the code.
We can install python 3.6 and install pandas v1.0 for that.

sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt-get install python3.6

Using pandas 3.6, we can simply pass the engine as pyxlsb to read_excel to read the file.

import pandas as pd
df3 = pd.read_excel('a.xlsb', engine = 'pyxlsb')

Reference to install python3.6 on Ubuntu 16.04: https://askubuntu.com/questions/865554/how-do-i-install-python-3-6-using-apt-get


问:
Android org.apache.http.client.HttpResponseException: Not Found
In my app I send user information to server with http as follows, I get org.apache.http.client.HttpResponseException: Not Found and I have spend more time but could not solution.please help me find out the solution.

I get error at this line:

jsonResponse = httpClient.execute(httpPost, resHandler);

```<code>public String addNewCardDetail(String loggedin_id, String fn, String ln,
        String cardholdername, String cardno,String cvv, String expdate, String add,
        String state, String city, String pincode) {

    jsonResponse = "";

    httpClient = new DefaultHttpClient();
    resHandler = new BasicResponseHandler();
    httpPost = new HttpPost("http://xxx.xxx.xxx.xx/users/createCustomerCardAddress");
    nameValuePairs = new ArrayList<NameValuePair>(11);

    nameValuePairs.add(new BasicNameValuePair("loggedin_id",loggedin_id));
    nameValuePairs.add(new BasicNameValuePair("firstname",fn));
    nameValuePairs.add(new BasicNameValuePair("lastname",ln));
    nameValuePairs.add(new BasicNameValuePair("cardHolderName",cardholdername));
    nameValuePairs.add(new BasicNameValuePair("cardNumber",cardno));
    nameValuePairs.add(new BasicNameValuePair("cardCvv",cvv));
    nameValuePairs.add(new BasicNameValuePair("expDate",expdate));
    nameValuePairs.add(new BasicNameValuePair("address",add));
    nameValuePairs.add(new BasicNameValuePair("state",state));
    nameValuePairs.add(new BasicNameValuePair("city",city));
    nameValuePairs.add(new BasicNameValuePair("pincode",pincode));

    Log.e("----------", "---------");
    for (int i = 0; i < nameValuePairs.size(); i++) {
        Log.e("add / edit new card", nameValuePairs.get(i).getName());
        Log.e("add / edit new card", nameValuePairs.get(i).getValue());
    }
    Log.e("----------", "---------");

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        jsonResponse = httpClient.execute(httpPost, resHandler); // I get org.apache.http.client.HttpResponseException: Not Found
        Log.e("add edit card response", "-"+jsonResponse);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return jsonResponse;
}
</code>```

My Log trace:

```<code>org.apache.http.client.HttpResponseException: Not Found
at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:71)
at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:59)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:773)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:743)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732)
at com.fssd.spot.parser.ParsorClass.addNewCardDetail(ParsorClass.java:1098)
at com.fssd.spot.payment.BillingAddress$AddNewcard.doInBackground(BillingAddress.java:146)
at com.fssd.spot.payment.BillingAddress$AddNewcard.doInBackground(BillingAddress.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
</code>```

答: This error cause of invalid authorization for the URL. Please re-check the HTTP request and do it again.</p>

Body:
In my app I send user information to server with http as follows, I get org.apache.http.client.HttpResponseException: Not Found and I have spend more time but could not solution.please help me find out the solution.

I get error at this line:

jsonResponse = httpClient.execute(httpPost, resHandler);

public String addNewCardDetail(String loggedin_id, String fn, String ln,
        String cardholdername, String cardno,String cvv, String expdate, String add,
        String state, String city, String pincode) {

    jsonResponse = "";

    httpClient = new DefaultHttpClient();
    resHandler = new BasicResponseHandler();
    httpPost = new HttpPost("http://xxx.xxx.xxx.xx/users/createCustomerCardAddress");
    nameValuePairs = new ArrayList<NameValuePair>(11);

    nameValuePairs.add(new BasicNameValuePair("loggedin_id",loggedin_id));
    nameValuePairs.add(new BasicNameValuePair("firstname",fn));
    nameValuePairs.add(new BasicNameValuePair("lastname",ln));
    nameValuePairs.add(new BasicNameValuePair("cardHolderName",cardholdername));
    nameValuePairs.add(new BasicNameValuePair("cardNumber",cardno));
    nameValuePairs.add(new BasicNameValuePair("cardCvv",cvv));
    nameValuePairs.add(new BasicNameValuePair("expDate",expdate));
    nameValuePairs.add(new BasicNameValuePair("address",add));
    nameValuePairs.add(new BasicNameValuePair("state",state));
    nameValuePairs.add(new BasicNameValuePair("city",city));
    nameValuePairs.add(new BasicNameValuePair("pincode",pincode));

    Log.e("----------", "---------");
    for (int i = 0; i < nameValuePairs.size(); i++) {
        Log.e("add / edit new card", nameValuePairs.get(i).getName());
        Log.e("add / edit new card", nameValuePairs.get(i).getValue());
    }
    Log.e("----------", "---------");

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        jsonResponse = httpClient.execute(httpPost, resHandler); // I get org.apache.http.client.HttpResponseException: Not Found
        Log.e("add edit card response", "-"+jsonResponse);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return jsonResponse;
}

My Log trace:

org.apache.http.client.HttpResponseException: Not Found
at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:71)
at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:59)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:773)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:743)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732)
at com.fssd.spot.parser.ParsorClass.addNewCardDetail(ParsorClass.java:1098)
at com.fssd.spot.payment.BillingAddress$AddNewcard.doInBackground(BillingAddress.java:146)
at com.fssd.spot.payment.BillingAddress$AddNewcard.doInBackground(BillingAddress.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)


问:
Does IdentityServer4 still allow ResourceAuthorize?
I'm looking at upgrading from IdentityServer3 to IdentityServer4, specifically because we're upgrading existing projects from .NET 4.5 to .NET Core 3.1.

The biggest issue I see right now is that we use the ResourceAuthorize attribute to check if the user has permission against a resource

```<code>[ResourceAuthorize("Read","urn://someresource")]
</code>```

But looking through the ID4 documentation and the code base, it doesn't look like ResourceAuthorize exists. The documentation does show examples of using Authorize, but I'm not seeing anything that lets me check for a permission against a resource.

Has the paradigm changed or is there another way to get this type of check done with ID4?

答:
You can add policies:

Startup.cs

```<code>    services.AddAuthorization(authorizationOptions =>
        {
            authorizationOptions.AddPolicy(
                "SomePolicy",
                policyBuilder =>
                {
                    policyBuilder.RequireAuthenticatedUser();
                    policyBuilder.AddRequirements(
                            new SomePolicyRequirement());
                });

        });
</code>```

SomePolicyRequirement.cs

```<code>public class SomePolicyRequirement : IAuthorizationRequirement
{
    public SomePolicyRequirement()
    {

    }
}
</code>```

SomePolicyHandler.cs

```<code>public class SomePolicyHandler : AuthorizationHandler<SomePolicyRequirement>
{
    public SomePolicyHandler()
    {

    }

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, SomePolicyRequirement requirement)
    {
        var endpoint = context.Resource as Endpoint;
        if (endpoint == null)
        {
            context.Fail();
            return Task.CompletedTask;
        }

        /*
        //RouteData can be controller, action or id
        var imageId = filterContext.RouteData.Values["id"].ToString();

        if (!Guid.TryParse(imageId, out Guid imageIdAsGuid))
        {
            context.Fail();
            return Task.CompletedTask;
        }*/

        /*
        //Repository check can go here
        var ownerId = context.User.Claims.FirstOrDefault(c => c.Type == "sub").Value;

        if (!_someRepository.IsImageOwner(imageIdAsGuid, ownerId))
        {
            context.Fail();
            return Task.CompletedTask;
        }*/

        // all checks out
        context.Succeed(requirement);
        return Task.CompletedTask;
    }
}
</code>```

Body:
I'm looking at upgrading from IdentityServer3 to IdentityServer4, specifically because we're upgrading existing projects from .NET 4.5 to .NET Core 3.1.

The biggest issue I see right now is that we use the ResourceAuthorize attribute to check if the user has permission against a resource

[ResourceAuthorize("Read","urn://someresource")]

But looking through the ID4 documentation and the code base, it doesn't look like ResourceAuthorize exists. The documentation does show examples of using Authorize, but I'm not seeing anything that lets me check for a permission against a resource.

Has the paradigm changed or is there another way to get this type of check done with ID4?

Body:
You can add policies:

Startup.cs

    services.AddAuthorization(authorizationOptions =>
        {
            authorizationOptions.AddPolicy(
                "SomePolicy",
                policyBuilder =>
                {
                    policyBuilder.RequireAuthenticatedUser();
                    policyBuilder.AddRequirements(
                            new SomePolicyRequirement());
                });

        });

SomePolicyRequirement.cs

public class SomePolicyRequirement : IAuthorizationRequirement
{
    public SomePolicyRequirement()
    {

    }
}

SomePolicyHandler.cs

public class SomePolicyHandler : AuthorizationHandler<SomePolicyRequirement>
{
    public SomePolicyHandler()
    {

    }

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, SomePolicyRequirement requirement)
    {
        var endpoint = context.Resource as Endpoint;
        if (endpoint == null)
        {
            context.Fail();
            return Task.CompletedTask;
        }

        /*
        //RouteData can be controller, action or id
        var imageId = filterContext.RouteData.Values["id"].ToString();

        if (!Guid.TryParse(imageId, out Guid imageIdAsGuid))
        {
            context.Fail();
            return Task.CompletedTask;
        }*/

        /*
        //Repository check can go here
        var ownerId = context.User.Claims.FirstOrDefault(c => c.Type == "sub").Value;

        if (!_someRepository.IsImageOwner(imageIdAsGuid, ownerId))
        {
            context.Fail();
            return Task.CompletedTask;
        }*/

        // all checks out
        context.Succeed(requirement);
        return Task.CompletedTask;
    }
}


问:
Menu control (WPF) issues
I want to create a scalable Menu control in my application. I used this answer to create a scalable window and then inserted the Menu control into it. I have some issues and cannot find a solution.

How to set the "center" vertical adjustment for the menu items? Now they are docked to the top. Are there any ways to move the first item ("File" in my case) to the right a bit?

And is it possible to avoid cutting of menu panel during window resizing? For now, even if I move the top border of inner grid a bit down, the menu panel is cut by half.

My code and its results for full-screen and smaller scale are below:

<Window x:Class="DigitalSteelCastingWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DigitalSteelCastingWPF"
        mc:Ignorable="d"
        Title="Digital Steel Casting"
        Name="myMainWindow"
        Height="1056" Width="1936"
        WindowStartupLocation="CenterScreen" WindowState="Maximized"
        FontSize="24"
        HorizontalAlignment="Center" VerticalAlignment="Center"
        WindowStyle="ThreeDBorderWindow">

    <Grid Name="MainGrid" SizeChanged="MainGrid_SizeChanged">

        <Grid.LayoutTransform>
            <ScaleTransform x:Name="ApplicationScaleTransform"
                        CenterX="0"
                        CenterY="0"
                        ScaleX="{Binding ElementName=myMainWindow, Path=ScaleValue}"
                        ScaleY="{Binding ElementName=myMainWindow, Path=ScaleValue}" />
        </Grid.LayoutTransform>

        <Grid VerticalAlignment="Center" HorizontalAlignment="Center" Height="1025" Width="1928">

            <StackPanel VerticalAlignment="Top">
                <Menu Width="Auto" Height="50" VerticalAlignment="Center" FontSize="24">
                    <MenuItem Header="_File">
                        <MenuItem x:Name="New" Header="_New" Height="50" HorizontalAlignment="Left" Width="250"/>
                        <MenuItem x:Name="Open" Header="_Open" Height="50" HorizontalAlignment="Left" Width="250"/>
                        <MenuItem x:Name="Exit" Header="_Exit" Height="50" HorizontalAlignment="Left" Width="250"/>
                    </MenuItem>
                    <MenuItem Header="_Tools">
                        <MenuItem x:Name="Options" Header="O_ptions" Height="50" HorizontalAlignment="Left" Width="250"/>
                    </MenuItem>
                </Menu>
            </StackPanel>

        </Grid>

    </Grid>

</Window>

```

答:
You can add a Viewbox</p>

```<code> <Grid>
        ***<Viewbox Stretch="Fill">***
            <Grid VerticalAlignment="Center" HorizontalAlignment="Center"  Height="1025" Width="1928">

                <StackPanel VerticalAlignment="Top">
                    <Menu Width="Auto" Height="50" VerticalAlignment="Center" FontSize="24">
                        <MenuItem Header="_File">
                            <MenuItem x:Name="New" Header="_New" Height="50" HorizontalAlignment="Left" Width="250"/>
                            <MenuItem x:Name="Open" Header="_Open" Height="50" HorizontalAlignment="Left" Width="250"/>
                            <MenuItem x:Name="Exit" Header="_Exit" Height="50" HorizontalAlignment="Left" Width="250"/>
                        </MenuItem>
                        <MenuItem Header="_Tools">
                            <MenuItem x:Name="Options" Header="O_ptions" Height="50" HorizontalAlignment="Left" Width="250"/>
                        </MenuItem>
                    </Menu>
                </StackPanel>

            </Grid>
        ***</Viewbox>***
        <Grid.LayoutTransform>
            <ScaleTransform x:Name="ApplicationScaleTransform"
                        CenterX="0"
                        CenterY="0"
                        ScaleX="{Binding ElementName=myMainWindow, Path=ScaleValue}"
                        ScaleY="{Binding ElementName=myMainWindow, Path=ScaleValue}" />
        </Grid.LayoutTransform>

    </Grid>
</code>```

Title: Menu control (WPF) issues

Body:
You can add a Viewbox

 <Grid>
        ***<Viewbox Stretch="Fill">***
            <Grid VerticalAlignment="Center" HorizontalAlignment="Center"  Height="1025" Width="1928">

                <StackPanel VerticalAlignment="Top">
                    <Menu Width="Auto" Height="50" VerticalAlignment="Center" FontSize="24">
                        <MenuItem Header="_File">
                            <MenuItem x:Name="New" Header="_New" Height="50" HorizontalAlignment="Left" Width="250"/>
                            <MenuItem x:Name="Open" Header="_Open" Height="50" HorizontalAlignment="Left" Width="250"/>
                            <MenuItem x:Name="Exit" Header="_Exit" Height="50" HorizontalAlignment="Left" Width="250"/>
                        </MenuItem>
                        <MenuItem Header="_Tools">
                            <MenuItem x:Name="Options" Header="O_ptions" Height="50" HorizontalAlignment="Left" Width="250"/>
                        </MenuItem>
                    </Menu>
                </StackPanel>

            </Grid>
        ***</Viewbox>***
        <Grid.LayoutTransform>
            <ScaleTransform x:Name="ApplicationScaleTransform"
                        CenterX="0"
                        CenterY="0"
                        ScaleX="{Binding ElementName=myMainWindow, Path=ScaleValue}"
                        ScaleY="{Binding ElementName=myMainWindow, Path=ScaleValue}" />
        </Grid.LayoutTransform>

    </Grid>


问:
How can I change default backround color of botman.io widget
Im using botman.io package for chatboot widget.
Everything works perfectly but problem is that i can't change default background color of chat widget. On inspect console it shown that boman widget calls ( https://cdn.jsdelivr.net/npm/botman-web-widget@0.0.20/build/assets/css/chat.css ) link, but i cant find that call on my localhost project. If anyone know solution i would appreciate.

```<code><script src="{{ asset('/js/webflow.js') }}"></script>
<script>
        var botmanWidget = {
        title:'Scarletbot',
        introMessage: 'Hello, I am a Scarlet! I am here to assist you and answer all your questions about our products and services!',
        mainColor:'#c02026',
        aboutText:'',
        bubbleBackground:'#c02026',
        headerTextColor: '#fff',
    };

</script>
<script id="botmanWidget" src="{{ asset('/js/widget.js') }}"></script>
</code>```

答:
I use brute force in the iframe to change background with jquery

$(document).on('click', '.desktop-closed-message-avatar img', function() {
    var iframe = document.getElementById("chatBotManFrame");
    iframe.addEventListener('load', function () {
        var htmlFrame = this.contentWindow.document.getElementsByTagName("html")[0];
        var bodyFrame = this.contentWindow.document.getElementsByTagName("body")[0];
        var headFrame = this.contentWindow.document.getElementsByTagName("head")[0];

        var image = "https://images.unsplash.com/photo-1501597301489-8b75b675ba0a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1349&q=80"

        htmlFrame.style.backgroundImage = "url("+image+")";
        bodyFrame.style.backgroundImage = "url("+image+")";
    });
});
```


问:
overloaded method value createDirectStream with alternatives
My spark version is 1.6.2, And My kafka version is 0.10.1.0. And I want to send a custom object as the kafka value type and I try to push this custom object into the kafka topic. And use spark streaming to read the data. And I'm using Direct approach. The following is my code:

```<code>import com.xxxxx.kafka.{KafkaJsonDeserializer, KafkaObjectDecoder, pharmacyData}
import kafka.serializer.StringDecoder
import org.apache.spark.streaming.kafka.KafkaUtils
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.streaming.{Seconds, StreamingContext}

object sparkReadKafka {
  val sparkConf = new SparkConf().setAppName("SparkReadKafka")
  val sc = new SparkContext(sparkConf)
  val ssc = new StreamingContext(sc, Seconds(1))

  def main(args: Array[String]): Unit = {
    val kafkaParams = Map[String, Object] (
      "bootstrap.servers" -> "kafka.kafka-cluster-shared.non-prod-5-az-scus.prod.us.xxxxx.net:9092",
      //"key.deserializer" -> classOf[StringDeserializer],
      //"value.deserializer" -> classOf[KafkaJsonDeserializer],
      "group.id" -> "consumer-group-2",
      "auto.offset.reset" -> "earliest",
      "auto.commit.interval.ms" -> "1000",
      "enable.auto.commit" -> (false: java.lang.Boolean),
      "session.timeout.ms" -> "30000"
    )

    val topic = "hw_insights"

    val stream = KafkaUtils.createDirectStream[String, pharmacyData, StringDecoder, KafkaObjectDecoder](ssc, kafkaParams, Set(topic))
  }
}
</code>```

And the error I got is similar to this(I have to remove some part for security purpose):

Error:(29, 47) overloaded method value createDirectStream with alternatives:
    (jssc: org.apache.spark.streaming.api.java.JavaStreamingContext,keyClass: Class[String],valueClass: Class[com.xxxxxxx.kafka.pharmacyData],keyDecoderClass: Class[kafka.serializer.StringDecoder],valueDecoderClass: Class[com.xxxxxxx.kafka.KafkaObjectDecoder],kafkaParams: java.util.Map[String,String],topics: java.util.Set[String])org.apache.spark.streaming.api.java.JavaPairInputDStream[String,com.xxxxxxx.kafka.pharmacyData]
    (ssc: org.apache.spark.streaming.StreamingContext,kafkaParams: scala.collection.immutable.Map[String,String],topics: scala.collection.immutable.Set[String])(implicit evidence$19: scala.reflect.ClassTag[String], implicit evidence$20: scala.reflect.ClassTag[com.xxxxxxx.kafka.pharmacyData], implicit evidence$21: scala.reflect.ClassTag[kafka.serializer.StringDecoder], implicit evidence$22: scala.reflect.ClassTag[com.xxxxxxx.kafka.KafkaObjectDecoder])org.apache.spark.streaming.dstream.InputDStream[(String, com.xxxxxxx.kafka.pharmacyData)]
   cannot be applied to (org.apache.spark.streaming.StreamingContext, scala.collection.immutable.Map[String,Object], scala.collection.immutable.Set[String])
      val stream = KafkaUtils.createDirectStream[String, pharmacyData, StringDecoder, KafkaObjectDecoder](ssc, kafkaParams, Set(topic))
  And below is my customer decoder class:

```<code>import kafka.serializer.Decoder
import org.codehaus.jackson.map.ObjectMapper

class KafkaObjectDecoder extends Decoder[pharmacyData] {
  override def fromBytes(bytes: Array[Byte]): pharmacyData = {
    val mapper = new ObjectMapper()
    val pdata = mapper.readValue(bytes, classOf[pharmacyData])
    pdata
  }
}
</code>```

Can someone please help me with issues? Thannk you!

答:
The error is saying your parameters are incorrect

cannot be applied to (org.apache.spark.streaming.StreamingContext, scala.collection.immutable.Map[String,Object], scala.collection.immutable.Set[String])

The closest method it thinks you want is

(jssc: org.apache.spark.streaming.api.java.JavaStreamingContext,keyClass: Class[String],valueClass: Class[com.xxxxxxx.kafka.pharmacyData],keyDecoderClass: Class[kafka.serializer.StringDecoder],valueDecoderClass: Class[com.xxxxxxx.kafka.KafkaObjectDecoder],kafkaParams: java.util.Map[String,String],topics: java.util.Set[String])

Body:
My spark version is 1.6.2, And My kafka version is 0.10.1.0. And I want to send a custom object as the kafka value type and I try to push this custom object into the kafka topic. And use spark streaming to read the data. And I'm using Direct approach. The following is my code:

import com.xxxxx.kafka.{KafkaJsonDeserializer, KafkaObjectDecoder, pharmacyData}
import kafka.serializer.StringDecoder
import org.apache.spark.streaming.kafka.KafkaUtils
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.streaming.{Seconds, StreamingContext}

object sparkReadKafka {
  val sparkConf = new SparkConf().setAppName("SparkReadKafka")
  val sc = new SparkContext(sparkConf)
  val ssc = new StreamingContext(sc, Seconds(1))

  def main(args: Array[String]): Unit = {
    val kafkaParams = Map[String, Object] (
      "bootstrap.servers" -> "kafka.kafka-cluster-shared.non-prod-5-az-scus.prod.us.xxxxx.net:9092",
      //"key.deserializer" -> classOf[StringDeserializer],
      //"value.deserializer" -> classOf[KafkaJsonDeserializer],
      "group.id" -> "consumer-group-2",
      "auto.offset.reset" -> "earliest",
      "auto.commit.interval.ms" -> "1000",
      "enable.auto.commit" -> (false: java.lang.Boolean),
      "session.timeout.ms" -> "30000"
    )

    val topic = "hw_insights"

    val stream = KafkaUtils.createDirectStream[String, pharmacyData, StringDecoder, KafkaObjectDecoder](ssc, kafkaParams, Set(topic))
  }
}

And the error I got is similar to this(I have to remove some part for security purpose):

Error:(29, 47) overloaded method value createDirectStream with alternatives:
    (jssc: org.apache.spark.streaming.api.java.JavaStreamingContext,keyClass: Class[String],valueClass: Class[com.xxxxxxx.kafka.pharmacyData],keyDecoderClass: Class[kafka.serializer.StringDecoder],valueDecoderClass: Class[com.xxxxxxx.kafka.KafkaObjectDecoder],kafkaParams: java.util.Map[String,String],topics: java.util.Set[String])org.apache.spark.streaming.api.java.JavaPairInputDStream[String,com.xxxxxxx.kafka.pharmacyData]
    (ssc: org.apache.spark.streaming.StreamingContext,kafkaParams: scala.collection.immutable.Map[String,String],topics: scala.collection.immutable.Set[String])(implicit evidence$19: scala.reflect.ClassTag[String], implicit evidence$20: scala.reflect.ClassTag[com.xxxxxxx.kafka.pharmacyData], implicit evidence$21: scala.reflect.ClassTag[kafka.serializer.StringDecoder], implicit evidence$22: scala.reflect.ClassTag[com.xxxxxxx.kafka.KafkaObjectDecoder])org.apache.spark.streaming.dstream.InputDStream[(String, com.xxxxxxx.kafka.pharmacyData)]
   cannot be applied to (org.apache.spark.streaming.StreamingContext, scala.collection.immutable.Map[String,Object], scala.collection.immutable.Set[String])
      val stream = KafkaUtils.createDirectStream[String, pharmacyData, StringDecoder, KafkaObjectDecoder](ssc, kafkaParams, Set(topic))
  And below is my customer decoder class:

import kafka.serializer.Decoder
import org.codehaus.jackson.map.ObjectMapper

class KafkaObjectDecoder extends Decoder[pharmacyData] {
  override def fromBytes(bytes: Array[Byte]): pharmacyData = {
    val mapper = new ObjectMapper()
    val pdata = mapper.readValue(bytes, classOf[pharmacyData])
    pdata
  }
}

Can someone please help me with issues? Thannk you!


问:
Is their an inbuilt method directly available to search a gitlab repo through it's name using python-gitlab
I am using python-gitlab which is a python wrapper for the original Gitlab API. I am actually using it to create scripts to access and modify gitlab projects. I came across a constraint while working with it, which is to mention the project id as the parameter when searching for a project which beats the purpose of using it because then I have to check the project id again and again to query through the projects for which I need to open up gitlab on my browser.

So I created a work around for it by querying the list of projects under a user and then searching for the repo name from the list and then accessing the id to alter stuff:

```<code>projects = gl.projects.list()
for project in projects:
    #here "test" is the name of a dummy project that I am trying to query
    if project.name == "test":
        project_id = project.id
        print(project_id)

p = gl.projects.get(project_id)
print(p)
</code>```

So, I just wanted to know if there was an inbuilt method in the package itself which may take in the name of the project directly or this is the only way possible for what I am trying to achieve.

答:
This thing can be done using the following code using the same projects.get() method but requires both the user name and the project name: </p>

```<code>p = gl.projects.get('user_name/project_name')
</code>```

Body:
I am using python-gitlab which is a python wrapper for the original Gitlab API. I am actually using it to create scripts to access and modify gitlab projects. I came across a constraint while working with it, which is to mention the project id as the parameter when searching for a project which beats the purpose of using it because then I have to check the project id again and again to query through the projects for which I need to open up gitlab on my browser.

So I created a work around for it by querying the list of projects under a user and then searching for the repo name from the list and then accessing the id to alter stuff:

projects = gl.projects.list()
for project in projects:
    #here "test" is the name of a dummy project that I am trying to query
    if project.name == "test":
        project_id = project.id
        print(project_id)

p = gl.projects.get(project_id)
print(p)

So, I just wanted to know if there was an inbuilt method in the package itself which may take in the name of the project directly or this is the only way possible for what I am trying to achieve.

Body:
This thing can be done using the following code using the same projects.get() method but requires both the user name and the project name:

p = gl.projects.get('user_name/project_name')


问:
Microservice to Microservice calls, authorization from a queue message
Context: I'm creating a cloud platform to support multiple applications with SSO. I'm using Keycloak for authentication and Netflix Zuul for authorization (API Gateway) thru Keycloak Spring Security Adapter.

Each microservice expect an Authorization header, which contains a valid JWT, from which it will take the username (sub) to process the request. Each microservice-to-microservice call should go thru Netflix Zuul first, passing the Authorization header to maintain a stateless validation. That strategy allow to every microservice to know who is the user (sub) who is invoking the microservice indirectly.

Problem/Question 1: What happens if a microservice is invoked from a queue message? One idea that I had is to storage in the queue the information related to the message + userInfo, and, create a dedicated microservice to process that kind of messages, with that approach this special microservice should read the userInfo from the queue and process the message.

UPDATE 1: Per an email reply from another forum, storing the JWT in a queue isn't a good idea, since it could be mined easily.

Problem/Question 2: But, what happens if the previous special microservice wants to call another normal microservice which expect to receive a JWT in a header? Should this special microservice create by himself a JWT to impersonate the user and be able to call the regular microservices?

Another solution that I thought was to storage the original JWT in the queue, but, what happens if the queue calls to the special microservice later? Just after the JWT is not valid anymore (it expired) and the microservice called will reject the request?

Possible solutions: (Updated per João Angelo discussion, see below)

I should authenticate the requests from my users (Authorization code flow) and my services (Client credentials grant), both requests should contain user information in the payload. When the request it comes from the user, I need to validate that the payload user info match with the JWT claims. When the request comes from a service, I just need to trust in that service (as long as it is under my control).

I will appreciate very much your help. Thanks.

答:
As you said your microservices use JWT for authentication which always passes through a gateway, in this way you can actually use the concept of FEIGN CLIENT.
Feign as rest client example.</p>


问:
Assign std:wstring to VCL UnicodeString most effectively
I have a range of std::wstring objects that need to be displayed and hence stored in various VCL objects.

I have looked in the documentation for a VCL String Assign() function, preferably one that takes a count as input but cannot find it.

What I do now:

```<code>my_vcl_object->Caption = my_wstring_text.c_str() ;
</code>```

From what I can see in the documentation, the VCL String operator=() takes a reference to String as input.

Does this mean that currently:

a (temp) VCL String object is created using the wchar_t pointer during construction ?

And hence all characters are counted till the NULL character

And next the Caption String copies the content of the temp. String ?

Or is there an undocumented operator=() for String that takes a wchar_t pointer and hence avoids step 1 ?

And what about step 2.  Is there a VCL function I can use to use the wstring length() as input to avoid having to count the characters each time ?  So that Caption can simply copy the memory essentially.

答:
The Caption is a String, which maps to AnsiString in C++Builder 2007 and earlier, and to UnicodeString in C++Builder 2009 and later.

The = assignment operator takes a whole String as input. So yes, your 3 points of analysis are correct. In your example, a temp String gets constructed and copied from.

However, AnsiString and UnicodeString both have a constructor that accepts 2 parameters as input, a pointer to the character data and a length, so you can construct the temp String explicitly with more than 1 parameter, eg:

my_vcl_object->Caption = String(my_wstring_text.c_str(), my_wstring_text.length());
```

Body:
I have a range of std::wstring objects that need to be displayed and hence stored in various VCL objects.

I have looked in the documentation for a VCL String Assign() function, preferably one that takes a count as input but cannot find it.

What I do now:

my_vcl_object->Caption = my_wstring_text.c_str() ;

From what I can see in the documentation, the VCL String operator=() takes a reference to String as input.

Does this mean that currently:

a (temp) VCL String object is created using the wchar_t pointer during construction ?

And hence all characters are counted till the NULL character

And next the Caption String copies the content of the temp. String ?

Or is there an undocumented operator=() for String that takes a wchar_t pointer and hence avoids step 1 ?

And what about step 2.  Is there a VCL function I can use to use the wstring length() as input to avoid having to count the characters each time ?  So that Caption can simply copy the memory essentially.


问:
None type object has no attribute delete()

getting error 'NoneType' object has no attribute 'delete'

```<code>class LogoutViewSet(viewsets.ViewSet):

    def (self,request):
        user_token=request.auth
        refresh_token=RefreshToken.objects.filter(access_token=user_token)
        refresh_token.delete()
        user_token.delete()
        return Response({'done':True})
</code>```

答:
Since request.auth is not a QuerySet you cannot use delete() method on it.

```<code>class LogoutViewSet(viewsets.ViewSet):

def (self,request):
    user_token=request.auth
    refresh_token=RefreshToken.objects.filter(access_token=user_token)
    refresh_token.delete()
    user_token = None
    return Response({'done':True})
</code>```

Body:
getting error 'NoneType' object has no attribute 'delete'

class LogoutViewSet(viewsets.ViewSet):

    def (self,request):
        user_token=request.auth
        refresh_token=RefreshToken.objects.filter(access_token=user_token)
        refresh_token.delete()
        user_token.delete()
        return Response({'done':True})

Body:
Since request.auth is not a QuerySet you cannot use delete() method on it.

class LogoutViewSet(viewsets.ViewSet):

def (self,request):
    user_token=request.auth
    refresh_token=RefreshToken.objects.filter(access_token=user_token)
    refresh_token.delete()
    user_token = None
    return Response({'done':True})


问:
Character references (Entities) to UTF Characters
I am facing a character reference problem. My CKEditor converts the special characters to corresponding Entities (in CKEditor I can't change the settings.) And this looks like as under.

```<code>"Ö" => "Ö"
"ö" => "ö"
"Ä" => "Ä"
"ä" => "ä"
"Ü" => "Ü"
"ü" => "ü"
</code>```

Now In my Java, PHP or Coldfusion script I want again to replace all the Entities with special characters.
Is there any method available for such replacements?

答: For PHP, try html_entity_decode

Body:
I am facing a character reference problem. My CKEditor converts the special characters to corresponding Entities (in CKEditor I can't change the settings.) And this looks like as under.

"Ö" => "Ö"
"ö" => "ö"
"Ä" => "Ä"
"ä" => "ä"
"Ü" => "Ü"
"ü" => "ü"

Now In my Java, PHP or Coldfusion script I want again to replace all the Entities with special characters.
Is there any method available for such replacements?

Body: For PHP, try html_entity_decode


问:
Apply a SUM function on the product of two fields in InfluxDB
I have the following query:

```<code>SELECT sum("field1" * "field2") FROM "my_db"."autogen"."data" GROUP BY time(1d) FILL(null)
</code>```

In short I would like to perform the operation sum on the product of two fields field and field2.

The above query returns an error: expected field argument in sum().

Is this kind of thing at all possible in InfluxDB?

答:
Here's a idea: try Sub Query

Note:I don't have editor right now so it might give error too

```<code>SELECT SUM(Multiplication) FROM
    (SELECT  "field1" * "field2" as Multiplication, time(1d) as Days FROM
        "my_db"."autogen"."data" GROUP BY time(1d) FILL(null)
    ) GROUP BY Days
</code>```

Body:
I have the following query:

SELECT sum("field1" * "field2") FROM "my_db"."autogen"."data" GROUP BY time(1d) FILL(null)

In short I would like to perform the operation sum on the product of two fields field and field2.

The above query returns an error: expected field argument in sum().

Is this kind of thing at all possible in InfluxDB?

Body:
Here's a idea: try Sub Query

Note:I don't have editor right now so it might give error too

SELECT SUM(Multiplication) FROM
    (SELECT  "field1" * "field2" as Multiplication, time(1d) as Days FROM
        "my_db"."autogen"."data" GROUP BY time(1d) FILL(null)
    ) GROUP BY Days


问:
ETS from fable package in R (can I do it with out tsibble)
I am trying to use ETS function from fable package (following this tutorial link). Ideally I would like to do it without using tsibble functionality. In particular I am trying to generate forecast:

```<code>library(tsibble)
library(fable)
library(tidyverse)

fit <- ETS(1:63)

forecast(fit, h =2)
</code>```

returns error:

```<code>Error in UseMethod("forecast") :
  no applicable method for 'forecast' applied to an object of class "c('mdl_defn', 'R6')"
</code>```

another try

```<code>summary(fit)
</code>```

also returns error

```<code>Error in object[[i]] : wrong arguments for subsetting an environment
</code>```

So can I used it without full tsibble functionality? It was so simple with ARIMA from forecast package.
If it is not possible without tsibble what would be the quickest way to cast it as tsibble data?

答:
You need to use tsibbles, but it is very easy to do so.

library(tsibble)
library(fable)
library(tidyverse)

ts(1:63) %>%
  as_tsibble() %>%
  model(ETS(value)) %>%
  forecast(h=2)

#> # A fable: 2 x 4 [1]
#> # Key:     .model [1]
#>   .model     index value .distribution
#>   <chr>      <dbl> <dbl> <dist>
#> 1 ETS(value)    64    64 N(64, 0)
#> 2 ETS(value)    65    65 N(65, 0)
```

Created on 2020-02-19 by the reprex package (v0.3.0)

Body:
I am trying to use ETS function from fable package (following this tutorial link). Ideally I would like to do it without using tsibble functionality. In particular I am trying to generate forecast:

library(tsibble)
library(fable)
library(tidyverse)

fit <- ETS(1:63)

forecast(fit, h =2)

returns error:

Error in UseMethod("forecast") :
  no applicable method for 'forecast' applied to an object of class "c('mdl_defn', 'R6')"

another try

summary(fit)

also returns error

Error in object[[i]] : wrong arguments for subsetting an environment

So can I used it without full tsibble functionality? It was so simple with ARIMA from forecast package.
If it is not possible without tsibble what would be the quickest way to cast it as tsibble data?

Body:
You need to use tsibbles, but it is very easy to do so.

library(tsibble)
library(fable)
library(tidyverse)

ts(1:63) %>%
  as_tsibble() %>%
  model(ETS(value)) %>%
  forecast(h=2)

#> # A fable: 2 x 4 [1]
#> # Key:     .model [1]
#>   .model     index value .distribution
#>   <chr>      <dbl> <dbl> <dist>
#> 1 ETS(value)    64    64 N(64, 0)
#> 2 ETS(value)    65    65 N(65, 0)

Created on 2020-02-19 by the reprex package (v0.3.0)


问:
How shared_ptr detects if it has to call delete[] or delete
I am curious to know, how shared_ptr class decides whether it has to call delete or delete[] for the below statements?

a. boost::shared_ptr <char> ptr(new char);

b. boost::shared_ptr <char []> ptr(new char[100]);

答:
It is done via template specialization. Here is the simple demonstration.

```<code>#include <iostream>
#include <type_traits>

template<typename T>
struct foo
{
    foo( T* d ) : m_data{ d } {  }
    ~foo() {
        if ( m_data )
        std::cout << "delete called." << std::endl;
    }

private:
    T* m_data {};
};

template<typename T>
struct foo<T[]>
{
    foo( T* d ) : m_data { d } { }
    ~foo() {
        if ( m_data )
            delete[] m_data;
        std::cout << "delete[] called." << std::endl;
    }
private:
    T* m_data {};
};

int main()
{
    foo<char> inst_1 { new char };
    foo<char []> inst_2 { new char[ 100 ] { 'a' } };
}
</code>```

online example

For T[] types, struct foo<T[]> instantiated, so compile-time polymorphism is done via template specialization and smart_ptr handles deallocation of both array and normal types with the help of this feature.

Body:
It is done via template specialization. Here is the simple demonstration.

#include <iostream>
#include <type_traits>

template<typename T>
struct foo
{
    foo( T* d ) : m_data{ d } {  }
    ~foo() {
        if ( m_data )
        std::cout << "delete called." << std::endl;
    }

private:
    T* m_data {};
};

template<typename T>
struct foo<T[]>
{
    foo( T* d ) : m_data { d } { }
    ~foo() {
        if ( m_data )
            delete[] m_data;
        std::cout << "delete[] called." << std::endl;
    }
private:
    T* m_data {};
};

int main()
{
    foo<char> inst_1 { new char };
    foo<char []> inst_2 { new char[ 100 ] { 'a' } };
}

online example

For T[] types, struct foo<T[]> instantiated, so compile-time polymorphism is done via template specialization and smart_ptr handles deallocation of both array and normal types with the help of this feature.


问:
is it possible to make certain part of the JsonFormat datetime optional?
I have a field which is defined with the seconds part, (i.e.: "ss") as follows

```<code>@JsonProperty("date")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss z")
private Date date;
</code>```

Is it possible to make the seconds part optional? so that both the following date String will work:

"2020-02-13T16:02:11 EST" will be parsed to "Thu Feb 13 16:02:11 EST 2020"

"2020-02-13T16:02 EST" will be parsed to "Thu Feb 13 16:02 EST 2020"

I am thinking about somethinglike (this does not work though...):
"yyyy-MM-dd'T'HH:mm[:ss] z"

thanks.

答:
Since the SimpleDateFormat class is notoriously troublesome and long outdated and also not thread-safe, I thought I’d show you how to solve your task with java.time, the modern Java date and time API. For now I am assuming that you cannot change the type of your date field, it needs to be Date, and also that you cannot change the format/s. I rewrote the class from your own answer in this way:

```<code>public class DateDeserializer extends StdDeserializer<Date> {

    private static final DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm[:ss] z", Locale.ENGLISH);

    public DateDeserializer() {
        this(null);
    }

    public DateDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String dateString = p.getText();
        if (dateString.isEmpty()) {
            //handle empty strings however you want,
            //but I am setting the Date objects null
            return null;
        }

        Instant parsedInstant = formatter.parse(dateString, Instant::from);
        return Date.from(parsedInstant);
    }
}
</code>```

In the format pattern string I am using square brackets, [], around the optional seconds of the minute. DateTimeFormatter is thread-safe (opposite SimpleDateFormat), so it is safe to have just one static instance even if used from several threads. DateTimeFormatter.parse() throws a runtime exception (unchecked exception) if it cannot parse the string, so I didn’t find any reason to make this explicit in our own code.

If you could make any of the following changes, it would improve matters still:

Educate the source of your date-time strings to use ISO 8601 format, for example 2020-02-13T16:02:11-05:00. The format they are using now is a peculiar mix of ISO 8601 and non-ISO, so you and they are really neither getting the advantages of the standard nor the full potential advantages of a more human-readable format. Formatters for ISO 8601 are built into java.time, so using the standard would save us from defining any formatter ourselves. And seconds are optional in ISO 8601, so they could still send strings with and without seconds.

Throw away the Date class. It is poorly designed and long outdated. Use Instant or another class from java.time and save the conversion that I am doing in the code.

Links

Oracle tutorial: Date Time explaining how to use java.time.

Wikipedia article: ISO 8601

Body:
I have a field which is defined with the seconds part, (i.e.: "ss") as follows

@JsonProperty("date")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss z")
private Date date;

Is it possible to make the seconds part optional? so that both the following date String will work:

"2020-02-13T16:02:11 EST" will be parsed to "Thu Feb 13 16:02:11 EST 2020"

"2020-02-13T16:02 EST" will be parsed to "Thu Feb 13 16:02 EST 2020"

I am thinking about somethinglike (this does not work though...):
"yyyy-MM-dd'T'HH:mm[:ss] z"

thanks.

Body:
Since the SimpleDateFormat class is notoriously troublesome and long outdated and also not thread-safe, I thought I’d show you how to solve your task with java.time, the modern Java date and time API. For now I am assuming that you cannot change the type of your date field, it needs to be Date, and also that you cannot change the format/s. I rewrote the class from your own answer in this way:

public class DateDeserializer extends StdDeserializer<Date> {

    private static final DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm[:ss] z", Locale.ENGLISH);

    public DateDeserializer() {
        this(null);
    }

    public DateDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String dateString = p.getText();
        if (dateString.isEmpty()) {
            //handle empty strings however you want,
            //but I am setting the Date objects null
            return null;
        }

        Instant parsedInstant = formatter.parse(dateString, Instant::from);
        return Date.from(parsedInstant);
    }
}

In the format pattern string I am using square brackets, [], around the optional seconds of the minute. DateTimeFormatter is thread-safe (opposite SimpleDateFormat), so it is safe to have just one static instance even if used from several threads. DateTimeFormatter.parse() throws a runtime exception (unchecked exception) if it cannot parse the string, so I didn’t find any reason to make this explicit in our own code.

If you could make any of the following changes, it would improve matters still:

Educate the source of your date-time strings to use ISO 8601 format, for example 2020-02-13T16:02:11-05:00. The format they are using now is a peculiar mix of ISO 8601 and non-ISO, so you and they are really neither getting the advantages of the standard nor the full potential advantages of a more human-readable format. Formatters for ISO 8601 are built into java.time, so using the standard would save us from defining any formatter ourselves. And seconds are optional in ISO 8601, so they could still send strings with and without seconds.

Throw away the Date class. It is poorly designed and long outdated. Use Instant or another class from java.time and save the conversion that I am doing in the code.

Links

Oracle tutorial: Date Time explaining how to use java.time.

Wikipedia article: ISO 8601


问:
How to clear all app data from root directory for logout purpose?
Whenever user is logged in their account, some database and shared preference store some data according to logged user, But after the logout and re-login previous data is still appear.

So, I want to delete this for preventing user privacy.

```<code>Logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                mAuth.signOut();
                //deletappData();
                Intent loginIntent=new Intent(MainActivity.this, LoginActivity.class);
        loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(loginIntent);
        finish();
            }
        });
</code>```

答:
```<code>    // To Clear Your Shared Preferences :

    SharedPreferences preferences = getSharedPreferences("loginPrefs",Context.MODE_PRIVATE);
                 SharedPreferences.Editor editor = preferences.edit();
                 editor.clear();
                 editor.commit();

// Clear SQLite Database :

public class MyApplication extends Application {
    protected static final String           LOG_TAG = "MyApplication";

    private static DatabaseAdapter          mDb;

    private static MyApplication    mInstance;

    /**
     * @return The instance of the database adapter.
     */
    public static DatabaseAdapter getDatabaseAdapter() {
        return mDb;
    }

    /**
     * @return The instance of the application.
     */
    public static Context getInstance() {
        return mInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.w(LOG_TAG, "Application::onCreate");
        mInstance = this;
        mDb = new DatabaseAdapter();
    }

    @Override
    public void onTerminate() {
        // Close the internal db
        getDatabaseAdapter().close(DatabaseAdapter.INTERNAL);

        Log.e(LOG_TAG, "::onTerminate::");
        super.onTerminate();
    }
}
</code>```

Body:
Whenever user is logged in their account, some database and shared preference store some data according to logged user, But after the logout and re-login previous data is still appear.

So, I want to delete this for preventing user privacy.

Logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                mAuth.signOut();
                //deletappData();
                Intent loginIntent=new Intent(MainActivity.this, LoginActivity.class);
        loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(loginIntent);
        finish();
            }
        });


问:
Which is more performant at scale, `className` or `ref`?
I have a lot of elements on the screen, so I need a lot of unique identifiers for them. I can do it using className="uniqueItem" or ref={ref => this.uniqueItem = ref} so which is more performant when there are many components re-rendering often?

答:
Ref would be fine as it would also give you high reusability which in the case of className would be less.

But speaking of performance, className will be more performant.