问:
Pygame Collisions Are Only Working on One Object
I'm coding a platformer on pygame, and I've got a problem where only one of my platform's collisions are being detected.

This is for my final in Computer Science course. I've tried using group collision but that only works with sprites, and if I wanted to go down that route I'd have to rewrite quite a bit of my code.

# in main loop
for i in platforms:
    if i.rect.colliderect(c) and c.isjump == False:
        # If player is on platform and not jumping
        c.falling = False
        c.isjump = False
        c.jumpcount = 10
        c.onplat = True
    else:
        c.falling = True
        c.onplat = False
```

Everything here works (and does not produce any errors), except when I test it, only one platform stops the player from falling while the other(s) just phase through the player. I can show more of the code if needed.

答:
If you've identified a platform, which "stops" the player, then you've to break the loop:

for i in platforms:
    if i.rect.colliderect(c) and c.isjump == False:
       c.falling = False
       c.isjump = False
       c.jumpcount = 10
       c.onplat = True

       break # <----- break the loop

    else:
       c.falling = True
       c.onplat = False
```

<p>else the result of the next platform would overwrite the result and the last platform in the list set the result in any case.</p>

<p>Note you can simplify the code, by finding <code>any</code> platform:</p>

<pre class="lang-py prettyprint-override"><code>if c.isjump == False and any([i for i in platforms if i.rect.colliderect(c)]):
   c.falling = False
   c.jumpcount = 10
   c.onplat = True
</code>```

Body:
I'm coding a platformer on pygame, and I've got a problem where only one of my platform's collisions are being detected.

This is for my final in Computer Science course. I've tried using group collision but that only works with sprites, and if I wanted to go down that route I'd have to rewrite quite a bit of my code.

# in main loop
for i in platforms:
    if i.rect.colliderect(c) and c.isjump == False:
        # If player is on platform and not jumping
        c.falling = False
        c.isjump = False
        c.jumpcount = 10
        c.onplat = True
    else:
        c.falling = True
        c.onplat = False

Everything here works (and does not produce any errors), except when I test it, only one platform stops the player from falling while the other(s) just phase through the player. I can show more of the code if needed.

Body:
If you've identified a platform, which "stops" the player, then you've to break the loop:

for i in platforms:
    if i.rect.colliderect(c) and c.isjump == False:
       c.falling = False
       c.isjump = False
       c.jumpcount = 10
       c.onplat = True

       break # <----- break the loop

    else:
       c.falling = True
       c.onplat = False

else the result of the next platform would overwrite the result and the last platform in the list set the result in any case.

Note you can simplify the code, by finding any platform:

if c.isjump == False and any([i for i in platforms if i.rect.colliderect(c)]):
   c.falling = False
   c.jumpcount = 10
   c.onplat = True


来源: stackexchange

问:
Access rights for Azure DevOps Services pipeline
What are the best practices for accesses permission for programmers working in Azure DevOps? I would like the programmers to be able to use it, by for example having the possibility to create branches.

As far as I can understand by reading documents such as
https://learn.microsoft.com/en-us/azure/devops/organizations/security/set-git-tfvc-repository-permissions?view=azure-devops#git-repository

The only permission needed is a contributor? Is this correct or have I misunderstood the whole thing? The organization I’m working for have for example set the contributor to be a member of :
Build Administrators, Endpoint creators, Release Administrators

答:
thanks for you quick answer. Have digged into the documentation and repository permissions. I gave definitely som insight.  My concern is that I want a predefined setting for managing the code repository on a team level, thus would no want to give project permission to the programmers. In my azure devops setup I have only on organization with hundreds of teams.

As I understand it, the permission for the repos are set at the project level.  I would like to minimize the project level access since it gives to wide accesses in other cases and other teams. So my hope was that giving programmers contributor access would give the more or less all needed access for the repos out of the box. Such as:
1. Clone, fetch, contribute to pull requests, and explore the contents of a repository
2. Contribute to a repository, create branches, create tags, manage notes

Do not really understand why more access are needed. But could for example give the security control to the build admin role by granting the access to change permission. In this case the ones with build amdnin could adminitrate the security for its own team repos.

Any thoughs on this? Apologize if I have misunderstood you answer...

ContentLicense: CC BY-SA 4.0


问:
Applying jQuery UI CSS classes to elements manually causes the JS to misbehave
Greetings,

So I am trying to manually apply the jQuery CSS classes to my elements, so that users do not have a 'flash' as my javascript styles everything, and so users without JavaScript enabled get to see the purdyness.

So here is an example of a button. I have applied all the classes the .button() call would add, and structured my markup in the same way.

```<code><button id="my-button" type="submit" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary">
    <span class="ui-button-icon-primary ui-icon ui-icon-plus"></span>
    <span class="ui-button-text">Doit!</span>
</button>
</code>```

This looks great on its own! Of course it has no hover styles etc, but that's expected.

Then I apply my Javascript:

```<code>$('#my-button').button();
</code>```

jQuery UI doesn't seem to be aware of the existing classes/markup, and it turns my lovely button into this:

```<code><button id="my-button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary" type="submit" role="button" aria-disabled="false">
    <span class="ui-button-icon-primary ui-icon ui-icon-plus"></span>
    <span class="ui-button-text">
        <span class="ui-button-icon-primary ui-icon ui-icon-plus"></span>
        <span class="ui-button-text">Doit!</span>
    </span>
</button>
</code>```

So finally my question:

How can I apply the CSS classes manually/without javascript, yet still use the javascript functions to add the interaction functionality?

edit: ok so the markup generated by .button() isn't exactly what I posted there ^^ that was a .button( call with an icon parameter. The issue is the same though, with a simple .button() call it just wraps everything inside a <span class="ui-button-text

答:
You could first clear the button and then run the .button() to recreate your ui-button

```<code>$('#my-button').html(function(){return $(this).text();}).button({ icons: {primary:'ui-icon-plus'}});
</code>```

http://jsfiddle.net/MHaxd/1/

ContentLicense: CC BY-SA 3.0

Body:
Greetings,

So I am trying to manually apply the jQuery CSS classes to my elements, so that users do not have a 'flash' as my javascript styles everything, and so users without JavaScript enabled get to see the purdyness.

So here is an example of a button. I have applied all the classes the .button() call would add, and structured my markup in the same way.

<button id="my-button" type="submit" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary">

    Doit!
</button>

This looks great on its own! Of course it has no hover styles etc, but that's expected.

Then I apply my Javascript:

$('#my-button').button();

jQuery UI doesn't seem to be aware of the existing classes/markup, and it turns my lovely button into this:

<button id="my-button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary" type="submit" role="button" aria-disabled="false">

        Doit!

</button>

So finally my question:

How can I apply the CSS classes manually/without javascript, yet still use the javascript functions to add the interaction functionality?

edit: ok so the markup generated by .button() isn't exactly what I posted there ^^ that was a .button( call with an icon parameter. The issue is the same though, with a simple .button() call it just wraps everything inside a <span class="ui-button-text

Body:
You could first clear the button and then run the .button() to recreate your ui-button

$('#my-button').html(function(){return $(this).text();}).button({ icons: {primary:'ui-icon-plus'}});

http://jsfiddle.net/MHaxd/1/


问:
Sending email passing name in laravel
I'm trying to send an email to a user by entering his name and I look for the user's email with this name, but it does not work, the success message appears but in my email I receive nothing. what am I doing wrong?

if(User::where('name', '=', $destinatario)->exists()){
        $exists = DB::table('users')
        ->select('email')
        ->where('name', $destinatario)
        ->get();
        Mail::to($exists)->send(new TestEmail($remetente, $nome, $assunto, $exists, $mensagem));
        return back()->with('sucess', 'Message sent!');
    }else{
        return back()->with('error', 'User does not exist!');
    }
```

<p><strong>Mailable:</strong></p>

```public function __construct($remetente, $nome, $assunto, $destinatario, $data)
{
    $this->remetente = $remetente;
    $this->nome = $nome;
    $this->assunto = $assunto;
    $this->destinatario = $destinatario;
    $this->data = $data;
}

public function build()
{
    //$address = 'gabriel.jg04@gmail.com';
    $subject = 'E-mail de Usuário';
    $name = 'Juelito';

    return $this->view('emails.test',['texto'=>$this->data])
                ->from($this->remetente, $this->nome)
                ->replyTo($this->destinatario, $name)
                ->subject($this->assunto);
}
```

答:
Problem is with get(). get() returns collection of users.

But your mailable expect single user.

If you want to send mail to one person you could do like that:

```<code>$user = User::where('name', '=', $destinatario)->first();
if($user){
    Mail::to($user)->send(new TestEmail($remetente, $nome, $assunto, $user, $mensagem));
    return back()->with('sucess', 'Message sent!');
} else {
    return back()->with('error', 'User does not exist!');
}
</code>```

If you want to send mail to multiple persons you could do like that:

```<code>$users = User::where('name', '=', $destinatario)->get();
if($users->count()){
    foreach($users as $user){
        Mail::to($user)->send(new TestEmail($remetente, $nome, $assunto, $user, $mensagem));
    }
    return back()->with('sucess', 'Message sent!');
} else {
    return back()->with('error', 'User does not exist!');
}
</code>```

Mailable:

```<code>public function __construct($remetente, $nome, $assunto, $destinatario, $data)
{
    $this->remetente = $remetente;
    $this->nome = $nome;
    $this->assunto = $assunto;
    $this->destinatario = $destinatario;
    $this->data = $data;
}

public function build()
{
    return $this->view('emails.test', ['texto' => $this->data])
        ->from($this->remetente, $this->nome)
        ->replyTo($this->destinatario->email, $this->desctinario->name)
        ->subject($this->assunto);
}
</code>```

Title: Sending email passing name in laravel

Body:
I'm trying to send an email to a user by entering his name and I look for the user's email with this name, but it does not work, the success message appears but in my email I receive nothing. what am I doing wrong?

if(User::where('name', '=', $destinatario)->exists()){
        $exists = DB::table('users')
        ->select('email')
        ->where('name', $destinatario)
        ->get();
        Mail::to($exists)->send(new TestEmail($remetente, $nome, $assunto, $exists, $mensagem));
        return back()->with('sucess', 'Message sent!');
    }else{
        return back()->with('error', 'User does not exist!');
    }

Mailable:

public function __construct($remetente, $nome, $assunto, $destinatario, $data)
{
    $this->remetente = $remetente;
    $this->nome = $nome;
    $this->assunto = $assunto;
    $this->destinatario = $destinatario;
    $this->data = $data;
}

public function build()
{
    //$address = 'gabriel.jg04@gmail.com';
    $subject = 'E-mail de Usuário';
    $name = 'Juelito';

    return $this->view('emails.test',['texto'=>$this->data])
                ->from($this->remetente, $this->nome)
                ->replyTo($this->destinatario, $name)
                ->subject($this->assunto);
}

