问:
Powershell Credentials Request Window Size
Powershell Noob here.

I have a basic Powershell script that requests user's credentials and then starts MMC programs for remote administration (example: dsa.msc). No issues with the script.

However, I am not happy with the size of the "Windows Powershell Credentials Request" window. I am using Get-Credential "$env:USERDNSDOMAIN\" but our domain name is pretty long.

What I would like:

(Preferred) Have the the domain name gathered in the script ($env:USERDNSDOMAIN) and the when the user is prompted for credentials; the username field will be empty and the user will only need to type their AD username. OR

Have the credentials be collected WITHIN the powershell window so there is enough room

Any assistance is appreciated. Thank you in advance.

答:
You cannot change the default modal dialog/UI in Windows. If you want this control, you can write your own Winfomr/WPF GUI. deploy that for users to execute.

If you have not done this, use this free tool (though WinForm only - for now)...

Online Powershell Form Designer

...for your first effort at GUI design, but read up on GUI design (Winform and WPF) to know what this is about and the other steps you are going to need to do, to get it to do anything.

Youtube -
'PowerShell gui design'

As for your two bullet points. You are halfway there. Just do this:

```<code>Get-Credential "$env:USERDNSDOMAIN\$env:USERNAME"
</code>```

Body:
You cannot change the default modal dialog/UI in Windows. If you want this control, you can write your own Winfomr/WPF GUI. deploy that for users to execute.

If you have not done this, use this free tool (though WinForm only - for now)...

Online Powershell Form Designer

...for your first effort at GUI design, but read up on GUI design (Winform and WPF) to know what this is about and the other steps you are going to need to do, to get it to do anything.

Youtube -
'PowerShell gui design'

As for your two bullet points. You are halfway there. Just do this:

Get-Credential "$env:USERDNSDOMAIN\$env:USERNAME"


来源: stackexchange

问:
Both slices change if one is changed
For some reason in Go, both slices change if I change either of them

```<code>package main

import (
    "fmt"
    "sort"
    )
func deleteAr(s []string, index int) []string{
    return append(s[:index], s[index+1:]...)
}

func main() {

var letters =[] string {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}
fmt.Println("original")

fmt.Println(letters)
var fletters =[] string {}

letters= deleteAr(letters, sort.StringSlice(letters).Search("E"))

fletters=letters
fmt.Println("after assigning but nothing changed in either slices")

fmt.Println(letters)
fmt.Println(fletters)

fletters = deleteAr(fletters , sort.StringSlice(fletters).Search("A"))
fletters = append(fletters , "b")
fmt.Println("after assigning deleting A and appending b to only fletters, but why letters changed too?")

fmt.Println(letters)
fmt.Println(fletters)

}
</code>```

result:

original

[A B C D E F G H I J K L M N O P Q R S T U V W X Y Z]

after assigning but nothing changed in either slices

[A B C D F G H I J K L M N O P Q R S T U V W X Y Z]

[A B C D F G H I J K L M N O P Q R S T U V W X Y Z]

after assigning deleting A and appending b to only fletters, but why letters changed too?

[B C D F G H I J K L M N O P Q R S T U V W X Y Z b]

[B C D F G H I J K L M N O P Q R S T U V W X Y Z b]

答:
A slice is a view on an array. In your code, letters and fletters both refer to the same underlying array, so changes made to one is also visible to the other.

A slice will create a new array and copy the contents of the old one into the new one only as a result of append operation, and only if the capacity of the underlying array is not sufficient to hold the new elements. Your operations never require a change in the underlying array capacity, so the slices all point to the same underlying array.

ContentLicense: CC BY-SA 4.0

Title: Both slices change if one is changed

Body:
For some reason in Go, both slices change if I change either of them

package main

import (
    "fmt"
    "sort"
    )
func deleteAr(s []string, index int) []string{
    return append(s[:index], s[index+1:]...)
}

func main() {

var letters =[] string {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}
fmt.Println("original")

fmt.Println(letters)
var fletters =[] string {}

letters= deleteAr(letters, sort.StringSlice(letters).Search("E"))

fletters=letters
fmt.Println("after assigning but nothing changed in either slices")

fmt.Println(letters)
fmt.Println(fletters)

fletters = deleteAr(fletters , sort.StringSlice(fletters).Search("A"))
fletters = append(fletters , "b")
fmt.Println("after assigning deleting A and appending b to only fletters, but why letters changed too?")

fmt.Println(letters)
fmt.Println(fletters)

}

result:

original

[A B C D E F G H I J K L M N O P Q R S T U V W X Y Z]

after assigning but nothing changed in either slices

[A B C D F G H I J K L M N O P Q R S T U V W X Y Z]

[A B C D F G H I J K L M N O P Q R S T U V W X Y Z]

after assigning deleting A and appending b to only fletters, but why letters changed too?

[B C D F G H I J K L M N O P Q R S T U V W X Y Z b]

[B C D F G H I J K L M N O P Q R S T U V W X Y Z b]


问:
trouble with python manage.py migrate -> No module named psycopg2
I am having some trouble with migrating Django using postgresql.

This is my first time with Django, and I am just following the tutorial.

As suggested on the Django website, I have created a virtualenv to run the Django project.

Next, I created a postgresql database with these settings:

In settings.py I have set these values for the database:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'django_tutorial',
        'USER': 'johan',
        'PASSWORD': '1234',
    }
}
</code>```

When installing psycopg2 with apt-get I get this message:

```<code>(venv)johan@johan-pc:~/sdp/django_tutorial/venv/django_tutorial$ sudo apt-get install python-psycopg2
Reading package lists... Done
Building dependency tree
Reading state information... Done
python-psycopg2 is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 95 not upgraded.
</code>```

As far as I can tell this would mean that psycopg2 is installed.

When running

```<code>$python manage.py migrate
</code>```

I get the following error message:

```<code>django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2
</code>```

If needed for the answer I could provide the entire stack trace.

Could someone explain what I could do to solve this? I have also looked on Google for a solution with no luck.

答:
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
I was also facing a similar problem when I tried to run the migration with Postgresql database. The below step worked for me fine.

Activate your Virtual Environment and run the following command

```<code>pip install psycopg2-binary
</code>```

Now try running python manage.py migrate

ContentLicense: CC BY-SA 3.0

Body:
I am having some trouble with migrating Django using postgresql.

This is my first time with Django, and I am just following the tutorial.

As suggested on the Django website, I have created a virtualenv to run the Django project.

Next, I created a postgresql database with these settings:

In settings.py I have set these values for the database:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'django_tutorial',
        'USER': 'johan',
        'PASSWORD': '1234',
    }
}

When installing psycopg2 with apt-get I get this message:

(venv)johan@johan-pc:~/sdp/django_tutorial/venv/django_tutorial$ sudo apt-get install python-psycopg2
Reading package lists... Done
Building dependency tree
Reading state information... Done
python-psycopg2 is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 95 not upgraded.

As far as I can tell this would mean that psycopg2 is installed.

When running

$python manage.py migrate

I get the following error message:

django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2

If needed for the answer I could provide the entire stack trace.

Could someone explain what I could do to solve this? I have also looked on Google for a solution with no luck.

Body:
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
I was also facing a similar problem when I tried to run the migration with Postgresql database. The below step worked for me fine.

Activate your Virtual Environment and run the following command

pip install psycopg2-binary

Now try running python manage.py migrate


问:
Is it possible to run multiple web instance in the same AWS EC2?
Background

I have followed this tutorial https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-cli-tutorial-ec2.html, composed a docker compose file, made a website A (compose of 4 containers) up and run serving 1 of my client.

However, now I have another client which I need to host another web site website B using similar strategies as above.

Here is the current running service of ECS / EC2

and here are the containers up and running, serving website A now

Questions & concerns

The website A is now situated as 1 of a service in the EC2 under my only cluster, can I use the same EC2 instance and run website B (as another service of the EC2)?

If so, how are the ports / inbound / outbound traffic being managed? Now website A already occupies port 80, 443, 27017 and 3002 of the EC2 instance for inbound traffic, if website B's containers also run in the same EC2 instances, can I still use port 80, 443, 27017 and 3002 for website B. I have read the docs of ALB (Amazon Load Balancer), seems it can fulfill the requirement, am I at the right track?

And the domain name, through route 53, I have registered a domain www.websiteA.com to serve the 1st website, I have also registered another www.websiteB.com preparing to serve website B, in my case, I guess I need to configure the new domain B pointing to the same EC2 IP?

During my deployment of website B, I do not want to affect the availability of website A, can it be maintained during the process of deploying website B's containers?

I want to clear all the concepts before kick-starting to deploy the website B, appreciate for any help, thank you

Follow-up actions

I come up decided to use AWS application load balancer to solve my issue, and have the following configurations setup.

I first look into load balancer

And configured as follows

I setup a load balancer which listens for requests using HTTP protocol with incoming port 80, whenever there are users access the web server (i.e.: the frontend container), listener will forward that request to the target group (i.e.: http-port-80-access)

And here is the target group (http-port-80-access) which contains a registered target (currently my ec2 instance running the containers), the host port of the container is 32849 which in turn made used by the associated load balancer (web-access-load-balancer) for dynamic port mapping.

I have also configured 1 more rule on top of the default rule, whenever user access url of websiteA, load balancer will forward the request to the target group (http-port-80-access).

All things set, and the healthy test also passed. I then used the following ecs-cli compose service up command to wire up the load balancer with the service

ecs-cli compose --file ./docker-compose-aws-prod.yml --cluster my-ecs-cluster-name --ecs-profile my-ecs-profile --cluster-config my-cluster --project-name my-project --ecs-params ./ecs-params.yml service up --target-group-arn arn:aws:elasticloadbalancing:us-east-2:xxxxxxxxx:targetgroup/http-port-80-access/xxxxxxxx --container-name frontend --container-port 80
```

where frontend is the service name of the frontend container of website A

However, turn out when I access www.websiteA.com through browser, nothing but ERR_CONNECTION_REFUSED, accessing www.websiteA.com:32849 did accessible, but is not what I desired.

I am wondering which part I configured wrongly

答: Run website B on different ports.  To allow end users to interact with website B without specify port numbers use a reverse-proxy.  See AWS CloudFront.</p>

Body:
Background

I have followed this tutorial https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-cli-tutorial-ec2.html, composed a docker compose file, made a website A (compose of 4 containers) up and run serving 1 of my client.

However, now I have another client which I need to host another web site website B using similar strategies as above.

Here is the current running service of ECS / EC2

and here are the containers up and running, serving website A now

Questions & concerns

The website A is now situated as 1 of a service in the EC2 under my only cluster, can I use the same EC2 instance and run website B (as another service of the EC2)?

If so, how are the ports / inbound / outbound traffic being managed? Now website A already occupies port 80, 443, 27017 and 3002 of the EC2 instance for inbound traffic, if website B's containers also run in the same EC2 instances, can I still use port 80, 443, 27017 and 3002 for website B. I have read the docs of ALB (Amazon Load Balancer), seems it can fulfill the requirement, am I at the right track?

