问:
Post() got an unexpected keyword argument 'user'
How can I solve this error in my Django Python code?

Post() got an unexpected keyword argument 'user'

```<code>views.py
    def post(request):
        if request.method=="POST":
            Image=request.FILES['image']
            caption=request.POST.get('ta','')
            userr=request.user
            post_obj=Post(user=userr,image=Image,caption=caption)
            print(userr,Image,caption,end='\n')

            post_obj.save()
            messages.success(request,"Succusfully sent your Post")
            return redirect('/user_homeview')
            return HttpResponse("successfully")
        else:
            # messages.error(request,"your  Post not succesfully sent! something went wrong!")
            return redirect('/user_homeview')
            return HttpResponse(" not successfully")

            return render(request,'userview/userhome.html')
    #Post() got an unexpected keyword argument 'user'
    so how i solve this error
        def post(request):
            if request.method=="POST":
                Image=request.FILES['image']
                caption=request.POST.get('ta','')
                userr=request.user
                post_obj=Post(user=userr,image=Image,caption=caption)
                print(userr,Image,caption,end='\n')

                post_obj.save()

        models.py
        from django.db import models
        from django.contrib.auth.models import User
        # # Create your models here.
        from django.db import models

        # # # Create your models here.
        class Post(models.Model):
             userr = models.ForeignKey(User,on_delete=models.CASCADE)
             image=models.FileField(upload_to='media/',blank=True)
             caption = models.CharField(max_length=200,default="")
             timeStamp=models.DateTimeField(auto_now_add=True,blank=True,null=True)
</code>```

答:
You have a typo, in this line:

post_obj=Post(user=userr,image=Image,caption=caption) ; regarding your models.py, it should be userr=userr

Body:
How can I solve this error in my Django Python code?

Post() got an unexpected keyword argument 'user'

views.py
    def post(request):
        if request.method=="POST":
            Image=request.FILES['image']
            caption=request.POST.get('ta','')
            userr=request.user
            post_obj=Post(user=userr,image=Image,caption=caption)
            print(userr,Image,caption,end='\n')

            post_obj.save()
            messages.success(request,"Succusfully sent your Post")
            return redirect('/user_homeview')
            return HttpResponse("successfully")
        else:
            # messages.error(request,"your  Post not succesfully sent! something went wrong!")
            return redirect('/user_homeview')
            return HttpResponse(" not successfully")

            return render(request,'userview/userhome.html')
    #Post() got an unexpected keyword argument 'user'
    so how i solve this error
        def post(request):
            if request.method=="POST":
                Image=request.FILES['image']
                caption=request.POST.get('ta','')
                userr=request.user
                post_obj=Post(user=userr,image=Image,caption=caption)
                print(userr,Image,caption,end='\n')

                post_obj.save()

        models.py
        from django.db import models
        from django.contrib.auth.models import User
        # # Create your models here.
        from django.db import models

        # # # Create your models here.
        class Post(models.Model):
             userr = models.ForeignKey(User,on_delete=models.CASCADE)
             image=models.FileField(upload_to='media/',blank=True)
             caption = models.CharField(max_length=200,default="")
             timeStamp=models.DateTimeField(auto_now_add=True,blank=True,null=True)


来源: stackexchange

问:
Java heap space error while creating ArrayList of large number of objects?
I have created an ArrayList (Java) of my custom class objects with a size around 3000.
But when I run my code it gets the error "Heap space error".

I want to keep thousands of objects in an ArrayList at runtime without getting out of heap space.

How can the heap space error be avoided?

答:
It seems like you need to pass your program more memory.

Try running it like this:

```<code>java -Xmx256M MyApp
</code>```

-Xmx sets the maximum heap size for Java.  Putting M afterwards means megabytes, and G afterwards means gigabytes. So you can always do this if you have a bunch of memory:

```<code>java -Xmx1g MyApp
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It seems like you need to pass your program more memory.

Try running it like this:

java -Xmx256M MyApp

-Xmx sets the maximum heap size for Java.  Putting M afterwards means megabytes, and G afterwards means gigabytes. So you can always do this if you have a bunch of memory:

java -Xmx1g MyApp


问:
MongooseIm Rest API connection issue with local Setup
I have setup the mongooseim [3.3.0] ubuntu 14.04 & it works perfect with android client setup. Then I need to test the REST API for creating room , Then I have got this error when running the swagger documentation.

```<code>curl -X GET --header 'Accept: application/json' --header 'Authorization: Basic dXNlcjpwYXNzd29yZA==' 'http://localhost:8089/api/rooms'

curl: (52) Empty reply from server
</code>```

This is the mongooseim configs which related to REST API.

```<code>{ 8089 , ejabberd_cowboy, [
      {num_acceptors, 10},
      {transport_options, [{max_connections, 1024}]},
      {protocol_options, [{compress, true}]},
      {ssl, [{certfile, "priv/ssl/fake_cert.pem"}, {keyfile, "priv/ssl/fake_key.pem"}, {password, ""}]},
      {modules, [
          {"_", "/api/sse", lasse_handler, [mongoose_client_api_sse]},
          {"_", "/api/messages/[:with]", mongoose_client_api_messages, []},
          {"_", "/api/contacts/[:jid]", mongoose_client_api_contacts, []},
          {"_", "/api/rooms/[:id]",    mongoose_client_api_rooms, []},
          {"_", "/api/rooms/[:id]/config",    mongoose_client_api_rooms_config, []},
          {"_", "/api/rooms/:id/users/[:user]",    mongoose_client_api_rooms_users, []},
          {"_", "/api/rooms/[:id]/messages",    mongoose_client_api_rooms_messages, []}
      ]}
  ]}
</code>```

This is the swagger document I have referred. https://mongooseim.readthedocs.io/en/3.3.0/swagger/index.html

答:
I noticed the following things:

The curl example you provided tries to send the request to MongooseIM over HTTP

Based on the part of the config file you provided I can see that MongooseIM expects HTTPS traffic.

It looks like changing the endpoint in your curl command to https://localhost:8089/api/rooms will help. Of course, if you run the command on the same machine as MongooseIM is running. Otherwise, please change the localhost to a proper name or IP address of the machine.

What's more, in the config file I can see that the REST API is configured with the default, fake and self-signed certificates. I strongly encourage you to change it to real certificates. For the sake of testing, you will need to add the option -k to your curl command in order to skip cert verification.

ContentLicense: CC BY-SA 4.0

Body:
I have setup the mongooseim [3.3.0] ubuntu 14.04 & it works perfect with android client setup. Then I need to test the REST API for creating room , Then I have got this error when running the swagger documentation.

curl -X GET --header 'Accept: application/json' --header 'Authorization: Basic dXNlcjpwYXNzd29yZA==' 'http://localhost:8089/api/rooms'

curl: (52) Empty reply from server

This is the mongooseim configs which related to REST API.

{ 8089 , ejabberd_cowboy, [
      {num_acceptors, 10},
      {transport_options, [{max_connections, 1024}]},
      {protocol_options, [{compress, true}]},
      {ssl, [{certfile, "priv/ssl/fake_cert.pem"}, {keyfile, "priv/ssl/fake_key.pem"}, {password, ""}]},
      {modules, [
          {"_", "/api/sse", lasse_handler, [mongoose_client_api_sse]},
          {"_", "/api/messages/[:with]", mongoose_client_api_messages, []},
          {"_", "/api/contacts/[:jid]", mongoose_client_api_contacts, []},
          {"_", "/api/rooms/[:id]",    mongoose_client_api_rooms, []},
          {"_", "/api/rooms/[:id]/config",    mongoose_client_api_rooms_config, []},
          {"_", "/api/rooms/:id/users/[:user]",    mongoose_client_api_rooms_users, []},
          {"_", "/api/rooms/[:id]/messages",    mongoose_client_api_rooms_messages, []}
      ]}
  ]}

This is the swagger document I have referred. https://mongooseim.readthedocs.io/en/3.3.0/swagger/index.html


问:
Extract first element from multi dimensional array from pandas dataframe
I have a data frame consists of reviews column which is a multi dimensional array, I would like to extract first element as shown below,

Suppose df['Reviews'] consists of following rows

I want the output in a separate column as shown below,

Please find sample data 3 values for the column below:

df['Reviews'] =
[['Just like home', 'A Warm Welcome to Wintry Amsterdam'], ['01/03/2018', '01/01/2018']]
[['Great food and staff', 'just perfect'], ['01/06/2018', '01/04/2018']]
[['Satisfaction', 'Delicious old school restaurant'], ['01/04/2018', '01/04/2018']]

Please help

答:
If you receive error, you probably have some empty data in Reviews. You can drop them, if such data is useless for you:
df.dropna(subset='Reviews', inplace=True)

or add checking type of data:

```<code>a = [[['Just like home', 'A Warm Welcome to Wintry Amsterdam'], ['01/03/2018', '01/01/2018']], [['Great food and staff', 'just perfect'], ['01/06/2018', '01/04/2018']], [['Satisfaction', 'Delicious old school restaurant'], ['01/04/2018', '01/04/2018']]]

