问:
Laravel 6.9 belongsToMany Relationships return one collection
I have Many To Many Relationships. I have three tables:

```<code>posts
posts_tag
tags
</code>```

Table "posts" have standart fields.

The structure of the table "posts_tag":

```<code>Schema::create('post_tag', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->bigInteger('post_id')->unsigned();
    $table->foreign('post_id')->references('id')->on('posts');

    $table->bigInteger('tag_id')->unsigned();
    $table->foreign('tag_id')->references('id')->on('tags');
});
</code>```

The structure of the table "tags":

```<code>Schema::create('tags', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->timestamps();
});
</code>```

The relationship is defined in the model:

```<code> class Tag extends Model
{

        public function posts()
    {
        return $this->belongsToMany(Post::class,'post_tag', 'post_id', 'tag_id');
    }
}
</code>```

I call the method $tag->posts:

```<code>public function getPostsByTag($id)
{
    $tag = Tag::find($id);

    dd($tag->posts);

}
</code>```

I get only one array:

```<code>Illuminate\Database\Eloquent\Collection {#571 ▼
  #items: array:1 [▶]
}
</code>```

screenshot database

I will be grateful for any help friends! If you're sorry for my English, I'm in the process of learning!

答:
In your Tag modal

```<code>class Tag extends Model
{
    public function posts()
    {
        return $this->belongsToMany(Post::class,'post_tag', 'post_id', 'tag_id');
    }
}
</code>```

In your Post modal

```<code>class Post extends Model
{
    public function tags()
    {
        return $this->belongsToMany(Tag::class,'post_tag', 'tag_id', 'post_id');
    }
}
</code>```

In your controller

```<code>public function getPostsByTag($id)
{
    $tag = Post::with('tags')->find($id);
    dd($tag);
}
</code>```

Body:
I have Many To Many Relationships. I have three tables:

posts
posts_tag
tags

Table "posts" have standart fields.

The structure of the table "posts_tag":

Schema::create('post_tag', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->bigInteger('post_id')->unsigned();
    $table->foreign('post_id')->references('id')->on('posts');

    $table->bigInteger('tag_id')->unsigned();
    $table->foreign('tag_id')->references('id')->on('tags');
});

The structure of the table "tags":

Schema::create('tags', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->timestamps();
});

The relationship is defined in the model:

 class Tag extends Model
{

        public function posts()
    {
        return $this->belongsToMany(Post::class,'post_tag', 'post_id', 'tag_id');
    }
}

I call the method $tag->posts:

public function getPostsByTag($id)
{
    $tag = Tag::find($id);

    dd($tag->posts);

}

I get only one array:

Illuminate\Database\Eloquent\Collection {#571 ▼
  #items: array:1 [▶]
}

screenshot database

I will be grateful for any help friends! If you're sorry for my English, I'm in the process of learning!

Body:
In your Tag modal

class Tag extends Model
{
    public function posts()
    {
        return $this->belongsToMany(Post::class,'post_tag', 'post_id', 'tag_id');
    }
}

In your Post modal

class Post extends Model
{
    public function tags()
    {
        return $this->belongsToMany(Tag::class,'post_tag', 'tag_id', 'post_id');
    }
}

In your controller

public function getPostsByTag($id)
{
    $tag = Post::with('tags')->find($id);
    dd($tag);
}


来源: stackexchange

问:
Distinct values in python list
I need to extract unique values in python list by omitting the repeated values altogether:

Input:

```<code>lis = ['a','l','f','a']
</code>```

Desired Output:

```<code>lis2 = ['l','f']
</code>```

So I need to remove all duplicate iteams.
Sets won't do cause I don't want 'a' in it

答:
this little function will create a dictionary of the number of occurrences of each element, then filter out the ones with multiple occurrences, and return the resulting list.</p>

```<code>lst = ['a','b', 'c', 'a']

def removeDupes(lst):
    counts = {}
    for item in lst:
        if counts.get(item):
            counts[item] += 1
        else:
            counts[item] = 1
    result = dict({(k, v) for k, v in counts.items() if v == 1})
    return result.keys()

print(removeDupes(lst)) # outputs: ['b', 'c']
</code>```

ContentLicense: CC BY-SA 4.0

Title: Distinct values in python list

Body:
I need to extract unique values in python list by omitting the repeated values altogether:

Input:

lis = ['a','l','f','a']

Desired Output:

lis2 = ['l','f']

So I need to remove all duplicate iteams.
Sets won't do cause I don't want 'a' in it

Body:
this little function will create a dictionary of the number of occurrences of each element, then filter out the ones with multiple occurrences, and return the resulting list.

lst = ['a','b', 'c', 'a']

def removeDupes(lst):
    counts = {}
    for item in lst:
        if counts.get(item):
            counts[item] += 1
        else:
            counts[item] = 1
    result = dict({(k, v) for k, v in counts.items() if v == 1})
    return result.keys()

print(removeDupes(lst)) # outputs: ['b', 'c']


问:
How to activate component only when data comes from server?
There is a parent component where I call its child component:

```<code> <app-add-object-layer-component></app-add-object-layer-component>
</code>```

Child has a service inside:

```<code> constructor(private editService: editService) {

 }

 getEditData(){
    return this.editService.get();
 }
</code>```

Child component is initialised always even there is no data returned.

Sure, I can move editService upper and use it like:

```<code><app-add-object-layer-component *ngIf="editService.getEditData()"></app-add-object-layer-component>
</code>```

But in this case parent component has alien dependency constructor(private editService: editService) {}

How to show/hide child component in parent component according to data returned by getEditData method?

答:
The code is wrong. editService.getEditData() will return promise. Which is defined and true always. You need to check resolved value. For that use async pipe.

"(editService.getEditData() | async)?.something"

more: https://malcoded.com/posts/angular-async-pipe/

```<code><app-add-object-layer-component *ngIf="(editService.getEditData() | async)?.something"></app-add-object-layer-component>
</code>```

Body:
There is a parent component where I call its child component:

 <app-add-object-layer-component></app-add-object-layer-component>

Child has a service inside:

 constructor(private editService: editService) {

 }

 getEditData(){
    return this.editService.get();
 }

Child component is initialised always even there is no data returned.

Sure, I can move editService upper and use it like:

<app-add-object-layer-component *ngIf="editService.getEditData()"></app-add-object-layer-component>

But in this case parent component has alien dependency constructor(private editService: editService) {}

How to show/hide child component in parent component according to data returned by getEditData method?

Body:
The code is wrong. editService.getEditData() will return promise. Which is defined and true always. You need to check resolved value. For that use async pipe.

"(editService.getEditData() | async)?.something"

more: https://malcoded.com/posts/angular-async-pipe/

<app-add-object-layer-component *ngIf="(editService.getEditData() | async)?.something"></app-add-object-layer-component>


问:
Set Custom icon to context menu for multiple charts (Highcharts)
I want to apply a custom image to a context menu for multiple charts, This is the code I found to apply a custom image to a context menu. Here is the link to fiddle

```<code>Highcharts.SVGRenderer.prototype.symbols.download = function(x, y, w, h) {
  var path = [
    // Arrow stem
    'M', x + w * 0.5, y,
    'L', x + w * 0.5, y + h * 0.7,
    // Arrow head
    'M', x + w * 0.3, y + h * 0.5,
    'L', x + w * 0.5, y + h * 0.7,
    'L', x + w * 0.7, y + h * 0.5,
    // Box
    'M', x, y + h * 0.9,
    'L', x, y + h,
    'L', x + w, y + h,
    'L', x + w, y + h * 0.9
  ];
  return path;
};

Highcharts.chart('container', {
exporting: {
    buttons: {
      contextButton: {
        symbol: 'download'
      }
    }
  }

});
</code>```

This code snippet changes the symbol based on the unique id, How do i apply the same across multiple charts whose unique id is not known?

答:
The example which you have shared defines this symbol as a 'download' which saves this symbol in the Highcharts core options and makes it possible to get it whenever you want to use it, even multiple times.

Demo: https://jsfiddle.net/BlackLabel/7rt21zLe/

```<code>Highcharts.SVGRenderer.prototype.symbols.download = function (x, y, w, h) {
    var path = [
        // Arrow stem
        'M', x + w * 0.5, y,
        'L', x + w * 0.5, y + h * 0.7,
        // Arrow head
        'M', x + w * 0.3, y + h * 0.5,
        'L', x + w * 0.5, y + h * 0.7,
        'L', x + w * 0.7, y + h * 0.5,
        // Box
        'M', x, y + h * 0.9,
        'L', x, y + h,
        'L', x + w, y + h,
        'L', x + w, y + h * 0.9
    ];
    return path;
};
</code>```

Body:
I want to apply a custom image to a context menu for multiple charts, This is the code I found to apply a custom image to a context menu. Here is the link to fiddle

Highcharts.SVGRenderer.prototype.symbols.download = function(x, y, w, h) {
  var path = [
    // Arrow stem
    'M', x + w * 0.5, y,
    'L', x + w * 0.5, y + h * 0.7,
    // Arrow head
    'M', x + w * 0.3, y + h * 0.5,
    'L', x + w * 0.5, y + h * 0.7,
    'L', x + w * 0.7, y + h * 0.5,
    // Box
    'M', x, y + h * 0.9,
    'L', x, y + h,
    'L', x + w, y + h,
    'L', x + w, y + h * 0.9
  ];
  return path;
};

Highcharts.chart('container', {
exporting: {
    buttons: {
      contextButton: {
        symbol: 'download'
      }
    }
  }

});

This code snippet changes the symbol based on the unique id, How do i apply the same across multiple charts whose unique id is not known?

Body:
The example which you have shared defines this symbol as a 'download' which saves this symbol in the Highcharts core options and makes it possible to get it whenever you want to use it, even multiple times.

Demo: https://jsfiddle.net/BlackLabel/7rt21zLe/

Highcharts.SVGRenderer.prototype.symbols.download = function (x, y, w, h) {
    var path = [
        // Arrow stem
        'M', x + w * 0.5, y,
        'L', x + w * 0.5, y + h * 0.7,
        // Arrow head
        'M', x + w * 0.3, y + h * 0.5,
        'L', x + w * 0.5, y + h * 0.7,
        'L', x + w * 0.7, y + h * 0.5,
        // Box
        'M', x, y + h * 0.9,
        'L', x, y + h,
        'L', x + w, y + h,
        'L', x + w, y + h * 0.9
    ];
    return path;
};


答:
Here's a one liner to make it simple!</p>

```<code>lis2 = list(set(lis) - set([x for x in lis if lis.count(x) > 1]))
</code>```

Title: Distinct values in python list

Body:
Here's a one liner to make it simple!

lis2 = list(set(lis) - set([x for x in lis if lis.count(x) > 1]))


问:
Error while reading text file on Android, open failed: EACCES (Permission denied)
I am trying to access a file in Android, below is the code:

```<code>File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"sos/xconfig.txt");

if(!file.exists())
   return text.toString();

 BufferedReader br = new BufferedReader(new FileReader(file));
 String line;

 while ((line = br.readLine()) != null) {
      text.append(line);
      text.append('\n');
    }
 br.close();
</code>```

I am also checking for read and write permission like this before reading :