Body:
Problem is with get(). get() returns collection of users.

But your mailable expect single user.

If you want to send mail to one person you could do like that:

$user = User::where('name', '=', $destinatario)->first();
if($user){
    Mail::to($user)->send(new TestEmail($remetente, $nome, $assunto, $user, $mensagem));
    return back()->with('sucess', 'Message sent!');
} else {
    return back()->with('error', 'User does not exist!');
}

If you want to send mail to multiple persons you could do like that:

$users = User::where('name', '=', $destinatario)->get();
if($users->count()){
    foreach($users as $user){
        Mail::to($user)->send(new TestEmail($remetente, $nome, $assunto, $user, $mensagem));
    }
    return back()->with('sucess', 'Message sent!');
} else {
    return back()->with('error', 'User does not exist!');
}

Mailable:

public function __construct($remetente, $nome, $assunto, $destinatario, $data)
{
    $this->remetente = $remetente;
    $this->nome = $nome;
    $this->assunto = $assunto;
    $this->destinatario = $destinatario;
    $this->data = $data;
}

public function build()
{
    return $this->view('emails.test', ['texto' => $this->data])
        ->from($this->remetente, $this->nome)
        ->replyTo($this->destinatario->email, $this->desctinario->name)
        ->subject($this->assunto);
}


问:
How can I insert and join from three tables?
I have to combine two tables and replace a value within a table with values from a 3rd column.

the tables look like this
order

```<code>order   date    product_type    quantity    cost
1      1/1/19   tops             2          49.99
2      1/2/19   bottom           3          190
3      1/2/19   jewelry          1          30

product
order   date    product type    product name
1       1/1/19  tops            sophia tank
2       1/2/19  bottom          boyfriend jeans
3       1/2/19  jewelry         alex necklace

 type
ascin_product      ascin
tops               0081112
bottom             121412
jewelry            12412415
</code>```

The output should look like this

```<code>order   date    quantity    cost    product name    ascin
1      1/1/19     2        49.99    sophia tank     0001112
2      1/2/19     3        190      boyfriend jeans 121412
3      1/2/19     1        30       alex necklace   12412415
</code>```

[enter image description here][2]

I can join order and product easily, I just don't know how to join the 3rd table based off of ascin product and then replace product type with ascin in the overall table

```<code>select order, date, product_type,product_name from product
inner join on order
product.product_type=order.product type
inner join on type
product.product_type=order.product type=type=ascin_product
</code>```

I don't know how to replace product type in my table with ascin

答:
I would create a view that joins product and type as a common object to select out of that is always a "complete" set of columns for product.  You will probably end up using it in a variety of places and not have to join those tables over and over.

Then I would do what you have already done and just join on orders and the view to get what you are looking for.

Body:
I have to combine two tables and replace a value within a table with values from a 3rd column.

the tables look like this
order

order   date    product_type    quantity    cost
1      1/1/19   tops             2          49.99
2      1/2/19   bottom           3          190
3      1/2/19   jewelry          1          30

product
order   date    product type    product name
1       1/1/19  tops            sophia tank
2       1/2/19  bottom          boyfriend jeans
3       1/2/19  jewelry         alex necklace

 type
ascin_product      ascin
tops               0081112
bottom             121412
jewelry            12412415

The output should look like this

order   date    quantity    cost    product name    ascin
1      1/1/19     2        49.99    sophia tank     0001112
2      1/2/19     3        190      boyfriend jeans 121412
3      1/2/19     1        30       alex necklace   12412415

[enter image description here][2]

I can join order and product easily, I just don't know how to join the 3rd table based off of ascin product and then replace product type with ascin in the overall table

select order, date, product_type,product_name from product
inner join on order
product.product_type=order.product type
inner join on type
product.product_type=order.product type=type=ascin_product

I don't know how to replace product type in my table with ascin


问:
How to export SQL Database directly to blob storage programmatically
I need to programmatically backup/export a SQL Database (either in Azure, or a compatible-one on-prem) to Azure Storage, and restore it to another SQL Database.  I would like to use only NuGet packages for code dependencies, since I cannot guarantee that either the build or production servers will have the Azure SDK installed.  I cannot find any code examples for something that I assume would be a common action.  The closest I found was this:

https://blog.hompus.nl/2013/03/13/backup-your-azure-sql-database-to-blob-storage-using-code/

But, this code exports to a local bacpac file (requiring RoleEnvironment, an SDK-only object).  I would think there should be a way to directly export to Blob Storage, without the intermediary file.  One thought was to create a Stream, and then run:

```<code>services.ExportBacpac(stream, "dbnameToBackup")
</code>```

And then write the stream to storage; however a Memory Stream wouldn't work--this could be a massive database (100-200 GB).

What would be a better way to do this?

答:
You can use Microsoft.Azure.Management.Fluent to export your database to a .bacpac  file and store it in a blob. To do this, there are few things you need to do.

Create an AZAD (Azure Active Directory) application and Service Principal that can access resources. Follow this link for a comprehensive guide.

From the first step, you are going to need "Application (client) ID", "Client Secret", and "Tenant ID".

Install Microsoft.Azure.Management.Fluent NuGet packages, and import  Microsoft.Azure.Management.Fluent, Microsoft.Azure.Management.ResourceManager.Fluent, and Microsoft.Azure.Management.ResourceManager.Fluent.Authentication namespaces.

Replace the placeholders in the code snippets below with proper values for your usecase.

Enjoy!

```<code>    var principalClientID = "<Applicaiton (Client) ID>";
    var principalClientSecret = "<ClientSecret>";
    var principalTenantID = "<TenantID>";

    var sqlServerName = "<SQL Server Name> (without '.database.windows.net'>";
    var sqlServerResourceGroupName = "<SQL Server Resource Group>";

    var databaseName = "<Database Name>";
    var databaseLogin = "<Database Login>";
    var databasePassword = "<Database Password>";

    var storageResourceGroupName = "<Storage Resource Group>";
    var storageName = "<Storage Account>";
    var storageBlobName = "<Storage Blob Name>";

    var bacpacFileName = "myBackup.bacpac";

    var credentials = new AzureCredentialsFactory().FromServicePrincipal(principalClientID, principalClientSecret, principalTenantID, AzureEnvironment.AzureGlobalCloud);
    var azure = await Azure.Authenticate(credentials).WithDefaultSubscriptionAsync();

    var storageAccount = await azure.StorageAccounts.GetByResourceGroupAsync(storageResourceGroupName, storageName);

    var sqlServer = await azure.SqlServers.GetByResourceGroupAsync(sqlServerResourceGroupName, sqlServerName);
    var database = await sqlServer.Databases.GetAsync(databaseName);

    await database.ExportTo(storageAccount, storageBlobName, bacpacFileName)
            .WithSqlAdministratorLoginAndPassword(databaseLogin, databasePassword)
            .ExecuteAsync();
</code>```

Body:
I need to programmatically backup/export a SQL Database (either in Azure, or a compatible-one on-prem) to Azure Storage, and restore it to another SQL Database.  I would like to use only NuGet packages for code dependencies, since I cannot guarantee that either the build or production servers will have the Azure SDK installed.  I cannot find any code examples for something that I assume would be a common action.  The closest I found was this:

https://blog.hompus.nl/2013/03/13/backup-your-azure-sql-database-to-blob-storage-using-code/

But, this code exports to a local bacpac file (requiring RoleEnvironment, an SDK-only object).  I would think there should be a way to directly export to Blob Storage, without the intermediary file.  One thought was to create a Stream, and then run:

services.ExportBacpac(stream, "dbnameToBackup")

And then write the stream to storage; however a Memory Stream wouldn't work--this could be a massive database (100-200 GB).

What would be a better way to do this?

Body:
You can use Microsoft.Azure.Management.Fluent to export your database to a .bacpac  file and store it in a blob. To do this, there are few things you need to do.

Create an AZAD (Azure Active Directory) application and Service Principal that can access resources. Follow this link for a comprehensive guide.

From the first step, you are going to need "Application (client) ID", "Client Secret", and "Tenant ID".

Install Microsoft.Azure.Management.Fluent NuGet packages, and import  Microsoft.Azure.Management.Fluent, Microsoft.Azure.Management.ResourceManager.Fluent, and Microsoft.Azure.Management.ResourceManager.Fluent.Authentication namespaces.

Replace the placeholders in the code snippets below with proper values for your usecase.

Enjoy!

    var principalClientID = "<Applicaiton (Client) ID>";
    var principalClientSecret = "<ClientSecret>";
    var principalTenantID = "<TenantID>";

    var sqlServerName = "<SQL Server Name> (without '.database.windows.net'>";
    var sqlServerResourceGroupName = "<SQL Server Resource Group>";

    var databaseName = "<Database Name>";
    var databaseLogin = "<Database Login>";
    var databasePassword = "<Database Password>";

    var storageResourceGroupName = "<Storage Resource Group>";
    var storageName = "<Storage Account>";
    var storageBlobName = "<Storage Blob Name>";

    var bacpacFileName = "myBackup.bacpac";

    var credentials = new AzureCredentialsFactory().FromServicePrincipal(principalClientID, principalClientSecret, principalTenantID, AzureEnvironment.AzureGlobalCloud);
    var azure = await Azure.Authenticate(credentials).WithDefaultSubscriptionAsync();

    var storageAccount = await azure.StorageAccounts.GetByResourceGroupAsync(storageResourceGroupName, storageName);

    var sqlServer = await azure.SqlServers.GetByResourceGroupAsync(sqlServerResourceGroupName, sqlServerName);
    var database = await sqlServer.Databases.GetAsync(databaseName);

    await database.ExportTo(storageAccount, storageBlobName, bacpacFileName)
            .WithSqlAdministratorLoginAndPassword(databaseLogin, databasePassword)
            .ExecuteAsync();


问:
spring boot unable to generate tables in mysql database
I am trying to update the data base schema from defiend JpaEntities but spring boot is not able to generate the database tables.
Log file:

application.properties file:

```<code>spring.datasource.url= jdbc:mysql://localhost:3306/banque_db
spring.datasource.username= root
spring.datasource.password=
spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto= update
spring.jpa.show-sql= true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
</code>```

client entity class:

```<code> @Entity(name="client")
public class Client implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long code;
private String name;
private String email;
@OneToMany(mappedBy = "compte")
private Collection<Compte> comptes;
// + getters and setters
</code>```

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
</code>```

http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

        org.springframework.boot
        spring-boot-starter-parent
        2.1.0.RELEASE

    com.Tuto

```<code><artifactId>MaBanque</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>MaBanque</name>
<description>Demo project for Spring Boot</description>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

答:
You have to set spring.jpa.hibernate.ddl-auto = create for db creation or create-drop

See docs for more details.