And the domain name, through route 53, I have registered a domain www.websiteA.com to serve the 1st website, I have also registered another www.websiteB.com preparing to serve website B, in my case, I guess I need to configure the new domain B pointing to the same EC2 IP?

During my deployment of website B, I do not want to affect the availability of website A, can it be maintained during the process of deploying website B's containers?

I want to clear all the concepts before kick-starting to deploy the website B, appreciate for any help, thank you

Follow-up actions

I come up decided to use AWS application load balancer to solve my issue, and have the following configurations setup.

I first look into load balancer

And configured as follows

I setup a load balancer which listens for requests using HTTP protocol with incoming port 80, whenever there are users access the web server (i.e.: the frontend container), listener will forward that request to the target group (i.e.: http-port-80-access)

And here is the target group (http-port-80-access) which contains a registered target (currently my ec2 instance running the containers), the host port of the container is 32849 which in turn made used by the associated load balancer (web-access-load-balancer) for dynamic port mapping.

I have also configured 1 more rule on top of the default rule, whenever user access url of websiteA, load balancer will forward the request to the target group (http-port-80-access).

All things set, and the healthy test also passed. I then used the following ecs-cli compose service up command to wire up the load balancer with the service

ecs-cli compose --file ./docker-compose-aws-prod.yml --cluster my-ecs-cluster-name --ecs-profile my-ecs-profile --cluster-config my-cluster --project-name my-project --ecs-params ./ecs-params.yml service up --target-group-arn arn:aws:elasticloadbalancing:us-east-2:xxxxxxxxx:targetgroup/http-port-80-access/xxxxxxxx --container-name frontend --container-port 80

where frontend is the service name of the frontend container of website A

However, turn out when I access www.websiteA.com through browser, nothing but ERR_CONNECTION_REFUSED, accessing www.websiteA.com:32849 did accessible, but is not what I desired.

I am wondering which part I configured wrongly


问:
How can I turn this jquery into a function?
I would like to turn the below jquery code into a function so i could add links to the list and not have to touch the jquery. I'm assuming I will have to put the image name into the href> tag somewhere.

html code

```<code><img id="storyimg" src="1.png" alt="img" />
<ul class="sb_menu">
    <li><a href="linkpage.htm" class="newslink1">Link 1</a></li>
    <li><a href="linkpage.htm" class="newslink2">Link 2</a></li>
    <li><a href="linkpage.htm" class="newslink3">Link 3</a></li>
</ul>
</code>```

jquery

```<code>$('a.newslink1').bind('mouseover', function() {
    $('img#storyimg').attr("src", "1.png");
});
$('a.newslink2').bind('mouseover', function() {
    $('img#storyimg').attr("src", "2.png");
});
$('a.newslink3').bind('mouseover', function() {
    $('img#storyimg').attr("src", "3.png");
});
</code>```

答:
Change your HTML markup and put the desired image in a data attribute, and change your class to a generic newslink:

```<code><img id="storyimg" src="1.png" alt="img" />
<ul class="sb_menu">
    <li><a href="linkpage.htm" class="newslink" data-img="1.png">Link 1</a></li>
    <li><a href="linkpage.htm" class="newslink" data-img="2.png">Link 2</a></li>
    <li><a href="linkpage.htm" class="newslink" data-img="3.png">Link 3</a></li>
</ul>
</code>```

Then do a generic event using that data attribute:

```<code>$('a.newslink').bind('mouseover', function(){
    $('img#storyimg').attr("src", $(this).data('img'));
});
</code>```

Body:
I would like to turn the below jquery code into a function so i could add links to the list and not have to touch the jquery. I'm assuming I will have to put the image name into the  tag somewhere.

html code

Link 1

Link 2

Link 3

jquery

$('a.newslink1').bind('mouseover', function() {
    $('img#storyimg').attr("src", "1.png");
});
$('a.newslink2').bind('mouseover', function() {
    $('img#storyimg').attr("src", "2.png");
});
$('a.newslink3').bind('mouseover', function() {
    $('img#storyimg').attr("src", "3.png");
});

Body:
Change your HTML markup and put the desired image in a data attribute, and change your class to a generic newslink:

<img id="storyimg" src="1.png" alt="img" />
<ul class="sb_menu">
    <li><a href="linkpage.htm" class="newslink" data-img="1.png">Link 1</a></li>
    <li><a href="linkpage.htm" class="newslink" data-img="2.png">Link 2</a></li>
    <li><a href="linkpage.htm" class="newslink" data-img="3.png">Link 3</a></li>
</ul>

Then do a generic event using that data attribute:

$('a.newslink').bind('mouseover', function(){
    $('img#storyimg').attr("src", $(this).data('img'));
});


问:
using xamarin forms with IServiceProvider
I was looking into "Dependency Injection" on xamarin forms and found some concepts that use something like ContainerBuilder. The solutions found online such as this, talk about how you can have DI setup and inject them into your view models. However, personally, I didn't find this or the whole concept of view models and binding very tidy for several reasons. I would rather create services that can be reused by the business logic, which seems to make the code a lot cleaner. I felt that implementing an IServiceProvider would result in a much cleaner implementation. I was planning on implementing a service provider something like this:

```<code>IServiceProvider Provider = new ServiceCollection()
                            .AddSingleton<OtherClass>()
                            .AddSingleton<MyClass>()
                            .BuildServiceProvider();
</code>```

Firstly, I am not sure why there are no xamarin examples of these. So, I am not sure if there is anything wrong with going towards this direction. I have looked into ServiceCollection class. The package it is from, Microsoft.Extensions.DependencyInjection, doesn't have "aspnetcore" in its name. It, however, has its owner as "aspnet". I am not entirely sure if ServiceCollection is only meant for web applications or it would make sense to use it for mobile apps.

Is it safe to use IServiceProvider with ServiceCollection as long as I use all singletons? is there any concern (in terms of performance or ram) I am missing?

Update

After the comments from Nkosi, I have taken another look at the link and noticed a couple of things:

The documentation link is dated around the same time Microsoft.Extensions.DependencyInjection was still in beta

All points in the list under "several advantages to using a dependency injection container" in the documentation also apply to DependencyInjection as far as I can see.

Autofac process seems to revolve around ViewModels which I am trying to avoid using.

Update 2

I managed to get DI directly into the behind code of pages with the help of a navigation function something like this:

```<code>public static async Task<TPage> NavigateAsync<TPage>()
    where TPage : Page
{
    var scope = Provider.CreateScope();
    var scopeProvider = scope.ServiceProvider;
    var page = scopeProvider.GetService<TPage>();
    if (navigation != null) await navigation.PushAsync(page);
    return page;
}
</code>```

答:
This implementation uses Splat and some helper/wrapper classes to conveniently access the container.

The way how the services are registered is a bit verbose but it could cover all uses cases I have encountered so far; and the life cycle can be changed quite easily as well, e.g. switching to a lazy creation of a service.

Simply use the ServiceProvider class to retrieve any instances from the IoC container anywhere in your code.

Registering of your Services

```<code>public partial class App : Application
{
    public App()
    {
        InitializeComponent();
        SetupBootstrapper(Locator.CurrentMutable);
        MainPage = new MainPage();
    }

    private void SetupBootstrapper(IMutableDependencyResolver resolver)
    {
        resolver.RegisterConstant(new Service(), typeof(IService));
        resolver.RegisterLazySingleton(() => new LazyService(), typeof(ILazyService));
        resolver.RegisterLazySingleton(() => new LazyServiceWithDI(
            ServiceProvider.Get<IService>()), typeof(ILazyServiceWithDI));
        // and so on ....
    }
</code>```

Usage of ServiceProvider

```<code>// get a new service instance with every call
var brandNewService = ServiceProvider.Get<IService>();

// get a deferred created singleton
var sameOldService = ServiceProvider.Get<ILazyService>();

// get a service which uses DI in its contructor
var another service = ServiceProvider.Get<ILazyServiceWithDI>();
</code>```

Implementation of ServiceProvider

```<code>public static class ServiceProvider
{
    public static T Get<T>(string contract = null)
    {
        T service = Locator.Current.GetService<T>(contract);
        if (service == null) throw new Exception($"IoC returned null for type '{typeof(T).Name}'.");
        return service;
    }

    public static IEnumerable<T> GetAll<T>(string contract = null)
    {
        bool IsEmpty(IEnumerable<T> collection)
        {
            return collection is null || !collection.Any();
        }

        IEnumerable<T> services = Locator.Current.GetServices<T>(contract).ToList();
        if (IsEmpty(services)) throw new Exception($"IoC returned null or empty collection for type '{typeof(T).Name}'.");

        return services;
    }
}
</code>```

Here is my csproj file. Nothing special, the only nuget package I added was Spat

Shared Project csproj

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <ProduceReferenceAssembly>true</ProduceReferenceAssembly>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DebugType>portable</DebugType>
    <DebugSymbols>true</DebugSymbols>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Splat" Version="9.3.11" />
    <PackageReference Include="Xamarin.Forms" Version="4.3.0.908675" />
    <PackageReference Include="Xamarin.Essentials" Version="1.3.1" />
  </ItemGroup>