```<code> if (ContextCompat.checkSelfPermission(activity, permission)
            == PackageManager.PERMISSION_DENIED) {

        // Requesting the permission
        ActivityCompat.requestPermissions(activity,
                new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE },
                requestCode);
        return false;
    }
    else {
        return true;
    }
</code>```

But I am still getting an error at this line : new FileReader(file).

Error : java.io.FileNotFoundException: /storage/emulated/0/sos/xconfig.txt: open failed: EACCES (Permission denied)

NOTE: I have already added uses-permission in menifest file.

```<code><uses-permission
    android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

答:
Are u using Android Q  ?
If that is the case you need to add this attribute in your AndroidManifest file :

```<code><manifest ... >
    <!-- This attribute is "false" by default on apps targeting Android Q. -->
    <application android:requestLegacyExternalStorage="true" ... >
     ...
    </application>
</manifest>
</code>```

Source : Exception 'open failed: EACCES (Permission denied)' on Android

Body:
I am trying to access a file in Android, below is the code:

File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"sos/xconfig.txt");

if(!file.exists())
   return text.toString();

 BufferedReader br = new BufferedReader(new FileReader(file));
 String line;

 while ((line = br.readLine()) != null) {
      text.append(line);
      text.append('\n');
    }
 br.close();

I am also checking for read and write permission like this before reading :

 if (ContextCompat.checkSelfPermission(activity, permission)
            == PackageManager.PERMISSION_DENIED) {

        // Requesting the permission
        ActivityCompat.requestPermissions(activity,
                new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE },
                requestCode);
        return false;
    }
    else {
        return true;
    }

But I am still getting an error at this line : new FileReader(file).

Error : java.io.FileNotFoundException: /storage/emulated/0/sos/xconfig.txt: open failed: EACCES (Permission denied)

NOTE: I have already added uses-permission in menifest file.

<uses-permission
    android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Body:
Are u using Android Q  ?
If that is the case you need to add this attribute in your AndroidManifest file :

<manifest ... >
    <!-- This attribute is "false" by default on apps targeting Android Q. -->
    <application android:requestLegacyExternalStorage="true" ... >
     ...
    </application>
</manifest>

Source : Exception 'open failed: EACCES (Permission denied)' on Android


问:
Data getting corrupted over aes file transfer python tkinter
I am working on a project where you can send a file over a socket and it is aes encrypted. And it works it encrypts the data and sends it over the socket and it decrypts it fine but the image is getting messed up below is the example of the before image and after how can I correct this?

Before:

After:

The encrypt and decrypt are in a separate module I created that is why they a referenced like they are below

Encryption and decryption code:

```<code>def encrypt(key, data, iv):
    encryptor = AES.new(key, AES.MODE_CBC, iv)
    return encryptor.encrypt(data)

def decrypt(key, data, iv):
    decryptor = AES.new(key, AES.MODE_CBC, iv)
    return decryptor.decrypt(data)
</code>```

Server Code:

```<code>s = socket.socket()
s.bind(("127.0.0.1", 5000))
s.listen(1)
c, addr = self.s.accept

name = c.recv(1024)
name = name.split("/")[-1]

newFile = open(self.curpath + name, "wb")
stop = False

while True:
    data = c.recv(24*1024)

    print(data[-4:])
    if data[-4:] == "DONE":
        break

    data = decrypt(self.key, data, self.iv)
    newFile.write(data)

    print("STOP")
    newFile.close()