Body:
I am trying to update the data base schema from defiend JpaEntities but spring boot is not able to generate the database tables.
Log file:

application.properties file:

spring.datasource.url= jdbc:mysql://localhost:3306/banque_db
spring.datasource.username= root
spring.datasource.password=
spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto= update
spring.jpa.show-sql= true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

client entity class:

 @Entity(name="client")
public class Client implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long code;
private String name;
private String email;
@OneToMany(mappedBy = "compte")
private Collection<Compte> comptes;
// + getters and setters

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

        org.springframework.boot
        spring-boot-starter-parent
        2.1.0.RELEASE

    com.Tuto

<artifactId>MaBanque</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>MaBanque</name>
<description>Demo project for Spring Boot</description>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>


问:
Deno launch from VSCode with rebuild
I am able to run deno from command line (deno vs ts-node : what's the difference). I would like to run it from VS code. I also tried to compile it first (by deno run) and run from vs code on result.
I made repo to show how to run it, but it runs two times, first time to compile source, second to run in vscode on compiled source. I would like to just run deno from vs code directly or compile ts file with deno before run them.</p>

答:
To compile TS files first without running the code, you could try deno fetch <filename>. This command downloads all the remote dependencies, compiling the code, but not evaluating the code.

Not clear what does "run deno from VSCode directly" mean, but you might visit vscode-deno and file a feature request.

Title: Deno launch from VSCode with rebuild


问:
Finding an exact match in a string with difference sizes and with similar matches
I have to parse through a file (which I know how to do), however, I need to search for specific patterns in a string and this is where I'm getting a bit confused.

Let's say we have the following strings:

```<code>GEO1D1JXUQ2LSO

GOE22D2OKDLALKCDSI

EO212D0FM2KDLA

LAFD21D1FM2KDF3BLA
</code>```

What are known about the strings are the prefix (GEO, GOE, EO,LAFD) and that there is 1, 2 or 3 numbers after the Prefix then the letter D, As shown in the example.

I have the prefixes beforehand, but that's it. How can I search through every string and identify which group it belongs to?

Note: there is some information in the string (like the number after the D) that I need as well but I'm only focusing on the how to identify which group it's part of so I can then grab more information of that group.

I am stuck because there are some prefixes that can exist within prefixes, like EO in GEO.

答:
The simplest way to check for a prefix is just string.startswith().

If you have prefixes that are prefixes of other prefixes (e.g. AOIO and AOI), then you just need to be careful to define the order of your checks such that longer prefixes are checked first.

Alternatively, you can use a regex to extract the prefix, and the other information you need. An example:

```<code>^([A-Z]*)[0-9]+D([0-9]+)
</code>```

This would give you two group captures, the first being the prefix and the second being the number after the D. See details here: https://regex101.com/r/GxSZSI/2

Example usage in Python:

```<code>>>> import re
>>> s = 'GOE22D2OKDLALKCDSI'
>>> m = re.match('^([A-Z]*)[0-9]+D([0-9]+)', s)
>>> m.groups()
('GOE', '2')
</code>```

Body:
I have to parse through a file (which I know how to do), however, I need to search for specific patterns in a string and this is where I'm getting a bit confused.

Let's say we have the following strings:

GEO1D1JXUQ2LSO

GOE22D2OKDLALKCDSI

EO212D0FM2KDLA

LAFD21D1FM2KDF3BLA

What are known about the strings are the prefix (GEO, GOE, EO,LAFD) and that there is 1, 2 or 3 numbers after the Prefix then the letter D, As shown in the example.

I have the prefixes beforehand, but that's it. How can I search through every string and identify which group it belongs to?

Note: there is some information in the string (like the number after the D) that I need as well but I'm only focusing on the how to identify which group it's part of so I can then grab more information of that group.

I am stuck because there are some prefixes that can exist within prefixes, like EO in GEO.

Body:
The simplest way to check for a prefix is just string.startswith().

If you have prefixes that are prefixes of other prefixes (e.g. AOIO and AOI), then you just need to be careful to define the order of your checks such that longer prefixes are checked first.

Alternatively, you can use a regex to extract the prefix, and the other information you need. An example:

^([A-Z]*)[0-9]+D([0-9]+)

This would give you two group captures, the first being the prefix and the second being the number after the D. See details here: https://regex101.com/r/GxSZSI/2

Example usage in Python:

>>> import re
>>> s = 'GOE22D2OKDLALKCDSI'
>>> m = re.match('^([A-Z]*)[0-9]+D([0-9]+)', s)
>>> m.groups()
('GOE', '2')


问:
How do I write a C-based module to process python dictionaries?
I recently need to write a module for a group chat bot that responds to every single message and find if there is anything that matches the keywords. The robot itself is based on Python and provides python APIs. Due to the need of business I may want to write this procedure in C language, so like this:

import my_c_module

DICTIONARY = {} # nested dictionary containing keywords, replies, modes, group context etc

async def respond_to_mesg():
    ....
    invokes the c function
    ....
```

the c function needs to process the message and dictionary and see matches.

The main part that confuses me is that I do not know how to get C to work with this dictionary. What kind of data structure needs to be used here?

答:
First you need to generate a shared library for the c file. Let's say the file name is library.c which has the function myfunction.

```<code>int myFunction(int num)
{
    if (num == 0)

        // if number is 0, do not perform any operation.
        return 0;
    else
        // if number is power of 2, return 1 else return 0

    num & (num - 1) == 0 ? return 1 : return 0
}
</code>```

You can compile the above c file library.c using the following command.

```<code>cc -fPIC -shared -o dicmodule.so library.c
</code>```

Above statement will generate a shared library with name dicmodule.so.  Now, let’s see how to make use of it in python. In python, we have one library called ctypes. Using this library we can use C function in python.

```<code>import ctypes
NUM = 16
# dicmodule loaded to the python file
# using fun.myFunction(),
# C function can be accessed
# but type of argument is the problem.

fun = ctype.CDLL(dicmodule.so)
# Now whenever argument
# will be passed to the function
# ctypes will check it.

fun.myFunction.argtypes(ctypes.c_int)

# now we can call this
# function using instant (fun)
# returnValue is the value
# return by function written in C
# code
returnVale = fun.myFunction(NUM)
</code>```

Hope this is clear.you need to modify this according to your needs.

Body:
I recently need to write a module for a group chat bot that responds to every single message and find if there is anything that matches the keywords. The robot itself is based on Python and provides python APIs. Due to the need of business I may want to write this procedure in C language, so like this:

import my_c_module

DICTIONARY = {} # nested dictionary containing keywords, replies, modes, group context etc

async def respond_to_mesg():
    ....
    invokes the c function
    ....

the c function needs to process the message and dictionary and see matches.

The main part that confuses me is that I do not know how to get C to work with this dictionary. What kind of data structure needs to be used here?

Body:
First you need to generate a shared library for the c file. Let's say the file name is library.c which has the function myfunction.

int myFunction(int num)
{
    if (num == 0)

        // if number is 0, do not perform any operation.
        return 0;
    else
        // if number is power of 2, return 1 else return 0

    num & (num - 1) == 0 ? return 1 : return 0
}

You can compile the above c file library.c using the following command.

cc -fPIC -shared -o dicmodule.so library.c

Above statement will generate a shared library with name dicmodule.so.  Now, let’s see how to make use of it in python. In python, we have one library called ctypes. Using this library we can use C function in python.

import ctypes
NUM = 16
# dicmodule loaded to the python file
# using fun.myFunction(),
# C function can be accessed
# but type of argument is the problem.

fun = ctype.CDLL(dicmodule.so)
# Now whenever argument
# will be passed to the function
# ctypes will check it.

fun.myFunction.argtypes(ctypes.c_int)

# now we can call this
# function using instant (fun)
# returnValue is the value
# return by function written in C
# code
returnVale = fun.myFunction(NUM)

Hope this is clear.you need to modify this according to your needs.


问:
How do you tell that your unit tests are correct?
I've only done minor unit testing at various points in my career.  Whenever I start diving into it again, it always troubles me how to prove that my tests are correct.  How can I tell that there isn't a bug in my unit test?  Usually I end up running the app, proving it works, then using the unit test as a sort of regression test.  What is the recommended approach and/or what is the approach you take to this problem?

Edit: I also realize that you could write small, granular unit tests that would be easy to understand. However, if you assume that small, granular code is flawless and bulletproof, you could just write small, granular programs and not need unit testing.

Edit2: For the arguments "unit testing is for making sure your changes don't break anything" and "this will only happen if the test has the exact same flaw as the code", what if the test overfits? It's possible to pass both good and bad code with a bad test.  My main question is what good is unit testing since if your tests can be flawed you can't really improve your confidence in your code, can't really prove your refactoring worked, and can't really prove that you met the specification?

答:
First let me start by saying that unit testing is NOT only about testing. It is more about the design of the application. To see this in action you should put a camera with your display and record your coding while writing unit testing. You will realize that you are making a lot of design decisions when writing unit tests.

How to know if my unit tests are good?

You cannot test the logical part period! If your code is saying that 2+2 = 5 and your test is making sure that 2+2 = 5 then for you 2+2 is 5. To write good unit tests you MUST have good understanding of the domain you are working with. When you know what you are trying to accomplish you will write good tests and good code to accomplish it. If you have many unit tests and your assumptions are wrong then sooner or later you will find out your mistakes.

OwnerDisplayName: Jake

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Abie

OwnerDisplayName: azamsharp


问:
How to add part of time in Android
I have a code returning me a string (HH:mm).

```<code>SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        java.util.Date dateObj;
        try {
            dateObj = curFormater.parse(start);

            SimpleDateFormat postFormater = new SimpleDateFormat("HH:mm");
            String newDateStr = postFormater.format(dateObj);
            startView.setText(newDateStr);
            Emission_start = newDateStr;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            Log.d(" * Error", e.toString());
        }
</code>```

It works great... But right now I would like to:

add x (is dynamically provided) minutes (x = from 5 to 1000 minutes) and transform to time (example time:3:45, add 25 minutes, transform to time 4:10)

Get current time and calculate difference between current time and time from step 1 (4:10)

Get time difference (from step 2) in minutes!

Thanks for your help!

答:
use Calendar

Calendar calInstance = new GregorianCalendar();
calInstance.setTime(dateObj);

Then add any fragment you want, for minutes do

```<code>calInstance.add(Calendar.MINUTE, XX)
</code>```

To, transform use your formatter

```<code>postFormatter.format(calInstance.getTime());
</code>```

is trivial

Diff in minutes can be calculated easily as well

long diffInMins = (currTimeInMillis - calInstance.getTimeInMillis())/(1000 * 60);

Title: How to add part of time in Android

Body:
I have a code returning me a string (HH:mm).

SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        java.util.Date dateObj;
        try {
            dateObj = curFormater.parse(start);

            SimpleDateFormat postFormater = new SimpleDateFormat("HH:mm");
            String newDateStr = postFormater.format(dateObj);
            startView.setText(newDateStr);
            Emission_start = newDateStr;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            Log.d(" * Error", e.toString());
        }

It works great... But right now I would like to:

add x (is dynamically provided) minutes (x = from 5 to 1000 minutes) and transform to time (example time:3:45, add 25 minutes, transform to time 4:10)

Get current time and calculate difference between current time and time from step 1 (4:10)

Get time difference (from step 2) in minutes!

Thanks for your help!

Body:
use Calendar

Calendar calInstance = new GregorianCalendar();
calInstance.setTime(dateObj);

Then add any fragment you want, for minutes do

calInstance.add(Calendar.MINUTE, XX)

To, transform use your formatter

postFormatter.format(calInstance.getTime());

is trivial

Diff in minutes can be calculated easily as well

long diffInMins = (currTimeInMillis - calInstance.getTimeInMillis())/(1000 * 60);


问:
Create profile at the same time that the user is created
I'm trying to create a profile in the DRF create function in serializer, but when save User model the next exception is triggered

ValueError: "<Usuario: Some Name>" needs to have a value for field "id" before this many-to-many relationship can be used.

This is my configuration background over python 3
Django == 1.11
DRF == Django rest framework

```<code>class CustomUserManager(BaseUserManager):
    def _create_user(self, firstname, lastname, password, **extra_fields):
        now = timezone.now()
        if not firstname:
            raise ValueError(u'The firstname is required.')

        user = self.model(
            firstname=firstname,
            lastname=lastname,
            last_login=now,
            **extra_fields
        )
        user.set_password(password)
        user.save()

        return user

class Usuario(
    AbstractBaseUser, PermissionsMixin,
    TimeStampedModel, SoftDeletableModel
):

    objects = CustomUserManager()

class Profile(models.Model):
    user = models.OneToOneField(Usuario, related_name='profile', on_delete=models.CASCADE)

class UserSerializer(serializers.ModelSerializer):
    profile = PerfilSerializer(read_only=True)

    def create(self, validate_data):
        user_data = validate_data
        profile_data = validate_data.pop('profile')

        usr = Usuario(**user_data)
        usr.save()

        profl = Profile(**profile_data)
        profl.save()
        profl.user.set(usr)

        return usr
</code>```

I want to get the model with the user instance and the profile created

答:
You are on the right track, just tweak your create on the profile serializer. Try this:

```<code>class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile

    def create(self, validated_data):
        user = User.objects.create(**validated_data)
        Profile.objects.create(user=user)
        return user
</code>```

Body:
I'm trying to create a profile in the DRF create function in serializer, but when save User model the next exception is triggered

ValueError: "<Usuario: Some Name>" needs to have a value for field "id" before this many-to-many relationship can be used.

This is my configuration background over python 3
Django == 1.11
DRF == Django rest framework

class CustomUserManager(BaseUserManager):
    def _create_user(self, firstname, lastname, password, **extra_fields):
        now = timezone.now()
        if not firstname:
            raise ValueError(u'The firstname is required.')

        user = self.model(
            firstname=firstname,
            lastname=lastname,
            last_login=now,
            **extra_fields
        )
        user.set_password(password)
        user.save()

        return user

class Usuario(
    AbstractBaseUser, PermissionsMixin,
    TimeStampedModel, SoftDeletableModel
):

    objects = CustomUserManager()

class Profile(models.Model):
    user = models.OneToOneField(Usuario, related_name='profile', on_delete=models.CASCADE)

class UserSerializer(serializers.ModelSerializer):
    profile = PerfilSerializer(read_only=True)

    def create(self, validate_data):
        user_data = validate_data
        profile_data = validate_data.pop('profile')

        usr = Usuario(**user_data)
        usr.save()

        profl = Profile(**profile_data)
        profl.save()
        profl.user.set(usr)

        return usr

I want to get the model with the user instance and the profile created

Body:
You are on the right track, just tweak your create on the profile serializer. Try this:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile

    def create(self, validated_data):
        user = User.objects.create(**validated_data)
        Profile.objects.create(user=user)
        return user


问:
How to edit a table field value in PHPMyAdmin
In PHPMyAdmin, I am looking at a table, but I see no way to edit a table entry (not sure of the correct terminology sorry).

The value I want to edit is DisableAdminPWReset (to 0).

How do I do this? There are no methods of editing this value that I can see. I am a SQL newb too.

答: I've experienced the same problem now. Following Dave's instructions on an answer above I was going to try to put an index on the table, but I've realized that normalized tables usually have a primary key configured. It was enough to enable editing table lines. I've just entered the table structure tab and clicked at my table primary key "primary" button/link to turn it formally into the primary key and the "problem" was solved.</p>


问:
How can i delete a partition fuction on sql
So i got and ETL that stores 3 years '17 (corrupt), '18(corrupt), '19:

STG_tables: import Data from 3 differents DB and Export it to

DWH_tables: This is the Relational fase where all the historical information is stored. Here only the normalization and parameterization of the tables and the fields are carried out to adapt them to the developed logical model, but no business rules are applied.

DIM_tables: Finally, in the Dimensional Fase, the business rules are applied and the tables and indexes are optimized for the queries, since this is where the analytical tools will attack.

I got 2 types of Reloads:

Daily Reload: This Job is responsible for executing the SSIS packages necessary to perform the incremental daily load of the Data Warehouse. it only loads the last partition of the large tables (corresponding to the current year) in the dimensional Fase.

Full Reload: Loads full 3 years (this one is not working)

This wasn't done by me and i have 0 technical documentation, so im just trying to figure out how this works, my thinking is that once i get to do this full reload, the data will restore.

Im getting error on STG_fase:

DROP TABLE DWH_PROD.DWH_XX;
  DROP TABLE ... ':' The partition function 'pfPetitions' is being used in one or more partition schemes.'. Possible reasons for the error: problems with the query, the property 'ResultSet' was not set correctly, parameters not set correctly or connection poorly established.

i dont know how to drop this partition so i can create it again
and cant find 'ResultSet' property, please help

```<code>USE DB;
GO

DROP TABLE DWH_PROD.DWH_ALBARANES_TARIFA;
DROP TABLE DWH_PROD.DWH_PETICIONES;
DROP TABLE DWH_PROD.DWH_SOLICITUDES;
DROP TABLE DWH_PROD.DWH_RESULTADOS;
DROP TABLE DWH_PROD.DWH_INCIDENCIAS;

-------i delete code so the text is not so big------
Here there are all the creation of the drop tables above

IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = N'DWH_ALBARANES_TARIFA')
    CREATE TABLE DWH_PROD.DWH_ALBARANES_TARIFA (
    );

IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = N'DWH_INCIDENCIAS')
    CREATE TABLE DWH_PROD.DWH_INCIDENCIAS (
    );

IF EXISTS (SELECT * FROM sys.partition_functions WHERE name = N'pfPeticiones')
    DROP PARTITION FUNCTION pfPeticiones;

CREATE PARTITION FUNCTION pfPeticiones (DATE)
AS RANGE RIGHT FOR VALUES
('2017-01-01', '2018-01-01', '2019-01-01');

IF EXISTS (SELECT * FROM sys.partition_schemes WHERE name = N'psPeticiones')
    DROP PARTITION SCHEME psPeticiones;

CREATE PARTITION SCHEME psPeticiones
AS PARTITION pfPeticiones
ALL TO ([Primary]);

IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = N'DWH_PETICIONES')
    CREATE TABLE DWH_PROD.DWH_PETICIONES (
    ) ON psPeticiones(FEC_PETICION);

IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = N'DWH_SOLICITUDES')
    CREATE TABLE DWH_PROD.DWH_SOLICITUDES (
    ) ON psPeticiones(FEC_PETICION);

IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = N'DWH_RESULTADOS')
    CREATE TABLE DWH_PROD.DWH_RESULTADOS (
    ) ON psPeticiones(FEC_PETICION);
</code>```

答:
You need to perform a few actions in order to do delete a partitioning function:

Delete or move (i.e. if you have a heap, create a clustered index on PRIMARY) all tables that use the partitioning schema.

Delete the partitioning schema.

Delete the partitioning function.

Body:
So i got and ETL that stores 3 years '17 (corrupt), '18(corrupt), '19:

STG_tables: import Data from 3 differents DB and Export it to

DWH_tables: This is the Relational fase where all the historical information is stored. Here only the normalization and parameterization of the tables and the fields are carried out to adapt them to the developed logical model, but no business rules are applied.

DIM_tables: Finally, in the Dimensional Fase, the business rules are applied and the tables and indexes are optimized for the queries, since this is where the analytical tools will attack.

I got 2 types of Reloads:

Daily Reload: This Job is responsible for executing the SSIS packages necessary to perform the incremental daily load of the Data Warehouse. it only loads the last partition of the large tables (corresponding to the current year) in the dimensional Fase.

Full Reload: Loads full 3 years (this one is not working)

This wasn't done by me and i have 0 technical documentation, so im just trying to figure out how this works, my thinking is that once i get to do this full reload, the data will restore.

Im getting error on STG_fase:

DROP TABLE DWH_PROD.DWH_XX;
  DROP TABLE ... ':' The partition function 'pfPetitions' is being used in one or more partition schemes.'. Possible reasons for the error: problems with the query, the property 'ResultSet' was not set correctly, parameters not set correctly or connection poorly established.

i dont know how to drop this partition so i can create it again
and cant find 'ResultSet' property, please help

USE DB;
GO

DROP TABLE DWH_PROD.DWH_ALBARANES_TARIFA;
DROP TABLE DWH_PROD.DWH_PETICIONES;
DROP TABLE DWH_PROD.DWH_SOLICITUDES;
DROP TABLE DWH_PROD.DWH_RESULTADOS;
DROP TABLE DWH_PROD.DWH_INCIDENCIAS;

-------i delete code so the text is not so big------
Here there are all the creation of the drop tables above

IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = N'DWH_ALBARANES_TARIFA')
    CREATE TABLE DWH_PROD.DWH_ALBARANES_TARIFA (
    );

IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = N'DWH_INCIDENCIAS')
    CREATE TABLE DWH_PROD.DWH_INCIDENCIAS (
    );

IF EXISTS (SELECT * FROM sys.partition_functions WHERE name = N'pfPeticiones')
    DROP PARTITION FUNCTION pfPeticiones;

CREATE PARTITION FUNCTION pfPeticiones (DATE)
AS RANGE RIGHT FOR VALUES
('2017-01-01', '2018-01-01', '2019-01-01');

IF EXISTS (SELECT * FROM sys.partition_schemes WHERE name = N'psPeticiones')
    DROP PARTITION SCHEME psPeticiones;

CREATE PARTITION SCHEME psPeticiones
AS PARTITION pfPeticiones
ALL TO ([Primary]);

IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = N'DWH_PETICIONES')
    CREATE TABLE DWH_PROD.DWH_PETICIONES (
    ) ON psPeticiones(FEC_PETICION);

IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = N'DWH_SOLICITUDES')
    CREATE TABLE DWH_PROD.DWH_SOLICITUDES (
    ) ON psPeticiones(FEC_PETICION);

IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = N'DWH_RESULTADOS')
    CREATE TABLE DWH_PROD.DWH_RESULTADOS (
    ) ON psPeticiones(FEC_PETICION);


问:
How to detect when an item is removed from an Primeng autocomplete | Angular 6
I am using a dynamic primeng autocomplete to let user select multiple items, but i am stuck on how to detect when user pressed the x to remove the item from the list. i know i can use the [(ngModel)] to detect value change, but my question is:

 Is there a way like a callback function to detect the removed item when the x is pressed ?

as defined:

```<code><p-autoComplete
            #autoCompleteObject
            [(ngModel)]="value" [suggestions]="filteredOptions"
            (completeMethod)="filterObjects($event)"
            [multiple]="true"
            [dropdown]="false"
            (onSelect)="emitData()"
            (onUnselect)="emitData()"
            placeholder="{{ label | i18n}}"
    >
        <ng-template let-item pTemplate="selectedItem">
            <div class="selected-item">
                <span >{{item[labelProperty]}}</span>
            </div>
        </ng-template>
        <ng-template let-item pTemplate="item">
            <div class="flex ">
                <span >{{item[labelProperty] | i18n}}</span>
            </div>
        </ng-template>

    </p-autoComplete>