df = pd.DataFrame(columns=['Reviews', 'Review'])
df['Reviews'] = a
df
</code>```

```<code>executed in 18ms, finished 07:39:04 2020-06-05
Reviews Review
0   [[Just like home, A Warm Welcome to Wintry Ams...   NaN
1   [[Great food and staff, just perfect], [01/06/...   NaN
2   [[Satisfaction, Delicious old school restauran...   NaN

</code>```

```<code>def get_review(reviews):
    if type(reviews) == list:
        return reviews[0]
    else:
        return None

df['Review'] = df['Reviews'].apply(get_review)
df
</code>```

```<code>    Reviews Review
0   [[Just like home, A Warm Welcome to Wintry Ams...   [Just like home, A Warm Welcome to Wintry Amst...
1   [[Great food and staff, just perfect], [01/06/...   [Great food and staff, just perfect]
2   [[Satisfaction, Delicious old school restauran...   [Satisfaction, Delicious old school restaurant]
</code>```

If you don't want column Review to be a list, simply covert it to string with some divider:

```<code>def get_review(reviews):
    if type(reviews) == list:
        return ', '.join(reviews[0])
    else:
        return ''

df['Review'] = df['Reviews'].apply(get_review)
df
</code>```

```<code>    Reviews Review
0   [[Just like home, A Warm Welcome to Wintry Ams...   Just like home, A Warm Welcome to Wintry Amste...
1   [[Great food and staff, just perfect], [01/06/...   Great food and staff, just perfect
2   [[Satisfaction, Delicious old school restauran...   Satisfaction, Delicious old school restaurant
</code>```

I your input data is not of type list (i.e. you reading it from CSV), you need to convert it to list first:

```<code>import ast

def get_review(reviews):
    if pd.notna(reviews) and reviews != '':
        r_list = ast.literal_eval(reviews)[0]
        if len(r_list) > 0:
            return ', '.join(r_list)
        else:
            return ''
    else:
        return ''

df2['Review'] = df2['Reviews'].apply(get_review)
df2
</code>```

```<code>
Reviews Review
Reviews Review
0   [['Just like home', 'A Warm Welcome to Wintry ...   Just like home, A Warm Welcome to Wintry Amste...
1   [['Great food and staff', 'just perfect'], ['0...   Great food and staff, just perfect
2   [['Satisfaction', 'Delicious old school restau...   Satisfaction, Delicious old school restaurant
</code>```

Body:
If you receive error, you probably have some empty data in Reviews. You can drop them, if such data is useless for you:
df.dropna(subset='Reviews', inplace=True)

or add checking type of data:

a = [[['Just like home', 'A Warm Welcome to Wintry Amsterdam'], ['01/03/2018', '01/01/2018']], [['Great food and staff', 'just perfect'], ['01/06/2018', '01/04/2018']], [['Satisfaction', 'Delicious old school restaurant'], ['01/04/2018', '01/04/2018']]]

df = pd.DataFrame(columns=['Reviews', 'Review'])
df['Reviews'] = a
df

executed in 18ms, finished 07:39:04 2020-06-05
Reviews Review
0   [[Just like home, A Warm Welcome to Wintry Ams...   NaN
1   [[Great food and staff, just perfect], [01/06/...   NaN
2   [[Satisfaction, Delicious old school restauran...   NaN

def get_review(reviews):
    if type(reviews) == list:
        return reviews[0]
    else:
        return None

df['Review'] = df['Reviews'].apply(get_review)
df

    Reviews Review
0   [[Just like home, A Warm Welcome to Wintry Ams...   [Just like home, A Warm Welcome to Wintry Amst...
1   [[Great food and staff, just perfect], [01/06/...   [Great food and staff, just perfect]
2   [[Satisfaction, Delicious old school restauran...   [Satisfaction, Delicious old school restaurant]

If you don't want column Review to be a list, simply covert it to string with some divider:

def get_review(reviews):
    if type(reviews) == list:
        return ', '.join(reviews[0])
    else:
        return ''

df['Review'] = df['Reviews'].apply(get_review)
df

    Reviews Review
0   [[Just like home, A Warm Welcome to Wintry Ams...   Just like home, A Warm Welcome to Wintry Amste...
1   [[Great food and staff, just perfect], [01/06/...   Great food and staff, just perfect
2   [[Satisfaction, Delicious old school restauran...   Satisfaction, Delicious old school restaurant

I your input data is not of type list (i.e. you reading it from CSV), you need to convert it to list first:

import ast

def get_review(reviews):
    if pd.notna(reviews) and reviews != '':
        r_list = ast.literal_eval(reviews)[0]
        if len(r_list) > 0:
            return ', '.join(r_list)
        else:
            return ''
    else:
        return ''

df2['Review'] = df2['Reviews'].apply(get_review)
df2

Reviews Review
Reviews Review
0   [['Just like home', 'A Warm Welcome to Wintry ...   Just like home, A Warm Welcome to Wintry Amste...
1   [['Great food and staff', 'just perfect'], ['0...   Great food and staff, just perfect
2   [['Satisfaction', 'Delicious old school restau...   Satisfaction, Delicious old school restaurant


问:
Angular docker cannot reach backend service container
I have an angular SPA and a backend service, both are deployed via docker containers. I can't seem to get the angular app to connect to the backend service.

Using Nginx in the angular container, with the following configuration

```<code>server {

  root /usr/share/nginx/html/;

  location / {
    try_files $uri $uri/ /index.html =404;
  }

  location http://backend-service {
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Server $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    proxy_pass http://backend-service:8080/;
  }
}
</code>```

And the environment file for the angular app

```<code>export const environment = {
  api: 'http://backend-service',
};
</code>```

The containers are linked and I can ping the backend container from within the Nginx/angular container by its service name, I think I've got something wrong in the nginx config file...

Any insight?

答:
The trick in the end was to remove the docker reference from the environment file

```<code>export const environment = {
  api: '/api',
};
</code>```

Then adjust the default.conf file to match:

```<code>server {
  listen 80;
  server_name terrible-spa;
  root /usr/share/nginx/html/;
  index index.html index.html;

  location /api {
    proxy_pass http://backend-service:8080/api;
  }

  location / {
    try_files $uri $uri/ /index.html =404;
  }
}
</code>```

This will correctly forward all calls /api to the backend-service container.

Body:
I have an angular SPA and a backend service, both are deployed via docker containers. I can't seem to get the angular app to connect to the backend service.

Using Nginx in the angular container, with the following configuration

server {

  root /usr/share/nginx/html/;

  location / {
    try_files $uri $uri/ /index.html =404;
  }

  location http://backend-service {
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Server $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    proxy_pass http://backend-service:8080/;
  }
}

And the environment file for the angular app

export const environment = {
  api: 'http://backend-service',
};

The containers are linked and I can ping the backend container from within the Nginx/angular container by its service name, I think I've got something wrong in the nginx config file...

Any insight?

Body:
The trick in the end was to remove the docker reference from the environment file

export const environment = {
  api: '/api',
};

Then adjust the default.conf file to match:

server {
  listen 80;
  server_name terrible-spa;
  root /usr/share/nginx/html/;
  index index.html index.html;

  location /api {
    proxy_pass http://backend-service:8080/api;
  }

  location / {
    try_files $uri $uri/ /index.html =404;
  }
}

This will correctly forward all calls /api to the backend-service container.


问:
Why result of put() from HashMap is compared with null when add into a HashSet in Java?
I try to understand the implementation of HashSet and I see that it uses the HashMap internally.
And when you add in an HashSet, internally you put in an HashMap like below:

```<code>private transient HashMap<E,Object> map;

private static final Object PRESENT = new Object();

public boolean add(E e) {
   return map.put(e, PRESENT)==null;
}
</code>```

But what I don't understand is why they use this ==null.

This is the signature oh put method:

```<code>public V put(K key, V value)
</code>```

I don't understand why the result of put is compared with null.

答:
Facts

Map.put  Returns the previous value associated with key, or null if there was no mapping for key.

Set.add Returns true if this set did not already contain the specified element

Explanation

If the element was not in the inner Map, the put returns null so the equals is True and means the value wasn't there before

If the element was in the inner Map, put would return previous value, in most case different of null , equality false is returned as there was a previous vlaue

Body:
I try to understand the implementation of HashSet and I see that it uses the HashMap internally.
And when you add in an HashSet, internally you put in an HashMap like below:

private transient HashMap<E,Object> map;

private static final Object PRESENT = new Object();

public boolean add(E e) {
   return map.put(e, PRESENT)==null;
}

But what I don't understand is why they use this ==null.

This is the signature oh put method:

public V put(K key, V value)

I don't understand why the result of put is compared with null.


问:
Can ASP.NET MVC be applied to web services?
I'm planning architecture for a web-based application using web services.  It has been recommended that I look into using the ASP.NET MVC Framework.  All of the information I'm finding on the MVC discusses its use with web pages, but I have found nothing regarding web services.  Can the MVC be used for web services? and if so, where might I find resources to support my research effort?</p>

答: It's not clear from your question whether you're building a web application that has a web service component, or just a web service. Web services, strictly speaking, don't have user interfaces, so the MVC model wouldn't directly apply. But there's really no substitute for thinking through what you're trying to do in a straightforward way. Architecture patterns can help, but they're only guides. It sounds like you're still feeling your way around, so don't think too much about these sorts of patterns at this stage: figure out what needs to be done and find out what technologies would be best suited to do it with. The overall architecture will emerge eventually.</p>

ContentLicense: CC BY-SA 2.5


问:
How to do "static overloaded const" in C#?
I'm creating a game in C#. Each level is made up of several tiles. Each tile is of a certain type e.g. grass floor, wooden wall, etc.

Ideally I would like to have one base class "Tile" and inherit from it to create classes for each type of tile. I would like to have the properties of the tile some kind of static/const/etc member of the sub-class since each type of tile is only ever going to have the same properties. I.e. I don't want 100 Tiles have a property which all have the same value, that seems rather inefficient.

The problem is you can't do that in C#. Are there any ways to achieve what I want?

My alternative idea was to separate it all into to trees, one with only the class "Tile" which represents an instance and another "TileType" from which I instanciate one object for each type and maybe access them through some kind of "TileTypeCollection". This feels strange though and I would rather do it in the first way.

Are there any general guidelines when dealing with a situation like this?

答: One way would be to have static properties on the child classes and a non static virtual accessor in the base class that when overriden returns the static values.</p>


问:
object FlinkKafkaConsumer010 is not a member of package org.apache.flink.streaming.connectors.kafka
I am trying to assembly a little program to connect to kafka topic using apache flink. I need to use FlinkKafkaConsumer010.

```<code>package uimp
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.util.serialization.SimpleStringSchema
import org.apache.flink.streaming.connectors.kafka.{FlinkKafkaConsumer010}
import java.util.Properties

object Silocompro {
  def main(args: Array[String]): Unit = {
 // set up the execution environment
    val env = StreamExecutionEnvironment.getExecutionEnvironment
    env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime)

    val propertiesTopicDemographic = new Properties()
    propertiesTopicDemographic.setProperty("bootstrap.servers", "bigdata.dataspartan.com:19093")
    propertiesTopicDemographic.setProperty("group.id", "demographic")

    val myConsumerDemographic = new FlinkKafkaConsumer010[String]("topic_demographic", new
    SimpleStringSchema(), propertiesTopicDemographic)

    val messageStreamDemographic = env
      .addSource(myConsumerDemographic)
      .print()

    env.execute("Flink Scala API Skeleton")

   }
 }
</code>```

My problem is when a try to assembly my program with this build.sbt, the compiler returns an error "object FlinkKafkaConsumer010 is not a member of package org.apache.flink.streaming.connectors.kafka":

```<code>      ThisBuild / resolvers ++= Seq("Apache Development Snapshot Repository" at
      "https://repository.apache.org/content/repositories/snapshots/",Resolver.mavenLocal)

      name := "silocompro"

      version := "1.0"

      organization := "uimp"

      ThisBuild / scalaVersion := "2.12.11"

      val flinkVersion = "1.9.0"

      val flinkDependencies = Seq(
         "org.apache.flink" %% "flink-scala" % flinkVersion % "provided",
         "org.apache.flink" %% "flink-streaming-scala" % flinkVersion % "provided",
         "org.apache.flink" %% "flink-core"% flinkVersion % "provided",
         "org.apache.flink" %% "flink-connector-kafka-base" % flinkVersion % "provided",
         "org.apache.flink" %% "flink-clients" % flinkVersion % "provided",
         "org.apache.flink" %% "flink-connector-kafka" % flinkVersion % "provided")

      lazy val root = (project in file(".")).
      settings( libraryDependencies ++= flinkDependencies)

      assembly / mainClass := Some("uimp.Silocompro")

      Compile / run  := Defaults.runTask(Compile / fullClasspath,
                               Compile / run / mainClass,
                               Compile / run / runner
                              ).evaluated

      Compile / run / fork := true
      Global / cancelable := true

      assembly / assemblyOption  := (assembly / assemblyOption).value.copy(includeScala = false)
</code>```

What is the reason of this dependency error?

答:
In the end I had a problem of dependencies. I have done some actions:

I have added a new resolver
https:/oss.sonatype.org/content/repositories

I have uninstalled
plugin metals(scala) from VS Code

I have added"org.apache.flink"%% "flink-connector-kafka-0.10"%flinkVersion - tomy flinkDependencies

And after this actions I solved my library dependencies problem. Thanks

Body:
I am trying to assembly a little program to connect to kafka topic using apache flink. I need to use FlinkKafkaConsumer010.

package uimp
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.util.serialization.SimpleStringSchema
import org.apache.flink.streaming.connectors.kafka.{FlinkKafkaConsumer010}
import java.util.Properties

object Silocompro {
  def main(args: Array[String]): Unit = {
 // set up the execution environment
    val env = StreamExecutionEnvironment.getExecutionEnvironment
    env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime)

    val propertiesTopicDemographic = new Properties()
    propertiesTopicDemographic.setProperty("bootstrap.servers", "bigdata.dataspartan.com:19093")
    propertiesTopicDemographic.setProperty("group.id", "demographic")

    val myConsumerDemographic = new FlinkKafkaConsumer010[String]("topic_demographic", new
    SimpleStringSchema(), propertiesTopicDemographic)

    val messageStreamDemographic = env
      .addSource(myConsumerDemographic)
      .print()

    env.execute("Flink Scala API Skeleton")

   }
 }

My problem is when a try to assembly my program with this build.sbt, the compiler returns an error "object FlinkKafkaConsumer010 is not a member of package org.apache.flink.streaming.connectors.kafka":

      ThisBuild / resolvers ++= Seq("Apache Development Snapshot Repository" at
      "https://repository.apache.org/content/repositories/snapshots/",Resolver.mavenLocal)

      name := "silocompro"

      version := "1.0"

      organization := "uimp"

      ThisBuild / scalaVersion := "2.12.11"

      val flinkVersion = "1.9.0"

      val flinkDependencies = Seq(
         "org.apache.flink" %% "flink-scala" % flinkVersion % "provided",
         "org.apache.flink" %% "flink-streaming-scala" % flinkVersion % "provided",
         "org.apache.flink" %% "flink-core"% flinkVersion % "provided",
         "org.apache.flink" %% "flink-connector-kafka-base" % flinkVersion % "provided",
         "org.apache.flink" %% "flink-clients" % flinkVersion % "provided",
         "org.apache.flink" %% "flink-connector-kafka" % flinkVersion % "provided")

      lazy val root = (project in file(".")).
      settings( libraryDependencies ++= flinkDependencies)

      assembly / mainClass := Some("uimp.Silocompro")

      Compile / run  := Defaults.runTask(Compile / fullClasspath,
                               Compile / run / mainClass,
                               Compile / run / runner
                              ).evaluated

      Compile / run / fork := true
      Global / cancelable := true

      assembly / assemblyOption  := (assembly / assemblyOption).value.copy(includeScala = false)

What is the reason of this dependency error?


问:
Counter not increasing in async map function
I am working with mongodb and nodejs. I have an array of customers I have to create each inside database.

```<code>const promises2 = customers.map(async customer => {
      if (!customer.customerId) {
        const counter = await Counter.findOne({ type: "Customer" });
        console.log({counter});
        const payload = {
          customerId: counter.sequence_value,
        };
        await Customer.create(payload);
        await Counter.findOneAndUpdate({ type: "Customer" }, { $inc: { sequence_value: 1 } });
      }
    });
    await Promise.all([...promises2]);
</code>```

The issue is counter is not increasing every time. I am getting same counter in all the created customers. What is the issue here?

Issue is something like this but don't have an answer.

答:
The problem is that all the calls overlap. Since the first thing they each do is get the current counter, they all get the same counter, then try to use it. Fundamentally, you don't want to do this:

```<code>const counter = await Counter.findOne({ type: "Customer" });
// ...
await Counter.findOneAndUpdate({ type: "Customer" }, { $inc: { sequence_value: 1 } });
</code>```

...because it creates a race condition: overlapping asynchronous operations can both get the same sequence value and then both issue an update to it.

You want an atomic operation for incrementing and retrieving a new ID. I don't use MongoDB, but I think the findOneAndUpdate operation can do that for you if you add the returnNewDocument option. If so, the minimal change would be to swap over to using that:

```<code>const promises2 = customers.map(async customer => {
  if (!customer.customerId) {
    const counter = await Counter.findOneAndUpdate(
      { type: "Customer" },
      { $inc: { sequence_value: 1 } },
      { returnNewDocument: true }
    );
    console.log({counter});
    const payload = {
      customerId: counter.sequence_value,
    };
    await Customer.create(payload);
  }
});
await Promise.all([...promises2]);
</code>```

...but there's no reason to create an array and then immediately copy it, just use it directly:

```<code>await Promise.all(customers.map(async customer => {
  if (!customer.customerId) {
    const counter = await Counter.findOneAndUpdate(
      { type: "Customer" },
      { $inc: { sequence_value: 1 } },
      { returnNewDocument: true }
    );
    console.log({counter});
    const payload = {
      customerId: counter.sequence_value,
    };
    await Customer.create(payload);
  }
}));
</code>```

The overall operation will fail if anything fails, and only the first failure is reported back to your code (the other operations then continue and succeed or fail as the case may be). If you want to know everything that happened (which is probably useful in this case), you can use allSettled instead of all:

```<code>// Gets an array of {status, value/reason} objects
const results = await Promise.allSettled(customers.map(async customer => {
  if (!customer.customerId) {
    const counter = await Counter.findOneAndUpdate(
      { type: "Customer" },
      { $inc: { sequence_value: 1 } },
      { returnNewDocument: true }
    );
    console.log({counter});
    const payload = {
      customerId: counter.sequence_value,
    };
    await Customer.create(payload);
  }
}));
const errors = results.filter(({status}) => status === "rejected").map(({reason}) => reason);
if (errors.length) {
  // Handle/report errors here
}
</code>```

Promise.allSettled is new in ES2021, but easily polyfilled if needed.

If I'm mistaken about the above use of findOneAndUpdate in some way, I'm sure MongoDB gives you a way to get those IDs without a race condition. But in the worst case, you can pre-allocate the IDs instead, something like this:

```<code>// Allocate IDs (in series)
const ids = [];
for (const customer of customers) {
  if (!customer.customerId) {
    const counter = await Counter.findOne({ type: "Customer" });
    await Counter.findOneAndUpdate({ type: "Customer" }, { $inc: { sequence_value: 1 } });
    ids.push(counter.sequence_value);
  }
}

// Create customers (in parallel)
const results = await Promise.allSettled(customers.map(async(customer, index) => {
  const customerId = ids[index];
  try {
    await Customer.create({
      customerId
    });
  } catch (e) {
    // Failed, remove the counter, but without allowing any error doing so to
    // shadow the error we're already handling
    try {
      await Counter.someDeleteMethodHere(/*...customerId...*/);
    } catch (e2) {
      // ...perhaps report `e2` here, but don't shadow `e`
    }
    throw e;
  }
});

// Get just the errors
const errors = results.filter(({status}) => status === "rejected").map(({reason}) => reason);
if (errors.length) {
  // Handle/report errors here
}
</code>```

Body:
I am working with mongodb and nodejs. I have an array of customers I have to create each inside database.

const promises2 = customers.map(async customer => {
      if (!customer.customerId) {
        const counter = await Counter.findOne({ type: "Customer" });
        console.log({counter});
        const payload = {
          customerId: counter.sequence_value,
        };
        await Customer.create(payload);
        await Counter.findOneAndUpdate({ type: "Customer" }, { $inc: { sequence_value: 1 } });
      }
    });
    await Promise.all([...promises2]);

The issue is counter is not increasing every time. I am getting same counter in all the created customers. What is the issue here?

Issue is something like this but don't have an answer.

Body:
The problem is that all the calls overlap. Since the first thing they each do is get the current counter, they all get the same counter, then try to use it. Fundamentally, you don't want to do this:

const counter = await Counter.findOne({ type: "Customer" });
// ...
await Counter.findOneAndUpdate({ type: "Customer" }, { $inc: { sequence_value: 1 } });

...because it creates a race condition: overlapping asynchronous operations can both get the same sequence value and then both issue an update to it.

You want an atomic operation for incrementing and retrieving a new ID. I don't use MongoDB, but I think the findOneAndUpdate operation can do that for you if you add the returnNewDocument option. If so, the minimal change would be to swap over to using that:

const promises2 = customers.map(async customer => {
  if (!customer.customerId) {
    const counter = await Counter.findOneAndUpdate(
      { type: "Customer" },
      { $inc: { sequence_value: 1 } },
      { returnNewDocument: true }
    );
    console.log({counter});
    const payload = {
      customerId: counter.sequence_value,
    };
    await Customer.create(payload);
  }
});
await Promise.all([...promises2]);

...but there's no reason to create an array and then immediately copy it, just use it directly:

await Promise.all(customers.map(async customer => {
  if (!customer.customerId) {
    const counter = await Counter.findOneAndUpdate(
      { type: "Customer" },
      { $inc: { sequence_value: 1 } },
      { returnNewDocument: true }
    );
    console.log({counter});
    const payload = {
      customerId: counter.sequence_value,
    };
    await Customer.create(payload);
  }
}));

The overall operation will fail if anything fails, and only the first failure is reported back to your code (the other operations then continue and succeed or fail as the case may be). If you want to know everything that happened (which is probably useful in this case), you can use allSettled instead of all:

// Gets an array of {status, value/reason} objects
const results = await Promise.allSettled(customers.map(async customer => {
  if (!customer.customerId) {
    const counter = await Counter.findOneAndUpdate(
      { type: "Customer" },
      { $inc: { sequence_value: 1 } },
      { returnNewDocument: true }
    );
    console.log({counter});
    const payload = {
      customerId: counter.sequence_value,
    };
    await Customer.create(payload);
  }
}));
const errors = results.filter(({status}) => status === "rejected").map(({reason}) => reason);
if (errors.length) {
  // Handle/report errors here
}

Promise.allSettled is new in ES2021, but easily polyfilled if needed.

If I'm mistaken about the above use of findOneAndUpdate in some way, I'm sure MongoDB gives you a way to get those IDs without a race condition. But in the worst case, you can pre-allocate the IDs instead, something like this:

// Allocate IDs (in series)
const ids = [];
for (const customer of customers) {
  if (!customer.customerId) {
    const counter = await Counter.findOne({ type: "Customer" });
    await Counter.findOneAndUpdate({ type: "Customer" }, { $inc: { sequence_value: 1 } });
    ids.push(counter.sequence_value);
  }
}

// Create customers (in parallel)
const results = await Promise.allSettled(customers.map(async(customer, index) => {
  const customerId = ids[index];
  try {
    await Customer.create({
      customerId
    });
  } catch (e) {
    // Failed, remove the counter, but without allowing any error doing so to
    // shadow the error we're already handling
    try {
      await Counter.someDeleteMethodHere(/*...customerId...*/);
    } catch (e2) {
      // ...perhaps report `e2` here, but don't shadow `e`
    }
    throw e;
  }
});

// Get just the errors
const errors = results.filter(({status}) => status === "rejected").map(({reason}) => reason);
if (errors.length) {
  // Handle/report errors here
}


问:
Trying to define a cython method results in `cdef statement not allowed here` error
I'm trying to convert a pure Python module into Cython compatible one using EasyCython module.

The issue however is, upon trying to execute the EasyCython, it fails with the error:

```<code>G:\Proc\python\FV>easycython F_V.pyx
Compiling F_V.pyx because it changed.
[1/1] Cythonizing F_V.pyx
C:\Users\Rika\Anaconda3\Lib\site-packages\Cython\Compiler\Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: G:\Proc\python\FV\F_V.pyx
  tree = Parsing.p_module(s, pxd, full_module_name)

Error compiling Cython file:
------------------------------------------------------------
...
    # or the network would mistake some one else for someother people! (for example someone has a profile image
    # while the other doesnt, when confronted with the profile image, the network most likely find more features
    # from the person that has already a profile image of him in the fbank (unless the change is noticeable
    # this really can be a major issue)))
    # @benchmark
    cpdef _identify_id(self, input_img_embedding, list embedding_list, bint short_circut=True, bint accumulate_score=False):
         ^
------------------------------------------------------------

F_V.pyx:929:10: cdef statement not allowed here
Traceback (most recent call last):
  File "C:\Users\Rika\Anaconda3\Lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Users\Rika\Anaconda3\Lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\Rika\Anaconda3\Scripts\easycython.exe\__main__.py", line 7, in <module>
  File "C:\Users\Rika\Anaconda3\Lib\site-packages\begin\main.py", line 54, in start
    collector=self._collector)
  File "C:\Users\Rika\Anaconda3\Lib\site-packages\begin\cmdline.py", line 253, in apply_options
    return_value = call_function(func, signature(ext), opts)
  File "C:\Users\Rika\Anaconda3\Lib\site-packages\begin\cmdline.py", line 236, in call_function
    return func(*pargs, **kwargs)
  File "C:\Users\Rika\Anaconda3\Lib\site-packages\easycython\easycython.py", line 77, in main
    ext_modules = cythonize(ext_modules),
  File "C:\Users\Rika\Anaconda3\Lib\site-packages\Cython\Build\Dependencies.py", line 1102, in cythonize
    cythonize_one(*args)
  File "C:\Users\Rika\Anaconda3\Lib\site-packages\Cython\Build\Dependencies.py", line 1225, in cythonize_one
    raise CompileError(None, pyx_file)
Cython.Compiler.Errors.CompileError: F_V.pyx
</code>```

Here are the two methods that are being annotated with cython types.

#@benchmark
cpdef _identify_id(self, input_img_embedding, list embedding_list, bint short_circut=True, bint accumulate_score=False):
    # These are the underlying types for the arguments and local variables used here
    # input_img_embedding_type: <class 'torch.Tensor'> shape:torch.Size([1, 512])
    # feature1 type: <class 'torch.Tensor'> shape: torch.Size([1, 512])
    # x1 type: <class 'torch.Tensor'> shape: torch.Size([1, 512])
    # cosine type: <class 'numpy.float32'> shape: ()
    # np.clip(cosine) type: <class 'numpy.float64'> shape: ()
    #
    cdef float min_theta = 1000.0
    cdef float total_theta = 0.0
    cdef char* id_name = 'None' #None
    for (name, feature1) in embedding_list:
        id_name = name
        x1 = feature1 / np.linalg.norm(feature1)
        cosine = np.dot(input_img_embedding.squeeze(0), x1.squeeze(0))
        cdef float cosine = np.clip(cosine, -1.0, 1.0)
        cdef float theta = math.acos(cosine)
        cdef float theta = theta * 180 / math.pi

        if short_circut:
            if theta < self._threshold:
                return id_name, theta

        if theta < min_theta:
            min_theta = theta

        total_theta += theta

    # the elses from now on are for debugging purposes
    if not short_circut and not accumulate_score:
        if min_theta < self._threshold:
            return id_name, min_theta
        else:
            return 'unknown', min_theta

    if accumulate_score:
        final_score = total_theta/len(embedding_list)
        if final_score < self._threshold:
            return id_name, final_score
        else:
            return 'unknown', final_score

    return 'unknown', theta # min_theta

#@benchmark
cpdef _check_in_fbank(self, img):
    """Checks whether a given image is represented in the face bank.

    Arguments:
        img {torch.tensor} -- input image to be verified

    Returns:
        tuple(name, theta)
    """
        # These are the underlying python types
        # img type: <class 'torch.Tensor'> shape: torch.Size([3, 112, 112])
        # feature0 type: <class 'torch.Tensor'> shape: torch.Size([1, 512])
        # x0 type: <class 'torch.Tensor'> shape: torch.Size([1, 512])

    with Benchmark_Block("model frwd took: "):
         feature0 = self.model(img.unsqueeze(0)).cpu().detach()
         x0 = feature0 / np.linalg.norm(feature0)

    cdef list lst = []
    for img_list in self._fbank_embeddings:
        cdef tuple f = self._identify_id(x0, img_list, short_circut=self.short_circut, accumulate_score=self.accumulate_score)
        lst.append(f)

    cdef tuple min_val  = min(lst, key=lambda t: t[1])
    print(f'lst of returned results : {lst}. The minimum is: {min_val} in {len(self._fbank_embeddings)} enteries')
    return min_val
```

What am I missing here?

答:
The issue happens to be that When using a python class, one should also use cdef as well. This kind of class is called an Extension Type.

From Cython documentation:

... a Cython extension type definition looks a lot like a Python class
  definition. Within it, you use the def statement to define methods
  that can be called from Python code. You can even define many of the
  special methods such as init() as you would in Python.

Note:

After doing so, in order to be able to use my class in Python, I had to inherit from it and instead use the inherited class. That is I had to do :

cdef class MyClass():
    def __init__(self, args)
        ...

    cpdef func1(self,...):
        ...

    cpdef func2(self, ....):
        ...
    ...

class MyClass2(MyClass):
    def __init__(self, args):
       super().__init__(args)
       pass
```

<p>And in you client code : </p>

<pre class="lang-py prettyprint-override"><code># use MyClass2 from now on
obj = MyClass2(args)
...
</code>```

Body:
I'm trying to convert a pure Python module into Cython compatible one using EasyCython module.

The issue however is, upon trying to execute the EasyCython, it fails with the error:

G:\Proc\python\FV>easycython F_V.pyx
Compiling F_V.pyx because it changed.
[1/1] Cythonizing F_V.pyx
C:\Users\Rika\Anaconda3\Lib\site-packages\Cython\Compiler\Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: G:\Proc\python\FV\F_V.pyx
  tree = Parsing.p_module(s, pxd, full_module_name)

Error compiling Cython file:
------------------------------------------------------------
...
    # or the network would mistake some one else for someother people! (for example someone has a profile image
    # while the other doesnt, when confronted with the profile image, the network most likely find more features
    # from the person that has already a profile image of him in the fbank (unless the change is noticeable
    # this really can be a major issue)))
    # @benchmark
    cpdef _identify_id(self, input_img_embedding, list embedding_list, bint short_circut=True, bint accumulate_score=False):
         ^
------------------------------------------------------------

F_V.pyx:929:10: cdef statement not allowed here
Traceback (most recent call last):
  File "C:\Users\Rika\Anaconda3\Lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Users\Rika\Anaconda3\Lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\Rika\Anaconda3\Scripts\easycython.exe\__main__.py", line 7, in <module>
  File "C:\Users\Rika\Anaconda3\Lib\site-packages\begin\main.py", line 54, in start
    collector=self._collector)
  File "C:\Users\Rika\Anaconda3\Lib\site-packages\begin\cmdline.py", line 253, in apply_options
    return_value = call_function(func, signature(ext), opts)
  File "C:\Users\Rika\Anaconda3\Lib\site-packages\begin\cmdline.py", line 236, in call_function
    return func(*pargs, **kwargs)
  File "C:\Users\Rika\Anaconda3\Lib\site-packages\easycython\easycython.py", line 77, in main
    ext_modules = cythonize(ext_modules),
  File "C:\Users\Rika\Anaconda3\Lib\site-packages\Cython\Build\Dependencies.py", line 1102, in cythonize
    cythonize_one(*args)
  File "C:\Users\Rika\Anaconda3\Lib\site-packages\Cython\Build\Dependencies.py", line 1225, in cythonize_one
    raise CompileError(None, pyx_file)
Cython.Compiler.Errors.CompileError: F_V.pyx

Here are the two methods that are being annotated with cython types.

#@benchmark
cpdef _identify_id(self, input_img_embedding, list embedding_list, bint short_circut=True, bint accumulate_score=False):
    # These are the underlying types for the arguments and local variables used here
    # input_img_embedding_type: <class 'torch.Tensor'> shape:torch.Size([1, 512])
    # feature1 type: <class 'torch.Tensor'> shape: torch.Size([1, 512])
    # x1 type: <class 'torch.Tensor'> shape: torch.Size([1, 512])
    # cosine type: <class 'numpy.float32'> shape: ()
    # np.clip(cosine) type: <class 'numpy.float64'> shape: ()
    #
    cdef float min_theta = 1000.0
    cdef float total_theta = 0.0
    cdef char* id_name = 'None' #None
    for (name, feature1) in embedding_list:
        id_name = name
        x1 = feature1 / np.linalg.norm(feature1)
        cosine = np.dot(input_img_embedding.squeeze(0), x1.squeeze(0))
        cdef float cosine = np.clip(cosine, -1.0, 1.0)
        cdef float theta = math.acos(cosine)
        cdef float theta = theta * 180 / math.pi

        if short_circut:
            if theta < self._threshold:
                return id_name, theta

        if theta < min_theta:
            min_theta = theta

        total_theta += theta

    # the elses from now on are for debugging purposes
    if not short_circut and not accumulate_score:
        if min_theta < self._threshold:
            return id_name, min_theta
        else:
            return 'unknown', min_theta

    if accumulate_score:
        final_score = total_theta/len(embedding_list)
        if final_score < self._threshold:
            return id_name, final_score
        else:
            return 'unknown', final_score

    return 'unknown', theta # min_theta

#@benchmark
cpdef _check_in_fbank(self, img):
    """Checks whether a given image is represented in the face bank.

    Arguments:
        img {torch.tensor} -- input image to be verified

    Returns:
        tuple(name, theta)
    """
        # These are the underlying python types
        # img type: <class 'torch.Tensor'> shape: torch.Size([3, 112, 112])
        # feature0 type: <class 'torch.Tensor'> shape: torch.Size([1, 512])
        # x0 type: <class 'torch.Tensor'> shape: torch.Size([1, 512])

    with Benchmark_Block("model frwd took: "):
         feature0 = self.model(img.unsqueeze(0)).cpu().detach()
         x0 = feature0 / np.linalg.norm(feature0)

    cdef list lst = []
    for img_list in self._fbank_embeddings:
        cdef tuple f = self._identify_id(x0, img_list, short_circut=self.short_circut, accumulate_score=self.accumulate_score)
        lst.append(f)

    cdef tuple min_val  = min(lst, key=lambda t: t[1])
    print(f'lst of returned results : {lst}. The minimum is: {min_val} in {len(self._fbank_embeddings)} enteries')
    return min_val

What am I missing here?

Body:
The issue happens to be that When using a python class, one should also use cdef as well. This kind of class is called an Extension Type.

From Cython documentation:

... a Cython extension type definition looks a lot like a Python class
  definition. Within it, you use the def statement to define methods
  that can be called from Python code. You can even define many of the
  special methods such as init() as you would in Python.

Note:

After doing so, in order to be able to use my class in Python, I had to inherit from it and instead use the inherited class. That is I had to do :

cdef class MyClass():
    def __init__(self, args)
        ...

    cpdef func1(self,...):
        ...

    cpdef func2(self, ....):
        ...
    ...

class MyClass2(MyClass):
    def __init__(self, args):
       super().__init__(args)
       pass

And in you client code :

# use MyClass2 from now on
obj = MyClass2(args)
...


问:
sort array of objects with more than one criteria
Lets say that I have an array of objects:

```<code>let updatedEvents = [
{
 "code": "3894",
 "date": "2020-06-01T20:00:00+0300",
 "timestamp": 1591030800
},
{
 "code": "1976",
 "date": "2020-06-01T20:00:00+0300",
 "timestamp": 1591030800
},
{
 "code": "0482",
 "date": "2020-06-01T20:00:00+0300",
 "timestamp": 1591030800
},
{
 "code": "0408",
 "date": "2020-06-01T20:00:00+0300",
 "timestamp": 1591030800
},
];
</code>```

If I want to sort them by event date and if event date is the same in any event then sort them by code in ascending order then the following would be correct? :

```<code>const sortedEventsByDateUniqueCode = updatedEvents.sort((eventOne, eventTwo) => {
 if (eventOne.date === eventTwo.date) {
  return -1;
 }
 if (eventOne.code > eventTwo.code) return 1;
 if (eventOne.code < eventTwo.code) return -1;
});
</code>```

答:
No: in your case, you start with

if (eventOne.date === eventTwo.date) {
  return -1;
}
```

<p>which will always put <code>eventOne</code> before <code>eventTwo</code> if they have the same <code>date</code>. However, what you want is to only check the <code>code</code> if they have the same <code>date</code>; otherwise, sort by <code>date</code>.</p>

<p>It gets quite verbose, but you can go for:</p>

<pre class="lang-js prettyprint-override"><code>if (eventOne.date < eventTwo.date) {
  return -1;
}
if (eventOne.date > eventTwo.date) {
  return 1;
}
if (eventOne.code < eventTwo.code) {
  return -1;
}
if (eventOne.code > eventTwo.code) {
  return 1;
}
return 0;
</code>```

As I said however, this is quite verbose; it would be nice if you could use a shorter version.

gorak has helpfully given a short one:

return (new Date(eventOne.date) - new Date(eventTwo.date)) || (eventOne.code - eventTwo.code);
```

<p>This works because dates and strings can be subtracted from each other (if two event <code>codes</code> have different lengths, then it may not work) and will return <code>0</code> if they are equal. <code>0</code> is falsey, so when it is used in the left-hand-side of the or <code>||</code> expression, it evaluates to false and returns the value on the right-hand-side. If, however, one <code>date</code> is smaller than the other, it will return a positive or negative number (not necessarily <code>-1</code> or <code>1</code>). </p>

<p>If you really want to use <code>-1</code>, <code>0</code> and <code>1</code>, then you could do something like:</p>

<pre class="lang-js prettyprint-override"><code>const dateDiff = new Date(eventOne.date) - new Date(eventTwo.date);
const codeDiff = eventOne.code - eventTwo.code;
return (dateDiff / Math.abs(dateDiff)) || (codeDiff / Math.abs(codeDiff)) || 0;
</code>```

Body:
Lets say that I have an array of objects:

let updatedEvents = [
{
 "code": "3894",
 "date": "2020-06-01T20:00:00+0300",
 "timestamp": 1591030800
},
{
 "code": "1976",
 "date": "2020-06-01T20:00:00+0300",
 "timestamp": 1591030800
},
{
 "code": "0482",
 "date": "2020-06-01T20:00:00+0300",
 "timestamp": 1591030800
},
{
 "code": "0408",
 "date": "2020-06-01T20:00:00+0300",
 "timestamp": 1591030800
},
];

If I want to sort them by event date and if event date is the same in any event then sort them by code in ascending order then the following would be correct? :

const sortedEventsByDateUniqueCode = updatedEvents.sort((eventOne, eventTwo) => {
 if (eventOne.date === eventTwo.date) {
  return -1;
 }
 if (eventOne.code > eventTwo.code) return 1;
 if (eventOne.code < eventTwo.code) return -1;
});

Body:
No: in your case, you start with

if (eventOne.date === eventTwo.date) {
  return -1;
}

which will always put eventOne before eventTwo if they have the same date. However, what you want is to only check the code if they have the same date; otherwise, sort by date.

It gets quite verbose, but you can go for:

if (eventOne.date < eventTwo.date) {
  return -1;
}
if (eventOne.date > eventTwo.date) {
  return 1;
}
if (eventOne.code < eventTwo.code) {
  return -1;
}
if (eventOne.code > eventTwo.code) {
  return 1;
}
return 0;

As I said however, this is quite verbose; it would be nice if you could use a shorter version.

gorak has helpfully given a short one:

return (new Date(eventOne.date) - new Date(eventTwo.date)) || (eventOne.code - eventTwo.code);

This works because dates and strings can be subtracted from each other (if two event codes have different lengths, then it may not work) and will return 0 if they are equal. 0 is falsey, so when it is used in the left-hand-side of the or || expression, it evaluates to false and returns the value on the right-hand-side. If, however, one date is smaller than the other, it will return a positive or negative number (not necessarily -1 or 1).

If you really want to use -1, 0 and 1, then you could do something like:

const dateDiff = new Date(eventOne.date) - new Date(eventTwo.date);
const codeDiff = eventOne.code - eventTwo.code;
return (dateDiff / Math.abs(dateDiff)) || (codeDiff / Math.abs(codeDiff)) || 0;


问:
How to remove first 10 characters from a string?
How to ignore the first 10 characters of a string?

Input:

```<code>str = "hello world!";
</code>```

Output:

```<code>d!
</code>```

答:
Calling SubString() allocates a new string. For optimal performance, you should avoid that extra allocation. Starting with C# 7.2 you can take advantage of the Span pattern.

When targeting .NET Framework, include the System.Memory NuGet package. For .NET Core projects this works out of the box.

```<code>static void Main(string[] args)
{
    var str = "hello world!";
    var span = str.AsSpan(10); // No allocation!

    // Outputs: d!
    foreach (var c in span)
    {
        Console.Write(c);
    }

    Console.WriteLine();
}
</code>```

Body:
How to ignore the first 10 characters of a string?

Input:

str = "hello world!";

Output:

d!

Body:
Calling SubString() allocates a new string. For optimal performance, you should avoid that extra allocation. Starting with C# 7.2 you can take advantage of the Span pattern.

When targeting .NET Framework, include the System.Memory NuGet package. For .NET Core projects this works out of the box.

static void Main(string[] args)
{
    var str = "hello world!";
    var span = str.AsSpan(10); // No allocation!

    // Outputs: d!
    foreach (var c in span)
    {
        Console.Write(c);
    }

    Console.WriteLine();
}


问:
why virtualenv (version 20) is much faster than python3 -m venv
I have tested on my 2015 macbook, virtualenv is 6 times faster.

virtualenv version is 20.0.21

```<code>$ time virtualenv $RANDOM
created virtual environment CPython3.8.3.final.0-64 in 340ms
  creator CPython3Posix(dest=/private/tmp/4997, clear=False, global=False)
  seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, via=copy, app_data_dir=/Users/noname/Library/Application Support/virtualenv/seed-app-data/v1.0.1)
  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

real    0m0.489s
user    0m0.269s
sys     0m0.283s
</code>```

```<code>$ time /usr/local/opt/python@3.8/bin/python3 -m venv $RANDOM

real    0m3.112s
user    0m2.334s
sys     0m0.731s
</code>```

python3.8 is installed via homebrew.

even with --creator venv --always-copy options, virtualenv is faster:

```<code>$ time virtualenv --creator venv --always-copy $RANDOM
created virtual environment CPython3.8.3.final.0-64 in 418ms
  creator Venv(dest=/private/tmp/28878, clear=False, global=False, describe=CPython3Posix)
  seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, via=copy, app_data_dir=/Users/noname/Library/Application Support/virtualenv/seed-app-data/v1.0.1)
  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

real    0m0.554s
user    0m0.316s
sys     0m0.309s
</code>```

why don't they have the same performance?

答:
As far as I understood most of the difference is due to the different methods used to provision the newly created virtual environments.

In February 2020 the version 20 of virtualenv was released, it was a full rewrite. And with it came the new concept called seeders, those define the different methods to provision the environments, i.e. make things such as pip and setuptools available in the environment. Current versions of virtualenv have two seeders:

pip which is probably similar to what venv and earlier versions of virtualenv do.

app-data, the current default seeder, which uses a different mechanism and is probably the larger contributor to the speed improvements.

From the documentation:

app-data - this method uses the user application data directory to create install images. These images are needed to be created only once, and subsequent virtual environments can just link/copy those images into their pure python library path (the site-packages folder). This allows all but the first virtual environment creation to be blazing fast (a pip mechanism takes usually 98% of the virtualenv creation time, so by creating this install image that we can just link into the virtual environments install directory we can achieve speedups of shaving the initial 1 minutes 10 seconds down to just 8 seconds in case of copy, or 0.8 seconds in case symlinks are available - this is on Windows, Linux/macOS with symlinks this can be as low as 100ms from 3+ seconds).

You can also read a bit more technical details in this discussion:

https://discuss.python.org/t/virtualenv-20-0-0-beta1-is-available/3077

Body:
I have tested on my 2015 macbook, virtualenv is 6 times faster.

virtualenv version is 20.0.21

$ time virtualenv $RANDOM
created virtual environment CPython3.8.3.final.0-64 in 340ms
  creator CPython3Posix(dest=/private/tmp/4997, clear=False, global=False)
  seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, via=copy, app_data_dir=/Users/noname/Library/Application Support/virtualenv/seed-app-data/v1.0.1)
  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

real    0m0.489s
user    0m0.269s
sys     0m0.283s

$ time /usr/local/opt/python@3.8/bin/python3 -m venv $RANDOM

real    0m3.112s
user    0m2.334s
sys     0m0.731s

python3.8 is installed via homebrew.

even with --creator venv --always-copy options, virtualenv is faster:

$ time virtualenv --creator venv --always-copy $RANDOM
created virtual environment CPython3.8.3.final.0-64 in 418ms
  creator Venv(dest=/private/tmp/28878, clear=False, global=False, describe=CPython3Posix)
  seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, via=copy, app_data_dir=/Users/noname/Library/Application Support/virtualenv/seed-app-data/v1.0.1)
  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

real    0m0.554s
user    0m0.316s
sys     0m0.309s

why don't they have the same performance?


问:
How to solve this error Error: Could not resolve the package
```<code>Compiler message:
Error: Could not resolve the package 'razorpay_flutter' in
'package:razorpay_flutter/razorpay_flutter.dart'.
lib/Screens/add_amount.dart:5:8: Error: Not found:
'package:razorpay_flutter/razorpay_flutter.dart'
import 'package:razorpay_flutter/razorpay_flutter.dart';
</code>```

I a implementing the flutter_razorpay in my flutter application but i am getting this error. And then i created a new project and again implemented this but same error appear every time when i import the package and hot reload

```<code>name: gamershub
environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.3
  flutter_spinkit: ^4.1.2+1
  cloud_firestore: ^0.13.6
  google_sign_in: ^4.5.1
  flutter_facebook_login: ^3.0.0
  firebase_auth: ^0.16.0
  fluttertoast: ^4.0.1
  razorpay_flutter:
dev_dependencies:
   flutter_test:
    sdk: flutter
</code>```

答:
There is a big chance either you are trying to use an incorrect version of the package or your indentation in pubspec.yaml might be wrong.

If that will not work for you. Please share your pubspec.yaml

Body:
Compiler message:
Error: Could not resolve the package 'razorpay_flutter' in
'package:razorpay_flutter/razorpay_flutter.dart'.
lib/Screens/add_amount.dart:5:8: Error: Not found:
'package:razorpay_flutter/razorpay_flutter.dart'
import 'package:razorpay_flutter/razorpay_flutter.dart';

I a implementing the flutter_razorpay in my flutter application but i am getting this error. And then i created a new project and again implemented this but same error appear every time when i import the package and hot reload

name: gamershub
environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.3
  flutter_spinkit: ^4.1.2+1
  cloud_firestore: ^0.13.6
  google_sign_in: ^4.5.1
  flutter_facebook_login: ^3.0.0
  firebase_auth: ^0.16.0
  fluttertoast: ^4.0.1
  razorpay_flutter:
dev_dependencies:
   flutter_test:
    sdk: flutter


答:
Modification version from zero323 , for spark 2.4

```<code>import re

def clean_names(df):
    p = re.compile("^(\w+?)_([a-z]+)\((\w+)(,\s\w+)\)(:\s\w+)?")
    return df.toDF(*[p.sub(r"\1_\3", c) for c in df.columns])
</code>```

current column name is like 0_first(is_flashsale, false): int

Title: Rename pivoted and aggregated column in PySpark Dataframe

Body:
With a dataframe as follows:

from pyspark.sql.functions import avg, first

rdd = sc.parallelize(
    [
        (0, "A", 223,"201603", "PORT"),
        (0, "A", 22,"201602", "PORT"),
        (0, "A", 422,"201601", "DOCK"),
        (1,"B", 3213,"201602", "DOCK"),
        (1,"B", 3213,"201601", "PORT"),
        (2,"C", 2321,"201601", "DOCK")
    ]
)
df_data = sqlContext.createDataFrame(rdd, ["id","type", "cost", "date", "ship"])

df_data.show()

I do a pivot on it,

df_data.groupby(df_data.id, df_data.type).pivot("date").agg(avg("cost"), first("ship")).show()

+---+----+----------------+--------------------+----------------+--------------------+----------------+--------------------+
| id|type|201601_avg(cost)|201601_first(ship)()|201602_avg(cost)|201602_first(ship)()|201603_avg(cost)|201603_first(ship)()|
+---+----+----------------+--------------------+----------------+--------------------+----------------+--------------------+
|  2|   C|          2321.0|                DOCK|            null|                null|            null|                null|
|  0|   A|           422.0|                DOCK|            22.0|                PORT|           223.0|                PORT|
|  1|   B|          3213.0|                PORT|          3213.0|                DOCK|            null|                null|
+---+----+----------------+--------------------+----------------+--------------------+----------------+--------------------+

But I get these really complicated names for the columns. Applying alias on the aggregation usually works, but because of the pivot in this case the names are even worse:

+---+----+--------------------------------------------------------------+------------------------------------------------------------------+--------------------------------------------------------------+------------------------------------------------------------------+--------------------------------------------------------------+------------------------------------------------------------------+
| id|type|201601_(avg(cost),mode=Complete,isDistinct=false) AS cost#1619|201601_(first(ship)(),mode=Complete,isDistinct=false) AS ship#1620|201602_(avg(cost),mode=Complete,isDistinct=false) AS cost#1619|201602_(first(ship)(),mode=Complete,isDistinct=false) AS ship#1620|201603_(avg(cost),mode=Complete,isDistinct=false) AS cost#1619|201603_(first(ship)(),mode=Complete,isDistinct=false) AS ship#1620|
+---+----+--------------------------------------------------------------+------------------------------------------------------------------+--------------------------------------------------------------+------------------------------------------------------------------+--------------------------------------------------------------+------------------------------------------------------------------+
|  2|   C|                                                        2321.0|                                                              DOCK|                                                          null|                                                              null|                                                          null|                                                              null|
|  0|   A|                                                         422.0|                                                              DOCK|                                                          22.0|                                                              PORT|                                                         223.0|                                                              PORT|
|  1|   B|                                                        3213.0|                                                              PORT|                                                        3213.0|                                                              DOCK|                                                          null|                                                              null|
+---+----+--------------------------------------------------------------+------------------------------------------------------------------+--------------------------------------------------------------+------------------------------------------------------------------+--------------------------------------------------------------+------------------------------------------------------------------+

Is there a way to rename the column names on the fly on the pivot and aggregation?

Body:
Modification version from zero323 , for spark 2.4

import re

def clean_names(df):
    p = re.compile("^(\w+?)_([a-z]+)\((\w+)(,\s\w+)\)(:\s\w+)?")
    return df.toDF(*[p.sub(r"\1_\3", c) for c in df.columns])

current column name is like 0_first(is_flashsale, false): int


问:
How to create new Parse.Object with relation in Parse-SDK-JS
Docs say it is required to create relation type column in the dashboard prior to adding any relations to object:

In the Data Browser, you can create a column on the Book object of
  type relation and name it authors.

Is it possible to create it from js sdk level? I tried something like here:

```<code>book.save(null).then(saved => {
  let relation = new Parse.Relation(saved.id, "authors");
  relation.add(author);
  saved.save(null);
}
</code>```

But it can not be saved saying TypeError: this.parent.set is not a function

I know I can add it manually in the dashboard as stated, but the idea is to create new classes automatically.

答:
I will Show you how to add a pointer and relation in Parse

```<code>Parse.User.currentAsync().then((current) => {
  if (current) {
    var pharmacy = new Parse.Object("Pharmacy");
   // add a pointer here
    pharmacy.set("owner", current);
    pharmacy
      .save()
      .then((pharmacy) => {
        //   add a relation here
        var relation = current.relation("pharmacy");
        relation.add(pharmacy)
        current.save()};

  }
});
</code>```

Body:
Docs say it is required to create relation type column in the dashboard prior to adding any relations to object:

In the Data Browser, you can create a column on the Book object of
  type relation and name it authors.

Is it possible to create it from js sdk level? I tried something like here:

book.save(null).then(saved => {
  let relation = new Parse.Relation(saved.id, "authors");
  relation.add(author);
  saved.save(null);
}

But it can not be saved saying TypeError: this.parent.set is not a function

I know I can add it manually in the dashboard as stated, but the idea is to create new classes automatically.

Body:
I will Show you how to add a pointer and relation in Parse

Parse.User.currentAsync().then((current) => {
  if (current) {
    var pharmacy = new Parse.Object("Pharmacy");
   // add a pointer here
    pharmacy.set("owner", current);
    pharmacy
      .save()
      .then((pharmacy) => {
        //   add a relation here
        var relation = current.relation("pharmacy");
        relation.add(pharmacy)
        current.save()};

  }
});


问:
T4 References for 'MvcTextTemplateHost' and 'VisualStudio'
I'm having problems creating MVC 3 T4 template. I have cleared the "Custom Tool" property for the template as MvcTextTemplateHost not found suggests. But I cant find which reference to include.

Also I need to find reference for Microsoft.VisualStudio.Web.Mvc.Scaffolding.BuiltIn, I cant find it in the list of references.

Which references are missing?

TIA

/Lasse

答: Click on controller.tt and go to properties in "custom tool namespace" enter TextTemplatingFileGenerator. and remove from other .tt if there are TextTemplatingFileGenerator.</p>


问:
Host name may not be empty
After upgrading my Android Studio, I got this error whenever I wanted to generate a signed Apk (without any detail of where the problem is). There was no problem when I just built Apk.</p>
```<code>The Host name may not be empty
</code>```

答:
Check your Gradle scripts root. If there is this file: gradle.properties (Global Properties), check that values are correct.

In my case, I removed all these properties and my problem solved

```<code>systemProp.http.proxyHost=
systemProp.http.proxyPort=80
systemProp.https.proxyHost=
systemProp.https.proxyPort=80
</code>```

Title: Host name may not be empty

Body:
After upgrading my Android Studio, I got this error whenever I wanted to generate a signed Apk (without any detail of where the problem is). There was no problem when I just built Apk.

The Host name may not be empty

Body:
Check your Gradle scripts root. If there is this file: gradle.properties (Global Properties), check that values are correct.

In my case, I removed all these properties and my problem solved

systemProp.http.proxyHost=
systemProp.http.proxyPort=80
systemProp.https.proxyHost=
systemProp.https.proxyPort=80


问:
How to assert a type parameter is not "dynamic" in a const constructor in Dart?
Suppose I have this very basic struct:

class Foo<T> {
  final T bar;

  const Foo(this.bar);
}
```

<p>I would like to enforce the type specialization, that is prevent the instance to be created with <code>Foo(1)</code> for example (<code>Foo<int>(1)</code> should be used instead).</p>

<p>One way to do so it to use add an <code>assert</code> statement in the constructor initializer list to ensure <code>T != dynamic</code>:</p>

<pre class="lang-dart prettyprint-override"><code>class Foo<T> {
  final T bar;

  const Foo(this.bar) : assert(T != dynamic, "Can't create a Foo of dynamic type");
}
</code>```

Unfortunately, it does not seem compatible with the const constructor as it raises an error: Invalid constant value for both T and dynamic.

Is there any workaround and why is dynamic considered as non-constant?

答:
Once your object is instantiated, T is fixed.  Therefore you could just assert somewhere else in your class.  It'd be constructible but unusable.

Consider using strict_raw_types instead.  Add:

analyzer:
  language:
    strict-raw-types: true
```

to your analysis_options.yaml file to disallow Foo(1). (Note that explicitly using Foo<dynamic>(1) would still be allowed.)

Body:
Suppose I have this very basic struct:

class Foo<T> {
  final T bar;

  const Foo(this.bar);
}

I would like to enforce the type specialization, that is prevent the instance to be created with Foo(1) for example (Foo<int>(1) should be used instead).

One way to do so it to use add an assert statement in the constructor initializer list to ensure T != dynamic:

class Foo<T> {
  final T bar;

  const Foo(this.bar) : assert(T != dynamic, "Can't create a Foo of dynamic type");
}

Unfortunately, it does not seem compatible with the const constructor as it raises an error: Invalid constant value for both T and dynamic.

Is there any workaround and why is dynamic considered as non-constant?

Body:
Once your object is instantiated, T is fixed.  Therefore you could just assert somewhere else in your class.  It'd be constructible but unusable.

Consider using strict_raw_types instead.  Add:

analyzer:
  language:
    strict-raw-types: true

to your analysis_options.yaml file to disallow Foo(1). (Note that explicitly using Foo<dynamic>(1) would still be allowed.)


问:
Typescript Object is possibly 'null' focusing using ref in react
typescript is still giving me error

Object is possibly 'null'.ts(2531)

even though I do this

```<code>myRef && myRef.current && myRef.current.focus();
</code>```

if I use

```<code>myRef?.current?.focus();
</code>```

I got

```<code>Property 'focus' does not exist on type 'never'.ts(2339)
</code>```

答:
When you define your reference, you should specify what type it will be:

const myRef = useRef<HTMLElement>(null);
```

<blockquote>
  <p><em>(Note that the above assumes you're using it like <code><div ref={myRef}></code> - if you're setting <code>myRef.current</code> manually, you need to specify the type as <code><HTMLElement|null></code>.</em></p>
</blockquote>

<p>Once you have done this, you should be able to use the following:</p>

<pre class="lang-js prettyprint-override"><code>myRef.current?.focus()
</code>```

Note that you do not need to use the existential check on myRef - that will always be an object with a current property - that's how react's API works.

Body:
typescript is still giving me error

Object is possibly 'null'.ts(2531)

even though I do this

myRef && myRef.current && myRef.current.focus();

if I use

myRef?.current?.focus();

I got

Property 'focus' does not exist on type 'never'.ts(2339)

Body:
When you define your reference, you should specify what type it will be:

const myRef = useRef<HTMLElement>(null);

(Note that the above assumes you're using it like <div ref={myRef}> - if you're setting myRef.current manually, you need to specify the type as <HTMLElement|null>.

Once you have done this, you should be able to use the following:

myRef.current?.focus()

Note that you do not need to use the existential check on myRef - that will always be an object with a current property - that's how react's API works.


问:
Stored procedure output variable being stored as input/output type
I'm attempting to get the metadata for a stored procedure in Microsoft SQL Server using the Java SQL API.

This is the structure of the stored procedure:

```<code>CREATE PROCEDURE [dbo].[testproc]
    (@rolloverType AS integer,
     @retval nvarchar(50) output)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT @retval = [col1]
    FROM [dbo].[Table_1]
    WHERE col3 = @rolloverType;
END
GO
</code>```

However, the Java SQL API is saying that @retval is an INOUT type, and Microsoft SQL Server Management Studio also shows this parameter as an Input/Output type. How can I construct this stored procedure so that @retval is only of type Output?

答:
As @GSerg commented, you can't.

In SQL, an OUTPUT parameter acts as both INPUT and OUTPUT, see this answer

You're obtaining an INOUT value because of the mapping used to refer ORACLE procedure parameter types, which are IN, OUT and INOUT.

From dba-oracle.com:

A variable passed as mode IN is always read-only.  A variable
  using IN mode can be read and used by the procedure/function but can
  not be changed and it cannot be the receiver of an assignment
  operation.

A variable passed in OUT mode is used to pass information back from
  the procedure to the calling program.  It is a write-only variable and
  has no value until the block assigns it a value.

A variable passed in INOUT mode has characteristics of both the IN and
  the OUT mode.  The variable value is passed in and can be read by the
  procedure.  The procedure can also change the value and it will be
  copied back to the passed variable when the procedure completes.

Body:
I'm attempting to get the metadata for a stored procedure in Microsoft SQL Server using the Java SQL API.

This is the structure of the stored procedure:

CREATE PROCEDURE [dbo].[testproc]
    (@rolloverType AS integer,
     @retval nvarchar(50) output)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT @retval = [col1]
    FROM [dbo].[Table_1]
    WHERE col3 = @rolloverType;
END
GO

However, the Java SQL API is saying that @retval is an INOUT type, and Microsoft SQL Server Management Studio also shows this parameter as an Input/Output type. How can I construct this stored procedure so that @retval is only of type Output?


问:
kdb+/q script how to encode-decode string
I am looking for encoding/decoding a string in q script
.Q.x10,.Q.j10,.Q.x12 and .Q.j12 does not seem to meet requirement.
e.g.
I want to encode "Hello world" and I should be able to decode it further</p>

答:
Your issue is that the default .Q.j10 and .Q.x10 don't allow for the space character " " since the space character is not in the default alphabet used:

```<code>q).Q.j10
64/:?["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"]
</code>```

If you look at the "tip" comment in the official documentation: https://code.kx.com/q/ref/dotq/#qj10-encode-binhex

you'll see that they suggest creating your own .Q.j10/.Q.x10 functions where the space character is the first character in your custom alphabet. Your alphabet still has to be only 64 characters though, so you would have to get rid of either the + or / (or replace them with another character of your choosing).

A similar question came up on the k4 topicbox on August 16th 2019 (subject "b64 encode") where Geo Carncross came up with this solution for b64 decoding:

```<code>q).Q.btoa"Hello World!"
"SGVsbG8gV29ybGQh"
q)
q){c:sum x="=";neg[c]_"c"$raze 256 vs'64 sv'0N 4#.Q.b6?x}"SGVsbG8gV29ybGQh"
"Hello World!"
</code>```

I haven't tested the latter though.

Body:
Your issue is that the default .Q.j10 and .Q.x10 don't allow for the space character " " since the space character is not in the default alphabet used:

q).Q.j10
64/:?["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"]

If you look at the "tip" comment in the official documentation: https://code.kx.com/q/ref/dotq/#qj10-encode-binhex

you'll see that they suggest creating your own .Q.j10/.Q.x10 functions where the space character is the first character in your custom alphabet. Your alphabet still has to be only 64 characters though, so you would have to get rid of either the + or / (or replace them with another character of your choosing).

A similar question came up on the k4 topicbox on August 16th 2019 (subject "b64 encode") where Geo Carncross came up with this solution for b64 decoding:

q).Q.btoa"Hello World!"
"SGVsbG8gV29ybGQh"
q)
q){c:sum x="=";neg[c]_"c"$raze 256 vs'64 sv'0N 4#.Q.b6?x}"SGVsbG8gV29ybGQh"
"Hello World!"

I haven't tested the latter though.


问:
Scala test match case classes on some field
I have

```<code>case class Foo(field1: String, field2: String, field3: String)

expected: Seq[Foo] = Seq(...)

result: Seq[Foo] = Seq(...)
</code>```

I want to write a Scala matcher that compare the elements of Seq without taking in consideration field1.

So two elements will match if field2 and field3 are equals. Field1 value is not considerated.

Example:

```<code>val expected = Seq(
  Foo(
    "f1", "f2", "f3"
  )
)

val result = Seq(
  Foo(
    "fx", "f2", "f3"
  )
)
</code>```

This two sequence has to match.

```<code>  result should matchWithoutId(expected)
</code>```

答:
Working with "sequences" states

if you want to change how containership is determined for an element
  type E, place an implicit Equality[E] in scope or use the explicitly
  DSL.

so the following should work

```<code>(expected should contain theSameElementsAs (result)) (decided by fooEqualityWithoutId)
</code>```

Note about contains usage

Note that when you use the explicitly DSL with contain you need to
  wrap the entire contain expression in parentheses

Here is the full example

```<code>import org.scalactic._
import org.scalatest._
import org.scalatest.matchers.should.Matchers
import org.scalactic.Explicitly._

class CustomizeEqualitySeqSpec extends FlatSpec with Matchers with Explicitly {
  case class Foo(field1: String, field2: String, field3: String)
  val expected = Seq(Foo("f1", "f2", "f3"))
  val result = Seq(Foo("fx", "f2", "f3"))

  val fooEqualityWithoutId = new Equality[Foo] {
    override def areEqual(a: Foo, b: Any): Boolean = b match {
      case Foo(_, field2, field3) => a.field2 == field2 && a.field3 == field3;
      case _ => false
    }
  }

  "Sequences" should "use custom Equality[E]" in {
    (expected should contain theSameElementsAs (result)) (decided by fooEqualityWithoutId)
  }
}
</code>```

Body:
I have

case class Foo(field1: String, field2: String, field3: String)

expected: Seq[Foo] = Seq(...)

result: Seq[Foo] = Seq(...)

I want to write a Scala matcher that compare the elements of Seq without taking in consideration field1.

So two elements will match if field2 and field3 are equals. Field1 value is not considerated.

Example:

val expected = Seq(
  Foo(
    "f1", "f2", "f3"
  )
)

val result = Seq(
  Foo(
    "fx", "f2", "f3"
  )
)

This two sequence has to match.

  result should matchWithoutId(expected)

Body:
Working with "sequences" states

if you want to change how containership is determined for an element
  type E, place an implicit Equality[E] in scope or use the explicitly
  DSL.

so the following should work

(expected should contain theSameElementsAs (result)) (decided by fooEqualityWithoutId)

Note about contains usage

Note that when you use the explicitly DSL with contain you need to
  wrap the entire contain expression in parentheses

Here is the full example

import org.scalactic._
import org.scalatest._
import org.scalatest.matchers.should.Matchers
import org.scalactic.Explicitly._

class CustomizeEqualitySeqSpec extends FlatSpec with Matchers with Explicitly {
  case class Foo(field1: String, field2: String, field3: String)
  val expected = Seq(Foo("f1", "f2", "f3"))
  val result = Seq(Foo("fx", "f2", "f3"))

  val fooEqualityWithoutId = new Equality[Foo] {
    override def areEqual(a: Foo, b: Any): Boolean = b match {
      case Foo(_, field2, field3) => a.field2 == field2 && a.field3 == field3;
      case _ => false
    }
  }

  "Sequences" should "use custom Equality[E]" in {
    (expected should contain theSameElementsAs (result)) (decided by fooEqualityWithoutId)
  }
}


问:
How to replacte whole string or part of string from in Swift4
I'm new to Swift, and stuck in-between development task.

I want to replace existing label string with another string or I want to replace part of string, also need to add this in my existing Swift in-built classes so I can further use it.

I'm very new Swift..please ignore any syntactical issues...

```<code>if str1.contains("ed"){
     str1.replacementObject(for: "MyNewString")
}
</code>```

I'm getting error on this..."cannot convert value from string to expected argument type 'NSKeyedArchiver'"

I'll be more happy, if you could help me.

答:
You may use replacingOccurrencesOf function of String.

```<code>   let aString = "abcdef"
   let bString = aString.replacingOccurrences(of: "abc", with: "def")
   print(bString) // defdef
</code>```

Body:
I'm new to Swift, and stuck in-between development task.

I want to replace existing label string with another string or I want to replace part of string, also need to add this in my existing Swift in-built classes so I can further use it.

I'm very new Swift..please ignore any syntactical issues...

if str1.contains("ed"){
     str1.replacementObject(for: "MyNewString")
}

I'm getting error on this..."cannot convert value from string to expected argument type 'NSKeyedArchiver'"

I'll be more happy, if you could help me.

Body:
You may use replacingOccurrencesOf function of String.

   let aString = "abcdef"
   let bString = aString.replacingOccurrences(of: "abc", with: "def")
   print(bString) // defdef


问:
Angular 9 Module Parse failed: Invalid Number
I am trying to bind data from the class to the view using [ngModel] on my form but keep getting this error. Any help would be appreciated. Thank you.

Blockquote../src/app/tdf/tdf.component.ts 19:58
  Module parse failed: Invalid number (19:58)
  File was processed with these loaders:
   * ./node_modules/@ngtools/webpack/src/index.js
  You may need an additional loader to handle the result of these loaders.
  |     constructor() {
  |         this.topics = ['Angular', 'React', 'Vue'];
          this.userModel = new User('rob', 'rob@gmail.com', 08966736738, '', 'morning', true);
  |     }
  |     ngOnInit() {}.
  Blockquote
  I have not been able to find a solution. G

import { Component, OnInit } from '@angular/core';
//import {NgForm} from '@angular/forms';
import { User } from '../user';

@Component({
  selector: 'app-tdf',
  templateUrl: './tdf.component.html',
  styleUrls: ['./tdf.component.scss']
})
export class TdfComponent implements OnInit {

  topics = ['Angular', 'React', 'Vue'];
  userModel = new User('rob', 'rob@gmail.com', 08966736738, '', 'morning', true)

  ngOnInit(): void {
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class ="container-fluid mb-5">
    <h1>Bootcamp Enrollment Form</h1>
    <h3>Template Driven Forms TDF</h3>
    <form #userForm="ngForm">

        {{ userForm.value | json }}
<hr />
{{userModel | json}}

        <div class="form-group">
            <label>Name</label>
            <input type="text" class="form-control" name="username" [ngModel]="userModel.name">
        </div>

        <div class="form-group">
            <label>Email</label>
            <input type="email" class="form-control" name="email" [ngModel]="userModel.email">
        </div>

        <div class="form-group">
            <label>Phone</label>
            <input type="tel" class="form-control" name="phone" [ngModel]="userModel.phone">
        </div>

        <div class="form-group">
            <select class="custom-select" name="topic" [ngModel]="userModel.topic">
                <option selected> I am interested in:</option>
                <option *ngFor="let topic of topics"> {{topic}}</option>
            </select>
        </div>

        <div class="mb-3">
            <label>Time Preference</label>
            <div class="form-check">
                <input class="form-check-input" [ngModel]="userModel.timePreference" type="radio" name="timePreference" value="morning">
                <label class="form-check-label">Morning (9AM - 12PM)</label>
            </div>

            <div class="form-check">
                <input class="form-check-input" [ngModel]="userModel.timePreference" type="radio" name="timePreference" value="evening">
                <label class="form-check-label">Evening (5PM - 8PM)</label>
            </div>
        </div>

        <div class="form-check">
            <input class="form-check-input" type="checkbox" name="subscribe" [ngModel]="userModel.subscribe">
            <label class="form-check-label">
                Send me promotional offers.
            </label>
        </div>

        <button class="btn btn-primary" type="submit">Submit Form</button>
    </form>
</div></code>```

答:
input type="tel"  needs a dom string as model:

See: MDN input type tel

```<code>userModel = new User('rob', 'rob@gmail.com', 08966736738, '', 'morning', true)
</code>```

-->

```<code>userModel = new User('rob', 'rob@gmail.com', '08966736738', '', 'morning', true)
</code>```

Body:
I am trying to bind data from the class to the view using [ngModel] on my form but keep getting this error. Any help would be appreciated. Thank you.

Blockquote../src/app/tdf/tdf.component.ts 19:58
  Module parse failed: Invalid number (19:58)
  File was processed with these loaders:
   * ./node_modules/@ngtools/webpack/src/index.js
  You may need an additional loader to handle the result of these loaders.
  |     constructor() {
  |         this.topics = ['Angular', 'React', 'Vue'];
          this.userModel = new User('rob', 'rob@gmail.com', 08966736738, '', 'morning', true);
  |     }
  |     ngOnInit() {}.
  Blockquote
  I have not been able to find a solution. G

import { Component, OnInit } from '@angular/core';
//import {NgForm} from '@angular/forms';
import { User } from '../user';

@Component({
  selector: 'app-tdf',
  templateUrl: './tdf.component.html',
  styleUrls: ['./tdf.component.scss']
})
export class TdfComponent implements OnInit {

  topics = ['Angular', 'React', 'Vue'];
  userModel = new User('rob', 'rob@gmail.com', 08966736738, '', 'morning', true)

  ngOnInit(): void {
  }

}

Bootcamp Enrollment Form

Template Driven Forms TDF

    <form #userForm="ngForm">

        {{ userForm.value | json }}

{{userModel | json}}

            Name
            <input type="text" class="form-control" name="username" [ngModel]="userModel.name">

            Email
            <input type="email" class="form-control" name="email" [ngModel]="userModel.email">

            Phone
            <input type="tel" class="form-control" name="phone" [ngModel]="userModel.phone">

            <select class="custom-select" name="topic" [ngModel]="userModel.topic">
                <option selected> I am interested in:</option>
                <option *ngFor="let topic of topics"> {{topic}}</option>
            </select>

            Time Preference

                <input class="form-check-input" [ngModel]="userModel.timePreference" type="radio" name="timePreference" value="morning">
                Morning (9AM - 12PM)

                <input class="form-check-input" [ngModel]="userModel.timePreference" type="radio" name="timePreference" value="evening">
                Evening (5PM - 8PM)

            <input class="form-check-input" type="checkbox" name="subscribe" [ngModel]="userModel.subscribe">

                Send me promotional offers.

        <button class="btn btn-primary" type="submit">Submit Form</button>
    </form>

Body:
input type="tel"  needs a dom string as model:

See: MDN input type tel

userModel = new User('rob', 'rob@gmail.com', 08966736738, '', 'morning', true)

-->

userModel = new User('rob', 'rob@gmail.com', '08966736738', '', 'morning', true)


问:
Dynamically passing the column name as well the values in python mysql query
This is the following code

```<code>pythonlist = ['Name','Mno']
datalist = ["qwerty",'234']
sql = "SELECT " + ",".join(pythonlist) + " FROM data WHERE name = '"+ "','".join(datalist) + "' INTO OUTFILE filename"
print(sql)
</code>```

OUTPUT:

```<code>SELECT Name,Mno FROM data WHERE Name= 'qwerty','234'
</code>```

DESIRED OUTPUT:

```<code>SELECT Name,Mno FROM data WHERE Name = 'qwerty' and Mno = 234
</code>```

Do note the removal of quotations marks in 'mno'.

The reason I am doing this is due because the column names, as well as values corresponding it to, will change frequently

答:
Code :

```<code>queryparams = {'Name': 'qwerty', 'Mno': '234'}

and_clause = []
[and_clause.append(' %s = %s ') for k,v in queryparams.items()]
and_clause_str = ' and '.join(and_clause)

sql = 'SELECT %s FROM data WHERE ' + and_clause_str

params = [','.join(queryparams.keys())]
for k,v in queryparams.items():
  params.append(str(k))
  params.append(str(v))
print(sql)
print(params)
cursor.execute(sql, params=tuple(params))
</code>```

This works if you add 10/20 more items to dictionary .
Aswell as prevents SQL-injection : Using params to pass values instead of string-concatenation .

Body:
This is the following code

pythonlist = ['Name','Mno']
datalist = ["qwerty",'234']
sql = "SELECT " + ",".join(pythonlist) + " FROM data WHERE name = '"+ "','".join(datalist) + "' INTO OUTFILE filename"
print(sql)

OUTPUT:

SELECT Name,Mno FROM data WHERE Name= 'qwerty','234'

DESIRED OUTPUT:

SELECT Name,Mno FROM data WHERE Name = 'qwerty' and Mno = 234

Do note the removal of quotations marks in 'mno'.

The reason I am doing this is due because the column names, as well as values corresponding it to, will change frequently

Body:
Code :

queryparams = {'Name': 'qwerty', 'Mno': '234'}

and_clause = []
[and_clause.append(' %s = %s ') for k,v in queryparams.items()]
and_clause_str = ' and '.join(and_clause)

sql = 'SELECT %s FROM data WHERE ' + and_clause_str

params = [','.join(queryparams.keys())]
for k,v in queryparams.items():
  params.append(str(k))
  params.append(str(v))
print(sql)
print(params)
cursor.execute(sql, params=tuple(params))

This works if you add 10/20 more items to dictionary .
Aswell as prevents SQL-injection : Using params to pass values instead of string-concatenation .


问:
How do I install a go module?
Usually, when i'm in a workspace, all I need to do is go install to install an executable into my pkg folder. However, let's say i'm creating a module outside of $GOPATH/src. I then have a folder called ModuleTest on my desktop that contains the go.mod file. How do I install the package I created so I can use it in other go programs.

I've tried running go get and go install while inside the ModuleTest folder but it doesn't install anything into $GOPATH/pkg or $GOPATH/bin.

EDIT: I guess what i'm asking is, how do I install a go module locally without first pushing it on github and then doing go get

答:
Just use the replace keyword.

It will be something like this:

```<code>module github.com/a/b

replace github.com/foo/bar => /Users/YourName/Projects/bar

require (
    github.com/foo/bar v1.0.0
)
</code>```

Title: How do I install a go module?

Body:
Just use the replace keyword.

It will be something like this:

module github.com/a/b

replace github.com/foo/bar => /Users/YourName/Projects/bar

require (
    github.com/foo/bar v1.0.0
)