</Project>
</code>```

Body:
I was looking into "Dependency Injection" on xamarin forms and found some concepts that use something like ContainerBuilder. The solutions found online such as this, talk about how you can have DI setup and inject them into your view models. However, personally, I didn't find this or the whole concept of view models and binding very tidy for several reasons. I would rather create services that can be reused by the business logic, which seems to make the code a lot cleaner. I felt that implementing an IServiceProvider would result in a much cleaner implementation. I was planning on implementing a service provider something like this:

IServiceProvider Provider = new ServiceCollection()
                            .AddSingleton<OtherClass>()
                            .AddSingleton<MyClass>()
                            .BuildServiceProvider();

Firstly, I am not sure why there are no xamarin examples of these. So, I am not sure if there is anything wrong with going towards this direction. I have looked into ServiceCollection class. The package it is from, Microsoft.Extensions.DependencyInjection, doesn't have "aspnetcore" in its name. It, however, has its owner as "aspnet". I am not entirely sure if ServiceCollection is only meant for web applications or it would make sense to use it for mobile apps.

Is it safe to use IServiceProvider with ServiceCollection as long as I use all singletons? is there any concern (in terms of performance or ram) I am missing?

Update

After the comments from Nkosi, I have taken another look at the link and noticed a couple of things:

The documentation link is dated around the same time Microsoft.Extensions.DependencyInjection was still in beta

All points in the list under "several advantages to using a dependency injection container" in the documentation also apply to DependencyInjection as far as I can see.

Autofac process seems to revolve around ViewModels which I am trying to avoid using.

Update 2

I managed to get DI directly into the behind code of pages with the help of a navigation function something like this:

public static async Task<TPage> NavigateAsync<TPage>()
    where TPage : Page
{
    var scope = Provider.CreateScope();
    var scopeProvider = scope.ServiceProvider;
    var page = scopeProvider.GetService<TPage>();
    if (navigation != null) await navigation.PushAsync(page);
    return page;
}

Body:
This implementation uses Splat and some helper/wrapper classes to conveniently access the container.

The way how the services are registered is a bit verbose but it could cover all uses cases I have encountered so far; and the life cycle can be changed quite easily as well, e.g. switching to a lazy creation of a service.

Simply use the ServiceProvider class to retrieve any instances from the IoC container anywhere in your code.

Registering of your Services

public partial class App : Application
{
    public App()
    {
        InitializeComponent();
        SetupBootstrapper(Locator.CurrentMutable);
        MainPage = new MainPage();
    }

    private void SetupBootstrapper(IMutableDependencyResolver resolver)
    {
        resolver.RegisterConstant(new Service(), typeof(IService));
        resolver.RegisterLazySingleton(() => new LazyService(), typeof(ILazyService));
        resolver.RegisterLazySingleton(() => new LazyServiceWithDI(
            ServiceProvider.Get<IService>()), typeof(ILazyServiceWithDI));
        // and so on ....
    }

Usage of ServiceProvider

// get a new service instance with every call
var brandNewService = ServiceProvider.Get<IService>();

// get a deferred created singleton
var sameOldService = ServiceProvider.Get<ILazyService>();

// get a service which uses DI in its contructor
var another service = ServiceProvider.Get<ILazyServiceWithDI>();

Implementation of ServiceProvider

public static class ServiceProvider
{
    public static T Get<T>(string contract = null)
    {
        T service = Locator.Current.GetService<T>(contract);
        if (service == null) throw new Exception($"IoC returned null for type '{typeof(T).Name}'.");
        return service;
    }

    public static IEnumerable<T> GetAll<T>(string contract = null)
    {
        bool IsEmpty(IEnumerable<T> collection)
        {
            return collection is null || !collection.Any();
        }

        IEnumerable<T> services = Locator.Current.GetServices<T>(contract).ToList();
        if (IsEmpty(services)) throw new Exception($"IoC returned null or empty collection for type '{typeof(T).Name}'.");

        return services;
    }
}

Here is my csproj file. Nothing special, the only nuget package I added was Spat

Shared Project csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <ProduceReferenceAssembly>true</ProduceReferenceAssembly>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DebugType>portable</DebugType>
    <DebugSymbols>true</DebugSymbols>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Splat" Version="9.3.11" />
    <PackageReference Include="Xamarin.Forms" Version="4.3.0.908675" />
    <PackageReference Include="Xamarin.Essentials" Version="1.3.1" />
  </ItemGroup>
</Project>


问:
react native encoding conversion
I'm trying to convert a fetch response from ISO-8859-1 to UTF-8 in react native.
I found this answer : Encoding conversion of a fetch response but in react native i'm having some troubles...

I didn't manage to use iconv, i tryed :

```<code>npm install --save iconv-lite // success
</code>```

then i do

```<code>var iconv = require('iconv-lite') // Error 500 from react native
</code>```

I didn't manage to use Buffer, it is unknown by react native and

```<code>require('buffer').Buffer // Error 500 from react native
</code>```

So here are my questions :

What is the best way to make an encoding conversion in react native ?

In case Encoding conversion of a fetch response is good: How do i use iconv ? How do i use Buffer ?

答:
Please consider this code:</p>

```<code>import iconv from "iconv-lite";
import {Buffer} from "buffer";

let str = iconv.decode(Buffer.from("hello"), 'us-ascii')
</code>```

Title: react native encoding conversion

Body:
I'm trying to convert a fetch response from ISO-8859-1 to UTF-8 in react native.
I found this answer : Encoding conversion of a fetch response but in react native i'm having some troubles...

I didn't manage to use iconv, i tryed :

npm install --save iconv-lite // success

then i do

var iconv = require('iconv-lite') // Error 500 from react native

I didn't manage to use Buffer, it is unknown by react native and

require('buffer').Buffer // Error 500 from react native

So here are my questions :

What is the best way to make an encoding conversion in react native ?

In case Encoding conversion of a fetch response is good: How do i use iconv ? How do i use Buffer ?

Body:
Please consider this code:

import iconv from "iconv-lite";
import {Buffer} from "buffer";

let str = iconv.decode(Buffer.from("hello"), 'us-ascii')


问:
Eloquent error: A facade root has not been set
I have been using Eloquent as a standalone package in Slim Framework 2 successfully.

But now that I want to make use of Illuminate\Support\Facades\DB since I need to show some statistics by getting the info from 2 tables and using a Left Join and a Counter from the database like this:

```<code>use Illuminate\Support\Facades\DB;
$projectsbyarea = DB::table('projects AS p')
        ->select(DB::raw('DISTINCT a.area, COUNT(a.area) AS Quantity'))
        ->leftJoin('areas AS a','p.area_id','=','a.id')
        ->where('p.status','in_process')
        ->where('a.area','<>','NULL')
        ->orderBy('p.area_id');
</code>```

I get the following error:

```<code>Type: RuntimeException
Message: A facade root has not been set.
File: ...\vendor\illuminate\support\Facades\Facade.php
Line: 206
</code>```

How can I solve it?

So far I have found out, in this link that I need to create a new app container and then bind it to the Facade. But I haven't found out how to make it work.

This is how I started the rest of my Eloquent and working fine:

```<code>use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule();

$capsule->addConnection([
    'my'         =>  $app->config->get('settings'),
    /* more settings ...*/
]);

/*booting Eloquent*/
$capsule->bootEloquent();
</code>```

How do I fix this?

Fixed
As @user5972059 said, I had to add $capsule->setAsGlobal();//This is important to make work the DB (Capsule) just above $capsule->bootEloquent();

Then, the query is executed like this:

```<code>use Illuminate\Database\Capsule\Manager as Capsule;
$projectsbyarea = Capsule::table('projects AS p')
            ->select(DB::raw('DISTINCT a.area, COUNT(a.area) AS Quantity'))
            ->leftJoin('areas AS a','p.area_id','=','a.id')
            ->where('p.status','in_process')
            ->where('a.area','<>','NULL')
            ->orderBy('p.area_id')
            ->get();
</code>```

答:
I got this error after running:

$ php artisan config:cache

The solution for me was to delete the /bootstrap/cache/config.php file. I'm running Laravel 5.5.

The seems to arise in multiple situation, and not just about facades.

Body:
I have been using Eloquent as a standalone package in Slim Framework 2 successfully.

But now that I want to make use of Illuminate\Support\Facades\DB since I need to show some statistics by getting the info from 2 tables and using a Left Join and a Counter from the database like this:

use Illuminate\Support\Facades\DB;
$projectsbyarea = DB::table('projects AS p')
        ->select(DB::raw('DISTINCT a.area, COUNT(a.area) AS Quantity'))
        ->leftJoin('areas AS a','p.area_id','=','a.id')
        ->where('p.status','in_process')
        ->where('a.area','<>','NULL')
        ->orderBy('p.area_id');

I get the following error:

Type: RuntimeException
Message: A facade root has not been set.
File: ...\vendor\illuminate\support\Facades\Facade.php
Line: 206

How can I solve it?

So far I have found out, in this link that I need to create a new app container and then bind it to the Facade. But I haven't found out how to make it work.

This is how I started the rest of my Eloquent and working fine:

use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule();

$capsule->addConnection([
    'my'         =>  $app->config->get('settings'),
    /* more settings ...*/
]);

/*booting Eloquent*/
$capsule->bootEloquent();

How do I fix this?

Fixed
As @user5972059 said, I had to add $capsule->setAsGlobal();//This is important to make work the DB (Capsule) just above $capsule->bootEloquent();

Then, the query is executed like this:

use Illuminate\Database\Capsule\Manager as Capsule;
$projectsbyarea = Capsule::table('projects AS p')
            ->select(DB::raw('DISTINCT a.area, COUNT(a.area) AS Quantity'))
            ->leftJoin('areas AS a','p.area_id','=','a.id')
            ->where('p.status','in_process')
            ->where('a.area','<>','NULL')
            ->orderBy('p.area_id')
            ->get();


问:
Why does fft-js not give a frequency bin for fs/2
I am performing a fft on a wave consisting of two simple sine waves with fft-js. The number of samples is 512 and the running time is 16 seconds. So the sample frequency is 32Hz. When looking into the resulting frequency this goes up to 15.9375 instead to the sample frequency divided by two (16 Hz). Why is this the case and is there a way to include the sample frequency divided by two?</p>

答:
This short Python example shows that you were right to look for the highest frequency and it is at a nonintuitive place. The Nyquist Frequency for the FFT is actually at the other end of the frequency vector:

```<code>import numpy as np
import matplotlib.pyplot as p
%matplotlib inline

T=1 # secs
d=0.1 # secs
n=int(T/d)

t=np.arange(0,T,d)
print(f'time : {t}')

freq=np.fft.fftfreq(n,d)
print(f' frequencies (unshifted) : {freq}')