</code>```

as used

```<code> <my-autocomplete-multiple [(ngModel)]="entryItems" label='type_here' [options]=allItems
                                          ngDefaultControl></my-autocomplete-multiple>
</code>```

As the photo below, i circled the x with red color

答:
According to the documentation, the onUnselect() callback method is invoked when a selected value is removed. The $event parameter is the unselected value in multiple mode.

Instead of binding emitData() to both the onSelect() and onUnselect() methods, I recommend using a separate method for each, like so:

```<code>(onSelect)="emitAddData($event)"
(onUnselect)="emitRemoveData($event)"
</code>```

Then the one that's bound to onUnselect() can handle whatever you need to do when an item is removed.

Body:
I am using a dynamic primeng autocomplete to let user select multiple items, but i am stuck on how to detect when user pressed the x to remove the item from the list. i know i can use the [(ngModel)] to detect value change, but my question is:

 Is there a way like a callback function to detect the removed item when the x is pressed ?

as defined:

        <ng-template let-item pTemplate="selectedItem">

                {{item[labelProperty]}}

        </ng-template>
        <ng-template let-item pTemplate="item">

                {{item[labelProperty] | i18n}}

        </ng-template>

as used

 <my-autocomplete-multiple [(ngModel)]="entryItems" label='type_here' [options]=allItems
                                          ngDefaultControl></my-autocomplete-multiple>

As the photo below, i circled the x with red color

Body:
According to the documentation, the onUnselect() callback method is invoked when a selected value is removed. The $event parameter is the unselected value in multiple mode.

Instead of binding emitData() to both the onSelect() and onUnselect() methods, I recommend using a separate method for each, like so:

(onSelect)="emitAddData($event)"
(onUnselect)="emitRemoveData($event)"

Then the one that's bound to onUnselect() can handle whatever you need to do when an item is removed.


问:
Use Puppeteer to Generate a PDF on Client Side
I'm struggling to get Puppeteer to download a file within the browser. I currently have it saving the file locally on Cloud9, but I want to click a download PDF button and have it download in Chrome.

I've tried saving the page.pdf to a variable and that hasn't worked. I've also tried opening the locally saved file, but I can't get that to work either.

```<code>var express = require("express");
var puppeteer = require("puppeteer");

module.exports = function pdf(url, req) {(async () => {
      var browser = await puppeteer.launch();
      var page = await browser.newPage();
      await page.goto('https://node-and-mysql-mbegg.c9users.io/clients/'+req.params.id+'/reports/monthlyreport/'+req.params.marketplace+'/'+req.params.month, {waitUntil: 'networkidle2'});
      await page.pdf({path: 'public/temp/Performance Report -'+req.params.month+'.pdf', format: 'A4', landscape: true, printBackground: true});

      await browser.close();
    })();
}

///Print PDF route
router.get("/clients/:id/reports/monthlyreport/:marketplace/:month/pdf", function(req, res) {
    var url = "/clients/"+req.params.id+"/reports/monthlyreport/"+req.params.marketplace+"/"+req.params.month
    pdf(url, req);
    res.contentType("application/pdf");
    res.send(pdf);;
});
</code>```

I know that the res.send(pdf) requires the page.pdf() to be saved to a variable and returned. I just didn't remove that from the route.

What happens when I save page.pdf() to a variable is I just get a blank file - not PDF - and it appears just to be a blank buffer or something. I don't know what I'm doing wrong to not get the file downloading in the chrome browser.

答:
While within the pdf function you seem to be waiting for each of the puppeteer operations, you are actually not waiting for the call to pdf function in your express route. Additionally, the pdf function right now doesn't return anything! You would need to make following modifications to your program:

The pdf function should return the filename to which the generated PDF was saved. While you are at it might as well get rid of the IIFE, its not required, simply declare the outer function as async.

In the route function, program should wait for the filename to be returned form the pdf(...) call. This can done by using Promise, or await. If await is preferred, the outer function should be marked as async.

The sendFile function provided by express on response objects should be used to send the generated PDF file to client. Please note that res.sendFile expects the absolute path to the file.

Following is a modified version of your program which implements these.

```<code>const express = require("express");
const puppeteer = require("puppeteer");
const path = require('path');

module.exports = async function pdf(url, req) {
    const filename = `public/temp/Performance Report -${req.params.month}.pdf`;
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.goto('https://node-and-mysql-mbegg.c9users.io/clients/'+req.params.id+'/reports/monthlyreport/'+req.params.marketplace+'/'+req.params.month, {waitUntil: 'networkidle2'});
    await page.pdf({path: filename, format: 'A4', landscape: true, printBackground: true});

    await browser.close();
    return filename;
}

///Print PDF route
router.get("/clients/:id/reports/monthlyreport/:marketplace/:month/pdf", async function(req, res) {
    var url = "/clients/"+req.params.id+"/reports/monthlyreport/"+req.params.marketplace+"/"+req.params.month

    const filename = await pdf(url, req);
    res.contentType("application/pdf");
    res.sendFile(path.join(__dirname, filename)); // if 'public/temp/...' path is not relative to cur dir, make relevant change here.
});
</code>```

Body:
I'm struggling to get Puppeteer to download a file within the browser. I currently have it saving the file locally on Cloud9, but I want to click a download PDF button and have it download in Chrome.

I've tried saving the page.pdf to a variable and that hasn't worked. I've also tried opening the locally saved file, but I can't get that to work either.

var express = require("express");
var puppeteer = require("puppeteer");

module.exports = function pdf(url, req) {(async () => {
      var browser = await puppeteer.launch();
      var page = await browser.newPage();
      await page.goto('https://node-and-mysql-mbegg.c9users.io/clients/'+req.params.id+'/reports/monthlyreport/'+req.params.marketplace+'/'+req.params.month, {waitUntil: 'networkidle2'});
      await page.pdf({path: 'public/temp/Performance Report -'+req.params.month+'.pdf', format: 'A4', landscape: true, printBackground: true});

      await browser.close();
    })();
}

///Print PDF route
router.get("/clients/:id/reports/monthlyreport/:marketplace/:month/pdf", function(req, res) {
    var url = "/clients/"+req.params.id+"/reports/monthlyreport/"+req.params.marketplace+"/"+req.params.month
    pdf(url, req);
    res.contentType("application/pdf");
    res.send(pdf);;
});

I know that the res.send(pdf) requires the page.pdf() to be saved to a variable and returned. I just didn't remove that from the route.

What happens when I save page.pdf() to a variable is I just get a blank file - not PDF - and it appears just to be a blank buffer or something. I don't know what I'm doing wrong to not get the file downloading in the chrome browser.

Body:
While within the pdf function you seem to be waiting for each of the puppeteer operations, you are actually not waiting for the call to pdf function in your express route. Additionally, the pdf function right now doesn't return anything! You would need to make following modifications to your program:

The pdf function should return the filename to which the generated PDF was saved. While you are at it might as well get rid of the IIFE, its not required, simply declare the outer function as async.

In the route function, program should wait for the filename to be returned form the pdf(...) call. This can done by using Promise, or await. If await is preferred, the outer function should be marked as async.

The sendFile function provided by express on response objects should be used to send the generated PDF file to client. Please note that res.sendFile expects the absolute path to the file.

Following is a modified version of your program which implements these.

const express = require("express");
const puppeteer = require("puppeteer");
const path = require('path');

module.exports = async function pdf(url, req) {
    const filename = `public/temp/Performance Report -${req.params.month}.pdf`;
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.goto('https://node-and-mysql-mbegg.c9users.io/clients/'+req.params.id+'/reports/monthlyreport/'+req.params.marketplace+'/'+req.params.month, {waitUntil: 'networkidle2'});
    await page.pdf({path: filename, format: 'A4', landscape: true, printBackground: true});

    await browser.close();
    return filename;
}

///Print PDF route
router.get("/clients/:id/reports/monthlyreport/:marketplace/:month/pdf", async function(req, res) {
    var url = "/clients/"+req.params.id+"/reports/monthlyreport/"+req.params.marketplace+"/"+req.params.month

    const filename = await pdf(url, req);
    res.contentType("application/pdf");
    res.sendFile(path.join(__dirname, filename)); // if 'public/temp/...' path is not relative to cur dir, make relevant change here.
});


问:
Access object in AppDelegate from ViewController
In AppDelegate.swift I've declared an NSStatusBar object like this:

```<code>var statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
statusItem.button?.title = "chess"
statusItem.button?.target = self
statusItem.button?.action = #selector(showSettings)
</code>```

and works fine, but I want to change the title in the viewController.swift

I trying this (In view controller):

```<code>var appd = AppDelegate()
appd.statusItem.button?.title = "ELO: \(parsing2.chess_daily.last.rating)"
</code>```

But the title not change... how can I do this???

答:
Get the delegate object from NSApplication, the default initializer AppDelegate() creates a new unrelated instance.

```<code>let appDelegate = NSApp.delegate as! AppDelegate
appDelegate.statusItem.button?.title = "ELO: \(parsing2.chess_daily.last.rating)"
</code>```

Body:
In AppDelegate.swift I've declared an NSStatusBar object like this:

var statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
statusItem.button?.title = "chess"
statusItem.button?.target = self
statusItem.button?.action = #selector(showSettings)

and works fine, but I want to change the title in the viewController.swift

I trying this (In view controller):

var appd = AppDelegate()
appd.statusItem.button?.title = "ELO: \(parsing2.chess_daily.last.rating)"

But the title not change... how can I do this???

Body:
Get the delegate object from NSApplication, the default initializer AppDelegate() creates a new unrelated instance.

let appDelegate = NSApp.delegate as! AppDelegate
appDelegate.statusItem.button?.title = "ELO: \(parsing2.chess_daily.last.rating)"


问:
How to show a json field from a blade view and edit multiple file uploads from json?
I'm creating a CRUD project with file uploads using json_encode for uploading the file to a database. How do I show the file that I've uploaded from the blade view? Is it possible to delete it from the view?

```<code>    $sid = Sid::find($id);
    $data = [];

    if($request->file('file_uploads'))
    {
        foreach($request->file('file_uploads') as $file)
        {
            $name = $file->getClientOriginalName();
            $path = 'public/file/'.$sid->employee_name;
            $file->move($path, $name);
            $data[] = $name;
        }
    }

        $sid->employee_sid          = $request->employee_sid;
        $sid->employee_npk          = $request->employee_npk;
        $sid->employee_name         = $request->employee_name;
        $sid->file_uploads          = count($data)? json_encode(array_merge(json_decode($sid->file_uploads, true),$data)): $sid->file_uploads;
        $sid->save();