</code>```

Client Code:

```<code>s. = socket.socket()
s.connect(("127.0.0.1", 5000)

item = "Splash.png"
s.send(item)

with open(item, "rb") as fp:
        while True:
            chunk = fp.read(64*1024)

            if len(chunk) == 0:
                break
            elif len(chunk) % 16 != 0:
                chunk += " " * (16 - len(chunk) % 16)
            s.send(encrypt(self.key, chunk, self.iv))

s.send("DONE")
print("Done")
</code>```

答: By using @t.m.adam comment I was able to get the software to run correctly using .rstrip(" ")

Body:
I am working on a project where you can send a file over a socket and it is aes encrypted. And it works it encrypts the data and sends it over the socket and it decrypts it fine but the image is getting messed up below is the example of the before image and after how can I correct this?

Before:

After:

The encrypt and decrypt are in a separate module I created that is why they a referenced like they are below

Encryption and decryption code:

def encrypt(key, data, iv):
    encryptor = AES.new(key, AES.MODE_CBC, iv)
    return encryptor.encrypt(data)

def decrypt(key, data, iv):
    decryptor = AES.new(key, AES.MODE_CBC, iv)
    return decryptor.decrypt(data)

Server Code:

s = socket.socket()
s.bind(("127.0.0.1", 5000))
s.listen(1)
c, addr = self.s.accept

name = c.recv(1024)
name = name.split("/")[-1]

newFile = open(self.curpath + name, "wb")
stop = False

while True:
    data = c.recv(24*1024)

    print(data[-4:])
    if data[-4:] == "DONE":
        break

    data = decrypt(self.key, data, self.iv)
    newFile.write(data)

    print("STOP")
    newFile.close()

Client Code:

s. = socket.socket()
s.connect(("127.0.0.1", 5000)

item = "Splash.png"
s.send(item)

with open(item, "rb") as fp:
        while True:
            chunk = fp.read(64*1024)

            if len(chunk) == 0:
                break
            elif len(chunk) % 16 != 0:
                chunk += " " * (16 - len(chunk) % 16)
            s.send(encrypt(self.key, chunk, self.iv))

s.send("DONE")
print("Done")


问:
Using a custom class as a JAX-WS return type?
I'm using NetBeans's Web Service generation tools. I've looked at the tutorials available, but cannot find anything on how to use a custom class as a return type. Most of the tutorials I've read are no more complex than Hello World: they take and return simple types like Strings.

So say I want a class that has 3 fields: a String, an int and a double[]. So far, the only way I can pass my own classes is by creating "envelope classes", with no methods, a parameter-less constructor, and with all fields declared public. I'd prefer to write standard Java classes. Obviously I cannot send the methods across SOAP, but I would have thought there was a way to ignore the methods when Marshalling the class, and only Marshall the fields.

Somebody has told me there are Annotations that facilitate this, but I can't find any tutorials on how to implement them. Any guidance would be greatly appreciated.

答:
JAX-WS uses JAXB for mapping types, so classes should conform to that specification. You can find JAXB annotations in the java.xml.bind.annotations package.

If you want to marshal a non-annotated class, conform to the rules for JavaBeans should work:

```<code>public class Foo {
  private String bar;
  public String getBar() { return bar; }
  public void setBar(String bar) { this.bar = bar; }

  public static void main(String[] args) {
    Foo foo = new Foo();
    foo.setBar("Hello, World!");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    JAXB.marshal(foo, out);
    foo = (Foo)
        JAXB.unmarshal(new ByteArrayInputStream(out.toByteArray()), Foo.class);
    System.out.println(foo.getBar());
  }
}
</code>```

If you want to use constructors with arguments, etc. look at the parts of the spec about factory methods and adapters.

ContentLicense: CC BY-SA 3.0

Body:
JAX-WS uses JAXB for mapping types, so classes should conform to that specification. You can find JAXB annotations in the java.xml.bind.annotations package.

If you want to marshal a non-annotated class, conform to the rules for JavaBeans should work:

public class Foo {
  private String bar;
  public String getBar() { return bar; }
  public void setBar(String bar) { this.bar = bar; }

  public static void main(String[] args) {
    Foo foo = new Foo();
    foo.setBar("Hello, World!");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    JAXB.marshal(foo, out);
    foo = (Foo)
        JAXB.unmarshal(new ByteArrayInputStream(out.toByteArray()), Foo.class);
    System.out.println(foo.getBar());
  }
}

If you want to use constructors with arguments, etc. look at the parts of the spec about factory methods and adapters.


问:
Download pdf files from external url's - Heroku, NodeJS, Angular 7
I am trying to download multiple pdf files from external sources to my nodejs server (in Heroku) temporarily and upload it to AWS S3 bucket.

I have tried multiple methods all of which works fine in my local machine but not in Heroku Dyno NodeJS Server. I am unable to even create folder in Heroku. I guess due to limited permission.

In Node

1) using var download = require('download-file') (using this currently in below code)

2) axios

3) res.download()

Download Files Code

```<code>const downloadFiles = async (unique_files) =>  {

  for (let index = 0; index < unique_files.length; index++) {
    let file_ext = unique_files[index].substr(unique_files[index].length - 4);
      if(file_ext == ".pdf") {
        await downloadzz(unique_files[index])
      }
  }

}

function downloadzz(link) {
  download(link, function(err){
    if (err) throw err
    console.log("DOWNLOAD Complete");

  });
}
</code>```

Upload Files Code

```<code>const uploadFiles = async (unique_files) =>  {

  for (let index = 0; index < unique_files.length; index++) {
    let file_ext = unique_files[index].substr(unique_files[index].length - 4);
      if(file_ext == ".pdf") {
        await uploadzz(unique_files[index])
      }
  }
}

function uploadzz(link) {
    fs.readFile(require('path').resolve(__dirname+'/../external-pdfs/', link.slice(link.lastIndexOf('/') + 1)), function (err, data) {

    params = {Bucket: pdfBucket, Key: link.slice(link.lastIndexOf('/') + 1), Body: data, ACL: "public-read" };
    s3.putObject(params, function(err, data) {
        if (err) {
            console.log("Failed Upload", err);
        } else {
            console.log("Successfully uploaded data to bucket", data);
        }
    });

  });
}
</code>```

I don't get any error but no folder seem to exist with a name external-pdfs on heroku server.

I am open for better solutions: for example, directly uploading file from external url to s3...
How can I in read file from a external url and directly upload to AWS S3 bucket?

答:
You can use axios. Setting the responseType as stream, you can get the file data and pass it as the body. Here it's an example code to get the pdf from a URL and uploading its info directly to S3:

```<code>const AWS = require('aws-sdk');
const axios = require('axios');

AWS.config.loadFromPath('./config.json');
const s3 = new AWS.S3({apiVersion: '2006-03-01'});
const URL = "<YOUR_URL>";

const uploadPdfToS3 = async () => {
    try{
        const {data, headers} = await axios.get(URL, {responseType: 'stream'});
        // Create params for putObject call
        const objectParams = {
            Bucket: "<YOUR_BUCKET>",
            Key: "<YOUR_KEY>",
            ContentLength: headers['content-length'],
            Body: data
        };
        // Create object upload promise
        await s3.putObject(objectParams).promise();
    } catch(err){
        console.log("ERROR --->" + err)
    }
}
</code>```

Body:
I am trying to download multiple pdf files from external sources to my nodejs server (in Heroku) temporarily and upload it to AWS S3 bucket.

I have tried multiple methods all of which works fine in my local machine but not in Heroku Dyno NodeJS Server. I am unable to even create folder in Heroku. I guess due to limited permission.

In Node

1) using var download = require('download-file') (using this currently in below code)

2) axios

3) res.download()

Download Files Code

const downloadFiles = async (unique_files) =>  {

  for (let index = 0; index < unique_files.length; index++) {
    let file_ext = unique_files[index].substr(unique_files[index].length - 4);
      if(file_ext == ".pdf") {
        await downloadzz(unique_files[index])
      }
  }

}

function downloadzz(link) {
  download(link, function(err){
    if (err) throw err
    console.log("DOWNLOAD Complete");

  });
}

Upload Files Code

const uploadFiles = async (unique_files) =>  {

  for (let index = 0; index < unique_files.length; index++) {
    let file_ext = unique_files[index].substr(unique_files[index].length - 4);
      if(file_ext == ".pdf") {
        await uploadzz(unique_files[index])
      }
  }
}

function uploadzz(link) {
    fs.readFile(require('path').resolve(__dirname+'/../external-pdfs/', link.slice(link.lastIndexOf('/') + 1)), function (err, data) {

    params = {Bucket: pdfBucket, Key: link.slice(link.lastIndexOf('/') + 1), Body: data, ACL: "public-read" };
    s3.putObject(params, function(err, data) {
        if (err) {
            console.log("Failed Upload", err);
        } else {
            console.log("Successfully uploaded data to bucket", data);
        }
    });

  });
}

I don't get any error but no folder seem to exist with a name external-pdfs on heroku server.

I am open for better solutions: for example, directly uploading file from external url to s3...
How can I in read file from a external url and directly upload to AWS S3 bucket?

Body:
You can use axios. Setting the responseType as stream, you can get the file data and pass it as the body. Here it's an example code to get the pdf from a URL and uploading its info directly to S3:

const AWS = require('aws-sdk');
const axios = require('axios');

AWS.config.loadFromPath('./config.json');
const s3 = new AWS.S3({apiVersion: '2006-03-01'});
const URL = "<YOUR_URL>";

const uploadPdfToS3 = async () => {
    try{
        const {data, headers} = await axios.get(URL, {responseType: 'stream'});
        // Create params for putObject call
        const objectParams = {
            Bucket: "<YOUR_BUCKET>",
            Key: "<YOUR_KEY>",
            ContentLength: headers['content-length'],
            Body: data
        };
        // Create object upload promise
        await s3.putObject(objectParams).promise();
    } catch(err){
        console.log("ERROR --->" + err)
    }
}


问:
how to mock resultmetadata for junit testing
having one function using resultmetadata.

```<code>    ResultSet rs // coming from some sql query.
    ResultSetMetaData rsmd = rs.getMetaData();
    if(rsmd.getColumnName(1).toString().equalsIgnoreCase("something"))
    {
    //do something here
    }
</code>```

i have mocked resultset before, but dont know how to mock resultmetadata or put desired column name in resultset ?
i tried :

```<code>    ResultSetMetaData rsmd = Mockito.mock(ResultSetMetaData.class);
    Mockito.when(rsmd.getColumnName(1)).thenReturn("Somwthing");
</code>```

but it didnt worked

答:
Here is an example of what you need to do:</p>

```<code>import org.mockito.Mockito;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;

public class Test {

    @org.junit.Test
    public void test() throws SQLException {

        // prepare the dependant mock
        ResultSetMetaData rsMetaMock = Mockito.mock(ResultSetMetaData.class);
        when(rsMetaMock.getColumnName(eq(1))).thenReturn("something");

        // prepare main mock for result set and define when
        // main mock to return dependant mock
        ResultSet rs = Mockito.mock(ResultSet.class);
        when(rs.getMetaData()).thenReturn(rsMetaMock);

        // application logic
        ResultSetMetaData rsmd = rs.getMetaData();

        //assertions
        assertEquals(rsmd.getColumnName(1), "something");
    }
}
</code>```

Body:
having one function using resultmetadata.

    ResultSet rs // coming from some sql query.
    ResultSetMetaData rsmd = rs.getMetaData();
    if(rsmd.getColumnName(1).toString().equalsIgnoreCase("something"))
    {
    //do something here
    }

i have mocked resultset before, but dont know how to mock resultmetadata or put desired column name in resultset ?
i tried :

    ResultSetMetaData rsmd = Mockito.mock(ResultSetMetaData.class);
    Mockito.when(rsmd.getColumnName(1)).thenReturn("Somwthing");

but it didnt worked

Body:
Here is an example of what you need to do:

import org.mockito.Mockito;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;

public class Test {

    @org.junit.Test
    public void test() throws SQLException {

        // prepare the dependant mock
        ResultSetMetaData rsMetaMock = Mockito.mock(ResultSetMetaData.class);
        when(rsMetaMock.getColumnName(eq(1))).thenReturn("something");

        // prepare main mock for result set and define when
        // main mock to return dependant mock
        ResultSet rs = Mockito.mock(ResultSet.class);
        when(rs.getMetaData()).thenReturn(rsMetaMock);

        // application logic
        ResultSetMetaData rsmd = rs.getMetaData();

        //assertions
        assertEquals(rsmd.getColumnName(1), "something");
    }
}


问:
How to implement listagg function in hibernate 5.0.1 without using native query
I am working in the spring boot 1.5 project.
I implemented listagg but I am getting "Unexcepted token error WITHIN " Please help me to implement listagg in hibernate without using native query.  </p>

```<code>Output:
    jobname     Empno
    AC_ACCOUNT  206
    AC_MGR      205
    AD_ASST     200
    AD_PRES     100
    AD_VP       101,102
    FI_ACCOUNT  110 ,113 ,111 ,109 ,112

select  jobname, listagg(empno, ',') within group (order by empno) empno
  from emp group by jobname;
</code>```

<p>-</p>

```<code>unexpected token: within","stack_trace":"antlr.NoViableAltException: unexpected token: within
at org.hibernate.hql.internal.antlr.HqlBaseParser.aliasedExpression(HqlBaseParser.java:2365)
at org.hibernate.hql.internal.antlr.HqlBaseParser.selectedPropertiesList(HqlBaseParser.java:1379)
at org.hibernate.hql.internal.antlr.HqlBaseParser.selectClause(HqlBaseParser.java:1282)
at org.hibernate.hql.internal.antlr.HqlBaseParser.selectFrom(HqlBaseParser.java:1022)
at org.hibernate.hql.internal.antlr.HqlBaseParser.queryRule(HqlBaseParser.java:730)
at org.hibernate.hql.internal.antlr.HqlBaseParser.selectStatement(HqlBaseParser.java:323)
at org.hibernate.hql.internal.antlr.HqlBaseParser.statement(HqlBaseParser.java:186)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:279)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:187)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:142)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:76)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:150)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:302)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:240)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1907)
at
</code>```

答:
To use listagg in hibernate query:

First register listagg function in Hibernate Dialect by extending Oracle10gDialect(in case you are using Oracle) or MySQLDialect(for MySQL)
public class CustomOracle10gDialect extends Oracle10gDialect {
 public CustomOracle10gDialect() {
     super();
     registerFunction("LISTAGG", new SQLFunctionTemplate(StandardBasicTypes.STRING,"LISTAGG(?1,',') WITHIN GROUP(ORDER BY ?1)"));
    }
}

Update your config file to use custom dialect. spring.jpa.database-platform=com.abc.CustomOracle10gDialect or com.abc.CustomOracle10gDialect

Use LISTAGG() Example - select c.id, listagg(firstName) from Contacts c where GROUP BY c.id

Body:
I am working in the spring boot 1.5 project.
I implemented listagg but I am getting "Unexcepted token error WITHIN " Please help me to implement listagg in hibernate without using native query.

Output:
    jobname     Empno
    AC_ACCOUNT  206
    AC_MGR      205
    AD_ASST     200
    AD_PRES     100
    AD_VP       101,102
    FI_ACCOUNT  110 ,113 ,111 ,109 ,112

select  jobname, listagg(empno, ',') within group (order by empno) empno
  from emp group by jobname;

-

unexpected token: within","stack_trace":"antlr.NoViableAltException: unexpected token: within
at org.hibernate.hql.internal.antlr.HqlBaseParser.aliasedExpression(HqlBaseParser.java:2365)
at org.hibernate.hql.internal.antlr.HqlBaseParser.selectedPropertiesList(HqlBaseParser.java:1379)
at org.hibernate.hql.internal.antlr.HqlBaseParser.selectClause(HqlBaseParser.java:1282)
at org.hibernate.hql.internal.antlr.HqlBaseParser.selectFrom(HqlBaseParser.java:1022)
at org.hibernate.hql.internal.antlr.HqlBaseParser.queryRule(HqlBaseParser.java:730)
at org.hibernate.hql.internal.antlr.HqlBaseParser.selectStatement(HqlBaseParser.java:323)
at org.hibernate.hql.internal.antlr.HqlBaseParser.statement(HqlBaseParser.java:186)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:279)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:187)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:142)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:76)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:150)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:302)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:240)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1907)
at


问:
What is the best tool for functional testing of a complex web application
I have a fairly complicated web application that is written using Grails. I am trying to set up a functional testing framework, initially using Selenium, but have run into two problems.

Part of the page I wish to test involves a treelike data structure that is displayed using jstree. The problem here is that the action I wish to simulate - the user clicking on a node to display its children - seems to be triggered by a click on a specific co-ordinate within a div, which is proving hard to test. I have managed to work around the problem by opening this node using Javascript passed directly to the browser by Selenium's executeScript() method.

The webapp makes heavy use of file uploads, and this is something that I definitely need to test. There is no straightforward way to submit file uploads using Selenium.

What is the best way of going about this? I am considering trying Tellurium (but it's not clear from my reading whether or not file uploads work) or iMacros (on the assumption that a browser extension will handle file uploads better). This can't be a rare situation that I'm in; can anybody suggest a better alternative?

答: We have used Rational functional tester to test Web 2.0 based application using dojo tool kit 1.0 . We used along with our own homegrown framework . It worked well with few exceptions like not very good support for new browsers of Firefox new releases etc.</p>


问:
Chrome Uncaught Type Error: Cannot read property undefined
I’m a complete novice to programming and am working my way through the book Learning to Program, by Steven Foote. I am trying to find out why Chrome is telling me I’ve got these two errors:

Uncaught TypeError: Cannot read property ‘currentDate’ of undefined

  Uncaught TypeError: Cannot read property ‘projectName’ of undefined

This is what I've written:

values.js

```<code>var kbValues = {
 projectName: 'kittenbook',
 versionNumber: '0.0.1',
 currentDate: new Date(),
 currentTime: [kbValues.currentDate.getFullYear() + '-' +
(kbValues.currentDate.getMonth() + 1)+ '-' +
kbValues.currentDate.getDate() + ' at ' +
kbValues.currentDate.getHours() + ':' +
kbValues.currentDate.getMinutes() + ':' +
kbValues.currentDate.getSeconds()]
};
</code>```

kittenbook.js

```<code>document.body.innerHTML = '<h1>Hello, ' + userName + '!</h1>' +
'<p>' + kbValues.projectName + '' + kbValues.versionNumber +
' accessed on: ' + kbValues.currentTime + '</p>';
</code>```

manifest.json

```<code>{
    "manifest_version": 2,
    "name": "kittenbook",
    "description": "Replace photos on Facebook with kittens",
    "version": "0.0.1",
    "content_scripts": [
        {
            "matches": ["*://www.facebook.com/*"],
            "js": ["js/values.js","js/kittenbook.js"]
        }
    ]
}
</code>```

I'm really very new to this.

答:
you cant use properties of a variable during its definition, you are trying to access currentDate of kbValues, before assigning it

As you can see this snippet will return an error:

var kbValues = {
 projectName: 'kittenbook',
 versionNumber: '0.0.1',
 currentDate: new Date(),
 currentTime: [kbValues.currentDate.getFullYear() + '-' +
  (kbValues.currentDate.getMonth() + 1)+ '-' +
   kbValues.currentDate.getDate() + ' at ' +
   kbValues.currentDate.getHours() + ':' +
   kbValues.currentDate.getMinutes() + ':' +
   kbValues.currentDate.getSeconds()]
};```
</div>
</div>
</p>