sfreq=np.fft.fftshift(freq)
print(f' frequencies (shifted) : {sfreq}')
</code>```

output:

```<code>time : [0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
 frequencies (unshifted) : [ 0.  1.  2.  3.  4. -5. -4. -3. -2. -1.]
 frequencies (shifted) : [-5. -4. -3. -2. -1.  0.  1.  2.  3.  4.]
</code>```

Now Paul is also right, that a proper use of the FFT should use anti-aliasing measures such that ideally the energy at the very highest frequencies are almost zero.

Body:
This short Python example shows that you were right to look for the highest frequency and it is at a nonintuitive place. The Nyquist Frequency for the FFT is actually at the other end of the frequency vector:

import numpy as np
import matplotlib.pyplot as p
%matplotlib inline

T=1 # secs
d=0.1 # secs
n=int(T/d)

t=np.arange(0,T,d)
print(f'time : {t}')

freq=np.fft.fftfreq(n,d)
print(f' frequencies (unshifted) : {freq}')

sfreq=np.fft.fftshift(freq)
print(f' frequencies (shifted) : {sfreq}')

output:

time : [0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
 frequencies (unshifted) : [ 0.  1.  2.  3.  4. -5. -4. -3. -2. -1.]
 frequencies (shifted) : [-5. -4. -3. -2. -1.  0.  1.  2.  3.  4.]

Now Paul is also right, that a proper use of the FFT should use anti-aliasing measures such that ideally the energy at the very highest frequencies are almost zero.


问:
Does Firebase Test Lab supports iOS XCUITests attachments?
I'm currently able to run my iOS App UI tests in Firebase Test Lab. These tests generate some screenshots that I'm adding to my tests results through XCAttachments. I need these screenshots later to be used by an internal automation tool but I can't seem to find them anywhere in the tests results.
I've already set my scheme to not delete attachments if the tests succeeds.

Was someone able to grab screenshots from iOS UI Tests in Firebase Test Lab?

答:
https://cloud.google.com/sdk/gcloud/reference/firebase/test/ios/run

says you can send test results to [--results-dir=RESULTS_DIR]
You might want to run your tests and see if that path contains your resultBundle


问:
Dask fails with freeze_support bug
I try to run a very simple Dask program like the following:

# myfile.py
from dask.distributed import Client

client = Client()
```

<p>But when I run this program, I get this odd error</p>

```    An attempt has been made to start a new process before the
    current process has finished its bootstrapping phase.

    This probably means that you are not using fork to start your
    child processes and you have forgotten to use the proper idiom
    in the main module:

        if __name__ == '__main__':
            freeze_support()
            ...

    The "freeze_support()" line can be omitted if the program
    is not going to be frozen to produce an executable.
```

答:
When calling Client() or LocalCluster() you are starting some new processes in your program.  Python doesn't like it when modules or scripts start processes like this.

To resolve the problem, include your code in a if __name__ == "__main__": block like the following:

# client = Client()

if __name__ == '__main__':
    client = Client()
    ...
```

<p>Alternatively you can choose to use threads rather than processes safely.</p>

<pre class="lang-py prettyprint-override"><code>client = Client(processes=False)
</code>```

Also, this problem will not occur if you run within an interactive session like IPython or Jupyter

Title: Dask fails with freeze_support bug

Body:
I try to run a very simple Dask program like the following:

# myfile.py
from dask.distributed import Client

client = Client()

But when I run this program, I get this odd error

    An attempt has been made to start a new process before the
    current process has finished its bootstrapping phase.

    This probably means that you are not using fork to start your
    child processes and you have forgotten to use the proper idiom
    in the main module:

        if __name__ == '__main__':
            freeze_support()
            ...

    The "freeze_support()" line can be omitted if the program
    is not going to be frozen to produce an executable.

Body:
When calling Client() or LocalCluster() you are starting some new processes in your program.  Python doesn't like it when modules or scripts start processes like this.

To resolve the problem, include your code in a if __name__ == "__main__": block like the following:

# client = Client()

if __name__ == '__main__':
    client = Client()
    ...

Alternatively you can choose to use threads rather than processes safely.

client = Client(processes=False)

Also, this problem will not occur if you run within an interactive session like IPython or Jupyter


问:
Mockito, void method with checked exception
I want to know why i need to handle exception ,when i am mocking a void method which throws exception.

For example

```<code>public class MyObject {
    public void call() throws SomeException {
        //do something
        }
}
</code>```

Now when i am doing this,

```<code>@Mock
MyObject myObject;

doNothing().when(myObject).call()
</code>```

it results in compilation error saying

"error: unreported exception SomeException; must be caught or declared to be thrown"

I am wondering , why i need to handle exception for the method, which is itself being mocked .

答:
I was having a similar issue with multiple checked exceptions. My code looked something like this:

```<code>public class MyObject {
    public void call() throws ExceptionOne, ExceptionTwo {
        //do something
        }
}
</code>```

and my test was:

```<code>@Mock
MyObject myObject;

@Test
public void exampleTest throws ExceptionOne {
    doThrow(new ExceptionOne()).when(myObject).call()
    // assert...
}
</code>```

the error message was unreported exception: ExceptionOne

The solution was to have exampleTest throw both exceptionOne AND exceptionTwo. if you only report one checked exception it's not going to run.

Body:
I want to know why i need to handle exception ,when i am mocking a void method which throws exception.

For example

public class MyObject {
    public void call() throws SomeException {
        //do something
        }
}

Now when i am doing this,

@Mock
MyObject myObject;

doNothing().when(myObject).call()

it results in compilation error saying

"error: unreported exception SomeException; must be caught or declared to be thrown"

I am wondering , why i need to handle exception for the method, which is itself being mocked .

Body:
I was having a similar issue with multiple checked exceptions. My code looked something like this:

public class MyObject {
    public void call() throws ExceptionOne, ExceptionTwo {
        //do something
        }
}

and my test was:

@Mock
MyObject myObject;

@Test
public void exampleTest throws ExceptionOne {
    doThrow(new ExceptionOne()).when(myObject).call()
    // assert...
}

the error message was unreported exception: ExceptionOne

The solution was to have exampleTest throw both exceptionOne AND exceptionTwo. if you only report one checked exception it's not going to run.


问:
AndroidX: 'com.google.android.material:material*' library is calling androidx.cardview:cardview:1.0.0 but this does not download
I'll try to explain at detail what's happening.

*Gradle version: 5.1.1.

Android Gradle Plugin Version: 3.4.0

This is my Project build.gradle:

```<code>buildscript {
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
        maven { url 'https://jitpack.io' }
        maven { url "https://maven.google.com" }

    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

This is my App build.gradle:

```<code>apply plugin: 'com.android.application'
android {
    compileSdkVersion 29
    defaultConfig {
        applicationId "com.example.androidxexamp"
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'

    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.google.android.material:material:1.2.0-alpha04'

}
</code>```

What's happening?

The library 'com.google.android.material:material:1.2.0-alpha04' tries to download the androidx.cardview:cardview:1.0.0 dependency. But this does not download:

Label: "Could not find cardview.aar (androidx.cardview:cardview:1.0.0).
Searched in the following locations:
    https://dl.google.com/dl/android/maven2/androidx/cardview/cardview/1.0.0/cardview-1.0.0.aar"

The point is: When I manually try to download from https://dl.google.com/dl/android/maven2/androidx/cardview/cardview/1.0.0/cardview-1.0.0.aar it perfectly downloads. But the IDE cannot.

So, I'm tried to manually insert the androidx.cardview:cardview:1.0.0 library. I donwloaded the cardview-1.0.0.aar file and successfully inserted to A.Studio.

But I need the material library in order to use TabLayout. So, when I include (implementation 'com.google.android.material:material:1.2.0-alpha04') this fails againg saying it cannot resolve at https://dl.google.com/dl/android/maven2/androidx/cardview/cardview/1.0.0/cardview-1.0.0.aar.

I'm trying to see if there is any chance to avoid that the material library stop calling out the cardview dependency, don't know if possible.

Also, if I insert ( implementation 'androidx.cardview:cardview:1.0.0') A Studio says cannot resolve this link.

Please, any advice? Thanks very much

答: Ok I got it working now. I upgraded the Gradle version from 5.1.1 to 6.1.1, after that, it could resolved the dependency. Thank you.</p>

Body:
I'll try to explain at detail what's happening.

*Gradle version: 5.1.1.

Android Gradle Plugin Version: 3.4.0

This is my Project build.gradle:

buildscript {
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
        maven { url 'https://jitpack.io' }
        maven { url "https://maven.google.com" }

    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

This is my App build.gradle:

apply plugin: 'com.android.application'
android {
    compileSdkVersion 29
    defaultConfig {
        applicationId "com.example.androidxexamp"
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'

    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.google.android.material:material:1.2.0-alpha04'

}

What's happening?

The library 'com.google.android.material:material:1.2.0-alpha04' tries to download the androidx.cardview:cardview:1.0.0 dependency. But this does not download:

Label: "Could not find cardview.aar (androidx.cardview:cardview:1.0.0).
Searched in the following locations:
    https://dl.google.com/dl/android/maven2/androidx/cardview/cardview/1.0.0/cardview-1.0.0.aar"

The point is: When I manually try to download from https://dl.google.com/dl/android/maven2/androidx/cardview/cardview/1.0.0/cardview-1.0.0.aar it perfectly downloads. But the IDE cannot.

So, I'm tried to manually insert the androidx.cardview:cardview:1.0.0 library. I donwloaded the cardview-1.0.0.aar file and successfully inserted to A.Studio.

But I need the material library in order to use TabLayout. So, when I include (implementation 'com.google.android.material:material:1.2.0-alpha04') this fails againg saying it cannot resolve at https://dl.google.com/dl/android/maven2/androidx/cardview/cardview/1.0.0/cardview-1.0.0.aar.

I'm trying to see if there is any chance to avoid that the material library stop calling out the cardview dependency, don't know if possible.

Also, if I insert ( implementation 'androidx.cardview:cardview:1.0.0') A Studio says cannot resolve this link.

Please, any advice? Thanks very much


问:
error: could not lock config file C:/Program Files/Git/mingw64/etc/gitconfig: Permission denied
I would like to run this Git command:

```<code>git submodule add https://github.com/example/example.git
</code>```

But I get this error:

Cloning into 'C:/projects/xxx/yyy/zzz/'...
  fatal: unable to access 'https://github.com/xxx/yyy.git/': error setting certificate verify locations:

  CAfile: C:\Program Files (x86)\git\bin\curl-ca-bundle.crt

  CApath: none

  fatal: clone of 'https://github.com/xxx/yyy.git' into submodule path 'C:/projects/xxx/yyy/zzz/example' failed

So, to fix this, I am trying to run this command:

```<code>git config --system http.sslcainfo "C:\Program Files (x86)\git\bin\curl-ca-bundle.crt"
</code>```

But I get this error message:

error: could not lock config file C:/Program Files/Git/mingw64/etc/gitconfig: Permission denied

How can I fix this?

答:
I had a similar problem, with Git Bash reporting the fatal "error setting certificate verify locations" for the git pull command. The actual problem turned out to be authentication, as I had recently changed my Windows password. The solution was to remove the git credentials in Credential Manager (Windows 7 | Control Panel | All Control Panel Items | Credential Manager), then try git pull twice to force Git Bash to supply the Windows popup prompting for the new password. No more certificate errors.

In the past after changing Windows password, we have only had to log out of BitBucket in order for Git Bash to initiate the Windows popup for entering the new password. This time the popup did not appear, and I started receiving the certificate error, so removing the credentials was the solution.

Body:
I would like to run this Git command:

git submodule add https://github.com/example/example.git

But I get this error:

Cloning into 'C:/projects/xxx/yyy/zzz/'...
  fatal: unable to access 'https://github.com/xxx/yyy.git/': error setting certificate verify locations:

  CAfile: C:\Program Files (x86)\git\bin\curl-ca-bundle.crt

  CApath: none

  fatal: clone of 'https://github.com/xxx/yyy.git' into submodule path 'C:/projects/xxx/yyy/zzz/example' failed

So, to fix this, I am trying to run this command:

git config --system http.sslcainfo "C:\Program Files (x86)\git\bin\curl-ca-bundle.crt"

But I get this error message:

error: could not lock config file C:/Program Files/Git/mingw64/etc/gitconfig: Permission denied

How can I fix this?


问:
Opening .csv files to get username and password is resulting in error
I have an assignment for school to create a game that uses a username and password system to log in.

I have followed the instructions on how it should work but, unfortunately, I keep receiving an error whenever I try to test my system with the logging in part.

Everything else works but it's just that part that I can't seem to figure out what's wrong.

The error is:

```<code>Traceback (most recent call last):
  File "C:\Users\Sidney\Documents\Python\Duo Dice\Duo Dice.py", line 18, in <module>
    if row[0]==username:
IndexError: list index out of range
</code>```

This error comes after I have created a username and password (done by answering the first question with 'no'). The username and password isn't required to be anything special. Then I restart the program, enter the username and password created on the last run and I get the error.

The username and password are saved in the users.csv file on my computer automatically by the script. I am also not making any mistakes when entering the username and password, nor do I already have the .csv file open in advance.

Any help is appreciated. Many thanks.

import csv

print("Welcome to the Duo-Dice!")
print("") #Creates a line break in the text to look neater
print("The rules are as follows: \n*The points rolled on each player's dice are added to their score. \n*If the total is an even number, an additional 10 points are added to the score. \n*If the total is an odd number, 5 points are subtracet form their score. \n*If they roll a double, they get to roll one extra die and get the number of points rolled \n added to their score. \n*The score of a player can not go below zero at any point whatsoever. \n*The person with the highest score at the end of five rounds wins. \n*If both players have the same score at the end of five rounds, they each roll 1 die and \n whoever gets the highest score wins (This will repeat until someone wins).")
print("")
#Login/Create-account setup
answer = input('Do you already have an account? \n')
loggedin = False
if answer == 'yes':
    csvfile = open('users.csv')
    reader = csv.reader(csvfile)
    username = input('What is your username? \n')
    password = input('What is your password? \n')
    for row in reader:
        if row[0]==username:
            if row[1]==password:
                print("You are logged in")
                loggedin = True
    if loggedin == False:
        print("Sorry, something's wrong, try again")
else:
    print("Ok, please make an account")
    username = input("Enter a username: \n")
    password = input("Passwords require a lowercase, uppercase and a number. Please enter a password: \n")
    capital = False
    number = False
    lower = False
    for x in password:
        if x.isupper() == True:
            capital = True
        elif x.islower() == True:
            lower = True
        elif x.isnumeric() == True:
            number = True
    if capital == False or lower == False or number == False:
        print("Invalid password, please try again")
    else:
        Address1 = input("Enter road and house number: \n")
        Address2 = input("Enter town: \n")
        DateBirth = input("Enter DoB")
        interest1 = input("What is one of your interests: \n")
        interest2 = input("Another interest please: \n")
        csvfile = open('users.csv','a')
        lineToWrite = username + ',' + password + "," + Address1 + "," + Address2
        csvfile.write(lineToWrite)
        csvfile.close()
```

答:
The problem is with your file users.csv -- it probably has a blank line at the end.
The csv module returns this as a row in the for loop iteration.

A couple options to fix it:

remove blank line from the end of the users.csv

file check for blank
row in the code:

```<code>for row in csv_reader:
    if not row:
        continue
    if row[0] == username:
</code>```

Also, there's no reason to continue looping after finding a match:

```<code>        if row[0] == username:
            if row[1]==password:
                print("You are logged in")
                loggedin = True
                break
</code>```

Body:
I have an assignment for school to create a game that uses a username and password system to log in.

I have followed the instructions on how it should work but, unfortunately, I keep receiving an error whenever I try to test my system with the logging in part.

Everything else works but it's just that part that I can't seem to figure out what's wrong.

The error is:

Traceback (most recent call last):
  File "C:\Users\Sidney\Documents\Python\Duo Dice\Duo Dice.py", line 18, in <module>
    if row[0]==username:
IndexError: list index out of range

This error comes after I have created a username and password (done by answering the first question with 'no'). The username and password isn't required to be anything special. Then I restart the program, enter the username and password created on the last run and I get the error.

The username and password are saved in the users.csv file on my computer automatically by the script. I am also not making any mistakes when entering the username and password, nor do I already have the .csv file open in advance.

Any help is appreciated. Many thanks.

import csv

print("Welcome to the Duo-Dice!")
print("") #Creates a line break in the text to look neater
print("The rules are as follows: \n*The points rolled on each player's dice are added to their score. \n*If the total is an even number, an additional 10 points are added to the score. \n*If the total is an odd number, 5 points are subtracet form their score. \n*If they roll a double, they get to roll one extra die and get the number of points rolled \n added to their score. \n*The score of a player can not go below zero at any point whatsoever. \n*The person with the highest score at the end of five rounds wins. \n*If both players have the same score at the end of five rounds, they each roll 1 die and \n whoever gets the highest score wins (This will repeat until someone wins).")
print("")
#Login/Create-account setup
answer = input('Do you already have an account? \n')
loggedin = False
if answer == 'yes':
    csvfile = open('users.csv')
    reader = csv.reader(csvfile)
    username = input('What is your username? \n')
    password = input('What is your password? \n')
    for row in reader:
        if row[0]==username:
            if row[1]==password:
                print("You are logged in")
                loggedin = True
    if loggedin == False:
        print("Sorry, something's wrong, try again")
else:
    print("Ok, please make an account")
    username = input("Enter a username: \n")
    password = input("Passwords require a lowercase, uppercase and a number. Please enter a password: \n")
    capital = False
    number = False
    lower = False
    for x in password:
        if x.isupper() == True:
            capital = True
        elif x.islower() == True:
            lower = True
        elif x.isnumeric() == True:
            number = True
    if capital == False or lower == False or number == False:
        print("Invalid password, please try again")
    else:
        Address1 = input("Enter road and house number: \n")
        Address2 = input("Enter town: \n")
        DateBirth = input("Enter DoB")
        interest1 = input("What is one of your interests: \n")
        interest2 = input("Another interest please: \n")
        csvfile = open('users.csv','a')
        lineToWrite = username + ',' + password + "," + Address1 + "," + Address2
        csvfile.write(lineToWrite)
        csvfile.close()

Body:
The problem is with your file users.csv -- it probably has a blank line at the end.
The csv module returns this as a row in the for loop iteration.

A couple options to fix it:

remove blank line from the end of the users.csv

file check for blank
row in the code:

for row in csv_reader:
    if not row:
        continue
    if row[0] == username:

Also, there's no reason to continue looping after finding a match:

        if row[0] == username:
            if row[1]==password:
                print("You are logged in")
                loggedin = True
                break


问:
Disable Auth doesn't work with BF nuget package 4.7.1

Version

Microsoft.Bot.Streaming and Microsoft.Bot.Builder

"4.7.1"

Describe the bug

For direct line speech local test, set IsAuthenticationDisabledAsync to true in building a BotFrameworkHttpAdapter. SendActivityAsync() fails to send response back with below error

Failed to fetch token before processing outgoing activity. An IIdentity is required in TurnState for this operation.

For webchat test, it failed at Conversation:: ReplyToActivityWithHttpMessagesAsync, I get 401 unauthorized issue

To Reproduce

Update nuget package of BF to 4.7.1

Implement public class DisabledAuthCredentialProvider : ICredentialProvider which set IsAuthenticationDisabledAsync to true

Build BotFrameworkHttpAdapterv with DisabledAuthCredentialProvider

See exception in  SendActivitiesAsync

(await this.GetAppCredentialsAsync(this.GetBotAppId(turnContext), (string) null, new CancellationToken()).ConfigureAwait(false)).GetTokenAsync(false);

答:
Seems to work for me (in Emulator). Running 4.7.1. Here's what I have in DisabledAuthCredentialProvider

```<code>public class DisabledAuthCredentialProvider : ICredentialProvider
    {
        public Task<string> GetAppPasswordAsync(string appId)
        {
            throw new NotImplementedException();
        }

        public Task<bool> IsAuthenticationDisabledAsync()
        {
            return Task.FromResult(true);
        }

        public Task<bool> IsValidAppIdAsync(string appId)
        {
            throw new NotImplementedException();
        }
    }
</code>```

I can share my bot if that helps.

Body:
Seems to work for me (in Emulator). Running 4.7.1. Here's what I have in DisabledAuthCredentialProvider

public class DisabledAuthCredentialProvider : ICredentialProvider
    {
        public Task<string> GetAppPasswordAsync(string appId)
        {
            throw new NotImplementedException();
        }

        public Task<bool> IsAuthenticationDisabledAsync()
        {
            return Task.FromResult(true);
        }

        public Task<bool> IsValidAppIdAsync(string appId)
        {
            throw new NotImplementedException();
        }
    }

I can share my bot if that helps.


问:
Creating a dataframe using 3 other data frames that have no common merge values
I'm trying to accomplish a very particular type of data cleaning process using R.

I am given 2 dataframe structures and one matrix structure. The matrix corresponds to DF1 as column headers and DF2 as row headers, but I want to take all of this data and convert to a rectangular dataframe with one observation per row (based on result matrix, matrix_data).

Using the code below, I am able to create one observation per row, but for large data sets (~1M+ unique entries), this can take several minutes to run (~5 min). Right now, I am using a for loop to cycle through DF1, and I'm using do.call(... replicate()) to append rows to DF2. Treatment of the matrix_data is simple - I unwrap the data into a vector and cbind it to the DF1_ext and DF2_ext dataframes. Is there a better way to execute this for() loop in R?

```<code>DF1 <- data.frame(x_1 = c('a','b','c','d','e'), y_1 = c('f','g','h','i','j'), z_1 = c('k','l','m','n','o'))
DF2 <- data.frame(v_2 = 1:3, w_2 = 4:6, x_2 = 7:9, y_2 = 10:12, z_2 = 13:15)
matrix_data <- matrix(data = 1:15, nrow = 3, ncol = 5)

DF1_ext <- NULL
DF1_length <- nrow(DF1) * nrow(DF2)

#Use ceiling function to determine which row to put in NULL dataframe
#i.e. ceiling() rounds up to nearest integer value, setting j = to incremental step in origin dataframe
#See resultant DF

for (k in 1:DF1_length) {
  j = ceiling(k / DF1_length * length(DF1[,2]))
  DF1_ext <- rbind(DF1_ext[], DF1[j,])
}

#replicate DF2 matrix with rbind() based on the number of rows in DF1
DF2_ext <- do.call(rbind, replicate(nrow(DF1), DF2, simplify = FALSE))

#cbind() all values together.
#matrix_data can be transposed or not. This matters in the actual analysis, but should not matter here.
DF_result <- cbind(DF1_ext, DF2_ext, as.vector(t(matrix_data)))

View(DF_result)
</code>```

I am seeking a more "R" way of executing this code, hoping that there may be some more efficient functions along the way. This code, as is, can be copied into R and run with only base functions. To be clear, I am seeking a better way of executing in R because this method executes very slowly, and it seems like a lot of running around to do compared to most R methodology.

答:
Perform the join using SQL and then cbind the unravelled transpose of matrix_data.

```<code>library(sqldf)
cbind(sqldf("select * from DF1 join DF2"), data = c(t(matrix_data)))
</code>```

Body:
I'm trying to accomplish a very particular type of data cleaning process using R.

I am given 2 dataframe structures and one matrix structure. The matrix corresponds to DF1 as column headers and DF2 as row headers, but I want to take all of this data and convert to a rectangular dataframe with one observation per row (based on result matrix, matrix_data).

Using the code below, I am able to create one observation per row, but for large data sets (~1M+ unique entries), this can take several minutes to run (~5 min). Right now, I am using a for loop to cycle through DF1, and I'm using do.call(... replicate()) to append rows to DF2. Treatment of the matrix_data is simple - I unwrap the data into a vector and cbind it to the DF1_ext and DF2_ext dataframes. Is there a better way to execute this for() loop in R?

DF1 <- data.frame(x_1 = c('a','b','c','d','e'), y_1 = c('f','g','h','i','j'), z_1 = c('k','l','m','n','o'))
DF2 <- data.frame(v_2 = 1:3, w_2 = 4:6, x_2 = 7:9, y_2 = 10:12, z_2 = 13:15)
matrix_data <- matrix(data = 1:15, nrow = 3, ncol = 5)

DF1_ext <- NULL
DF1_length <- nrow(DF1) * nrow(DF2)

#Use ceiling function to determine which row to put in NULL dataframe
#i.e. ceiling() rounds up to nearest integer value, setting j = to incremental step in origin dataframe
#See resultant DF

for (k in 1:DF1_length) {
  j = ceiling(k / DF1_length * length(DF1[,2]))
  DF1_ext <- rbind(DF1_ext[], DF1[j,])
}

#replicate DF2 matrix with rbind() based on the number of rows in DF1
DF2_ext <- do.call(rbind, replicate(nrow(DF1), DF2, simplify = FALSE))

#cbind() all values together.
#matrix_data can be transposed or not. This matters in the actual analysis, but should not matter here.
DF_result <- cbind(DF1_ext, DF2_ext, as.vector(t(matrix_data)))

View(DF_result)

I am seeking a more "R" way of executing this code, hoping that there may be some more efficient functions along the way. This code, as is, can be copied into R and run with only base functions. To be clear, I am seeking a better way of executing in R because this method executes very slowly, and it seems like a lot of running around to do compared to most R methodology.

Body:
Perform the join using SQL and then cbind the unravelled transpose of matrix_data.

library(sqldf)
cbind(sqldf("select * from DF1 join DF2"), data = c(t(matrix_data)))


问:
print JSON objects using perl
I am new to perl and i had written below snippet of code to get the JSON objects from the data. But the input data has both hashes and arrays, So how do i get those values for "id" which is an array ?

```<code>  use strict;
  use warnings;
  use Data::Dumper;
  use JSON

 my $data = '{"total":325,"id": [78,234,737,1253,1459,1733,2166,2653,2855,3133,3414,3538,3729,3905,3991,4110,4160,4536,4692,4701]}';

 print Dumper($data);
 my @hash_ref = from_json($data);

 foreach my $hash_scalar (@hash_ref) {

    foreach (keys %{$hash_scalar}) {
        print "$_ => ${$hash_scalar}{$_}\n";
        }
    }
</code>```

Output Getting

#

```<code>$VAR1 = '{"total":325,"id":
[78,234,737,1253,1459,1733,2166,2653,2855,3133,3414,3538,3729,3905,3991,4110,4160,4536,4692,4701]}';
id => ARRAY(0x2afee4c)
total => 325
</code>```

答:
Perhaps following code will cover your question in more complete extent.

NOTE: I've added a hash in data block as bonus

```<code>use strict;
use warnings;
use feature 'say';

use JSON;
use Data::Dumper;

my $debug = 0;

my $data = '{ "total":325,
              "id": [78,234,737,1253,1459,1733,2166,2653,2855,3133,3414,3538,3729,3905,3991,4110,4160,4536,4692,4701],
              "person": {
                "first": "John",
                "last": "Smith",
                "age": 27,
                "occupation": "accountant",
                "wife": "Maria Smith",
                "son": "Alex Smith",
                "daughter": "Samantha Smith",
                "dog": "Sparky",
                "hobby": "photography"
               }
            }';

say Dumper($data) if $debug;

my $json = from_json($data);

say Dumper($json) if $debug;

while( my($k,$v) = each %{$json} ) {
    say "Key: $k";
    if( ref $v eq 'ARRAY' ) {
        say "\tValue is ARRAY";
        for ( @{$v} ) { say "\t\t[$_]" }
    } elsif( ref $v eq 'HASH' ) {
        say "\tValue is HASH";
        while( my($hk,$hv) = each %{$v} ) {
            say "\t\t$hk => $hv";
        }
    } else {
        say "\tValue: $v";
    }
}

say '-' x 40;
say 'Element with index 5 is ' . $json->{id}[5];
say 'Name of the son      is ' . $json->{person}{son};
say 'Name of the daughter is ' . $json->{person}{daughter};
</code>```

Output

```<code>Key: person
        Value is HASH
                son => Alex Smith
                occupation => accountant
                daughter => Samantha Smith
                age => 27
                wife => Maria Smith
                dog => Sparky
                last => Smith
                first => John
                hobby => photography
Key: id
        Value is ARRAY
                [78]
                [234]
                [737]
                [1253]
                [1459]
                [1733]
                [2166]
                [2653]
                [2855]
                [3133]
                [3414]
                [3538]
                [3729]
                [3905]
                [3991]
                [4110]
                [4160]
                [4536]
                [4692]
                [4701]
Key: total
        Value: 325
----------------------------------------
Element with index 5 is 1733
Name of the son      is Alex Smith
Name of the daughter is Samantha Smith
</code>```

Title: print JSON objects using perl

Body:
I am new to perl and i had written below snippet of code to get the JSON objects from the data. But the input data has both hashes and arrays, So how do i get those values for "id" which is an array ?

  use strict;
  use warnings;
  use Data::Dumper;
  use JSON

 my $data = '{"total":325,"id": [78,234,737,1253,1459,1733,2166,2653,2855,3133,3414,3538,3729,3905,3991,4110,4160,4536,4692,4701]}';

 print Dumper($data);
 my @hash_ref = from_json($data);

 foreach my $hash_scalar (@hash_ref) {

    foreach (keys %{$hash_scalar}) {
        print "$_ => ${$hash_scalar}{$_}\n";
        }
    }

Output Getting

#

$VAR1 = '{"total":325,"id":
[78,234,737,1253,1459,1733,2166,2653,2855,3133,3414,3538,3729,3905,3991,4110,4160,4536,4692,4701]}';
id => ARRAY(0x2afee4c)
total => 325

Body:
Perhaps following code will cover your question in more complete extent.

NOTE: I've added a hash in data block as bonus

use strict;
use warnings;
use feature 'say';

use JSON;
use Data::Dumper;

my $debug = 0;

my $data = '{ "total":325,
              "id": [78,234,737,1253,1459,1733,2166,2653,2855,3133,3414,3538,3729,3905,3991,4110,4160,4536,4692,4701],
              "person": {
                "first": "John",
                "last": "Smith",
                "age": 27,
                "occupation": "accountant",
                "wife": "Maria Smith",
                "son": "Alex Smith",
                "daughter": "Samantha Smith",
                "dog": "Sparky",
                "hobby": "photography"
               }
            }';