</code>```

I want to show the file/image that I uploaded before in the blade view and to know if it is possible to delete it from view-blade.

This is my upload files from the edit form.

```<code>      <div class="col-md-12">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label for="UploadFileSertifUnit">Upload Sertifikat Unit</label>
                                <input type="file" id="UploadFileSertifUnit" name="file_uploads[]" multiple>
                                <p>Ukuran Max : 2 MB</p>
                            </div>
                        </div>
                    </div>
                </div>
</code>```

I want to show the file above this code.

答:
Can try use this lib.

"DropzoneJS is an open source library that provides drag’n’drop file uploads with image previews."

https://www.dropzonejs.com/

Body:
I'm creating a CRUD project with file uploads using json_encode for uploading the file to a database. How do I show the file that I've uploaded from the blade view? Is it possible to delete it from the view?

    $sid = Sid::find($id);
    $data = [];

    if($request->file('file_uploads'))
    {
        foreach($request->file('file_uploads') as $file)
        {
            $name = $file->getClientOriginalName();
            $path = 'public/file/'.$sid->employee_name;
            $file->move($path, $name);
            $data[] = $name;
        }
    }

        $sid->employee_sid          = $request->employee_sid;
        $sid->employee_npk          = $request->employee_npk;
        $sid->employee_name         = $request->employee_name;
        $sid->file_uploads          = count($data)? json_encode(array_merge(json_decode($sid->file_uploads, true),$data)): $sid->file_uploads;
        $sid->save();

I want to show the file/image that I uploaded before in the blade view and to know if it is possible to delete it from view-blade.

This is my upload files from the edit form.

                                Upload Sertifikat Unit
                                <input type="file" id="UploadFileSertifUnit" name="file_uploads[]" multiple>

Ukuran Max : 2 MB

I want to show the file above this code.


问:
where is the instancemethod decorator?
In my code I have a method that returns an instance of a class, like this:

```<code>class MyClass:
  def fun( self, *args ): # the method
    return Props( self, *args )

class Props: # the returned object
  def __init__( self, parent, *args ):
    self.parent = parent
    self.args = args
</code>```

To keep things organized I am considering to place Props inside MyClass. I would then like to bypass fun and directly make the class an instance method of MyClass, like this:

```<code>class MyClass:
  @instancemethod # does not exist!
  class fun:
    def __init__( self, parent, *args ):
      self.parent = parent
      self.args = args
</code>```

Note the comment - the instancemethod decorator does not exist.

Is there a way to do this, i.e. to turn a callable object into an instance method? If I change @instancemethod to @classmethod the construction works, except then of course parent is the class, not the instance. I am surprised that I cannot find anything about what seems to be the opposite operation.

Curious to have this cleared up!

Edit:

It seems that my question was not clear. What I have is a member function, fun, that returns not a single value or tuple but an object full of data. This data is generated based on the contents of the MyClass object and function arguments. My initial code does exactly what I want. The second code is how I would prefer to write it.

Moreover I noticed that the decorator I am looking for is simply the following:

```<code>def instancemethod( cls ):
  def f( *args ):
    return cls( *args )
  return f
</code>```

It is, of course, identical to the 'fun' method that I aimed to bypass. Note also that the trivial 'return cls' is not identical, even though it might seem like that at first sight.

With this decorator, my second class definition is valid and produces the desired result, namely, a.fun() returns an object that is (potentially) initialized based on the data in a:

```<code>a = MyClass()
p = a.fun(1,2,3)

print a        # <__main__.MyClass instance at 0xb775b84c>
print p.parent # <__main__.MyClass instance at 0xb775b84c>
print p.args   # (1, 2, 3)
</code>```

This still leaves me with the question if the instancemethod defined here is not available as a python builtin, because it seems an omission next to classmethod and staticmethod. But, if not, I suppose I can live with this construction.

答:
I'm not sure exactly what you're trying to do, but I suspect you want to read up on descriptors.

Basically, a descriptor is an attribute of a class that is itself a class that defines  __get__ and __set__ methods. In your case, you could move the code from Props.__init__ to Props.__set__, set Props as the fun attribute of the class, and all should work as you want.

Title: where is the instancemethod decorator?

Body:
In my code I have a method that returns an instance of a class, like this:

class MyClass:
  def fun( self, *args ): # the method
    return Props( self, *args )

class Props: # the returned object
  def __init__( self, parent, *args ):
    self.parent = parent
    self.args = args

To keep things organized I am considering to place Props inside MyClass. I would then like to bypass fun and directly make the class an instance method of MyClass, like this:

class MyClass:
  @instancemethod # does not exist!
  class fun:
    def __init__( self, parent, *args ):
      self.parent = parent
      self.args = args

Note the comment - the instancemethod decorator does not exist.

Is there a way to do this, i.e. to turn a callable object into an instance method? If I change @instancemethod to @classmethod the construction works, except then of course parent is the class, not the instance. I am surprised that I cannot find anything about what seems to be the opposite operation.

Curious to have this cleared up!

Edit:

It seems that my question was not clear. What I have is a member function, fun, that returns not a single value or tuple but an object full of data. This data is generated based on the contents of the MyClass object and function arguments. My initial code does exactly what I want. The second code is how I would prefer to write it.

Moreover I noticed that the decorator I am looking for is simply the following:

def instancemethod( cls ):
  def f( *args ):
    return cls( *args )
  return f

It is, of course, identical to the 'fun' method that I aimed to bypass. Note also that the trivial 'return cls' is not identical, even though it might seem like that at first sight.

With this decorator, my second class definition is valid and produces the desired result, namely, a.fun() returns an object that is (potentially) initialized based on the data in a:

a = MyClass()
p = a.fun(1,2,3)

print a        # <__main__.MyClass instance at 0xb775b84c>
print p.parent # <__main__.MyClass instance at 0xb775b84c>
print p.args   # (1, 2, 3)

This still leaves me with the question if the instancemethod defined here is not available as a python builtin, because it seems an omission next to classmethod and staticmethod. But, if not, I suppose I can live with this construction.


问:
Swift - Viewcontrollers not deinit when segue is performed
I am fairly new to the whole concept of memory management and ARC.

I've recently looked into it and found mixed success.

Firstly it should be noted that some ViewController do deinitialize but I am still learning and cleaning up my application.

However, a common pattern I have noticed is that when I use the line navigationController?.popViewController(animated: true) this does infact deinit a view controller, given if there are no strong references.

However, my issue is that when I use a segue and use performSegue(withIdentifier: "showDetail_Segue", sender: nil) the deinit method is never used/called. (I just have a print statement to indicate whether a view has been deinitalized). In most cases, when I perform a segue, I am passing data to another view controller and as a result, I use the following function override func prepare(for segue: UIStoryboardSegue, sender: Any?) {}.

I have tried to change my segue to navigationController?.pushViewController(VC, animated: true) but my application crashes.

Am I missing something here?

The ViewControllers that deinitliaze when the navigationController is popped also do not deinitialze when performing a segue programmatically.

Could someone please tell me what I'm doing wrong?

Thank you.

答:
When you call performSegue and this segue is a push to another VC you are creating a new instance of VC, but your navigation stack is still the same  you only add the VC to the stack.

Remember:

Stack: [root, vc1, vc2]

vc2.performSegue (push)

Stack: [root, vc1, vc2, vc3]

The class only call the denit when you are dismissing a VC.

I Hope this helps you.


问:
SQL query MAX() function
```<code>select ProductID,ProductName,QuantityPerUnit
from Products
where Products.UnitPrice=Max(UnitPrice)
</code>```

What is wrong in this query?

I had tried 'having' in place of 'where' tag.

```<code>select ProductID,ProductName,QuantityPerUnit
from Products
having Products.UnitPrice=Max(UnitPrice)
</code>```

it must produce result with max unit price,

```<code>ProductID   ProductName     QuantityPerUnit
38          Côte de Blaye   12 - 75 cl bottles
</code>```

答:
You cannot simply use aggregate function in a where clause unless it's in a subquery.

Try :::

```<code>select ProductID,ProductName,QuantityPerUnit from Products
Where  Products.UnitPrice= (select Max(UnitPrice) from Products)
</code>```

If you're using TSQL, then better use

```<code>select top 1 With ties  ProductID,ProductName,QuantityPerUnit from Products
Order by  UnitPrice desc
</code>```

This will give you all the products with highest unit price and is efficient since there's no subquery.

Title: SQL query MAX() function

Body:
select ProductID,ProductName,QuantityPerUnit
from Products
where Products.UnitPrice=Max(UnitPrice)

What is wrong in this query?

I had tried 'having' in place of 'where' tag.

select ProductID,ProductName,QuantityPerUnit
from Products
having Products.UnitPrice=Max(UnitPrice)

it must produce result with max unit price,

ProductID   ProductName     QuantityPerUnit
38          Côte de Blaye   12 - 75 cl bottles

Body:
You cannot simply use aggregate function in a where clause unless it's in a subquery.

Try :::

select ProductID,ProductName,QuantityPerUnit from Products
Where  Products.UnitPrice= (select Max(UnitPrice) from Products)

If you're using TSQL, then better use

select top 1 With ties  ProductID,ProductName,QuantityPerUnit from Products
Order by  UnitPrice desc

This will give you all the products with highest unit price and is efficient since there's no subquery.


问:
cassandra java client using openssl
I am trying to connect to cassandra cluster via java datastax driver with openssl as per this doc https://docs.datastax.com/en/developer/java-driver/3.1/manual/ssl/ with my client cert and key and the truststore as my cassandra cluster requires two way mutual cert authentication

Here is my code

public static void main( String[] args ) throws Exception
    {
        KeyStore ks = KeyStore.getInstance("JKS");
        // make sure you close this stream properly (not shown here for brevity)
        InputStream trustStore = new FileInputStream("MyTrustStore");
        ks.load(trustStore, "abcdef".toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);

        SslContextBuilder builder = SslContextBuilder
          .forClient()
          .sslProvider(SslProvider.OPENSSL)
          .trustManager(tmf)
          // only if you use client authentication
          .keyManager(new File("client_cert"), new File("private_key"));

        SSLOptions sslOptions = new NettySSLOptions(builder.build());

        Cluster cluster = Cluster.builder()
          .addContactPoint("w.x.y.z")
          .withSSL(sslOptions)
          .build();

    }
```