<p>instead you should try assigning the date before variable definition, in this way you will be able to access it</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var currentDate = new Date();

var kbValues = {
 projectName: 'kittenbook',
 versionNumber: '0.0.1',
 currentDate,
 currentTime: [currentDate.getFullYear() + '-' +
  (currentDate.getMonth() + 1)+ '-' +
   currentDate.getDate() + ' at ' +
   currentDate.getHours() + ':' +
   currentDate.getMinutes() + ':' +
   currentDate.getSeconds()]
};

console.log(kbValues)</code>```

Body:
I’m a complete novice to programming and am working my way through the book Learning to Program, by Steven Foote. I am trying to find out why Chrome is telling me I’ve got these two errors:

Uncaught TypeError: Cannot read property ‘currentDate’ of undefined

  Uncaught TypeError: Cannot read property ‘projectName’ of undefined

This is what I've written:

values.js

var kbValues = {
 projectName: 'kittenbook',
 versionNumber: '0.0.1',
 currentDate: new Date(),
 currentTime: [kbValues.currentDate.getFullYear() + '-' +
(kbValues.currentDate.getMonth() + 1)+ '-' +
kbValues.currentDate.getDate() + ' at ' +
kbValues.currentDate.getHours() + ':' +
kbValues.currentDate.getMinutes() + ':' +
kbValues.currentDate.getSeconds()]
};

kittenbook.js

document.body.innerHTML = '
Hello, ' + userName + '!
' +
'
' + kbValues.projectName + '' + kbValues.versionNumber +
' accessed on: ' + kbValues.currentTime + '
';

manifest.json

{
    "manifest_version": 2,
    "name": "kittenbook",
    "description": "Replace photos on Facebook with kittens",
    "version": "0.0.1",
    "content_scripts": [
        {
            "matches": ["*://www.facebook.com/*"],
            "js": ["js/values.js","js/kittenbook.js"]
        }
    ]
}

I'm really very new to this.

Body:
you cant use properties of a variable during its definition, you are trying to access currentDate of kbValues, before assigning it

As you can see this snippet will return an error:

var kbValues = {
 projectName: 'kittenbook',
 versionNumber: '0.0.1',
 currentDate: new Date(),
 currentTime: [kbValues.currentDate.getFullYear() + '-' +
  (kbValues.currentDate.getMonth() + 1)+ '-' +
   kbValues.currentDate.getDate() + ' at ' +
   kbValues.currentDate.getHours() + ':' +
   kbValues.currentDate.getMinutes() + ':' +
   kbValues.currentDate.getSeconds()]
};

instead you should try assigning the date before variable definition, in this way you will be able to access it

var currentDate = new Date();

var kbValues = {
 projectName: 'kittenbook',
 versionNumber: '0.0.1',
 currentDate,
 currentTime: [currentDate.getFullYear() + '-' +
  (currentDate.getMonth() + 1)+ '-' +
   currentDate.getDate() + ' at ' +
   currentDate.getHours() + ':' +
   currentDate.getMinutes() + ':' +
   currentDate.getSeconds()]
};

console.log(kbValues)


问:
Groundwork / Nagios' check_by_ssh is returning "Remote command execution failed"
I'm using Groundwork / Nagios, and I'm trying to set up check_by_ssh. Right now, the command is:

$USER1$/check_by_ssh -i
  ~nagios/.ssh/id_dsa -H $HOSTADDRESS$
  -t 60 -l "$USER24$" -C "/tmp/test"

where /tmp/test is a Hello World program.

but it's returning the message
"Remote command execution failed:********************************************"

I have ssh keys set up for nagios to log into $HOSTADDRESS$ as $USER24$, but I'm still getting the error. (The private key is in ~nagios/.ssh on the groundwork box, and the public key is in ~/$USER24$/.ssh on the remote host)

So basically, check_by_ssh is failing to run any program.

答:
In my case this happened after one of our servers got rebuilt.
The problem was that the known_hosts file on the icinga master still had the SSH key of the target host from before it was rebuilt.
The solution was to simply edit the known_hosts file and delete the line related to the target host.
For me this was located in: /var/spool/icinga2/.ssh/known_hosts

Once you do this and run the check, the first time you will probably see a message like:

Remote command execution failed: Warning: Permanently added
  '172.16.0.90' (ED25519) to the list of known hosts.

That's normal, run the check again and it should be working


问:
Dynamically create buttons in react native
I want to create a checkbox dynamically according to the data in API and then call the function inside my render function.

Can anyone suggest me any way, as I had used forEach but the data seem do not passed and hence I'm getting an error: forEach is undefined.

My snippet:

```<code>sizel=()=> this.state.data.sizes.forEach(function(size){
    <CheckBox
     title={size}
   checked=''
   />
 })
</code>```

答:
check data.sizes has length also should not be undefined.

add this:

const { sizes } = this.state.data;
if( sizes && sizes.length){
 this.state.data.sizes.map(size => <CheckBox title={size} checked=''/> )
}
```

Body:
I want to create a checkbox dynamically according to the data in API and then call the function inside my render function.

Can anyone suggest me any way, as I had used forEach but the data seem do not passed and hence I'm getting an error: forEach is undefined.

My snippet:

sizel=()=> this.state.data.sizes.forEach(function(size){
    <CheckBox
     title={size}
   checked=''
   />
 })


问:
Django form is not valid but no error is sent
I started to learn Django today, but I am stuck at using forms. I have created two forms: /contact and /blog-new. The form at the Contact page is working fine, but the one at /blog-new is redirecting me to the home page after the submission button is pressed and no information is printed in the terminal nor saved in the database.

Code on Github

I appreciate if someone can explain to me what I did wrong as I cannot figure it out. Thank you!

mysite/blog/forms.py

```<code>from django import forms

from .models import BlogPost

class BlogPostModelForm(forms.ModelForm):
    class Meta:
        model = BlogPost
        fields = ['title', 'slug', 'content']
</code>```

mysite/blog/views.py

```<code>from .forms import BlogPostModelForm
def blog_post_create_view(request):
    # create objects
    # ? use a form
    # request.user -> return something
    form = BlogPostModelForm(request.POST or None)
    if form.is_valid():
        print(form.cleaned_data)
        form.save()
        form = BlogPostModelForm()
    template_name = 'form.html'
    context = {'form': form}
    return render(request, template_name, context)
</code>```

mysite/blog/models.py

```<code>from django.db import models

# Create your models here.
class BlogPost(models.Model):
    title = models.TextField()
    slug = models.SlugField(unique=True)
    content = models.TextField(null=True, blank=True)
</code>```

mysite/mysite/urls.py

```<code>from blog.views import (
    blog_post_create_view,
)

urlpatterns = [
    ..
    path('blog-new', blog_post_create_view),
    ..
]
</code>```

mysite/templates/form.html

```<code>{% extends "base.html" %}

{% block content %}

{% if title %}
    <h1>{{ title }}</h1>
{% endif %}

<form method='POST' action='.'> {% csrf_token %}
    {{ form.as_p }}
    <button type='submit'>Send</button>
</form>

{% endblock %}
</code>```

答:
You need to point to right url in action attribute of form.

That was not actually the solution but something that helped me to figure out what was wrong.

It is not necessary to point to /blog-new/ as . for action will point to the same page, but I have tried with /blog-new/ as action URL and I was surprised to see that /blog-new/ page doesn't exist.

The bug was in mysite/mysite/urls.py for missing a /:

```<code>path('blog-new', blog_post_create_view),
</code>```

It is funny (and annoying) how a symbol like / missing from your code will mess up everything and make you spend hours trying to find a solution as simple as that.

Thank you for your time spend to have a look over my code and try to help me!

Body:
I started to learn Django today, but I am stuck at using forms. I have created two forms: /contact and /blog-new. The form at the Contact page is working fine, but the one at /blog-new is redirecting me to the home page after the submission button is pressed and no information is printed in the terminal nor saved in the database.

Code on Github

I appreciate if someone can explain to me what I did wrong as I cannot figure it out. Thank you!

mysite/blog/forms.py

from django import forms

from .models import BlogPost

class BlogPostModelForm(forms.ModelForm):
    class Meta:
        model = BlogPost
        fields = ['title', 'slug', 'content']

mysite/blog/views.py

from .forms import BlogPostModelForm
def blog_post_create_view(request):
    # create objects
    # ? use a form
    # request.user -> return something
    form = BlogPostModelForm(request.POST or None)
    if form.is_valid():
        print(form.cleaned_data)
        form.save()
        form = BlogPostModelForm()
    template_name = 'form.html'
    context = {'form': form}
    return render(request, template_name, context)

mysite/blog/models.py

from django.db import models

# Create your models here.
class BlogPost(models.Model):
    title = models.TextField()
    slug = models.SlugField(unique=True)
    content = models.TextField(null=True, blank=True)

mysite/mysite/urls.py

from blog.views import (
    blog_post_create_view,
)

urlpatterns = [
    ..
    path('blog-new', blog_post_create_view),
    ..
]

mysite/templates/form.html

{% extends "base.html" %}

{% block content %}

{% if title %}

{{ title }}

{% endif %}

<form method='POST' action='.'> {% csrf_token %}
    {{ form.as_p }}
    <button type='submit'>Send</button>
</form>

{% endblock %}

Body:
You need to point to right url in action attribute of form.

That was not actually the solution but something that helped me to figure out what was wrong.

It is not necessary to point to /blog-new/ as . for action will point to the same page, but I have tried with /blog-new/ as action URL and I was surprised to see that /blog-new/ page doesn't exist.

The bug was in mysite/mysite/urls.py for missing a /:

path('blog-new', blog_post_create_view),

It is funny (and annoying) how a symbol like / missing from your code will mess up everything and make you spend hours trying to find a solution as simple as that.

Thank you for your time spend to have a look over my code and try to help me!


问:
How do I control IntelliJ Idea autoformat bracket placement for (Java) lambdas?
Without going into the politics of the company, I need to change the behaviour of the IntelliJ Java formatter thus....

```<code>someMethod(() -> {
   // do stuff
}
</code>```

Needs to format to:

```<code> someMethod(() ->
 {
    // do stuff
 }
</code>```