say Dumper($data) if $debug;

my $json = from_json($data);

say Dumper($json) if $debug;

while( my($k,$v) = each %{$json} ) {
    say "Key: $k";
    if( ref $v eq 'ARRAY' ) {
        say "\tValue is ARRAY";
        for ( @{$v} ) { say "\t\t[$_]" }
    } elsif( ref $v eq 'HASH' ) {
        say "\tValue is HASH";
        while( my($hk,$hv) = each %{$v} ) {
            say "\t\t$hk => $hv";
        }
    } else {
        say "\tValue: $v";
    }
}

say '-' x 40;
say 'Element with index 5 is ' . $json->{id}[5];
say 'Name of the son      is ' . $json->{person}{son};
say 'Name of the daughter is ' . $json->{person}{daughter};

Output

Key: person
        Value is HASH
                son => Alex Smith
                occupation => accountant
                daughter => Samantha Smith
                age => 27
                wife => Maria Smith
                dog => Sparky
                last => Smith
                first => John
                hobby => photography
Key: id
        Value is ARRAY
                [78]
                [234]
                [737]
                [1253]
                [1459]
                [1733]
                [2166]
                [2653]
                [2855]
                [3133]
                [3414]
                [3538]
                [3729]
                [3905]
                [3991]
                [4110]
                [4160]
                [4536]
                [4692]
                [4701]