<p>with the following dependencies in my pom</p>

<pre class="lang-xml prettyprint-override"><code><dependencies>
        <dependency>
            <groupId>com.datastax.cassandra</groupId>
            <artifactId>cassandra-driver-core</artifactId>
            <version>3.6.0</version>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-tcnative</artifactId>
            <version>2.0.25.Final</version>
        </dependency>

        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-tcnative-boringssl-static</artifactId>
            <version>2.0.0.Final</version>
            <classifier>osx-x86_64</classifier>
        </dependency>
</dependencies>
</code>```

But I get an error as

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError: failed to load the required native library
    at io.netty.handler.ssl.OpenSsl.ensureAvailability(OpenSsl.java:327)
    at io.netty.handler.ssl.ReferenceCountedOpenSslContext.<init>(ReferenceCountedOpenSslContext.java:193)
    at io.netty.handler.ssl.ReferenceCountedOpenSslContext.<init>(ReferenceCountedOpenSslContext.java:182)
    at io.netty.handler.ssl.OpenSslContext.<init>(OpenSslContext.java:34)
    at io.netty.handler.ssl.OpenSslClientContext.<init>(OpenSslClientContext.java:188)
    at io.netty.handler.ssl.SslContext.newClientContextInternal(SslContext.java:775)
    at io.netty.handler.ssl.SslContextBuilder.build(SslContextBuilder.java:446)
    at com.example.App.main(App.java:41)
Caused by: java.lang.IllegalArgumentException: Failed to load any of the given libraries: [netty_tcnative_osx_x86_64, netty_tcnative_x86_64, netty_tcnative]
    at io.netty.util.internal.NativeLibraryLoader.loadFirstAvailable(NativeLibraryLoader.java:93)
    at io.netty.handler.ssl.OpenSsl.loadTcNative(OpenSsl.java:421)
    at io.netty.handler.ssl.OpenSsl.<clinit>(OpenSsl.java:89)
    ... 7 more
</code>```

I have tried removing the boringssl-static dep or the tcnative dep from pom but it still doesnt seem to work. Any help would be greatly appreciated.

Thank you in advance

答:
I suspect what could possibly be happening here is caused by some incompatibility between the versions of netty, netty-tcnative and netty-tcnative-boringssl-static being used here.

In previous experimentation, I have found that versions of netty and netty-tcnative are particularly important as there can be incompatibilities between the two.

datastax java driver 3.6.0 depends on netty 4.0.56.Final and lists netty-tcnative 2.0.7.Final as an optional dependency.  You can also find in the documentation for java driver 3.6.0 that 2.0.7.Final is recommended:

There are known runtime incompatibilities between newer versions of netty-tcnative and the version of netty that the driver uses. For best results, use version 2.0.7.Final.

I also suspect that not using the same version of netty-tcnative and netty-tcnative-boringssl-static might cause incompatibilities.  I would recommend trying the same versions.

Since I've tested this, I would first try the following configuration:

<dependencies>
    <dependency>
        <groupId>com.datastax.cassandra</groupId>
        <artifactId>cassandra-driver-core</artifactId>
        <version>3.6.0</version>
    </dependency>
    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-tcnative</artifactId>
        <version>2.0.7.Final</version>
    </dependency>
    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-tcnative-boringssl-static</artifactId>
        <version>2.0.7.Final</version>
        <classifier>osx-x86_64</classifier>
    </dependency>
</dependencies>
```

Title: cassandra java client using openssl

Body:
I am trying to connect to cassandra cluster via java datastax driver with openssl as per this doc https://docs.datastax.com/en/developer/java-driver/3.1/manual/ssl/ with my client cert and key and the truststore as my cassandra cluster requires two way mutual cert authentication

Here is my code

public static void main( String[] args ) throws Exception
    {
        KeyStore ks = KeyStore.getInstance("JKS");
        // make sure you close this stream properly (not shown here for brevity)
        InputStream trustStore = new FileInputStream("MyTrustStore");
        ks.load(trustStore, "abcdef".toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);

        SslContextBuilder builder = SslContextBuilder
          .forClient()
          .sslProvider(SslProvider.OPENSSL)
          .trustManager(tmf)
          // only if you use client authentication
          .keyManager(new File("client_cert"), new File("private_key"));

        SSLOptions sslOptions = new NettySSLOptions(builder.build());

        Cluster cluster = Cluster.builder()
          .addContactPoint("w.x.y.z")
          .withSSL(sslOptions)
          .build();

    }

with the following dependencies in my pom

<dependencies>
        <dependency>
            <groupId>com.datastax.cassandra</groupId>
            <artifactId>cassandra-driver-core</artifactId>
            <version>3.6.0</version>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-tcnative</artifactId>
            <version>2.0.25.Final</version>
        </dependency>

        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-tcnative-boringssl-static</artifactId>
            <version>2.0.0.Final</version>
            <classifier>osx-x86_64</classifier>
        </dependency>
</dependencies>

But I get an error as

Exception in thread "main" java.lang.UnsatisfiedLinkError: failed to load the required native library
    at io.netty.handler.ssl.OpenSsl.ensureAvailability(OpenSsl.java:327)
    at io.netty.handler.ssl.ReferenceCountedOpenSslContext.<init>(ReferenceCountedOpenSslContext.java:193)
    at io.netty.handler.ssl.ReferenceCountedOpenSslContext.<init>(ReferenceCountedOpenSslContext.java:182)
    at io.netty.handler.ssl.OpenSslContext.<init>(OpenSslContext.java:34)
    at io.netty.handler.ssl.OpenSslClientContext.<init>(OpenSslClientContext.java:188)
    at io.netty.handler.ssl.SslContext.newClientContextInternal(SslContext.java:775)
    at io.netty.handler.ssl.SslContextBuilder.build(SslContextBuilder.java:446)
    at com.example.App.main(App.java:41)
Caused by: java.lang.IllegalArgumentException: Failed to load any of the given libraries: [netty_tcnative_osx_x86_64, netty_tcnative_x86_64, netty_tcnative]
    at io.netty.util.internal.NativeLibraryLoader.loadFirstAvailable(NativeLibraryLoader.java:93)
    at io.netty.handler.ssl.OpenSsl.loadTcNative(OpenSsl.java:421)
    at io.netty.handler.ssl.OpenSsl.<clinit>(OpenSsl.java:89)
    ... 7 more

I have tried removing the boringssl-static dep or the tcnative dep from pom but it still doesnt seem to work. Any help would be greatly appreciated.

Thank you in advance


问:
How to type a Typescript array to accept only a specific set of values?
I am writing a type declaration file for a library I do not control. One of the methods accepts an array of strings as a parameter, but these strings can only be very specific values. Currently I am typing this parameter as a string[], but I was wondering if there was a way to enhance this to include the specific values as well.

Example source (I cannot change this):

```<code>Fruits(filter) {
    for (let fruit of filter.fruits)
    {
        switch(fruit)
        {
            case 'Apple':
                ...do stuff
            case 'Pear':
                ...do stuff
            default:
                console.error('Invalid Fruit');
                return false;
        }
    }
    return true;
}
</code>```

My current type declaration:

```<code>function Fruits(filter: FruitFilter): boolean;

interface FruitFilter {
    fruits: string[];
}
</code>```

As I was writing this question I came up with a partial solution by defining a union type of the strings that are valid, then setting the type of the field to an array of that union rather than an array of strings. This gives me the checking I want, but I noticed that if you enter an invalid string, it marks all of the strings in the array as invalid with the error Type 'string' is not assignable to type 'Fruit'. Is there a better way of doing this so that only the offending string is marked as invalid, or is this as close as I'm going to get?

Partial solution:

```<code>function Fruits(filter: FruitFilter): boolean;

type Fruit = 'Apple' | 'Pear'