I got it moving { to new line for regular methods :( but struggling to find the option to do same for lambdas.

答: File | Settings | Editor | Code Style | Java > 'Wrapping and Braces' tab > 'Braces placement' section > 'In lambda declaration' option > set to 'Next line' instead of default 'End of line'.

Body:
Without going into the politics of the company, I need to change the behaviour of the IntelliJ Java formatter thus....

someMethod(() -> {
   // do stuff
}

Needs to format to:

 someMethod(() ->
 {
    // do stuff
 }

I got it moving { to new line for regular methods :( but struggling to find the option to do same for lambdas.


问:
How to correctly plot the floating numbers in text format in matplotlib piechart?
I have done a clustering algorithm and represented the results in a pie chart as shown below.

```<code>fig, ax = plt.subplots(figsize=(20, 10), subplot_kw=dict(aspect="equal"))
contents  = []

for k,v  in clusters.items():
    indi= str(len(clusters[k])) + " users " +  "Cluster_"+ str(k)
    contents.append(indi)

#contents = ['23 users Cluster_0', '21 users Cluster_1']

data = [float(x.split()[0]) for x in contents]
Cluster= [x.split()[-1] for x in contents]

def func(pct, allvals):
    absolute = int(pct/100.*np.sum(allvals))
    return "{:.0f}%\n({:d} users)".format(pct, absolute)

wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data),
                                  textprops=dict(color="w"))

ax.legend(wedges, Cluster,
          title="CLuster",
          loc="center left",
          bbox_to_anchor=(1, 0, 0.5, 1))

plt.setp(autotexts, size=10, weight="bold")

ax.set_title("Distribution of users: A pie chart")

</code>```

Even though the users are 23 and 21 in each cluster, the piechart shows 22 and 20. In the def func() int conversion is not rounding up the number to the closest, that is, if it is 22.9, it is showing as 22. Shouldn't it be 23 if it has to round up?

答:
Change int() to int(round()):

```<code>fig, ax = plt.subplots(figsize=(20, 10), subplot_kw=dict(aspect="equal"))
contents  = []

contents = ['23 users Cluster_0', '21 users Cluster_1']

data = [float(x.split()[0]) for x in contents]
Cluster= [x.split()[-1] for x in contents]

def func(pct, allvals):
    absolute = int(round(pct/100.*np.sum(allvals)))
    return "{:.0f}%\n({:d} users)".format(pct, absolute)

wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data),
                                  textprops=dict(color="w"))

ax.legend(wedges, Cluster,
          title="CLuster",
          loc="center left",
          bbox_to_anchor=(1, 0, 0.5, 1))

plt.setp(autotexts, size=10, weight="bold")

ax.set_title("Distribution of users: A pie chart")
</code>```

Output:

Body:
I have done a clustering algorithm and represented the results in a pie chart as shown below.

fig, ax = plt.subplots(figsize=(20, 10), subplot_kw=dict(aspect="equal"))
contents  = []

for k,v  in clusters.items():
    indi= str(len(clusters[k])) + " users " +  "Cluster_"+ str(k)
    contents.append(indi)

#contents = ['23 users Cluster_0', '21 users Cluster_1']

data = [float(x.split()[0]) for x in contents]
Cluster= [x.split()[-1] for x in contents]

def func(pct, allvals):
    absolute = int(pct/100.*np.sum(allvals))
    return "{:.0f}%\n({:d} users)".format(pct, absolute)

wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data),
                                  textprops=dict(color="w"))

ax.legend(wedges, Cluster,
          title="CLuster",
          loc="center left",
          bbox_to_anchor=(1, 0, 0.5, 1))

plt.setp(autotexts, size=10, weight="bold")

ax.set_title("Distribution of users: A pie chart")

Even though the users are 23 and 21 in each cluster, the piechart shows 22 and 20. In the def func() int conversion is not rounding up the number to the closest, that is, if it is 22.9, it is showing as 22. Shouldn't it be 23 if it has to round up?

Body:
Change int() to int(round()):

fig, ax = plt.subplots(figsize=(20, 10), subplot_kw=dict(aspect="equal"))
contents  = []

contents = ['23 users Cluster_0', '21 users Cluster_1']

data = [float(x.split()[0]) for x in contents]
Cluster= [x.split()[-1] for x in contents]

def func(pct, allvals):
    absolute = int(round(pct/100.*np.sum(allvals)))
    return "{:.0f}%\n({:d} users)".format(pct, absolute)

wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data),
                                  textprops=dict(color="w"))

ax.legend(wedges, Cluster,
          title="CLuster",
          loc="center left",
          bbox_to_anchor=(1, 0, 0.5, 1))

plt.setp(autotexts, size=10, weight="bold")

ax.set_title("Distribution of users: A pie chart")

Output:


问:
Django template - how to access form in forms (context) given an index number (generated by an iterator)
I have two forms - a source form and a result form.

Forms.py

```<code>class SourceForm(forms.Form):
    some_source_field = forms.forms.CharField(...)

class ResultForm(forms.Form):
    some_result_field = forms.forms.CharField(...)
</code>```

My view has uses formset_factory to render two instances of each and passes this to the template with a range of numbers that matches how many forms are to be rendered.

Views.py

```<code>class MyView(Vew):

    def get(self, request):

        forms_to_render = 2

        SourceFormSet = formset_factory(SourceForm, extra=forms_to_render)
        ResultFormSet = formset_factory(ResultForm, extra=forms_to_render)

        context = {
            'source_forms': SourceFormSet,
            'result_forms': ResultFormSet,
            'init': range(0, forms_to_render),
        }
</code>```

In my template, I want to generate a container for which holds a source_form and result_form, for each of the numbers in the given range (2 in this case), as below.

template.html

```<code>{% for i in init %}
  <div class="container-fluid" id="primary_container_{{ i }}">
    {{ source_forms.i }}
    {{ result_forms.i }}
  </div>
{% endfor %}
</code>```

Background: I have a javascript queue which unhides one primary_container at a time to be processed; I hide the "just-processed" container and populate it in the background while the user works on the next formset in the queue. The purpose is minimize the wait time while a form populates.

If I hard-code the index value of 0 or 1 in, the form renders.

```<code>{{ source_forms.0 }} <!-- works fine -->
{{ source_forms.1 }} <!-- works fine -->
</code>```

However, this doesn't work

```<code>{% for i in init %}
  {{ source_forms.i }} <!-- doesn't render form -->
{% endfor %}
</code>```

I thought maybe i was no longer the correct data type, so I tried this, which also doesn't work

```<code>{% for i in init %}
  {% with forloop.counter0 as x %}
    {{ source_forms.x }} <!-- doesn't render form -->
  {% endwith %}
{% endfor %}
</code>```

I got it working by doing this:

```<code>{% for i in init %}
  {% for form in source_forms %}
    {% if forloop.counter0 == i %}
      {{ form }} <!-- renders form -->
    {% endif %}
  {% endfor %}
{% endfor %}
</code>```

But is there a simpler way to get the correct form in forms given the index i?

答:
The Django template engine by design does not let you do indexing.

The answer is to use a custom tag to do indexing (or to use the Jinja template engine, which is a bit of a sledgehammer if this is the only nut to crack). This is one I wrote earlier, for indexing a dict-like entity.

```<code>from django import template
register = template.Library()

@register.filter
def lookup( d, key):
    """ filter: d is dict-like. return d[key] with '' as default using get method """
    return d.get( key, '')
</code>```

Usage: {{ dict_thing|lookup:key }}

In your case I would somewhat expect the following to work:

```<code>@register.filter
def index( lst, index):
    return lst[index]
</code>```

Usage: {{ source_forms|index:x }}

Note: no whitepace allowed around the | or : in the template

Another way I have used in the past is to pass a generator function ( yield result ) in the context to the template, which you can then iterate over in the template using {% for x in generator %}  I think Python's zip may be all you need here:

```<code>return render( ... context={
   'formpairs': zip( SourceFormSet, ResultFormSet), ...
})
</code>```

and in the template

```<code>{% for pair in formpairs %}
  <div class="container-fluid" id="primary_container_{{ forloop.counter }}">
  {{ pair.0 }}
  {{ pair.1 }}
  </div>
{% endfor %}
</code>```

Body:
I have two forms - a source form and a result form.

Forms.py

class SourceForm(forms.Form):
    some_source_field = forms.forms.CharField(...)

class ResultForm(forms.Form):
    some_result_field = forms.forms.CharField(...)

My view has uses formset_factory to render two instances of each and passes this to the template with a range of numbers that matches how many forms are to be rendered.

Views.py

class MyView(Vew):

    def get(self, request):

        forms_to_render = 2

        SourceFormSet = formset_factory(SourceForm, extra=forms_to_render)
        ResultFormSet = formset_factory(ResultForm, extra=forms_to_render)

        context = {
            'source_forms': SourceFormSet,
            'result_forms': ResultFormSet,
            'init': range(0, forms_to_render),
        }

In my template, I want to generate a container for which holds a source_form and result_form, for each of the numbers in the given range (2 in this case), as below.

template.html

{% for i in init %}

    {{ source_forms.i }}
    {{ result_forms.i }}

{% endfor %}

Background: I have a javascript queue which unhides one primary_container at a time to be processed; I hide the "just-processed" container and populate it in the background while the user works on the next formset in the queue. The purpose is minimize the wait time while a form populates.

If I hard-code the index value of 0 or 1 in, the form renders.

{{ source_forms.0 }}
{{ source_forms.1 }}

However, this doesn't work

{% for i in init %}
  {{ source_forms.i }}
{% endfor %}

I thought maybe i was no longer the correct data type, so I tried this, which also doesn't work

{% for i in init %}
  {% with forloop.counter0 as x %}
    {{ source_forms.x }}
  {% endwith %}
{% endfor %}

I got it working by doing this:

{% for i in init %}
  {% for form in source_forms %}
    {% if forloop.counter0 == i %}
      {{ form }}
    {% endif %}
  {% endfor %}
{% endfor %}

But is there a simpler way to get the correct form in forms given the index i?

Body:
The Django template engine by design does not let you do indexing.

The answer is to use a custom tag to do indexing (or to use the Jinja template engine, which is a bit of a sledgehammer if this is the only nut to crack). This is one I wrote earlier, for indexing a dict-like entity.

from django import template
register = template.Library()

@register.filter
def lookup( d, key):
    """ filter: d is dict-like. return d[key] with '' as default using get method """
    return d.get( key, '')

Usage: {{ dict_thing|lookup:key }}

In your case I would somewhat expect the following to work:

@register.filter
def index( lst, index):
    return lst[index]

Usage: {{ source_forms|index:x }}

Note: no whitepace allowed around the | or : in the template

Another way I have used in the past is to pass a generator function ( yield result ) in the context to the template, which you can then iterate over in the template using {% for x in generator %}  I think Python's zip may be all you need here:

return render( ... context={
   'formpairs': zip( SourceFormSet, ResultFormSet), ...
})

and in the template

{% for pair in formpairs %}
  <div class="container-fluid" id="primary_container_{{ forloop.counter }}">
  {{ pair.0 }}
  {{ pair.1 }}
  </div>
{% endfor %}


问:
Is there a risk that Apple will not accept me as an applied iPhone Developer (with paid membership)?
What does it mean that I have to "apply"? Can day say: "No, we don't like your nose. Do something else!"? Did they do that in the past?

I've been investing now two full months worth about 20.000 USD on learning for iPhone programming, and I didn't apply yet...

答:
There is no reason for them not to accept you as a iPhone developer.  There is no situation that I know of where they have denied the application provisioning for testing out on the iPhone.  They can and will deny your app submission to the app store in some cases.  Usually those cases include:

Using copyrighted assets which you do not have a license for

Competing with one of their apps (mail client was the only one I know of)

No value added (yet another "flashlight" app - pretty rare)

Opening the iPhone to scripting attack through download.

Does not conform to their UI guides

The last of these is the trickiest.  A friend of mine had his app rejected because he used a UI widget in an unexpected way.  This is pretty subjective IMO but they did tell him exactly why they denied it and accepted it when he fixed the issue.

Also about the 20,000,  I can't agree here.  In addition to learning and bettering yourself as a programmer, you are assuming that you would be paid for every off hour you spend learning - not very realistic.

OwnerDisplayName: Unknown Individual

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Stephen Pape

OwnerDisplayName: Nick


问:
How to optimize text output in if/ else for Python 3.6?
```<code>def statistic():
    if db.session.query(func.count(Exchange.exchange_id)).filter_by(user_id=g.user.user_id).scalar() == 0:
        text_info = '(big test message 1)'
    else:
        text_info = '(big  message 2)'

    return render_template('console/statistic.html', text_info=text_info)
</code>```

Hello, I'm using Python 3.6 + Flask. I output texts from the variable text_info on the 5 pages. But the text is large and looks awful in the code. How can I optimize and minimize the output in text_info? Open from file? What can you tell? thanks

答:
the easiest way

You might indeed load the text from files:

(...)
with open('file_one.txt') as file:
    text_info = file.read()
(...)
```

<p>Please note, however, that you'd end up adding a context manager / <code>with</code> expression for each message you want to have in the app and probably you'd have to create <code>N files for N messages</code>...</p>

<hr>

<p><strong>the proper way</strong></p>

<p>You can prepare a simple config for the app (for this example I will use TOML, let's say the filename is <code>config.toml</code>):</p>

```[strings]
first = "my first big string"
second = "my second big string"
```

<p>and then you can consume it as follows:</p>

<pre class="lang-py prettyprint-override"><code>import pytoml # you can install it using pip

(...)
with open('config.toml', 'rb') as config:
    cfg = pytoml.loads(config.read())

string1 = cfg['strings']['first']
string2 = cfg['strings']['second']
(...)
</code>```

Remember, hardcoding values is not a great idea in general. In a real-world app, you'd end up either using a config file of some kind (yaml/toml/ini/properties/other) or getting these values as a result of some API call.

Body:
def statistic():
    if db.session.query(func.count(Exchange.exchange_id)).filter_by(user_id=g.user.user_id).scalar() == 0:
        text_info = '(big test message 1)'
    else:
        text_info = '(big  message 2)'

    return render_template('console/statistic.html', text_info=text_info)

Hello, I'm using Python 3.6 + Flask. I output texts from the variable text_info on the 5 pages. But the text is large and looks awful in the code. How can I optimize and minimize the output in text_info? Open from file? What can you tell? thanks

Body:
the easiest way

You might indeed load the text from files:

(...)
with open('file_one.txt') as file:
    text_info = file.read()
(...)

Please note, however, that you'd end up adding a context manager / with expression for each message you want to have in the app and probably you'd have to create N files for N messages...

the proper way

You can prepare a simple config for the app (for this example I will use TOML, let's say the filename is config.toml):

[strings]
first = "my first big string"
second = "my second big string"

and then you can consume it as follows:

import pytoml # you can install it using pip

(...)
with open('config.toml', 'rb') as config:
    cfg = pytoml.loads(config.read())

string1 = cfg['strings']['first']
string2 = cfg['strings']['second']
(...)

Remember, hardcoding values is not a great idea in general. In a real-world app, you'd end up either using a config file of some kind (yaml/toml/ini/properties/other) or getting these values as a result of some API call.


问:
MySQL Group by aggregate functions
Sorry if i sound total newbie but i know im one step away from solving this problem.
Is there any way that i can GROUP BY the number_of_trans? i would like to know how many users have the same number of transaction, grouped by the number of transaction. my query is like this:

```<code>SELECT
  cust_id, COUNT(*) AS number_of_trans
FROM
  table
GROUP BY
  cust_id
HAVING COUNT(*) > 1
ORDER BY
  number_of_trans
</code>```

the result im getting is like this

```<code>+------------------+--------------+
| cust_id          | numb_of_trans|
+------------------+--------------+
| 01               |  2           |
| 02               |  3           |
| 03               |  3           |
| 04               |  4           |
| 05               |  4           |
+------------------+--------------+
</code>```

while im expecting a result like this:

```<code>+------------------+--------------+
| numb_of_trans    | count        |
+------------------+--------------+
| 1                |  null        |
| 2                |  1           |
| 3                |  2           |
| 4                |  2           |
| 5                |  null        |
+------------------+--------------+
</code>```

答:
Can you try below statement.</p>

```<code>SELECT
number_of_trans, count(number_of_trans) as count FROM table GROUP BY number_of_trans ORDER BY number_of_trans.
</code>```

Title: MySQL Group by aggregate functions

Body:
Sorry if i sound total newbie but i know im one step away from solving this problem.
Is there any way that i can GROUP BY the number_of_trans? i would like to know how many users have the same number of transaction, grouped by the number of transaction. my query is like this:

SELECT
  cust_id, COUNT(*) AS number_of_trans
FROM
  table
GROUP BY
  cust_id
HAVING COUNT(*) > 1
ORDER BY
  number_of_trans

the result im getting is like this

+------------------+--------------+
| cust_id          | numb_of_trans|
+------------------+--------------+
| 01               |  2           |
| 02               |  3           |
| 03               |  3           |
| 04               |  4           |
| 05               |  4           |
+------------------+--------------+

while im expecting a result like this:

+------------------+--------------+
| numb_of_trans    | count        |
+------------------+--------------+
| 1                |  null        |
| 2                |  1           |
| 3                |  2           |
| 4                |  2           |
| 5                |  null        |
+------------------+--------------+

Body:
Can you try below statement.

SELECT
number_of_trans, count(number_of_trans) as count FROM table GROUP BY number_of_trans ORDER BY number_of_trans.


问:
Why is this drilldown graph made by python-highcharts not working?
I am trying to use the python-highcharts package to generate drilldown column graphs. I have run the drilldown example* on that repo and it is giving me the following code :

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <link href="https://www.highcharts.com/highslide/highslide.css" rel="stylesheet" />
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script type="text/javascript" src="https://code.highcharts.com/6/highcharts.js"></script>
        <script type="text/javascript" src="https://code.highcharts.com/6/highcharts-more.js"></script>
        <script type="text/javascript" src="https://code.highcharts.com/6/modules/heatmap.js"></script>
        <script type="text/javascript" src="https://code.highcharts.com/6/modules/exporting.js"></script>
        <script type="text/javascript" src="https://code.highcharts.com/modules/drilldown.js"></script>
    </head>
    <body style="margin:0;padding:0">
                <div id="container" style="width:850px;height:400px;">Loading....</div>

    <script>
        $(function(){

            Highcharts.setOptions({"global": {}, "lang": {}});
            var option = {"chart": {"renderTo": "container", "width": 850, "height": 400, "type": "column"}, "colors": {}, "credits": {"enabled": false}, "drilldown": {}, "exporting": {}, "labels": {}, "legend": {"enabled": false}, "loading": {}, "navigation": {}, "pane": {}, "plotOptions": {"series": {"borderWidth": 0, "dataLabels": {"enabled": true, "format": "{point.y:.1f}%"}}}, "series": {}, "subtitle": {"text": "Click the columns to view versions. Source: <a href=\"http://netmarketshare.com\">netmarketshare.com</a>."}, "title": {"text": "Browser market shares. January, 2015 to May, 2015"}, "tooltip": {"headerFormat": "<span style=\"font-size:11px\">{series.name}</span><br>", "pointFormat": "<span style=\"color:{point.color}\">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>"}, "xAxis": {"type": "category"}, "yAxis": {"title": {"text": "Total percent market share"}}};

            var drilldowndata = [{"data": [["v11.0", 24.13], ["v8.0", 17.2], ["v9.0", 8.11], ["v10.0", 5.33], ["v6.0", 1.06], ["v7.0", 0.5]], "type": "column", "name": "Microsoft Internet Explorer", "id": "Microsoft Internet Explorer"}, {"data": [["v40.0", 5], ["v41.0", 4.32], ["v42.0", 3.68], ["v39.0", 2.96], ["v36.0", 2.53], ["v43.0", 1.45], ["v31.0", 1.24], ["v35.0", 0.85], ["v38.0", 0.6], ["v32.0", 0.55], ["v37.0", 0.38], ["v33.0", 0.19], ["v34.0", 0.14], ["v30.0", 0.14]], "type": "column", "name": "Chrome", "id": "Chrome"}, {"data": [["v35", 2.76], ["v36", 2.32], ["v37", 2.31], ["v34", 1.27], ["v38", 1.02], ["v31", 0.33], ["v33", 0.22], ["v32", 0.15]], "type": "column", "name": "Firefox", "id": "Firefox"}, {"data": [["v8.0", 2.56], ["v7.1", 0.77], ["v5.1", 0.42], ["v5.0", 0.3], ["v6.1", 0.29], ["v7.0", 0.26], ["v6.2", 0.17]], "type": "column", "name": "Safari", "id": "Safari"}, {"data": [["v12.x", 0.34], ["v28", 0.24], ["v27", 0.17], ["v29", 0.16]], "type": "column", "name": "Opera", "id": "Opera"}];
            option.drilldown.series = drilldowndata;

            var chart = new Highcharts.Chart(option);

            var data = [{"data": [{"name": "Microsoft Internet Explorer", "y": 56.33, "drilldown": "Microsoft Internet Explorer"}, {"name": "Chrome", "y": 24.030000000000005, "drilldown": "Chrome"}, {"name": "Firefox", "y": 10.38, "drilldown": "Firefox"}, {"name": "Safari", "y": 4.77, "drilldown": "Safari"}, {"name": "Opera", "y": 0.9100000000000001, "drilldown": "Opera"}, {"name": "Proprietary or Undetectable", "y": 0.2, "drilldown": null}], "type": "column", "name": "Brands", "colorByPoint": true}];
            var dataLen = data.length;
            for (var ix = 0; ix < dataLen; ix++) {
                chart.addSeries(data[ix]);
            }

    });
        </script>

    </body>
</html>

</code>```

When opened in a recent browser (up-to-date Google Chrome) this draws the chart, but the drilldown functionality does not work. I have looked at other working examples such as this one but cannot figure out why my code doesn't work.

Why is this code not making a proper drilldown chart and how can I fix it?

*Note that since I want the chart in a single file, I have replaced the last line of the python script (H.htmlcontent) with H.save_file("test_hc").

答:
You have incompatible module version:

```<code><script type="text/javascript" src="https://code.highcharts.com/modules/drilldown.js"></script>
</code>```

It should be:

```<code><script type="text/javascript" src="https://code.highcharts.com/6/modules/drilldown.js"></script>
</code>```

Live demo: http://jsfiddle.net/BlackLabel/6m4e8x0y/4878/

Body:
I am trying to use the python-highcharts package to generate drilldown column graphs. I have run the drilldown example* on that repo and it is giving me the following code :

<!DOCTYPE html>

        <meta charset="utf-8" />
        <link href="https://www.highcharts.com/highslide/highslide.css" rel="stylesheet" />

Loading....

When opened in a recent browser (up-to-date Google Chrome) this draws the chart, but the drilldown functionality does not work. I have looked at other working examples such as this one but cannot figure out why my code doesn't work.

Why is this code not making a proper drilldown chart and how can I fix it?

*Note that since I want the chart in a single file, I have replaced the last line of the python script (H.htmlcontent) with H.save_file("test_hc").

Body:
You have incompatible module version:

<script type="text/javascript" src="https://code.highcharts.com/modules/drilldown.js"></script>

It should be:

<script type="text/javascript" src="https://code.highcharts.com/6/modules/drilldown.js"></script>

Live demo: http://jsfiddle.net/BlackLabel/6m4e8x0y/4878/


问:
Set account recovery preference for AWS Cognito User Pool with Terraform
In the spirit of infrastructure as code, I've configured an AWS Cognito User Pool via Terraform with the helpful aws_cognito_user_pool resource.

However, I can't seem to locate the argument/config mapping for the account recovery preference under the MFA and verification section.

Without specification, it appears that this is my default selection:

(Not Recommended) Phone if available, otherwise email, and do allow a user to reset their password via phone if they are also using it for MFA.

Goal

I'd like to set this to Email only instead, as annotated by the red rectangle in the image below:

Does anyone know what Terraform argument I need to use to achieve this please? None of the options documented in the aws_cognito_user_pool resource seem to map to this.

答:
Following the David's idea, if you want to enable the "email only" option, you should to set

```<code>--account-recovery-setting 'RecoveryMechanisms=[{Priority=1,Name=verified_email}]'
</code>```

Regards,

Body:
Following the David's idea, if you want to enable the "email only" option, you should to set

--account-recovery-setting 'RecoveryMechanisms=[{Priority=1,Name=verified_email}]'

Regards,


问:
What code should I surround with run(){}?
I finished a 2000-line Swing + SQL program and I'd like to add to it a login window before everything is initialized. The login window is a JFrame class, instanced from the main program.

So my main app needs to implement Runnable. All I want with the thread I'm creating out of it is waiting -with wait()- until the login thread finishes -and uses notify()-.

My program consist of dozens of visual components, methods, main(), constructor, initializer, etc. What's the minimum amount of code I should surround with run(){}?

This is an example of what I want to do. It's not by any means correct (I suppose) but you'll get it:

```<code>private void initialize() { // Called from main()

    this.setBounds(100, 200, 1024, 576);
    this.setTitle("Main app");
    this.setVisible(false);

    Runnable runnable = new Visual_Login();
    Thread login_thread = new Thread(runnable);

    login_thread.run();
    main_thread.wait();

    this.setVisible(true);
    this.setContentPane(getJContentPane());

}
</code>```

(...I hope I'm understanding concurrency well)

Thank you in advance.

答:
You don't need another thread here.

At the end of login action, if the login is successful create an instance of your main jframe class and dispose the login jframe

```<code>class MainFrame extend  JFrame{
 ...
}

class LoginFrame extends JFrame{
.
.
.
 public void login(){
   boolean loginSuccess = checkCredentials(username,password);
   if(loginSuccess){
      MainFrame main = new MainFrame();
      .
      .
      this.dispose();

   }else{
    //show some error to user
   }
 }
}
</code>```

Body:
I finished a 2000-line Swing + SQL program and I'd like to add to it a login window before everything is initialized. The login window is a JFrame class, instanced from the main program.

So my main app needs to implement Runnable. All I want with the thread I'm creating out of it is waiting -with wait()- until the login thread finishes -and uses notify()-.

My program consist of dozens of visual components, methods, main(), constructor, initializer, etc. What's the minimum amount of code I should surround with run(){}?

This is an example of what I want to do. It's not by any means correct (I suppose) but you'll get it:

private void initialize() { // Called from main()

    this.setBounds(100, 200, 1024, 576);
    this.setTitle("Main app");
    this.setVisible(false);

    Runnable runnable = new Visual_Login();
    Thread login_thread = new Thread(runnable);

    login_thread.run();
    main_thread.wait();

    this.setVisible(true);
    this.setContentPane(getJContentPane());

}

(...I hope I'm understanding concurrency well)

Thank you in advance.

Body:
You don't need another thread here.

At the end of login action, if the login is successful create an instance of your main jframe class and dispose the login jframe

class MainFrame extend  JFrame{
 ...
}

class LoginFrame extends JFrame{
.
.
.
 public void login(){
   boolean loginSuccess = checkCredentials(username,password);
   if(loginSuccess){
      MainFrame main = new MainFrame();
      .
      .
      this.dispose();

   }else{
    //show some error to user
   }
 }
}


问:
How to access a file after it was uploaded with Dropzone.js and PHP
I would like to access a file after it was uploaded to the server via dropzone.js (v5) and PHP, i.e. I'd like to retrieve the file URL. How can I get it?

form.php:

```<code><form action="upload.php" class="dropzone" enctype="multipart/form-data">
    <div class="fallback">
        <input name="file" type="file" multiple />
    </div>
</form>

<script src="/js/dropzone.js"></script>
<script>
    Dropzone.autoDiscover = false;
    $('.dropzone').dropzone({
        init: function () {
            this.on("complete", function (file) {
                runthisfunction();
            }) // end on complete
        }
    });
</script>
</code>```

upload.php:

```<code><?php
if (!empty($_FILES)) {
    $random = randomString(18);
    $tempFile = $_FILES['file']['tmp_name'];
    $name = $_FILES['file']['name'];
    $fileExt = strtolower(substr(basename($name), strrpos(basename($name), ".") + 1));
    $newname = $random.'.'.$fileExt;
    move_uploaded_file($tempFile,"images/$newname");
} // end if files not empty
?>
</code>```

I have tried retrieving the uploaded file URL via the file object, but no success:

```<code>this.on("complete", function (file) {
    console.log(file);
    console.log(file.dataURL);
    console.log(file.name);
}) // end on complete
</code>```

Since the file is uploaded with PHP and renamed within the upload.php, I believe I would need to "POST" this filename somehow to another file and then retrieve it back. How can I do that?

答:
Your intuition about needing to get the filename back from the server is correct.  There's a simple example in the Dropzone FAQ which shows the basic idea.

1) Your server has to respond to the upload POST with the details of where it put the file - eg URL, filename, path, etc.  So in your case, at the end of your PHP code, you'd need to do something like:

```<code>// ... rest of your PHP ...
move_uploaded_file($tempFile,"images/$newname");

// Let the browser/JS know we are sending a JSON response back.  Make sure there
// is no output before this.
header('Content-type: application/json');
echo json_encode([
    'status' => 'OK',  // Not required, but maybe useful
    'image'  => "images/$newname",
]);
</code>```

2) In your JS, you need to accept that response from the server, and do something with it.  The Dropzone docs show for the success event:

The file has been uploaded successfully. Gets the server response as second argument.

This sounds like the one we need.  So replace your complete handler with one for success, and add a 2nd argument:

```<code>this.on("success", function (file, response) {
    console.dir(response);
    // response.image will be the relative path to your uploaded image.
    // You could also use response.status to check everything went OK,
    // maybe show an error msg from the server if not.
});
</code>```

The Dropzone FAQ item I linked to above shows using an .emit() method to display the image, I'm not familiar with that and it doesn't seem to be described in the docs.  Try it, maybe that works and suits your needs.  If not, you could do something like:

```<code>// Maybe you have an <img class='thumbnail'> in your HTML, ready to show the upload
$('.thumbnail').attr('src', response.image).fadeIn();
</code>```

Body:
I would like to access a file after it was uploaded to the server via dropzone.js (v5) and PHP, i.e. I'd like to retrieve the file URL. How can I get it?

form.php:

<form action="upload.php" class="dropzone" enctype="multipart/form-data">

        <input name="file" type="file" multiple />

</form>

upload.php:

<?php
if (!empty($_FILES)) {
    $random = randomString(18);
    $tempFile = $_FILES['file']['tmp_name'];
    $name = $_FILES['file']['name'];
    $fileExt = strtolower(substr(basename($name), strrpos(basename($name), ".") + 1));
    $newname = $random.'.'.$fileExt;
    move_uploaded_file($tempFile,"images/$newname");
} // end if files not empty
?>

I have tried retrieving the uploaded file URL via the file object, but no success:

this.on("complete", function (file) {
    console.log(file);
    console.log(file.dataURL);
    console.log(file.name);
}) // end on complete

Since the file is uploaded with PHP and renamed within the upload.php, I believe I would need to "POST" this filename somehow to another file and then retrieve it back. How can I do that?

Body:
Your intuition about needing to get the filename back from the server is correct.  There's a simple example in the Dropzone FAQ which shows the basic idea.

1) Your server has to respond to the upload POST with the details of where it put the file - eg URL, filename, path, etc.  So in your case, at the end of your PHP code, you'd need to do something like:

// ... rest of your PHP ...
move_uploaded_file($tempFile,"images/$newname");

// Let the browser/JS know we are sending a JSON response back.  Make sure there
// is no output before this.
header('Content-type: application/json');
echo json_encode([
    'status' => 'OK',  // Not required, but maybe useful
    'image'  => "images/$newname",
]);

2) In your JS, you need to accept that response from the server, and do something with it.  The Dropzone docs show for the success event:

The file has been uploaded successfully. Gets the server response as second argument.

This sounds like the one we need.  So replace your complete handler with one for success, and add a 2nd argument:

this.on("success", function (file, response) {
    console.dir(response);
    // response.image will be the relative path to your uploaded image.
    // You could also use response.status to check everything went OK,
    // maybe show an error msg from the server if not.
});

The Dropzone FAQ item I linked to above shows using an .emit() method to display the image, I'm not familiar with that and it doesn't seem to be described in the docs.  Try it, maybe that works and suits your needs.  If not, you could do something like:

// Maybe you have an <img class='thumbnail'> in your HTML, ready to show the upload
$('.thumbnail').attr('src', response.image).fadeIn();


问:
How to pass an Object Model (that has an Array of Objects Models in it) to API for insert as Params
i am new to angular, trying to make parameters of my object Model, whenever i stringify my object it makes a large string that API does not accept. What should i do..?

here is the object that i want to convert to parameters.

```<code>{
    "qaevaluationid": 1,
    "agentid": 1,
    "callerid": "1234",
    "calledon": "02/13/2020 10:38:14 AM",
    "duration": "304",
    "overallfeedback": "adasdasd",
    "isfatal": false,
    "fatalcallreasonid": "3",
    "evaluationtypeid": "1",
    "callratings": [{
        "callratingid": 1,
        "createdby": 1,
        "createdbyname": "john",
        "createdon": null,
        "evaluationfactorid": 8,
        "is_deleted": "F",
        "modifiedby": -1,
        "modifiedbyname": "",
        "modifiedon": null,
        "qaevaluationid": 1,
        "rating": "7"
    }, {
        "callratingid": 2,
        "createdby": 1,
        "createdbyname": "john",
        "createdon": null,
        "evaluationfactorid": 9,
        "is_deleted": "F",
        "modifiedby": -1,
        "modifiedbyname": "",
        "modifiedon": null,
        "qaevaluationid": 1,
        "rating": "6"
    }, {
        "callratingid": 3,
        "createdby": 1,
        "createdbyname": "john",
        "createdon": null,
        "evaluationfactorid": 10,
        "is_deleted": "F",
        "modifiedby": -1,
        "modifiedbyname": "",
        "modifiedon": null,
        "qaevaluationid": 1,
        "rating": "8"
    }],
    "createdby": 1,
    "createdbyname": "John",
    "createdon": null,
    "modifiedby": -1,
    "modifiedbyname": null,
    "modifiedon": null,
    "is_deleted": "F"
}
</code>```

and in TypeScript i am doing like this

```<code>this.httpOptions.params = new HttpParams();

this.httpOptions.params = this.httpOptions.params.set('qaEval', JSON.stringify(qaevaluation));

return this._httpClient.post<APIResponse<QAEvaluation>>(this.myAppUrl + 'QAEvaluation/insert', { qaEval: qaevaluation }, this.httpOptions)
      .pipe(retry(1), catchError(this.errorHandler));
</code>```

getting this error

"Http failure response for
  https://localhost:44304/QAEvaluation/insert?qaEval=%7B%22qaevaluationid%22:-1,%22agentid%22:1,%22callerid%22:%221234%22,%22calledon%22:%2202/13/2020%2010:38:14%20AM%22,%22duration%22:%22304%22,%22overallfeedback%22:%22adasdasd%22,%22isfatal%22:false
  ……. This goes on and on : 404 OK"

答:
updated my controller to accept FormBody with dynamic object  and removed http params from typescript like.. And It Worked.

```<code>return this._http.post<APIResponse<QAEvaluation>>(this.myAppUrl + 'QAEvaluation/insert', { qaEval: qaevaluation }, { headers: new HttpHeaders({ 'Content-Type': 'application/json; charset=utf-8' }) })
          .pipe(retry(1), catchError(this.errorHandler));
</code>```

also used serialization to parse into my resultant object

```<code>    public ActionResult Insert([FromBody]dynamic qaEval)
            {

                    var objModel1 = Newtonsoft.Json.JsonConvert.DeserializeObject(qaEval.ToString());

                    var objModel = Newtonsoft.Json.JsonConvert.SerializeObject(objModel1.qaEval);

    QAEvaluationModel model = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.QAEvaluationModel>(objModel);

qaEvaluationRepository.Add(model);

return Ok(new Models.APIResponse
                    {
                        HasError = false,
                        Message = "Success",
                        Content = null
                    });
    }
</code>```

Body:
i am new to angular, trying to make parameters of my object Model, whenever i stringify my object it makes a large string that API does not accept. What should i do..?

here is the object that i want to convert to parameters.

{
    "qaevaluationid": 1,
    "agentid": 1,
    "callerid": "1234",
    "calledon": "02/13/2020 10:38:14 AM",
    "duration": "304",
    "overallfeedback": "adasdasd",
    "isfatal": false,
    "fatalcallreasonid": "3",
    "evaluationtypeid": "1",
    "callratings": [{
        "callratingid": 1,
        "createdby": 1,
        "createdbyname": "john",
        "createdon": null,
        "evaluationfactorid": 8,
        "is_deleted": "F",
        "modifiedby": -1,
        "modifiedbyname": "",
        "modifiedon": null,
        "qaevaluationid": 1,
        "rating": "7"
    }, {
        "callratingid": 2,
        "createdby": 1,
        "createdbyname": "john",
        "createdon": null,
        "evaluationfactorid": 9,
        "is_deleted": "F",
        "modifiedby": -1,
        "modifiedbyname": "",
        "modifiedon": null,
        "qaevaluationid": 1,
        "rating": "6"
    }, {
        "callratingid": 3,
        "createdby": 1,
        "createdbyname": "john",
        "createdon": null,
        "evaluationfactorid": 10,
        "is_deleted": "F",
        "modifiedby": -1,
        "modifiedbyname": "",
        "modifiedon": null,
        "qaevaluationid": 1,
        "rating": "8"
    }],
    "createdby": 1,
    "createdbyname": "John",
    "createdon": null,
    "modifiedby": -1,
    "modifiedbyname": null,
    "modifiedon": null,
    "is_deleted": "F"
}

and in TypeScript i am doing like this

this.httpOptions.params = new HttpParams();

this.httpOptions.params = this.httpOptions.params.set('qaEval', JSON.stringify(qaevaluation));

return this._httpClient.post<APIResponse<QAEvaluation>>(this.myAppUrl + 'QAEvaluation/insert', { qaEval: qaevaluation }, this.httpOptions)
      .pipe(retry(1), catchError(this.errorHandler));

getting this error

"Http failure response for
  https://localhost:44304/QAEvaluation/insert?qaEval=%7B%22qaevaluationid%22:-1,%22agentid%22:1,%22callerid%22:%221234%22,%22calledon%22:%2202/13/2020%2010:38:14%20AM%22,%22duration%22:%22304%22,%22overallfeedback%22:%22adasdasd%22,%22isfatal%22:false
  ……. This goes on and on : 404 OK"

Body:
updated my controller to accept FormBody with dynamic object  and removed http params from typescript like.. And It Worked.

return this._http.post<APIResponse<QAEvaluation>>(this.myAppUrl + 'QAEvaluation/insert', { qaEval: qaevaluation }, { headers: new HttpHeaders({ 'Content-Type': 'application/json; charset=utf-8' }) })
          .pipe(retry(1), catchError(this.errorHandler));

also used serialization to parse into my resultant object

    public ActionResult Insert([FromBody]dynamic qaEval)
            {

                    var objModel1 = Newtonsoft.Json.JsonConvert.DeserializeObject(qaEval.ToString());

                    var objModel = Newtonsoft.Json.JsonConvert.SerializeObject(objModel1.qaEval);

    QAEvaluationModel model = Newtonsoft.Json.JsonConvert.DeserializeObject<Models.QAEvaluationModel>(objModel);

qaEvaluationRepository.Add(model);

return Ok(new Models.APIResponse
                    {
                        HasError = false,
                        Message = "Success",
                        Content = null
                    });
    }


问:
Building UI using Litho and JSON
I was looking for Backend Driven UI libraries for Android and came across Litho for Declarative UI. I was wondering if there is any helper/extension library for Litho that can generate the UI based on JSON. </p>

答: Not smth we are aware of. But due to its declarative nature it's not hard to build one by yourself. Conceptually, you'll just need to propagate all props from json fields to Component props and a special field for a Component type.</p>

Title: Building UI using Litho and JSON


问:
Angular 8 multiple mat-checkbox required validation
I have multiple dynamic mat-checkbox and i want to implement validation "at least one of them is selected".
Here is the html code:

```<code><div class="form-check" *ngFor="let data of pointsDepart; let i=index" [ngClass]="i == 1 ? 'marginTop': ''">
        <mat-checkbox color="primary" formControlName="pointDepart" ngDefaultControl>{{data}}</mat-checkbox>
</div>
</code>```

How can I implement my validator, please ? thank you

答:
You can try the below link for the validation of check boxs and email id
https://stackblitz.com/edit/angular-at-least-one-checkbox-checked</p>

Body:
I have multiple dynamic mat-checkbox and i want to implement validation "at least one of them is selected".
Here is the html code:

        <mat-checkbox color="primary" formControlName="pointDepart" ngDefaultControl>{{data}}</mat-checkbox>

How can I implement my validator, please ? thank you


问:
Non-Destructive Type Assertions in TypeScript
I am looking for a good way of constraining a literal value in TypeScript to certain type without loosing inferred type information.

Let's consider a type Named that is guaranteed to have a name.

type Named = {
  name: string
};
```

<p>Using a type annotation creates an error for the extra field <code>born</code> in the literal used to define the const <code>cat1</code>.</p>

<pre class="lang-js prettyprint-override"><code>const cat1: Named = {
  name: 'Findus',
  born: 1984,  // this is an error
};
const name1 = cat1.name;
const born1 = cat1.born;  // this is an error
</code>```

By using a typecast I can define the const cat2 but it looses type information for the field born which creates a problem while trying to access that field later on.

const cat2 = {
  name: 'Findus',
  born: 1984,
} as Named;
const name2 = cat2.name;
const born2 = cat2.born;  // this is an error
```

<p>One way to solve the problem is to use an IIFE to type check the literal while defining the const <code>cat3</code>.</p>

<pre class="lang-js prettyprint-override"><code>const cat3 = (<C extends Named>(c: C) => c)({
  name: 'Findus',
  born: 1984,
});
const name3 = cat3.name;
const born3 = cat3.born;
</code>```

Is this the intended way of doing the constraining, or are there better alternative ways of writing compatible code?

答:
Simply say that your type is a record with one required parameter name

```<code>interface Named extends Record<string, any> {
    name: string
}
</code>```

Or you can use something like this

```<code>type Named<T> = T & {
    name: string
}

const a: Named<{ surname: string } > = {
    name: 'hello',
    surname: 'world'
};
</code>```

Body:
I am looking for a good way of constraining a literal value in TypeScript to certain type without loosing inferred type information.

Let's consider a type Named that is guaranteed to have a name.

type Named = {
  name: string
};

Using a type annotation creates an error for the extra field born in the literal used to define the const cat1.

const cat1: Named = {
  name: 'Findus',
  born: 1984,  // this is an error
};
const name1 = cat1.name;
const born1 = cat1.born;  // this is an error

By using a typecast I can define the const cat2 but it looses type information for the field born which creates a problem while trying to access that field later on.

const cat2 = {
  name: 'Findus',
  born: 1984,
} as Named;
const name2 = cat2.name;
const born2 = cat2.born;  // this is an error

One way to solve the problem is to use an IIFE to type check the literal while defining the const cat3.

const cat3 = (<C extends Named>(c: C) => c)({
  name: 'Findus',
  born: 1984,
});
const name3 = cat3.name;
const born3 = cat3.born;

Is this the intended way of doing the constraining, or are there better alternative ways of writing compatible code?

Body:
Simply say that your type is a record with one required parameter name

interface Named extends Record<string, any> {
    name: string
}

Or you can use something like this

type Named<T> = T & {
    name: string
}

const a: Named<{ surname: string } > = {
    name: 'hello',
    surname: 'world'
};


问:
In retrospect, best open source stack/tools to build facebook
I have been doing high performance scientific computing in c++ most of my life. I am trying to learn to developing AJAXy web applications. As an exercise, I would like to build something that has a subset of functionality of facebook (profiles, posts with comment threads, friend lists) + the ability to search any post/comment.

I have no experience developing these kind of apps, except minor amount of toying with Google Appengine with GWT+Java and little bit of python. What tools/stack would you suggest using for it? I understand that this a very vague question, but I'd like to get a few opinions and your thought process about how would you go about using it.

How does the choice change, if you want a fast prototype as fast as possible, vs if you are trying to build something that can scale and last a few cycles of feature requests.

To be more specific, I'm lost in questions like, should I consider Drupal, should I consider Lucene for search, Would GWT get me what I want in the UI or would python+django be faster to develop. Probably I should not over think and pick something. But some perspective from others would be nice.

答: One disadvantage with google app engine is that there is no CMS like drupal or Joomla for google app engine so you're going to have to write your own if you want some of that functionality. The advantages of google app engine however outweigh the disadvantage since you have easier development, easier deployment, won't have to fiddle with phpmyadmin or other ugly sql interfaces, with app engine you also leverage google's huge infrastructure and since it's cloud computing you only pay for what you use. If you want something you as a developer will be most happy about - then I recommend you choose Google App Engine. </p>