Key: total
        Value: 325
----------------------------------------
Element with index 5 is 1733
Name of the son      is Alex Smith
Name of the daughter is Samantha Smith


问:
How do I reverse this string properly in c#?
Problem:
I have many strings/equations in this format or one similar:
-4x^2 + 6x^5 -12y + 3xy

BUT I need them in the following order (the reverse - descending instead of ascending powers):
3xy - 12y + 6x^5 - 4x^2

Current attempt (gets close):

```<code>string str ="-4x^2 + 6x^5 -12y + 3xy";

var reverseString = string.Join(" ", str.Split(' ').Reverse());
//This returns: 3xy + 12y - 6x^5 + -4x^2
//Desired rtrn: 3xy - 12y + 6x^5 - 4x^2
</code>```

Issues with current attempt:

"+" and "-" are not reordered correctly.

In the case of negative numbers "+ -" should just be " - ". (e.g 2x + -3x should be 2x - 3x).

In the circumstance the equation starts with a negative number or
is inside a bracket opening, this needs to still remain as "-2x" or
"(-2x ...) (no space) for example not become "- 2x" with a space.

Question:

How would I get the string and +/- in the correct order and fix the issues with my current attempt?

Should I try again after learning regex? (If that's more suitable).

Thank you for any help.

答:
You will need to use a Character array and then split the string first in order to achieve this. After this is done then you can use a string to get the string output.</p>

```<code>string valueStr = "-4x^2 + 6x^5 -12y + 3xy";
string result = string.Join(" ", valueStr.Split(new char[] { ' ' }).Reverse());
</code>```

Body:
Problem:
I have many strings/equations in this format or one similar:
-4x^2 + 6x^5 -12y + 3xy

BUT I need them in the following order (the reverse - descending instead of ascending powers):
3xy - 12y + 6x^5 - 4x^2

Current attempt (gets close):

string str ="-4x^2 + 6x^5 -12y + 3xy";

var reverseString = string.Join(" ", str.Split(' ').Reverse());
//This returns: 3xy + 12y - 6x^5 + -4x^2
//Desired rtrn: 3xy - 12y + 6x^5 - 4x^2

Issues with current attempt:

"+" and "-" are not reordered correctly.

In the case of negative numbers "+ -" should just be " - ". (e.g 2x + -3x should be 2x - 3x).

In the circumstance the equation starts with a negative number or
is inside a bracket opening, this needs to still remain as "-2x" or
"(-2x ...) (no space) for example not become "- 2x" with a space.

Question:

How would I get the string and +/- in the correct order and fix the issues with my current attempt?

Should I try again after learning regex? (If that's more suitable).

Thank you for any help.

Body:
You will need to use a Character array and then split the string first in order to achieve this. After this is done then you can use a string to get the string output.

string valueStr = "-4x^2 + 6x^5 -12y + 3xy";
string result = string.Join(" ", valueStr.Split(new char[] { ' ' }).Reverse());


问:
Rank and Array Formulas In Google Sheets based on criteria from two columns
I am struggling to rank two columns with an array formula:

The current formula:

```<code>=if(B2<>"",if(B2=B1,if(C1=1,2, C1+1),1),)
</code>```

Here is a link to the Google Sheet sample:

https://docs.google.com/spreadsheets/d/14BX3mO2Nd-RTMyhivwJ9w_rnVbVjSqE72o3Rdx-GQME/edit?usp=sharing

I'd like to be able to create an array formula in Column C but multiple attempts has me stumped if that's possible. Essentially Column C should be ranked in order of lowest $ to highest $ from column A and the order in which it appears so rank values do not repeat. Additionally, the rank should only be the same item in column B and different for each item.

Body:
I am struggling to rank two columns with an array formula:

The current formula:

=if(B2<>"",if(B2=B1,if(C1=1,2, C1+1),1),)

Here is a link to the Google Sheet sample:

https://docs.google.com/spreadsheets/d/14BX3mO2Nd-RTMyhivwJ9w_rnVbVjSqE72o3Rdx-GQME/edit?usp=sharing

I'd like to be able to create an array formula in Column C but multiple attempts has me stumped if that's possible. Essentially Column C should be ranked in order of lowest $ to highest $ from column A and the order in which it appears so rank values do not repeat. Additionally, the rank should only be the same item in column B and different for each item.

Body:
This should work if put in C1:

=ARRAYFORMULA({"Rank";IF(B2:B="",,COUNTIFS(B2:B,B2:B,A2:A+1/(1000*ROW(A2:A)),"<="&A2:A+1/(1000*ROW(A2:A))))})


问:
onelogin php-saml userdata not found
I am using one-login's php-saml library to use as an SP to connect to a client's IDP. For some reason though, when the client sends their SAML response, the array that is set by

```<code>$_SESSION['samlUserdata'] = $auth->getAttributes()
</code>```

returns empty. If anyone has any insight as to what reason(s) why this could be happening, it would be greatly appreciated if you would share.

答:
First of all, I would recommend to check your own saml metadata.

Do you have a list of attributes you want to get? Like:

```<code>    <md:AttributeConsumingService index="1">
        <md:ServiceName xml:lang="en">Service</md:ServiceName>
        <md:ServiceDescription xml:lang="en">Sign-on</md:ServiceDescription>
        <md:RequestedAttribute Name="username" isRequired="true" />
        <md:RequestedAttribute Name="email" isRequired="true" />
        <md:RequestedAttribute Name="firstName" isRequired="true" />
        <md:RequestedAttribute Name="lastName" isRequired="true" />
    </md:AttributeConsumingService>
</code>```

Second, if applicable, try to capture an incoming request and analyze it manually.

Also, ensure the client is properly configured according to your metadata.

It won't send everything about a logged in user.

The client has to explicitly declare/map/configure attributes for your SAML.

Title: onelogin php-saml userdata not found

Body:
I am using one-login's php-saml library to use as an SP to connect to a client's IDP. For some reason though, when the client sends their SAML response, the array that is set by

$_SESSION['samlUserdata'] = $auth->getAttributes()

returns empty. If anyone has any insight as to what reason(s) why this could be happening, it would be greatly appreciated if you would share.

Body:
First of all, I would recommend to check your own saml metadata.

Do you have a list of attributes you want to get? Like:

    <md:AttributeConsumingService index="1">
        <md:ServiceName xml:lang="en">Service</md:ServiceName>
        <md:ServiceDescription xml:lang="en">Sign-on</md:ServiceDescription>
        <md:RequestedAttribute Name="username" isRequired="true" />
        <md:RequestedAttribute Name="email" isRequired="true" />
        <md:RequestedAttribute Name="firstName" isRequired="true" />
        <md:RequestedAttribute Name="lastName" isRequired="true" />
    </md:AttributeConsumingService>

Second, if applicable, try to capture an incoming request and analyze it manually.

Also, ensure the client is properly configured according to your metadata.

It won't send everything about a logged in user.

The client has to explicitly declare/map/configure attributes for your SAML.


问:
Writing down to next cell using openpyxl

I am using python get data from an api trying to get a process, host name, start time of the process, user name, ip address, domain, and time stamp of each connection. Each process can have multiple results for the following columns that needs to move down each row. What is happening is that everything is being written into Row 2 as it gets over written. Here is my script.

wb = Workbook()
ws1 = wb.create_sheet("Sheet_A")
ws1.title = "Results"
ws1['A1'] = "Process"
ws1['B1'] = "Host Name"
ws1['C1'] = "Process Time"
ws1['D1'] = "User Name"
ws1['E1'] = "Domain"
ws1['F1'] = "Netconn Time"

c = CbResponseAPI()

rows = 1

base_query = c.select(Process).where('start:-500m (hostname:1 OR hostname:2 OR hostname:3 OR hostname:4) netconn_count:[1 TO *] -ipaddr:192.168.0.0/16 -ipaddr:10.0.0.0/8 -ipaddr:172.16.0.0/12 -ipaddr:127.0.0.1')

for proc in base_query:
        # print proc
        ws1['A2'] = proc.process_name
        ws1['B2'] = proc.hostname
        ws1['C2'] = proc.start
        ws1['D2'] = proc.username
        rows+=1
        for netconn in proc.netconns:
            ws1['E2'] = netconn.domain
            ws1['F2'] = netconn.timestamp
            ws1['G2'] = netconn.remote_ip
            rows+=1

wb.save('Rav.xlsx')
```

<p><img src="https://i.stack.imgur.com/Yt7ah.png" alt="This is the end result of the script just one row, I should have thousands"></p>

<p>Here is my edit</p>

```for i, proc in enumerate(base_query):
        # print proc
        ws1[f'A{i+2}'] = proc.process_name
        ws1[f'B{i+2}'] = proc.hostname
        ws1[f'C{i+2}'] = proc.start
        ws1[f'D{i+2}'] = proc.username
        rows+=1
        for netconn in proc.netconns:
            ws1[f'E{i+2}'] = netconn.domain
            ws1[f'F{i+2}'] = netconn.timestamp
            ws1[f'G{i+2}'] = netconn.remote_ip
            rows+=1
```

<p>Here is the output of print(proc) and print(netconn)</p>

```process_md5          : f8d0c92070e59a059a889d5e269c0da9
sensor_id            : 656
filtering_known_dlls : False
modload_count        : 45
parent_unique_id     : 00000290-0000-023c-01d5-e25a6a09eddc-000000000001
cmdline              : C:\Windows\ADWS\Microsoft.ActiveDirectory.WebServices.exe
last_update          : 2020-02-17 14:48:26.878000
id                   : 00000290-0000-0760-01d5-e25a77d2e409
parent_name          : services.exe
group                : default group
parent_id            : 00000290-0000-023c-01d5-e25a6a09eddc
hostname             :
filemod_count        : 0
start                : 2020-02-13 10:43:46.254000
comms_ip             : 0.0.0.0
regmod_count         : 5
interface_ip         : 10.140.51.10
process_pid          : 1888
username             : SYSTEM
process_sha256       : d40478a82bb2993f39a3ed6066cd0599be37ff9a0898636a680926fe145c64d6
terminated           : False
emet_config          :
process_name         : microsoft.activedirectory.webservices.exe
emet_count           : 0
last_server_update   : 2020-02-17 14:49:19.877000
path                 : c:\windows\adws\microsoft.activedirectory.webservices.exe
netconn_count        : 12008
parent_pid           : 572
crossproc_count      : 11
segment_id           : 1581950959796
host_type            : domain_controller
processblock_count   : 0
os_type              : windows
childproc_count      : 0
unique_id            : 00000290-0000-0760-01d5-e25a77d2e409-017053a000b4
Cb Network Connection event:
timestamp            : 2020-02-17 14:44:26.844000
domain               :
remote_ip            : ::1
remote_port          : 389
proto                : IPPROTO_TCP
direction            : Outbound
local_ip             : ::1
local_port           : 52995
proxy_ip             : 0.0.0.0
proxy_port           : 0
```

答:
You just need to enumerate the for loop to give yourself a counter, to move to the next line. Then add 2 to i because you're starting on row 2, and i will start at 0.

for i, proc in enumerate(base_query):
        # print proc
        ws1[f'A{i+2}'] = proc.process_name
        ws1[f'B{i+2}'] = proc.hostname
        ws1[f'C{i+2}'] = proc.start
        ws1[f'D{i+2}'] = proc.username
        for netconn in proc.netconns:
            ws1[f'E{i+2}'] = netconn.domain
            ws1[f'F{i+2}'] = netconn.timestamp
            ws1[f'G{i+2}'] = netconn.remote_ip

wb.save('Rav.xlsx')
```

<p>Here's my working example:</p>

<pre class="lang-py prettyprint-override"><code>import openpyxl
from openpyxl import Workbook

wb = Workbook()
ws1 = wb.create_sheet("Sheet_A")
ws1.title = "Results"
ws1['A1'] = "Process"
ws1['B1'] = "Host Name"
ws1['C1'] = "Process Time"
ws1['D1'] = "User Name"
ws1['E1'] = "Domain"
ws1['F1'] = "Netconn Time"

loop = [['process_name', 'hostname'],['process_name', 'hostname'],['process_name', 'hostname'],]

for i, proc in enumerate(loop):
        # print proc
        ws1[f'A{i+2}'] = proc[0]
        ws1[f'B{i+2}'] = proc[1]

wb.save('Rav.xlsx')
</code>```

Output

Body:
I am using python get data from an api trying to get a process, host name, start time of the process, user name, ip address, domain, and time stamp of each connection. Each process can have multiple results for the following columns that needs to move down each row. What is happening is that everything is being written into Row 2 as it gets over written. Here is my script.

wb = Workbook()
ws1 = wb.create_sheet("Sheet_A")
ws1.title = "Results"
ws1['A1'] = "Process"
ws1['B1'] = "Host Name"
ws1['C1'] = "Process Time"
ws1['D1'] = "User Name"
ws1['E1'] = "Domain"
ws1['F1'] = "Netconn Time"

c = CbResponseAPI()

rows = 1

base_query = c.select(Process).where('start:-500m (hostname:1 OR hostname:2 OR hostname:3 OR hostname:4) netconn_count:[1 TO *] -ipaddr:192.168.0.0/16 -ipaddr:10.0.0.0/8 -ipaddr:172.16.0.0/12 -ipaddr:127.0.0.1')

for proc in base_query:
        # print proc
        ws1['A2'] = proc.process_name
        ws1['B2'] = proc.hostname
        ws1['C2'] = proc.start
        ws1['D2'] = proc.username
        rows+=1
        for netconn in proc.netconns:
            ws1['E2'] = netconn.domain
            ws1['F2'] = netconn.timestamp
            ws1['G2'] = netconn.remote_ip
            rows+=1

wb.save('Rav.xlsx')

Here is my edit

for i, proc in enumerate(base_query):
        # print proc
        ws1[f'A{i+2}'] = proc.process_name
        ws1[f'B{i+2}'] = proc.hostname
        ws1[f'C{i+2}'] = proc.start
        ws1[f'D{i+2}'] = proc.username
        rows+=1
        for netconn in proc.netconns:
            ws1[f'E{i+2}'] = netconn.domain
            ws1[f'F{i+2}'] = netconn.timestamp
            ws1[f'G{i+2}'] = netconn.remote_ip
            rows+=1

Here is the output of print(proc) and print(netconn)

process_md5          : f8d0c92070e59a059a889d5e269c0da9
sensor_id            : 656
filtering_known_dlls : False
modload_count        : 45
parent_unique_id     : 00000290-0000-023c-01d5-e25a6a09eddc-000000000001
cmdline              : C:\Windows\ADWS\Microsoft.ActiveDirectory.WebServices.exe
last_update          : 2020-02-17 14:48:26.878000
id                   : 00000290-0000-0760-01d5-e25a77d2e409
parent_name          : services.exe
group                : default group
parent_id            : 00000290-0000-023c-01d5-e25a6a09eddc
hostname             :
filemod_count        : 0
start                : 2020-02-13 10:43:46.254000
comms_ip             : 0.0.0.0
regmod_count         : 5
interface_ip         : 10.140.51.10
process_pid          : 1888
username             : SYSTEM
process_sha256       : d40478a82bb2993f39a3ed6066cd0599be37ff9a0898636a680926fe145c64d6
terminated           : False
emet_config          :
process_name         : microsoft.activedirectory.webservices.exe
emet_count           : 0
last_server_update   : 2020-02-17 14:49:19.877000
path                 : c:\windows\adws\microsoft.activedirectory.webservices.exe
netconn_count        : 12008
parent_pid           : 572
crossproc_count      : 11
segment_id           : 1581950959796
host_type            : domain_controller
processblock_count   : 0
os_type              : windows
childproc_count      : 0
unique_id            : 00000290-0000-0760-01d5-e25a77d2e409-017053a000b4
Cb Network Connection event:
timestamp            : 2020-02-17 14:44:26.844000
domain               :
remote_ip            : ::1
remote_port          : 389
proto                : IPPROTO_TCP
direction            : Outbound
local_ip             : ::1
local_port           : 52995
proxy_ip             : 0.0.0.0
proxy_port           : 0

Body:
You just need to enumerate the for loop to give yourself a counter, to move to the next line. Then add 2 to i because you're starting on row 2, and i will start at 0.

for i, proc in enumerate(base_query):
        # print proc
        ws1[f'A{i+2}'] = proc.process_name
        ws1[f'B{i+2}'] = proc.hostname
        ws1[f'C{i+2}'] = proc.start
        ws1[f'D{i+2}'] = proc.username
        for netconn in proc.netconns:
            ws1[f'E{i+2}'] = netconn.domain
            ws1[f'F{i+2}'] = netconn.timestamp
            ws1[f'G{i+2}'] = netconn.remote_ip

wb.save('Rav.xlsx')

Here's my working example:

import openpyxl
from openpyxl import Workbook

wb = Workbook()
ws1 = wb.create_sheet("Sheet_A")
ws1.title = "Results"
ws1['A1'] = "Process"
ws1['B1'] = "Host Name"
ws1['C1'] = "Process Time"
ws1['D1'] = "User Name"
ws1['E1'] = "Domain"
ws1['F1'] = "Netconn Time"

loop = [['process_name', 'hostname'],['process_name', 'hostname'],['process_name', 'hostname'],]

for i, proc in enumerate(loop):
        # print proc
        ws1[f'A{i+2}'] = proc[0]
        ws1[f'B{i+2}'] = proc[1]

wb.save('Rav.xlsx')

Output


问:
Removing pages from search engine results
Hey everyone, I'm a bit new to SEO. I built a one page website that initially utilized several pages (but are now removed), and it looks as if Google has indexed those so that they show up as search results. Is there any way to remove those from the search results? Thanks.</p>

答:
Use a robots.txt file:
Robots.txt

example robots.txt:

```<code>User-agent: *
Disallow: /url1.html
Disallow: /url2.html
</code>```

Body:
Use a robots.txt file:
Robots.txt

example robots.txt:

User-agent: *
Disallow: /url1.html
Disallow: /url2.html


问:
How to get the current date and time of your timezone in Java?
I have my app hosted in a London Server. I am in Madrid, Spain. So the timezone is -2 hours.

How can I obtain the current date / time with my time zone.

```<code>Date curr_date = new Date(System.currentTimeMillis());
</code>```

e.g.

```<code>Date curr_date = new Date(System.currentTimeMillis("MAD_TIMEZONE"));
</code>```

With Joda-Time

```<code>DateTimeZone zone = DateTimeZone.forID("Europe/Madrid");
DateTime dt = new DateTime(zone);
int day = dt.getDayOfMonth();
int year = dt.getYear();
int month = dt.getMonthOfYear();
int hours = dt.getHourOfDay();
int minutes = dt.getMinuteOfHour();
</code>```

答:
Date in 24 hrs format

Output:14/02/2020 19:56:49 PM

```<code> Date date = new Date();
 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss aa");
 dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
 System.out.println("date is: "+dateFormat.format(date));
</code>```

Date in 12 hrs format

Output:14/02/2020 07:57:11 PM

```<code> Date date = new Date();`enter code here`
 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa");
 dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
 System.out.println("date is: "+dateFormat.format(date));
</code>```

Body:
I have my app hosted in a London Server. I am in Madrid, Spain. So the timezone is -2 hours.

How can I obtain the current date / time with my time zone.

Date curr_date = new Date(System.currentTimeMillis());

e.g.

Date curr_date = new Date(System.currentTimeMillis("MAD_TIMEZONE"));

With Joda-Time

DateTimeZone zone = DateTimeZone.forID("Europe/Madrid");
DateTime dt = new DateTime(zone);
int day = dt.getDayOfMonth();
int year = dt.getYear();
int month = dt.getMonthOfYear();
int hours = dt.getHourOfDay();
int minutes = dt.getMinuteOfHour();

Body:
Date in 24 hrs format

Output:14/02/2020 19:56:49 PM

 Date date = new Date();
 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss aa");
 dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
 System.out.println("date is: "+dateFormat.format(date));

Date in 12 hrs format

Output:14/02/2020 07:57:11 PM

 Date date = new Date();`enter code here`
 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa");
 dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
 System.out.println("date is: "+dateFormat.format(date));


答:
What about the data.table package? rbindlist is a must faster alternative to rbind.

Also, @akrun suggested bind_rows from dplyr, which is also much faster than do.call.

```<code>library(data.table)
DF2_ext <- rbindlist(replicate(nrow(DF1), DF2, simplify = FALSE))

library(microbenchmark)
microbenchmark(do.call(rbind, replicate(nrow(DF1), DF2, simplify = FALSE)),
           rbindlist(replicate(nrow(DF1), DF2, simplify = FALSE)),
           bind_rows(replicate(nrow(DF1), DF2, simplify = FALSE)),
           cbind(sqldf("select * from DF1 join DF2"), data = c(t(matrix_data))))

Unit: microseconds
expr       min         lq       mean     median         uq       max neval cld
do.call(rbind, replicate(nrow(DF1), DF2, simplify = FALSE))   424.572   451.0790   515.0016   473.8225   500.0185  1243.674   100  a
rbindlist(replicate(nrow(DF1), DF2, simplify = FALSE))   105.988   124.3765   164.1111   159.7705   173.8210   563.697   100  a
bind_rows(replicate(nrow(DF1), DF2, simplify = FALSE))    36.590    48.9140   528.4883    62.6580    75.0540 46448.825   100  a
cbind(sqldf("select * from DF1 join DF2"), data = c(t(matrix_data))) 15201.367 15771.5310 18581.6682 16308.9790 18329.5940 54964.681   100   b
</code>```

Title: Creating a dataframe using 3 other data frames that have no common merge values

Body:
What about the data.table package? rbindlist is a must faster alternative to rbind.

Also, @akrun suggested bind_rows from dplyr, which is also much faster than do.call.

library(data.table)
DF2_ext <- rbindlist(replicate(nrow(DF1), DF2, simplify = FALSE))

library(microbenchmark)
microbenchmark(do.call(rbind, replicate(nrow(DF1), DF2, simplify = FALSE)),
           rbindlist(replicate(nrow(DF1), DF2, simplify = FALSE)),
           bind_rows(replicate(nrow(DF1), DF2, simplify = FALSE)),
           cbind(sqldf("select * from DF1 join DF2"), data = c(t(matrix_data))))

Unit: microseconds
expr       min         lq       mean     median         uq       max neval cld
do.call(rbind, replicate(nrow(DF1), DF2, simplify = FALSE))   424.572   451.0790   515.0016   473.8225   500.0185  1243.674   100  a
rbindlist(replicate(nrow(DF1), DF2, simplify = FALSE))   105.988   124.3765   164.1111   159.7705   173.8210   563.697   100  a
bind_rows(replicate(nrow(DF1), DF2, simplify = FALSE))    36.590    48.9140   528.4883    62.6580    75.0540 46448.825   100  a
cbind(sqldf("select * from DF1 join DF2"), data = c(t(matrix_data))) 15201.367 15771.5310 18581.6682 16308.9790 18329.5940 54964.681   100   b


问:
PyTorch tensor indexing or conditional selection?
```<code>    for c in range(self.n_class):
        target[c][label == c] = 1
</code>```

self.n_class is 32. and target is 32 x 1024 x 2048 tensor.

I know that target[c] select the each one of 1 x 1024 x 2048.
But I don't understand [label == c].

Because by thumb of rule, an integer should go in the square [].

Could someone explain what second square does and how it makes sense?

答:
PyTorch supports "Advanced Indexing." It implements the ability to accept a tensor argument to the [] operator.

The result of the == operator is a boolean mask. The [] operator is using that mask to select elements. This example below might help clarify:

```<code>>>> x=torch.arange(0,10)
>>> x
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> x < 5
tensor([ True,  True,  True,  True,  True, False, False, False, False, False])
>>> x[x < 5]
tensor([0, 1, 2, 3, 4])
>>> x[x > 5]
tensor([6, 7, 8, 9])
>>>
</code>```

Some general docs:
https://www.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/BasicIndexing.html

Advanced indexing in numpy:
https://numpy.org/doc/1.18/reference/arrays.indexing.html

Body:
    for c in range(self.n_class):
        target[c][label == c] = 1

self.n_class is 32. and target is 32 x 1024 x 2048 tensor.

I know that target[c] select the each one of 1 x 1024 x 2048.
But I don't understand [label == c].

Because by thumb of rule, an integer should go in the square [].

Could someone explain what second square does and how it makes sense?

Body:
PyTorch supports "Advanced Indexing." It implements the ability to accept a tensor argument to the [] operator.

The result of the == operator is a boolean mask. The [] operator is using that mask to select elements. This example below might help clarify:

>>> x=torch.arange(0,10)
>>> x
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> x < 5
tensor([ True,  True,  True,  True,  True, False, False, False, False, False])
>>> x[x < 5]
tensor([0, 1, 2, 3, 4])
>>> x[x > 5]
tensor([6, 7, 8, 9])
>>>

Some general docs:
https://www.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/BasicIndexing.html

Advanced indexing in numpy:
https://numpy.org/doc/1.18/reference/arrays.indexing.html