interface FruitFilter {
    fruits: Fruit[];
}
</code>```

答:
So, your problem seems to be this:

```<code>type Fruit = "Apple" | "Pear";
interface FruitFilter {
  fruits: Fruit[];
}
declare function Fruits(filter: FruitFilter): boolean;
Fruits({ fruits: ["Apple", "Apple", "Pear"] }); // okay
Fruits({ fruits: ["Apple", "App1e", "Pear"] }); // error
// actual error: ~~~~~~~  ~~~~~~~  ~~~~~~ <-- string not assignable to Fruit
// expected error:        ~~~~~~~ <-- "App1e" not assignable to Fruit
</code>```

It's not that you have an error, but that the error isn't properly constrained to the "bad" elements of the array.

My guess about why this is happening is that the compiler tends to widen string literals to string and tuple types to arrays unless you give it hints not to do that.  Therefore, when it can't verify that the fruits is of type Fruit[], it backs up and looks at what you gave it.  It widens ["Apple", "App1e", "Pear"] to string[] (forgetting both about the string literals and the fact that it is a three-element tuple), realizes that string[] is not assignable to Fruit[], and then proceeds to warn you about this by flagging each element.  I did a brief search of GitHub issues to see if this has ever been reported, but I haven't seen it.  It may be worth filing something.

Anyway, to test my guess, I decided to alter the declaration of Fruits() to hint that we want a tuple of string literals if at all possible.  Note that there is currently no convenient way to do this; the ways to do hinting right now are, uh, alchemical:

```<code>// ⚗❓
declare function Fruits2<S extends string, T extends S[] | [S]>(arr: {
  fruits: T & { [K in keyof T]: Fruit };
}): boolean;
Fruits2({ fruits: ["Apple", "Apple", "Pear"] }); // okay
Fruits2({ fruits: ["Apple", "App1e", "Pear"] }); // error
//                          ~~~~~~~ <--string is not assignable to never
</code>```

Well, the placement of that error is where you want it, although the message is possibly still confusing.  That's what happens when the compiler tries to assign "Apple" to the intersection Fruit & "App1e" which doesn't exist.  The compiler reduces Fruit & "App1e" to never... correctly, but possibly a bit too soon for the error message to be useful.

Anyway, I don't recommend this "solution" since it's much more complicated and only gives you a somewhat better error experience in error situations.  But at least this is something like an answer as to why it's happening, along with a possible direction for how to address it (e.g., find or file an issue about it).  Okay, good luck!

Link to code

Body:
I am writing a type declaration file for a library I do not control. One of the methods accepts an array of strings as a parameter, but these strings can only be very specific values. Currently I am typing this parameter as a string[], but I was wondering if there was a way to enhance this to include the specific values as well.

Example source (I cannot change this):

Fruits(filter) {
    for (let fruit of filter.fruits)
    {
        switch(fruit)
        {
            case 'Apple':
                ...do stuff
            case 'Pear':
                ...do stuff
            default:
                console.error('Invalid Fruit');
                return false;
        }
    }
    return true;
}

My current type declaration:

function Fruits(filter: FruitFilter): boolean;

interface FruitFilter {
    fruits: string[];
}

As I was writing this question I came up with a partial solution by defining a union type of the strings that are valid, then setting the type of the field to an array of that union rather than an array of strings. This gives me the checking I want, but I noticed that if you enter an invalid string, it marks all of the strings in the array as invalid with the error Type 'string' is not assignable to type 'Fruit'. Is there a better way of doing this so that only the offending string is marked as invalid, or is this as close as I'm going to get?

Partial solution:

function Fruits(filter: FruitFilter): boolean;

type Fruit = 'Apple' | 'Pear'

interface FruitFilter {
    fruits: Fruit[];
}

Body:
So, your problem seems to be this:

type Fruit = "Apple" | "Pear";
interface FruitFilter {
  fruits: Fruit[];
}
declare function Fruits(filter: FruitFilter): boolean;
Fruits({ fruits: ["Apple", "Apple", "Pear"] }); // okay
Fruits({ fruits: ["Apple", "App1e", "Pear"] }); // error
// actual error: ~~~~~~~  ~~~~~~~  ~~~~~~ <-- string not assignable to Fruit
// expected error:        ~~~~~~~ <-- "App1e" not assignable to Fruit

It's not that you have an error, but that the error isn't properly constrained to the "bad" elements of the array.

My guess about why this is happening is that the compiler tends to widen string literals to string and tuple types to arrays unless you give it hints not to do that.  Therefore, when it can't verify that the fruits is of type Fruit[], it backs up and looks at what you gave it.  It widens ["Apple", "App1e", "Pear"] to string[] (forgetting both about the string literals and the fact that it is a three-element tuple), realizes that string[] is not assignable to Fruit[], and then proceeds to warn you about this by flagging each element.  I did a brief search of GitHub issues to see if this has ever been reported, but I haven't seen it.  It may be worth filing something.

Anyway, to test my guess, I decided to alter the declaration of Fruits() to hint that we want a tuple of string literals if at all possible.  Note that there is currently no convenient way to do this; the ways to do hinting right now are, uh, alchemical:

// ⚗❓
declare function Fruits2<S extends string, T extends S[] | [S]>(arr: {
  fruits: T & { [K in keyof T]: Fruit };
}): boolean;
Fruits2({ fruits: ["Apple", "Apple", "Pear"] }); // okay
Fruits2({ fruits: ["Apple", "App1e", "Pear"] }); // error
//                          ~~~~~~~ <--string is not assignable to never

Well, the placement of that error is where you want it, although the message is possibly still confusing.  That's what happens when the compiler tries to assign "Apple" to the intersection Fruit & "App1e" which doesn't exist.  The compiler reduces Fruit & "App1e" to never... correctly, but possibly a bit too soon for the error message to be useful.

Anyway, I don't recommend this "solution" since it's much more complicated and only gives you a somewhat better error experience in error situations.  But at least this is something like an answer as to why it's happening, along with a possible direction for how to address it (e.g., find or file an issue about it).  Okay, good luck!

<a href="https://typescript-play.js.org/#code/C4TwDgpgBAYgTgVwJbCgXigIgIJjAGwkygB8sAFCAQzkwG4AoJAO2AjgDMqBjaeZYDCT42cKAG8GUKB0QoAzgC5Yc4AG0AuowC+DACYRu+GtA4Jm3YEgD2zFQPkAKDsNHL+KISPYBKZQCNra0IqZkYPYCdxGVUlKDUcPEJMABosXAIiNMxKGkwNKG0fOigAelKoawBrKhAGCKiYh2UEjOTsjIBGLIpqWgKikvKodjhrOAZhnmAEKnwRuDG4ZQA-NfWV6Q31re2oAB4AWkOoeWA4FgBzKGZrVCp5eSRL5ip-Qihga3sUSYqIAAekEsED0CyWymkUN2eyOJ0SYG6xFu90ez1e72gXx+wAYfyggD4NwCbu4B0skAPBuAPH2yYBsfcAyuT6QzGOCmcyWGx2BoAJn2AGURgC2Mw9PJTucrmkACr8wXCqA8zSkeI8jQAPkcNGWEikTQUyilADIJPEANJQFhQKoQEDWDhQCUadyqQo6PxQQLBahheqxTmOaKyZrxBHtdJJHo5Pr5QrFMoVaq1b0OX3+2ItYPhrrh3L9aNDf6Lcb46HFkulqHbNYHY5nC7Ma5IEUoqAPJ4vN4fbHMCAAN3YDCAA" rel="noreferrer">Link to code


问:
Creating views on the fly from array
I need to create a a bunch a views on the fly. I was wondering what would be the best way to go about doing this as ill need to define coordinates, tag, colours of each view.

Would i need to create a multidimensional array and if so how can i do this?

```<code>CGRect viewRect1 = { 80.0, 200.0, 160.0, 100.0 };
UIview *myview1 = [[UIview alloc] initWithFrame:viewRect1];
[myview1 setBackgroundColor:[UIColor darkGrayColor]];
</code>```

答:
You need to define a structure to hold the data which is needed to create your UIView.

```<code>@interface MyViewDataHolder :NSObject
{
     CGRect mViewRect;
     UIColor* mDarkGrayColor;
     NSInterger mTag;
}

@end
</code>```

Then create an object of above class AND assign the values in member then add that in your NSArray...

EDITED:

In MyViewDataHolder.h class

```<code>@interface MyViewDataHolder :NSObject
{
    CGRect mViewRect;
    UIColor* mDarkGrayColor;
    NSInteger mTag;
}
@property (nonatomic,assign) CGRect mViewRect;
@property (nonatomic,retain) UIColor* mDarkGrayColor;
@property (nonatomic,assign) NSInteger mTag;

@end
</code>```

In MyViewDataHolder.mm class

```<code>#import "MyViewDataHolder.h"

@implementation MyViewDataHolder

@synthesize mViewRect,mDarkGrayColor,mTag;

-(void) dealloc
{
    [mDarkGrayColor release]
    mDarkGrayColor = nil;
}
</code>```

Now How to use it  ....

Create objects of MyViewDataHolder like below ...

```<code>MyViewDataHolder* myObj1 = [[MyViewDataHolder alloc] init];
myObj1.mViewRect = CGRectMake(x,y,width,height);
myObj1.tag = 1;
myObj1.mDarkGrayColor = [UIColor redColor];
</code>```

Create as much as you need

Then Create an NSMutableArray and add each objects of MyViewDataHolder into NSMutableArray.

```<code>NSMutableArray* myArray = [[NSMutableArray alloc] init];
[myArray addObject:myObj1];
[myArray addObject:myObj2];
[myArray addObject:myObj3];
and So on ....
</code>```

When you need the stored info you could use as below ...

```<code>for(int index =0; index < [myArray count]; index++)
{

     MyViewDataHolder* myObj = (MyViewDataHolder*)[myArray objectAtIndex:index];
     myView = [[UIView alloc] initWithFrame:myObj.mViewRect];
     //incriment x and y to refelect where you want your next view to be suituated
     myView.tag = myObj.mTag;
     myView.backgroundColor =  myObj.mDarkGrayColor;
     [self.view addSubview:myView];
     [myView release];
}
</code>```

The code reflect the approach , Although  I didn't compile the code So use it as reference

Thanks ,

Title: Creating views on the fly from array

Body:
I need to create a a bunch a views on the fly. I was wondering what would be the best way to go about doing this as ill need to define coordinates, tag, colours of each view.

Would i need to create a multidimensional array and if so how can i do this?

CGRect viewRect1 = { 80.0, 200.0, 160.0, 100.0 };
UIview *myview1 = [[UIview alloc] initWithFrame:viewRect1];
[myview1 setBackgroundColor:[UIColor darkGrayColor]];

Body:
You need to define a structure to hold the data which is needed to create your UIView.

@interface MyViewDataHolder :NSObject
{
     CGRect mViewRect;
     UIColor* mDarkGrayColor;
     NSInterger mTag;
}

@end

Then create an object of above class AND assign the values in member then add that in your NSArray...

EDITED:

In MyViewDataHolder.h class

@interface MyViewDataHolder :NSObject
{
    CGRect mViewRect;
    UIColor* mDarkGrayColor;
    NSInteger mTag;
}
@property (nonatomic,assign) CGRect mViewRect;
@property (nonatomic,retain) UIColor* mDarkGrayColor;
@property (nonatomic,assign) NSInteger mTag;

@end

In MyViewDataHolder.mm class

#import "MyViewDataHolder.h"

@implementation MyViewDataHolder

@synthesize mViewRect,mDarkGrayColor,mTag;

-(void) dealloc
{
    [mDarkGrayColor release]
    mDarkGrayColor = nil;
}

Now How to use it  ....

Create objects of MyViewDataHolder like below ...

MyViewDataHolder* myObj1 = [[MyViewDataHolder alloc] init];
myObj1.mViewRect = CGRectMake(x,y,width,height);
myObj1.tag = 1;
myObj1.mDarkGrayColor = [UIColor redColor];

Create as much as you need

Then Create an NSMutableArray and add each objects of MyViewDataHolder into NSMutableArray.

NSMutableArray* myArray = [[NSMutableArray alloc] init];
[myArray addObject:myObj1];
[myArray addObject:myObj2];
[myArray addObject:myObj3];
and So on ....

When you need the stored info you could use as below ...

for(int index =0; index < [myArray count]; index++)
{

     MyViewDataHolder* myObj = (MyViewDataHolder*)[myArray objectAtIndex:index];
     myView = [[UIView alloc] initWithFrame:myObj.mViewRect];
     //incriment x and y to refelect where you want your next view to be suituated
     myView.tag = myObj.mTag;
     myView.backgroundColor =  myObj.mDarkGrayColor;
     [self.view addSubview:myView];
     [myView release];
}

The code reflect the approach , Although  I didn't compile the code So use it as reference

Thanks ,