问:
Place text fields side by side in input-group Bootstarp
I am new to Bootstrap. I am trying to add an input group in which text fields are place side-by-side. However, it is not grouping well. I am getting extra space between the text fields and button.

Here is my code:

```<code><div class="form-group researchPapers">
    <div class="input-group">
        <div class="col-sm-12 form-group">
            <input type="text" id="title[]" name="title[]" class="form-control" placeholder="Title of Paper" />
        </div>
        <div class="col-sm-12 form-group">
            <input type="text" id="journal[]" name="journal[]" class="form-control" placeholder="Name of Journal" />
        </div>
        <div class="input-group-addon">
            <a href="javascript:void(0)" class="btn btn-success addMore"><span class="glyphicon glyphicon glyphicon-plus" aria-hidden="true"></span> Add New</a>
        </div>
    </div>
</div>
</code>```

Any help is highly appreciated.

答:
Removed col-sm-12 form form-group and removed margin of last form-group

```<code><div class="form-group researchPapers">
    <div class="input-group">
        <div class="form-group">
            <input type="text" id="title[]" name="title[]" class="form-control" placeholder="Title of Paper" />
        </div>
        <div class="form-group">
            <input type="text" id="journal[]" name="journal[]" class="form-control" placeholder="Name of Journal" />
        </div>
        <div class="input-group-addon">
            <a href="javascript:void(0)" class="btn btn-success addMore"><span class="glyphicon glyphicon glyphicon-plus" aria-hidden="true"></span> Add New</a>
        </div>
    </div>
</div>
</code>```

CSS

```<code>.input-group .form-group:nth-child(2) {
    margin-bottom: 0;
}
</code>```

For general idea of multiple inputs (Use bootstrap 4 classes for flex
  i am giving general idea)

```<code><div class="form-group">
            <input type="text" id="journal[]" name="journal[]" class="form-control" placeholder="Name of Journal" style="
    flex-basis: 1;
"><input type="text" id="journal[]" name="journal[]" class="form-control" placeholder="Name of Journal"><input type="text" id="journal[]" name="journal[]" class="form-control" placeholder="Name of Journal"><input type="text" id="journal[]" name="journal[]" class="form-control" placeholder="Name of Journal">
        </div>
</code>```

CSS

```<code>.input-group .form-group:nth-child(2) {
    margin-bottom: 0;
    display: flex;
}
.input-group .form-group:nth-child(2) input + input {
    margin-left: 15px;
}
</code>```

Body:
I am new to Bootstrap. I am trying to add an input group in which text fields are place side-by-side. However, it is not grouping well. I am getting extra space between the text fields and button.

Here is my code:

            <input type="text" id="title[]" name="title[]" class="form-control" placeholder="Title of Paper" />

            <input type="text" id="journal[]" name="journal[]" class="form-control" placeholder="Name of Journal" />

             Add New

Any help is highly appreciated.

Body:
Removed col-sm-12 form form-group and removed margin of last form-group

<div class="form-group researchPapers">
    <div class="input-group">
        <div class="form-group">
            <input type="text" id="title[]" name="title[]" class="form-control" placeholder="Title of Paper" />
        </div>
        <div class="form-group">
            <input type="text" id="journal[]" name="journal[]" class="form-control" placeholder="Name of Journal" />
        </div>
        <div class="input-group-addon">
            <a href="javascript:void(0)" class="btn btn-success addMore"><span class="glyphicon glyphicon glyphicon-plus" aria-hidden="true"></span> Add New</a>
        </div>
    </div>
</div>

CSS

.input-group .form-group:nth-child(2) {
    margin-bottom: 0;
}

For general idea of multiple inputs (Use bootstrap 4 classes for flex
  i am giving general idea)

<div class="form-group">
            <input type="text" id="journal[]" name="journal[]" class="form-control" placeholder="Name of Journal" style="
    flex-basis: 1;
"><input type="text" id="journal[]" name="journal[]" class="form-control" placeholder="Name of Journal"><input type="text" id="journal[]" name="journal[]" class="form-control" placeholder="Name of Journal"><input type="text" id="journal[]" name="journal[]" class="form-control" placeholder="Name of Journal">
        </div>

CSS

.input-group .form-group:nth-child(2) {
    margin-bottom: 0;
    display: flex;
}
.input-group .form-group:nth-child(2) input + input {
    margin-left: 15px;
}


来源: stackexchange

问:
send javascript array variable to php script using jquery ajax (getting string as output instead of array)
I am trying to send JavaScript array to PHP script using Ajax but when i try to var_dump $_POST['file_paths'] getting string instead of array as an output, i want output in array format not in string format. is it because of Ajax setting i am using in code like contentType: false and processData: false.

i tried JSON decoding and encoding still getting string as an output , if anyone can point me in right direction.( need output in array format not in string)

HTML Markup : (folder upload)

```<code><form id='submit' action='' method="post">
            <div id="upload">
                <div class="fileContainer">

                    <input id="myfiles" type="file" name="myfiles[]" multiple="multiple" webkitdirectory multiple directory />
                </div>
            </div>
            <input id="directory_name" type="text" name="directory_name" placeholder="Directory Name" >
</form>
</code>```

This is simple js to fetch all form data like parent directory name , and file data and file path using

webkitRelativePath

after fetching all data sending two array 1st is file array and second is file_paths array to php script, when i console.log file_paths array getting array.

JS script:

```<code>            $(document).ready(function() {
                $('#myfiles').on("change", function() {

                    var myfiles = document.getElementById("myfiles");
                    var file_paths = [];
                    var files = myfiles.files;
                    var new_directory_name =$('#directory_name').val();
                    var data = new FormData();
                    data.append('new_directory_name',new_directory_name);
                    data.append('action', 'upload_folder_to_server');
                    data.append('data_room_id', 55);
                    data.append('username', 'saurabh');
                    for (i = 0; i < files.length; i++) {
                        data.append('file' + i, files[i]);
                        file_paths.push(files[i].webkitRelativePath);
                        console.log(files[i].webkitRelativePath);
                    }
                    //file_paths = JSON.stringify(file_paths);
                    console.log(file_paths);
                    data.append('file_paths', file_paths);
                    $.ajax({
                        method: "POST",
                        url: ajaxurl,
                        contentType: false,
                        data: data,
                        processData: false,
                        //cache: false
                    }).done(function(msg) {
                        $("#loadedfiles").append(msg);
                    });
                });
            });
</code>```

javascript output:

```<code>Array(3) [ "first folder/second folder/third folder/upload_groupmembers_additonal_login_sample(7).xlsx", "first folder/second folder/upload_groupmembers_additonal_login_sample(7).xlsx", "first folder/upload_groupmembers_additonal_login_sample(7).xlsx" ]
</code>```

In PHP Script  when var_dump file_paths getting output in string format.
PHP Script:

```<code>function upload_folder_to_server()
{
    var_dump($_POST['file_paths']);
}
add_action('wp_ajax_upload_folder_to_server', 'upload_folder_to_server');
add_action('wp_ajax_nopriv_upload_folder_to_server', 'upload_folder_to_server');
</code>```

Output:

```<code>string(232) "first folder/second folder/third folder/upload_groupmembers_additonal_login_sample(7).xlsx,first folder/second folder/upload_groupmembers_additonal_login_sample(7).xlsx,first folder/upload_groupmembers_additonal_login_sample(7).xlsx"
</code>```

can someone explain me why i am getting string in PHP and array in JavaScript

答:
```<code>  var myfiles = document.getElementById("myfiles");
                    var file_paths = [];
                    var files = myfiles.files;
                    var new_directory_name =$('#directory_name').val();
                    var data = new FormData();
                    data.append('new_directory_name',new_directory_name);
                    data.append('action', 'upload_folder_to_server');
                    data.append('data_room_id', 55);
                    data.append('username', 'saurabh');
                    for (i = 0; i < files.length; i++) {
                        data.append('file' + i, files[i]);
                        file_paths.push(files[i].webkitRelativePath);
                        console.log(files[i].webkitRelativePath);
                    }
                    //file_paths = JSON.stringify(file_paths);
                    console.log(file_paths);
                    data.append('file_paths', file_paths);
</code>```

replace with this and try

```<code>var myfiles = document.getElementById("myfiles");
var file_paths = [];
var files = myfiles.files;
var new_directory_name =$('#directory_name').val();
var data = new FormData();
data.set('new_directory_name',new_directory_name);
data.set('action', 'upload_folder_to_server');
data.set('data_room_id', 55);
data.set('username', 'saurabh');
for (i = 0; i < files.length; i++) {
data.set('file' + i, files[i]);
file_paths.push(files[i].webkitRelativePath);
console.log(files[i].webkitRelativePath);
}
data.set('file_paths', file_paths);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to send JavaScript array to PHP script using Ajax but when i try to var_dump $_POST['file_paths'] getting string instead of array as an output, i want output in array format not in string format. is it because of Ajax setting i am using in code like contentType: false and processData: false.

i tried JSON decoding and encoding still getting string as an output , if anyone can point me in right direction.( need output in array format not in string)

HTML Markup : (folder upload)

<form id='submit' action='' method="post">

                    <input id="myfiles" type="file" name="myfiles[]" multiple="multiple" webkitdirectory multiple directory />

            <input id="directory_name" type="text" name="directory_name" placeholder="Directory Name" >
</form>

This is simple js to fetch all form data like parent directory name , and file data and file path using

webkitRelativePath

after fetching all data sending two array 1st is file array and second is file_paths array to php script, when i console.log file_paths array getting array.

JS script:

            $(document).ready(function() {
                $('#myfiles').on("change", function() {

                    var myfiles = document.getElementById("myfiles");
                    var file_paths = [];
                    var files = myfiles.files;
                    var new_directory_name =$('#directory_name').val();
                    var data = new FormData();
                    data.append('new_directory_name',new_directory_name);
                    data.append('action', 'upload_folder_to_server');
                    data.append('data_room_id', 55);
                    data.append('username', 'saurabh');
                    for (i = 0; i < files.length; i++) {
                        data.append('file' + i, files[i]);
                        file_paths.push(files[i].webkitRelativePath);
                        console.log(files[i].webkitRelativePath);
                    }
                    //file_paths = JSON.stringify(file_paths);
                    console.log(file_paths);
                    data.append('file_paths', file_paths);
                    $.ajax({
                        method: "POST",
                        url: ajaxurl,
                        contentType: false,
                        data: data,
                        processData: false,
                        //cache: false
                    }).done(function(msg) {
                        $("#loadedfiles").append(msg);
                    });
                });
            });

javascript output:

Array(3) [ "first folder/second folder/third folder/upload_groupmembers_additonal_login_sample(7).xlsx", "first folder/second folder/upload_groupmembers_additonal_login_sample(7).xlsx", "first folder/upload_groupmembers_additonal_login_sample(7).xlsx" ]

In PHP Script  when var_dump file_paths getting output in string format.
PHP Script:

function upload_folder_to_server()
{
    var_dump($_POST['file_paths']);
}
add_action('wp_ajax_upload_folder_to_server', 'upload_folder_to_server');
add_action('wp_ajax_nopriv_upload_folder_to_server', 'upload_folder_to_server');

Output:

string(232) "first folder/second folder/third folder/upload_groupmembers_additonal_login_sample(7).xlsx,first folder/second folder/upload_groupmembers_additonal_login_sample(7).xlsx,first folder/upload_groupmembers_additonal_login_sample(7).xlsx"

can someone explain me why i am getting string in PHP and array in JavaScript

Body:
  var myfiles = document.getElementById("myfiles");
                    var file_paths = [];
                    var files = myfiles.files;
                    var new_directory_name =$('#directory_name').val();
                    var data = new FormData();
                    data.append('new_directory_name',new_directory_name);
                    data.append('action', 'upload_folder_to_server');
                    data.append('data_room_id', 55);
                    data.append('username', 'saurabh');
                    for (i = 0; i < files.length; i++) {
                        data.append('file' + i, files[i]);
                        file_paths.push(files[i].webkitRelativePath);
                        console.log(files[i].webkitRelativePath);
                    }
                    //file_paths = JSON.stringify(file_paths);
                    console.log(file_paths);
                    data.append('file_paths', file_paths);

replace with this and try

var myfiles = document.getElementById("myfiles");
var file_paths = [];
var files = myfiles.files;
var new_directory_name =$('#directory_name').val();
var data = new FormData();
data.set('new_directory_name',new_directory_name);
data.set('action', 'upload_folder_to_server');
data.set('data_room_id', 55);
data.set('username', 'saurabh');
for (i = 0; i < files.length; i++) {
data.set('file' + i, files[i]);
file_paths.push(files[i].webkitRelativePath);
console.log(files[i].webkitRelativePath);
}
data.set('file_paths', file_paths);


问:
How to Reset a Boundary Timer Time Cicle and/or Time Duration in Activiti 5.22.0?
Does anyone know how can I programmatically reset a Boundary

Timer Time Cicle and/or Time Duration from a Java TaskListener using Activiti 5.22.0?

答:
```<code>Can you please try this?

processInstanceId => process Instance ID
jobs = processEngine.getManagementService().createTimerJobQuery().processInstanceId(processInstanceId).list();
TimerJobEntity tJobEntity = (TimerJobEntity) job;
tJobEntity.setDuedate(date);

where date is new date that we want to set.
</code>```


答:
The problem is that you seem to misunderstand what transforms.Normalize does. To quote from the PyTorch documentation:

Normalize a tensor image with mean and standard deviation. Given mean:
  (M1,...,Mn) and std: (S1,..,Sn) for n channels, this transform will
  normalize each channel of the input torch.*Tensor i.e. input[channel] = (input[channel] - mean[channel]) / std[channel]

The calculation for a value of, say 100, and the std and mean you provided would then be: 100 - 0.5 / 0.5 = 199.
Of course, you could increase std and mean, but this does not guarantee you the exact result that you might expect.
As suggested in the comments, the best way would probably be to invert the operations that you performed in order to get the tensor to [0 255] in the first place.

Edit:

As it turns out, according to this forum post, it seems that the transformations from PIL images to tensors automatically turn your value range to [0 1] (and to [0 255] if you transform to a PIL image, respectively), as is written in the fine-print of transforms.ToTensor. For the return transformation it is not explicitly stated, but can be enforced via the mode.

Title: (pytorch) I want to normalize [0 255] integer tensor to [0 1] float tensor

Body:
I want to normalize [0 255] integer tensor to [0 1] float tensor.

I used cifar10 dataset and wanted to deal with integer image tensor.

so I made them integer tensor
when I loaded dataset, I used "transforms.ToTensor()" so the values were set to [0 1] float

tensor([[[0.4588, 0.4588, 0.4588,  ..., 0.4980, 0.4980, 0.5020],
         [0.4706, 0.4706, 0.4706,  ..., 0.5098, 0.5098, 0.5137],
         [0.4824, 0.4824, 0.4824,  ..., 0.5216, 0.5216, 0.5294],
         ...,
         [0.3098, 0.3020, 0.2863,  ..., 0.4549, 0.3608, 0.3137],
         [0.2902, 0.2902, 0.2902,  ..., 0.4431, 0.3333, 0.3020],
         [0.2706, 0.2941, 0.2941,  ..., 0.4157, 0.3529, 0.3059]],

        [[0.7725, 0.7725, 0.7725,  ..., 0.7569, 0.7569, 0.7608],
         [0.7765, 0.7765, 0.7765,  ..., 0.7608, 0.7608, 0.7686],
         [0.7765, 0.7765, 0.7765,  ..., 0.7608, 0.7608, 0.7725],
         ...,
         [0.6510, 0.6314, 0.6078,  ..., 0.6941, 0.6510, 0.6392],
         [0.6314, 0.6235, 0.6118,  ..., 0.6784, 0.6196, 0.6275],
         [0.6157, 0.6235, 0.6157,  ..., 0.6549, 0.6431, 0.6314]],

To make them [0 255] integer tensor.

temp = np.floor(temp_images*256)
temp_int = torch.tensor(temp, dtype=torch.int32)
temp_images = torch.clamp(temp, 0, 255)

and the result was

torch.IntTensor
tensor([[[[ 94., 100., 100.,  ...,  98., 100., 102.],
          [ 86., 100., 101.,  ...,  83.,  91., 103.],
          [ 90., 100.,  99.,  ...,  80.,  66.,  86.],
          ...,
          [ 92.,  92.,  90.,  ...,  77., 107., 119.],
          [ 76.,  91., 100.,  ...,  95., 158., 170.],
          [ 86.,  83.,  87.,  ...,  97., 176., 205.]],

         [[105., 111., 111.,  ..., 109., 112., 113.],
          [ 97., 111., 112.,  ...,  94., 102., 114.],
          [101., 111., 110.,  ...,  90.,  77.,  97.],
          ...,
          [111., 110., 108.,  ...,  88., 120., 131.],
          [ 95., 108., 114.,  ..., 105., 165., 172.],
          [106., 100., 101.,  ..., 108., 183., 206.]],

         [[ 62.,  68.,  68.,  ...,  66.,  68.,  70.],
          [ 55.,  69.,  70.,  ...,  51.,  59.,  71.],
          [ 59.,  69.,  68.,  ...,  48.,  34.,  54.],
          ...,
          [ 59.,  59.,  56.,  ...,  54.,  95., 107.],
          [ 49.,  61.,  66.,  ...,  76., 152., 166.],
          [ 61.,  55.,  54.,  ...,  73., 170., 206.]]],

before forwarding them to the network,
I want to make them [0 1] float tensor again.

So I tried

transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))

But, the result is not normalized to [0 1] and rather it becomes bigger...!

tensor([[[117., 117., 117.,  ..., 127., 127., 128.],
         [120., 120., 120.,  ..., 130., 130., 131.],
         [123., 123., 123.,  ..., 133., 133., 135.],
         ...,
         [ 79.,  77.,  73.,  ..., 116.,  92.,  80.],
         [ 74.,  74.,  74.,  ..., 113.,  85.,  77.],
         [ 69.,  75.,  75.,  ..., 106.,  90.,  78.]],

        [[197., 197., 197.,  ..., 193., 193., 194.],
         [198., 198., 198.,  ..., 194., 194., 196.],
         [198., 198., 198.,  ..., 194., 194., 197.],

to

tensor([[[233., 233., 233.,  ..., 253., 253., 255.],
         [239., 239., 239.,  ..., 259., 259., 261.],
         [245., 245., 245.,  ..., 265., 265., 269.],
         ...,
         [157., 153., 145.,  ..., 231., 183., 159.],
         [147., 147., 147.,  ..., 225., 169., 153.],
         [137., 149., 149.,  ..., 211., 179., 155.]],

        [[393., 393., 393.,  ..., 385., 385., 387.],
         [395., 395., 395.,  ..., 387., 387., 391.],
         [395., 395., 395.,  ..., 387., 387., 393.],
         ...,
         [331., 321., 309.,  ..., 353., 331., 325.],
         [321., 317., 311.,  ..., 345., 315., 319.],
         [313., 317., 313.,  ..., 333., 327., 321.]],

How I can normalize [0 255] integer tensor to [0 1] float tensor?


问:
trying to implement a side navigation with a toggle button in <mat-toolbar>?
I am having a side navigation panel with some details.
In the header component I am having a button which should toggle the side navigation.
I have implemented a toolbar using .My requirement is that when i click on  that button, the side navigation should toggle in and out.
How to implement it ?

My navigation.component.html:

```<code><mat-toolbar>
      </mat-toolbar>
<mat-sidenav-container>

    <mat-list>
    <mat-list-item>Accounts</mat-list-item>
    <mat-list-item>UserProfile</mat-list-item>
    <mat-list-item>Contact me</mat-list-item>
    <mat-list-item>Gspeed</mat-list-item>

  </mat-list>

 </mat-sidenav-container>
</code>```

header.component.html

```<code><body [ngClass]="selectedStyle" ><div >

    <select [(ngModel)]="selectedStyle" >
       <option *ngFor="let s of styles" [ngValue]="s">{{s}}</option>
    </select>
    <button mat-icon-button (click)="toggleSidenav()">
      <mat-icon >Details</mat-icon></button>

    </div>
   </body>
</code>```

app.component.ts

```<code>import { Component, OnInit,Output,EventEmitter } from '@angular/core';

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

  styles: string[] = [];
  selectedStyle: string;
  open: false;
   toggleSidenav(){
     open: !this.open;
   }

  constructor() {

  }

  ngOnInit(){

    this.styles = ['red','green','blue','none'];
    }

}
</code>```

答:
change your togglelSSideNav() function
and use ngIf to check open status</p>

```<code>     toggleSidenav(){
     this.open=!this.open;
   }
</code>```

Body:
I am having a side navigation panel with some details.
In the header component I am having a button which should toggle the side navigation.
I have implemented a toolbar using .My requirement is that when i click on  that button, the side navigation should toggle in and out.
How to implement it ?

My navigation.component.html:

<mat-toolbar>
      </mat-toolbar>
<mat-sidenav-container>

    <mat-list>
    <mat-list-item>Accounts</mat-list-item>
    <mat-list-item>UserProfile</mat-list-item>
    <mat-list-item>Contact me</mat-list-item>
    <mat-list-item>Gspeed</mat-list-item>

  </mat-list>

 </mat-sidenav-container>

header.component.html

    <select [(ngModel)]="selectedStyle" >
       <option *ngFor="let s of styles" [ngValue]="s">{{s}}</option>
    </select>
    <button mat-icon-button (click)="toggleSidenav()">
      <mat-icon >Details</mat-icon></button>

app.component.ts

import { Component, OnInit,Output,EventEmitter } from '@angular/core';

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

  styles: string[] = [];
  selectedStyle: string;
  open: false;
   toggleSidenav(){
     open: !this.open;
   }

  constructor() {

  }

  ngOnInit(){

    this.styles = ['red','green','blue','none'];
    }

}

Body:
change your togglelSSideNav() function
and use ngIf to check open status

     toggleSidenav(){
     this.open=!this.open;
   }


问:
How to set up a Docker redis container with ssl
I'm following this tutorial.

In my case I am operating in a Docker environment, and I have a secured site (i.e. https://localhost). which requires secured ssl communication.

I adjusted the web, and celery containers for secure connection.

But I don't know how to configure the Redis container for secure connection with ssl

Note that when I run without ssl connection in the web and celery containers, the connection is fine.

How do I configure and run redis with ssl?

Thanks

EDIT:

I followed this tutorial to set redis with ssl and this tutorial to set redis with ssl via stunnel in Docker container.

I successfully tested the connection from my localhost to the redis docker container, by invoking redis-cli from localhost (via stunnel) to the redis docker container, using the following call from the localhost:

```<code>redis-cli -h 127.0.0.1 -p 6381
127.0.0.1:6381> auth foobared
OK
127.0.0.1:6381>
</code>```

Related files on the redis server Docker side:

docker-compose file (my webapp includes multiple services, but to for simplification I removed all services except for the redis container):

```<code>version: '3'

services:
  redis:
    build:
      context: ./redis
      dockerfile: Dockerfile
    restart: always
    command: sh -c "stunnel /stunnel_take2.conf && /usr/local/bin/redis-server /etc/redis/redis.conf"
    expose:
      - '6379'
    ports:
     - "6379:6379"
    volumes:
      - /home/avner/avner/certs:/etc/certs
      - /home/avner/avner/redis/conf:/etc/redis
</code>```

redis container Dockerfile

```<code>FROM redis:5-alpine

RUN apk add --no-cache \
    stunnel~=5.56 \
    python3~=3.8

COPY stunnel-redis-server.conf /

WORKDIR /

ENV PYTHONUNBUFFERED=1
</code>```

redis server redis conf file - redis/conf/redis.conf

```<code>...
requirepass foobared
...
</code>```

redis server stunnel conf file - redis/stunnel-redis-server.conf

```<code>cert = /etc/certs/private.pem
pid = /var/run/stunnel.pid

[redis]
accept = 172.19.0.2:6380
connect = 127.0.0.1:6379
</code>```

Related files on the client side (localhost):

redis client stunnel conf file - /etc/stunnel/redis-client.conf

```<code>cert = /etc/cert/private.pem
client = yes
pid = /var/run/stunnel.pid
[redis]
accept = 127.0.0.1:6381
connect = 172.19.0.2:6380
</code>```

答: Redis doesn't provide SSL by itself, you have to do it yourself. There's an in-depth post about it which you can read and follow. Or, if you want to use a Dockerized solution, you can use ready images like this one or this one. When it comes to setting up Celery to work with Redis over SSL, just follow the documentation.</p>

Body:
I'm following this tutorial.

In my case I am operating in a Docker environment, and I have a secured site (i.e. https://localhost). which requires secured ssl communication.

I adjusted the web, and celery containers for secure connection.

But I don't know how to configure the Redis container for secure connection with ssl

Note that when I run without ssl connection in the web and celery containers, the connection is fine.

How do I configure and run redis with ssl?

Thanks

EDIT:

I followed this tutorial to set redis with ssl and this tutorial to set redis with ssl via stunnel in Docker container.

I successfully tested the connection from my localhost to the redis docker container, by invoking redis-cli from localhost (via stunnel) to the redis docker container, using the following call from the localhost:

redis-cli -h 127.0.0.1 -p 6381
127.0.0.1:6381> auth foobared
OK
127.0.0.1:6381>

Related files on the redis server Docker side:

docker-compose file (my webapp includes multiple services, but to for simplification I removed all services except for the redis container):

version: '3'

services:
  redis:
    build:
      context: ./redis
      dockerfile: Dockerfile
    restart: always
    command: sh -c "stunnel /stunnel_take2.conf && /usr/local/bin/redis-server /etc/redis/redis.conf"
    expose:
      - '6379'
    ports:
     - "6379:6379"
    volumes:
      - /home/avner/avner/certs:/etc/certs
      - /home/avner/avner/redis/conf:/etc/redis

redis container Dockerfile

FROM redis:5-alpine

RUN apk add --no-cache \
    stunnel~=5.56 \
    python3~=3.8

COPY stunnel-redis-server.conf /

WORKDIR /

ENV PYTHONUNBUFFERED=1

redis server redis conf file - redis/conf/redis.conf

...
requirepass foobared
...

redis server stunnel conf file - redis/stunnel-redis-server.conf

cert = /etc/certs/private.pem
pid = /var/run/stunnel.pid

[redis]
accept = 172.19.0.2:6380
connect = 127.0.0.1:6379

Related files on the client side (localhost):

redis client stunnel conf file - /etc/stunnel/redis-client.conf

cert = /etc/cert/private.pem
client = yes
pid = /var/run/stunnel.pid
[redis]
accept = 127.0.0.1:6381
connect = 172.19.0.2:6380


问:
not able to show x axis data with datetimelabel format with {hh:mm} in high charts
i want to show x axis data in the form of hh:mm like 10:00 , 12:00, 14:00 but im getting something like Fri Feb 14 2020 08:50:57 GMT+0530 (India Standard Time), i want this should be 08:57, i wanted to show the data in hrs and min format.

sample data
Fri Feb 14 2020 08:50:57 GMT+0530 (India Standard Time)

code

```<code>function getdata() {
            $.ajax
                ({
                    type: "GET",
                    url: "url",
                    dataType: 'json',
                    headers: {
                        'Authorization': "Basic YWRtaW46YWRtaW5AMTIz"
                    },
                    data: '{}',
                    success: function (data) {
                        var disolved_oxygen = data.map(function (data) {
                            var disolvedoxy = data.do;
                            return parseInt(disolvedoxy);
                        }
                        )

                        var ph = data.map(function (data) {
                            var phvalue = data.ph;
                            return parseInt(phvalue);
                        }

                        )
                        var xdata = data.map(function (data) {
                            return (UtcToIst(data.timestatmp));
                        }
                        )
                        Highcharts.chart('container', {
                            credits: {
                                enabled: false
                            },
                            title: {
                                text: 'Central'
                            },

                            subtitle: {
                                text: 'Device Id: 1'
                            },

                            yAxis: {
                                title: {
                                    text: ''
                                }
                            },

                            xAxis: {
                                tickInterval: 5,
                                type: 'datetime',
                                dateTimeLabelFormats: {
                                    day: "%e-%b-%y",
                                    month: "%b-%y"
                                },
                                categories: xdata
                            },
                            legend: {
                                layout: 'vertical',
                                align: 'right',

                                verticalAlign: 'middle'
                            },

                            plotOptions: {
                                series: {
                                    label: {

                                    }
                                }
                            },
                            series: [{
                                name: 'Dissolved Oxygen(mg/L)',
                                data: disolved_oxygen
                            }, {
                                name: 'pH',
                                data: ph
                            }],

                            responsive: {
                                rules: [{
                                    condition: {
                                        maxWidth: 500
                                    },
                                    chartOptions: {
                                        legend: {
                                            layout: 'horizontal',
                                            align: 'center',
                                            verticalAlign: 'bottom'
                                        }
                                    }
                                }]
                            }

                        });
                    }
                });
        }
</code>```

答:
You can use the pointInterval feature to achieve it.

Demo: https://jsfiddle.net/BlackLabel/r4d60avy/

Code:

```<code>  xAxis: {
    type: 'datetime'
  },

  plotOptions: {
    series: {
      pointStart: Date.UTC(2010, 0, 1),
      pointInterval: 60 * 60 * 1000 // one hour
    }
  },
</code>```

API: https://api.highcharts.com/highcharts/series.line.pointInterval

Body:
i want to show x axis data in the form of hh:mm like 10:00 , 12:00, 14:00 but im getting something like Fri Feb 14 2020 08:50:57 GMT+0530 (India Standard Time), i want this should be 08:57, i wanted to show the data in hrs and min format.

sample data
Fri Feb 14 2020 08:50:57 GMT+0530 (India Standard Time)

code

function getdata() {
            $.ajax
                ({
                    type: "GET",
                    url: "url",
                    dataType: 'json',
                    headers: {
                        'Authorization': "Basic YWRtaW46YWRtaW5AMTIz"
                    },
                    data: '{}',
                    success: function (data) {
                        var disolved_oxygen = data.map(function (data) {
                            var disolvedoxy = data.do;
                            return parseInt(disolvedoxy);
                        }
                        )

                        var ph = data.map(function (data) {
                            var phvalue = data.ph;
                            return parseInt(phvalue);
                        }

                        )
                        var xdata = data.map(function (data) {
                            return (UtcToIst(data.timestatmp));
                        }
                        )
                        Highcharts.chart('container', {
                            credits: {
                                enabled: false
                            },
                            title: {
                                text: 'Central'
                            },

                            subtitle: {
                                text: 'Device Id: 1'
                            },

                            yAxis: {
                                title: {
                                    text: ''
                                }
                            },

                            xAxis: {
                                tickInterval: 5,
                                type: 'datetime',
                                dateTimeLabelFormats: {
                                    day: "%e-%b-%y",
                                    month: "%b-%y"
                                },
                                categories: xdata
                            },
                            legend: {
                                layout: 'vertical',
                                align: 'right',

                                verticalAlign: 'middle'
                            },

                            plotOptions: {
                                series: {
                                    label: {

                                    }
                                }
                            },
                            series: [{
                                name: 'Dissolved Oxygen(mg/L)',
                                data: disolved_oxygen
                            }, {
                                name: 'pH',
                                data: ph
                            }],

                            responsive: {
                                rules: [{
                                    condition: {
                                        maxWidth: 500
                                    },
                                    chartOptions: {
                                        legend: {
                                            layout: 'horizontal',
                                            align: 'center',
                                            verticalAlign: 'bottom'
                                        }
                                    }
                                }]
                            }

                        });
                    }
                });
        }

Body:
You can use the pointInterval feature to achieve it.

Demo: https://jsfiddle.net/BlackLabel/r4d60avy/

Code:

  xAxis: {
    type: 'datetime'
  },

  plotOptions: {
    series: {
      pointStart: Date.UTC(2010, 0, 1),
      pointInterval: 60 * 60 * 1000 // one hour
    }
  },

API: https://api.highcharts.com/highcharts/series.line.pointInterval


问:
Flutter how to create a zip file
How to create a zip file with Flutter? I tried with archive package but it does not have any sample to create a zip file. Please help. I am totally new in Flutter. After creating the zip file with archive package error getting while extracting the zip file.

With archive package this is what I did:

```<code>  void _generateItemArchive(ZipFileEncoder encoder, int id) async {
List<Item> _itemList = await DBProvider.db.getAllItem(id);
_itemList.forEach((Item _item) {
  encoder.addFile(File(_item.photo));
});
</code>```

}

```<code>ZipFileEncoder encoder = ZipFileEncoder();
encoder.create(join(documentsDirectory.path, 'product.zip'));

encoder.addFile(File('${documentsDirectory.path}/TestDB.db'));

List<Supplier> _supplierList = await DBProvider.db.getAllSupplier();
_supplierList.forEach((Supplier _supplier) {
  encoder.addFile(File(_supplier.photo));
  _generateItemArchive(encoder, _supplier.id);
});
</code>```

I am getting an error when I tried to call encoder.close(); I need to add the files from database record.

答:
There is also a new plugin optimized for Android and iOS available here (this is my library). Sample for zipping files:</p>
```<code>  final sourceDir = Directory("source_dir");
  final files = [
    File(sourceDir.path + "/file1"),
    File(sourceDir.path + "/file2")
  ];
  final zipFile = File("zip_file_path");
  try {
    FlutterArchive.zipFiles(
        sourceDir: sourceDir, files: files, zipFile: zipFile);
  } catch (e) {
    print(e);
  }
</code>```

Title: Flutter how to create a zip file

Body:
How to create a zip file with Flutter? I tried with archive package but it does not have any sample to create a zip file. Please help. I am totally new in Flutter. After creating the zip file with archive package error getting while extracting the zip file.

With archive package this is what I did:

  void _generateItemArchive(ZipFileEncoder encoder, int id) async {
List<Item> _itemList = await DBProvider.db.getAllItem(id);
_itemList.forEach((Item _item) {
  encoder.addFile(File(_item.photo));
});

}

ZipFileEncoder encoder = ZipFileEncoder();
encoder.create(join(documentsDirectory.path, 'product.zip'));

encoder.addFile(File('${documentsDirectory.path}/TestDB.db'));

List<Supplier> _supplierList = await DBProvider.db.getAllSupplier();
_supplierList.forEach((Supplier _supplier) {
  encoder.addFile(File(_supplier.photo));
  _generateItemArchive(encoder, _supplier.id);
});

I am getting an error when I tried to call encoder.close(); I need to add the files from database record.

Body:
There is also a new plugin optimized for Android and iOS available here (this is my library). Sample for zipping files:

  final sourceDir = Directory("source_dir");
  final files = [
    File(sourceDir.path + "/file1"),
    File(sourceDir.path + "/file2")
  ];
  final zipFile = File("zip_file_path");
  try {
    FlutterArchive.zipFiles(
        sourceDir: sourceDir, files: files, zipFile: zipFile);
  } catch (e) {
    print(e);
  }


问:
Vector subscript out of range in SFML game
Im working on a game as a project for my game development course. It is using vectors to spawn enemies at the top of the screen and run down as well as creating "bullets" that are fired by both the player and the boss. After adding the boss and code for his bullets the previously working code is now throwing a vector subscript out of range error. This error is always thrown right after hitting an enemy and didn't happen before the boss was introduced.

```<code>            bullets[i].shape.move(bullets[i].currVelocity);

            //Bullet Removal
            if (bullets[i].shape.getPosition().x < 0 || bullets[i].shape.getPosition().x > window.getSize().x
                || bullets[i].shape.getPosition().y < 0 || bullets[i].shape.getPosition().y > window.getSize().y) {
                bullets.erase(bullets.begin() + i);
            }
            else {
                //Collision Code
                for (size_t k = 0; k < enemies.size(); k++) {
                    if (bullets[i].shape.getGlobalBounds().intersects(enemies[k].getGlobalBounds())) {
                        bullets.erase(bullets.begin() + i);
                        enemies.erase(enemies.begin() + k);
                        score = score + 1;
                        fiveScore = fiveScore + 1;
                        std::cout << "Score: " << score << std::endl;
                        hitSound.play();
                        if (fiveScore == 5) {
                            fiveScore = 0;
                            //scoreUpSound.play();
                        }
                        if (score >= 100 && bossSpawned == false) {
                            bossSpawned = true;
                            boss.setPosition(250.0f, 50.0f);
                        }
                        break;
                    }
                }
                if (bullets[i].shape.getGlobalBounds().intersects(boss.getGlobalBounds())) {
                    bullets.erase(bullets.begin() + i);
                    hitSound.play();
                    bossHP = bossHP - 1;
                    if (bossHP <= 0) {
                        bossSpawned = false;
                        boss.setPosition(3214.0f, 4322.0f);
                        text.setString("You have completed your quest." "\n" "The warlock is slain and the realm is" "\n" "safe, yet as life returns to the kingdom" "\n" "you are dissatisfied. Your brother and" "\n" "lover are both deceased and" "\n" "you feel only death will heal your pain.");
                        text.setPosition(25.0f, 150.0f);
                        window.clear();
                        window.draw(text);
                        window.display();
                        Sleep(9000);
                        return 0;
                    }
                    break;
                }
            }
        }
</code>```

This is the code for the player's bullet collisions.

```<code>            b2.shape.setPosition(bossCenter);
            b2.currVelocity = bossAimDirNorm * b2.maxSpeed;

            bossbullets.push_back(BossBullet(b2));
        }

        for (size_t z = 0; z < bossbullets.size(); z++) {
            bossbullets[z].shape.move(bossbullets[z].currVelocity);

            //BossBullet Removal
            if (bossbullets[z].shape.getPosition().x < 0 || bossbullets[z].shape.getPosition().x > window.getSize().x
                || bossbullets[z].shape.getPosition().y < 0 || bossbullets[z].shape.getPosition().y > window.getSize().y) {
                bossbullets.erase(bossbullets.begin() + z);
            }
            else {
                //Collision Code
                if (bossbullets[z].shape.getGlobalBounds().intersects(player.getGlobalBounds())) {
                        bossbullets.erase(bossbullets.begin() + z);
                        playerDead = true;
                        text.setString("You have failed your quest.");
                        text.setPosition(150.0f, 150.0f);
                        window.clear();
                        window.draw(text);
                        window.display();
                        Sleep(5000);
                        return 0;
                }
            }
        }
</code>```

This is the code for the boss' bullet collisions. Any help or even ideas of what could be wrong would be helpful. Reverting to before I added the boss is the only solution I've found for now.

答:
You are erasing from your vector while looping over it. This changes the size of your vector which can often be a source of errors.

Take a look at Remove elements of a vector inside the loop for a way to do it instead.

Body:
Im working on a game as a project for my game development course. It is using vectors to spawn enemies at the top of the screen and run down as well as creating "bullets" that are fired by both the player and the boss. After adding the boss and code for his bullets the previously working code is now throwing a vector subscript out of range error. This error is always thrown right after hitting an enemy and didn't happen before the boss was introduced.

            bullets[i].shape.move(bullets[i].currVelocity);

            //Bullet Removal
            if (bullets[i].shape.getPosition().x < 0 || bullets[i].shape.getPosition().x > window.getSize().x
                || bullets[i].shape.getPosition().y < 0 || bullets[i].shape.getPosition().y > window.getSize().y) {
                bullets.erase(bullets.begin() + i);
            }
            else {
                //Collision Code
                for (size_t k = 0; k < enemies.size(); k++) {
                    if (bullets[i].shape.getGlobalBounds().intersects(enemies[k].getGlobalBounds())) {
                        bullets.erase(bullets.begin() + i);
                        enemies.erase(enemies.begin() + k);
                        score = score + 1;
                        fiveScore = fiveScore + 1;
                        std::cout << "Score: " << score << std::endl;
                        hitSound.play();
                        if (fiveScore == 5) {
                            fiveScore = 0;
                            //scoreUpSound.play();
                        }
                        if (score >= 100 && bossSpawned == false) {
                            bossSpawned = true;
                            boss.setPosition(250.0f, 50.0f);
                        }
                        break;
                    }
                }
                if (bullets[i].shape.getGlobalBounds().intersects(boss.getGlobalBounds())) {
                    bullets.erase(bullets.begin() + i);
                    hitSound.play();
                    bossHP = bossHP - 1;
                    if (bossHP <= 0) {
                        bossSpawned = false;
                        boss.setPosition(3214.0f, 4322.0f);
                        text.setString("You have completed your quest." "\n" "The warlock is slain and the realm is" "\n" "safe, yet as life returns to the kingdom" "\n" "you are dissatisfied. Your brother and" "\n" "lover are both deceased and" "\n" "you feel only death will heal your pain.");
                        text.setPosition(25.0f, 150.0f);
                        window.clear();
                        window.draw(text);
                        window.display();
                        Sleep(9000);
                        return 0;
                    }
                    break;
                }
            }
        }

This is the code for the player's bullet collisions.

            b2.shape.setPosition(bossCenter);
            b2.currVelocity = bossAimDirNorm * b2.maxSpeed;

            bossbullets.push_back(BossBullet(b2));
        }

        for (size_t z = 0; z < bossbullets.size(); z++) {
            bossbullets[z].shape.move(bossbullets[z].currVelocity);

            //BossBullet Removal
            if (bossbullets[z].shape.getPosition().x < 0 || bossbullets[z].shape.getPosition().x > window.getSize().x
                || bossbullets[z].shape.getPosition().y < 0 || bossbullets[z].shape.getPosition().y > window.getSize().y) {
                bossbullets.erase(bossbullets.begin() + z);
            }
            else {
                //Collision Code
                if (bossbullets[z].shape.getGlobalBounds().intersects(player.getGlobalBounds())) {
                        bossbullets.erase(bossbullets.begin() + z);
                        playerDead = true;
                        text.setString("You have failed your quest.");
                        text.setPosition(150.0f, 150.0f);
                        window.clear();
                        window.draw(text);
                        window.display();
                        Sleep(5000);
                        return 0;
                }
            }
        }

This is the code for the boss' bullet collisions. Any help or even ideas of what could be wrong would be helpful. Reverting to before I added the boss is the only solution I've found for now.


问:
React:Unable to resolve path to module and intellisense in my own typescript react moudle does not working
I have created my own env module following this repo:

https://github.com/codeBelt/Custom-Environment-Variables-Setup

in the index file, I import the environment module and I got an error from typescript ( not a compilation error, the code is working)

```<code>import environment from 'environment';
console.log(environment.api);
</code>```

2 issues:

environment.  and typescript don't manage to complete it ( inteliisense)

i got "Unable to resolve path to module 'environment'.eslint(import/no-unresolved)"

I have the following files :

enviornments/Base.ts

```<code>export default function baseEnv(baseUrl: string) {
  const baseAPi = window.config.API_URL || baseUrl;

  return {
    api: {
      settings: `${baseAPi}?action=get_settings`
    },
    isProduction: true,
    isDevelopment: false,
    isTesting: false
  };
};

export type Environment = ReturnType<typeof baseEnv>;
</code>```

enviorments/production.ts

```<code>import environment, { Environment } from './base';
/*
 * base.ts is the default environment for production.
 * You shouldn't have to override anything.
 */

const baseApi = 'http://api';
const env = environment(baseApi);

const productionEnv: Environment = {
  ...env
};

export default productionEnv;
</code>```

enviornments.d.ts

```<code>declare module 'environment' {
  import baseEnv from 'environments/base';

  const value: ReturnType<typeof baseEnv>;

  export default value;
}
</code>```

答:
How to manually add a path to be resolved in eslintrc

here is the solution

1 - open eslintrc.

2 add settings object as follows:

```<code>"settings": {
    "import/resolver": {
      "node": {
        "paths": ["src"]
      }
    }
},
</code>```

Body:
I have created my own env module following this repo:

https://github.com/codeBelt/Custom-Environment-Variables-Setup

in the index file, I import the environment module and I got an error from typescript ( not a compilation error, the code is working)

import environment from 'environment';
console.log(environment.api);

2 issues:

environment.  and typescript don't manage to complete it ( inteliisense)

i got "Unable to resolve path to module 'environment'.eslint(import/no-unresolved)"

I have the following files :

enviornments/Base.ts

export default function baseEnv(baseUrl: string) {
  const baseAPi = window.config.API_URL || baseUrl;

  return {
    api: {
      settings: `${baseAPi}?action=get_settings`
    },
    isProduction: true,
    isDevelopment: false,
    isTesting: false
  };
};

export type Environment = ReturnType<typeof baseEnv>;

enviorments/production.ts

import environment, { Environment } from './base';
/*
 * base.ts is the default environment for production.
 * You shouldn't have to override anything.
 */

const baseApi = 'http://api';
const env = environment(baseApi);

const productionEnv: Environment = {
  ...env
};

export default productionEnv;

enviornments.d.ts

declare module 'environment' {
  import baseEnv from 'environments/base';

  const value: ReturnType<typeof baseEnv>;

  export default value;
}

Body:
How to manually add a path to be resolved in eslintrc

here is the solution

1 - open eslintrc.

2 add settings object as follows:

"settings": {
    "import/resolver": {
      "node": {
        "paths": ["src"]
      }
    }
},


问:
My setState does not refresh after receiving user input. I'm trying to build a chat page
```<code>`final myController = TextEditingController();
@override
void dispose() {
  myController.dispose();
}`
</code>```

This creates a controller for the text input

```<code>`Widget textField(String hint, TextInputType type) {
  return Padding(
    padding: const EdgeInsets.all(8.0),
    child: CupertinoTextField(
      minLines: 1,
      maxLines: null,
      controller: myController,
      textCapitalization: TextCapitalization.sentences,
      placeholder: hint,
      placeholderStyle: TextStyle(color: hintcolor),
      keyboardType: type,
      style: TextStyle(color: secondarycolor),
    ),
  );
}`
</code>```

This creates the text field with the controller

```<code>`Expanded(child: textField('Type a message', TextInputType.multiline)),
          IconButton(
              icon: Icon(
                Icons.send,
                color: profilesecondarycolor,
              ),
              onPressed: () {
                messagesTo.add(myController.text);
                Future.delayed(Duration(seconds: 1), () {
                  return setState(() {
                    messages = messagesTo.map((content) {
                      Card(child: Text(content));
                    }).toList();
                  });
                });
              })`
</code>```

This is the button that is supposed to add the text to the list

```<code>`body: ListView(children: messagesTo == null ? chats : messages),`
</code>```

This is supposed to show the list

```<code>`List<Widget> messages;
List<String> messagesTo;
List<Widget> chats = [Text('Welcome')];`
</code>```

Defining the terms

It just shows welcome and when i click the button, nothing happens... please help

答:
You can copy paste run full code below

Some parts of your code need to change, you can check full code for detail

code snippet

```<code>List<Widget> messages = [];
List<String> messagesTo = [];
Widget chats = Text('Welcome');

onPressed: () {
                  messagesTo.add(myController.text);

                  Future.delayed(Duration(seconds: 1), () {
                    setState(() {
                      messages = [];
                      messagesTo.forEach((content) =>
                          messages.add(Card(child: Text(content))));
                    });
                  });
                }
...
messages.length == 0
                    ? chats
                    : Container(
                        height: 200,
                        child: ListView(shrinkWrap: true, children: messages)),
</code>```

working demo

full code

```<code>import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final myController = TextEditingController();
  List<Widget> messages = [];
  List<String> messagesTo = [];
  Widget chats = Text('Welcome');

  Widget textField(String hint, TextInputType type) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: CupertinoTextField(
        minLines: 1,
        maxLines: null,
        controller: myController,
        textCapitalization: TextCapitalization.sentences,
        placeholder: hint,
        placeholderStyle: TextStyle(color: Colors.blue),
        keyboardType: type,
        style: TextStyle(color: Colors.red),
      ),
    );
  }

  @override
  void dispose() {
    myController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: true,
      //resizeToAvoidBottomPadding: true,
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            messages.length == 0
                ? chats
                : Container(
                    height: 200,
                    child: ListView(shrinkWrap: true, children: messages)),
            Container(
                height: 50,
                child: textField('Type a message', TextInputType.multiline)),
            IconButton(
                icon: Icon(
                  Icons.send,
                  color: Colors.yellow,
                ),
                onPressed: () {
                  messagesTo.add(myController.text);

                  Future.delayed(Duration(seconds: 1), () {
                    setState(() {
                      messages = [];
                      messagesTo.forEach((content) =>
                          messages.add(Card(child: Text(content))));
                    });
                  });
                }),
          ],
        ),
      ),
    );
  }
}
</code>```

Body:
`final myController = TextEditingController();
@override
void dispose() {
  myController.dispose();
}`

This creates a controller for the text input

`Widget textField(String hint, TextInputType type) {
  return Padding(
    padding: const EdgeInsets.all(8.0),
    child: CupertinoTextField(
      minLines: 1,
      maxLines: null,
      controller: myController,
      textCapitalization: TextCapitalization.sentences,
      placeholder: hint,
      placeholderStyle: TextStyle(color: hintcolor),
      keyboardType: type,
      style: TextStyle(color: secondarycolor),
    ),
  );
}`

This creates the text field with the controller

`Expanded(child: textField('Type a message', TextInputType.multiline)),
          IconButton(
              icon: Icon(
                Icons.send,
                color: profilesecondarycolor,
              ),
              onPressed: () {
                messagesTo.add(myController.text);
                Future.delayed(Duration(seconds: 1), () {
                  return setState(() {
                    messages = messagesTo.map((content) {
                      Card(child: Text(content));
                    }).toList();
                  });
                });
              })`

This is the button that is supposed to add the text to the list

`body: ListView(children: messagesTo == null ? chats : messages),`

This is supposed to show the list

`List<Widget> messages;
List<String> messagesTo;
List<Widget> chats = [Text('Welcome')];`

Defining the terms

It just shows welcome and when i click the button, nothing happens... please help

Body:
You can copy paste run full code below

Some parts of your code need to change, you can check full code for detail

code snippet

List<Widget> messages = [];
List<String> messagesTo = [];
Widget chats = Text('Welcome');

onPressed: () {
                  messagesTo.add(myController.text);

                  Future.delayed(Duration(seconds: 1), () {
                    setState(() {
                      messages = [];
                      messagesTo.forEach((content) =>
                          messages.add(Card(child: Text(content))));
                    });
                  });
                }
...
messages.length == 0
                    ? chats
                    : Container(
                        height: 200,
                        child: ListView(shrinkWrap: true, children: messages)),

working demo

full code

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final myController = TextEditingController();
  List<Widget> messages = [];
  List<String> messagesTo = [];
  Widget chats = Text('Welcome');

  Widget textField(String hint, TextInputType type) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: CupertinoTextField(
        minLines: 1,
        maxLines: null,
        controller: myController,
        textCapitalization: TextCapitalization.sentences,
        placeholder: hint,
        placeholderStyle: TextStyle(color: Colors.blue),
        keyboardType: type,
        style: TextStyle(color: Colors.red),
      ),
    );
  }

  @override
  void dispose() {
    myController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: true,
      //resizeToAvoidBottomPadding: true,
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            messages.length == 0
                ? chats
                : Container(
                    height: 200,
                    child: ListView(shrinkWrap: true, children: messages)),
            Container(
                height: 50,
                child: textField('Type a message', TextInputType.multiline)),
            IconButton(
                icon: Icon(
                  Icons.send,
                  color: Colors.yellow,
                ),
                onPressed: () {
                  messagesTo.add(myController.text);

                  Future.delayed(Duration(seconds: 1), () {
                    setState(() {
                      messages = [];
                      messagesTo.forEach((content) =>
                          messages.add(Card(child: Text(content))));
                    });
                  });
                }),
          ],
        ),
      ),
    );
  }
}


问:
Reorder panels in ridgeline plot
I have a dataframe like this:

```<code>set.seed(3467)

 df<- data.frame(method= c(rep("A", 1000), rep("B", 1000), rep("C", 1000)),
        beta=c(rnorm(1000, mean=0, sd=1),rnorm(1000, mean=2, sd=1.4),rnorm(1000, mean=0, sd=0.5)))
</code>```

I wish to create a ridgeline plot similar to this:

```<code>library(ggplot2)
library(ggridges)

ggplot() +
geom_rect(data = data.frame(x = 1),
        xmin = -0.391, xmax = 0.549, ymin = -Inf, ymax = Inf,
        alpha = 0.5, fill = "gray") +
 geom_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  size=0.75)+
 xlim(-5,5)+
 scale_fill_manual(values = c("#483d8b50", "#0072B250","#228b2250")) +
 scale_color_manual(values = c("#483d8b", "#0072B2", "#228b22"), guide = "none") +
 stat_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  quantile_lines = TRUE, quantiles = c(0.025, 0.5, 0.975), alpha = 0.6, size=0.75)+
scale_y_discrete(expand = expand_scale(add = c(0.1, 0.9)))
</code>```

However, I wish to order the y-axis in the order of method= "B", "C", "A" not method= "A", "B", "C"

I have tried the following method, without success, to reorder the density plots:

```<code>library(dplyr)
df %>%
 mutate(method = fct_relevel(method,
                        "B", "C", "A"))%>%
ggplot() +
geom_rect(data = data.frame(x = 1),
        xmin = -0.391, xmax = 0.549, ymin = -Inf, ymax = Inf,
        alpha = 0.5, fill = "gray") +
 geom_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  size=0.75)+
 xlim(-5,5)+
 scale_fill_manual(values = c("#483d8b50", "#0072B250","#228b2250")) +
 scale_color_manual(values = c("#483d8b", "#0072B2", "#228b22"), guide = "none") +
 stat_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  quantile_lines = TRUE, quantiles = c(0.025, 0.5, 0.975), alpha = 0.6, size=0.75)+
scale_y_discrete(expand = expand_scale(add = c(0.1, 0.9)))
</code>```

答:
You were nearly there. - You need to specify the levels argument within fct_relevel. (See ?fct_relevel: there is no levels argument, but ..., you have to specify its name!)

library(tidyverse)
library(ggridges)
set.seed(3467)

df<- data.frame(method= c(rep("A", 1000), rep("B", 1000), rep("C", 1000)),
                beta=c(rnorm(1000, mean=0, sd=1),rnorm(1000, mean=2, sd=1.4),rnorm(1000, mean=0, sd=0.5)))

# here is the main change:
df <- df %>%
  mutate(method = fct_relevel(method, levels = "B", "C", "A"))

  ggplot(df) +
  geom_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method))
#> Picking joint bandwidth of 0.225
```

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

Title: Reorder panels in ridgeline plot

Body:
I have a dataframe like this:

set.seed(3467)

 df<- data.frame(method= c(rep("A", 1000), rep("B", 1000), rep("C", 1000)),
        beta=c(rnorm(1000, mean=0, sd=1),rnorm(1000, mean=2, sd=1.4),rnorm(1000, mean=0, sd=0.5)))

I wish to create a ridgeline plot similar to this:

library(ggplot2)
library(ggridges)

ggplot() +
geom_rect(data = data.frame(x = 1),
        xmin = -0.391, xmax = 0.549, ymin = -Inf, ymax = Inf,
        alpha = 0.5, fill = "gray") +
 geom_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  size=0.75)+
 xlim(-5,5)+
 scale_fill_manual(values = c("#483d8b50", "#0072B250","#228b2250")) +
 scale_color_manual(values = c("#483d8b", "#0072B2", "#228b22"), guide = "none") +
 stat_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  quantile_lines = TRUE, quantiles = c(0.025, 0.5, 0.975), alpha = 0.6, size=0.75)+
scale_y_discrete(expand = expand_scale(add = c(0.1, 0.9)))

However, I wish to order the y-axis in the order of method= "B", "C", "A" not method= "A", "B", "C"

I have tried the following method, without success, to reorder the density plots:

library(dplyr)
df %>%
 mutate(method = fct_relevel(method,
                        "B", "C", "A"))%>%
ggplot() +
geom_rect(data = data.frame(x = 1),
        xmin = -0.391, xmax = 0.549, ymin = -Inf, ymax = Inf,
        alpha = 0.5, fill = "gray") +
 geom_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  size=0.75)+
 xlim(-5,5)+
 scale_fill_manual(values = c("#483d8b50", "#0072B250","#228b2250")) +
 scale_color_manual(values = c("#483d8b", "#0072B2", "#228b22"), guide = "none") +
 stat_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method),
                  quantile_lines = TRUE, quantiles = c(0.025, 0.5, 0.975), alpha = 0.6, size=0.75)+
scale_y_discrete(expand = expand_scale(add = c(0.1, 0.9)))

Body:
You were nearly there. - You need to specify the levels argument within fct_relevel. (See ?fct_relevel: there is no levels argument, but ..., you have to specify its name!)

library(tidyverse)
library(ggridges)
set.seed(3467)

df<- data.frame(method= c(rep("A", 1000), rep("B", 1000), rep("C", 1000)),
                beta=c(rnorm(1000, mean=0, sd=1),rnorm(1000, mean=2, sd=1.4),rnorm(1000, mean=0, sd=0.5)))

# here is the main change:
df <- df %>%
  mutate(method = fct_relevel(method, levels = "B", "C", "A"))

  ggplot(df) +
  geom_density_ridges(data = df, aes(x = beta, y = method, color = method, fill = method))
#> Picking joint bandwidth of 0.225

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


问:
Why does the addition of precise numbers give an imprecise result in R?
I would like to add precise numbers together, and get a precise result. I know that I need to set my desired digit length in the options. For example:

```<code>> options(digits=20)
> x <- 42.616999999999997 + 42.405999999999999 + 42.869
</code>```

I expect to get an answer with the level of precision set. In the above case:

```<code>> x
[1] 127.89199999999999591
</code>```

This result is duly produced on my personal computer, but I cannot replicate it on my work computer, which - with the exact same code and the exact same environment (no difference in packages) - produces the following result:

```<code>> x
[1] 127.892
</code>```

I am unclear about what else could differ between my personal and work computer. It might be useful to know that my personal computer is running R version 3.6.2, while my work computer is running 3.4.2 (I cannot update it because of installation restrictions).

Thank you in advance for your help!

答:
In help("options") we read:

digits: controls the number of significant (see signif) digits to
  print when printing numeric values. It is a suggestion only. Valid
  values are 1...22 with default 7. See the note in print.default about
  values greater than 15.

Your value is greater than 15, so let's check the note in help("print.default"):

Large number of digits

Note that for large values of digits, currently
  for digits >= 16, the calculation of the number of significant digits
  will depend on the platform's internal (C library) implementation of
  sprintf() functionality.

This explains why you observe different results on different computers. Indeed, on my system:

```<code>options(digits=20)
42.616999999999997 + 42.405999999999999 + 42.869
#[1] 127.892
</code>```

However, you can enforce a specific number of digits after the decimal point by using the R function sprintf:

```<code>sprintf("%.17f", 42.616999999999997 + 42.405999999999999 + 42.869)
#[1] "127.89199999999999591"
</code>```

Note that all of this is only about how numbers are printed. Internally, R uses always double precision (please read this post to understand the consequences).

If you need more precise results you'd need to use arbitrary precision numbers, e.g., by using the R package Rmpfr.

Body:
I would like to add precise numbers together, and get a precise result. I know that I need to set my desired digit length in the options. For example:

> options(digits=20)
> x <- 42.616999999999997 + 42.405999999999999 + 42.869

I expect to get an answer with the level of precision set. In the above case:

> x
[1] 127.89199999999999591

This result is duly produced on my personal computer, but I cannot replicate it on my work computer, which - with the exact same code and the exact same environment (no difference in packages) - produces the following result:

> x
[1] 127.892

I am unclear about what else could differ between my personal and work computer. It might be useful to know that my personal computer is running R version 3.6.2, while my work computer is running 3.4.2 (I cannot update it because of installation restrictions).

Thank you in advance for your help!

Body:
In help("options") we read:

digits: controls the number of significant (see signif) digits to
  print when printing numeric values. It is a suggestion only. Valid
  values are 1...22 with default 7. See the note in print.default about
  values greater than 15.

Your value is greater than 15, so let's check the note in help("print.default"):

Large number of digits

Note that for large values of digits, currently
  for digits >= 16, the calculation of the number of significant digits
  will depend on the platform's internal (C library) implementation of
  sprintf() functionality.

This explains why you observe different results on different computers. Indeed, on my system:

options(digits=20)
42.616999999999997 + 42.405999999999999 + 42.869
#[1] 127.892

However, you can enforce a specific number of digits after the decimal point by using the R function sprintf:

sprintf("%.17f", 42.616999999999997 + 42.405999999999999 + 42.869)
#[1] "127.89199999999999591"

Note that all of this is only about how numbers are printed. Internally, R uses always double precision (please read this post to understand the consequences).

If you need more precise results you'd need to use arbitrary precision numbers, e.g., by using the R package Rmpfr.


问:
How to get the print parameters using redmon and ghostscript?
I am using redmon and ghostscript to create a pdf printer. The first step is to convert the document to pdf format(ghostscript can help do this). Then I need to get the print parameters(collate, color, copies .etc) when user prints. Finally I will send the pdf file and the print parameters to my server. I have redirect the port to my application.exe. Is there anyway to get the print parameters in my application?</p>

答:
The values for NumCopies, Duplex, collate etc will be in the PostScript file created by Windows, in the device-specific portion of the PostScript program, and stored in the page device dictionary.

The PDF format (as implied by Steve Friedl above), does not have an equivalent means of storing parameters in the PDF file. When printing PDF such parameters are normally stored as a Job Definition FIle (JDF) or similar.

Since you can't store the values in the PDF file, Ghostscript discards them when creating a PDF.

The only way you can retrieve these values is to read the incoming PostScript program, locate the device-specific portion and parse the values out yourself. Obviously you would invoke your application to do this before then passing the PostScript file to Ghostscript for creation of a PDF file. So you would have to run your application from RedMon, and then have your application run Ghostscript.


问:
Express.js why does placement of app.use() affect test results?
I am practicing my knowledge in Express.js .

I have one recipe router with the code below:

```<code>const express = require("express");
const router = express.Router();

const Recipe = require("../models/recipe.model");

const createRecipeItem = async recipeData => {
  await Recipe.init();
  const doc = Recipe(recipeData);
  await doc.save();
};

router.post("/", async (req, res, next) => {
  try {
    await createRecipeItem(req.body);
  } catch (err) {
    next(err);
  }
  res.status(201).send(req.body);
});

module.exports = router;
</code>```

I have another supply router, the code is below:

```<code>const express = require("express");
const router = express.Router();

const Supply = require("../models/supply.model");

const createSupplyItem = async supplyData => {
  await Supply.init();
  const doc = Supply(supplyData);
  await doc.save();
};

const updateItem = async (name, itemData) => {
  const result = await Supply.findOneAndUpdate({ name }, itemData, {
    new: true
  });
  return result;
};

router.post("/", async (req, res, next) => {
  try {
    await createSupplyItem(req.body);
  } catch (err) {
    next(err);
  }
  const respObj = {};
  respObj.name = req.body.name;
  respObj.qty = req.body.qty;
  res.status(201).send(respObj);
});

router.patch("/:name", async (req, res, next) => {
  const updatedItem = await updateItem(req.params.name, req.body);
  const response = {};
  response.name = updatedItem.name;
  response.qty = updatedItem.qty;
  res.status(200).send(response);
});

module.exports = router;
</code>```

I wrote tests for the two routers using supertest

Inside my app.js my code is written like this:

```<code>const supplyRouter = require("./routes/supply.route");
const recipeRouter = require("./routes/recipe.route");

app.use("/recipes", recipeRouter);
app.use("/supplies", supplyRouter);

</code>```

when the code is written like this:

```<code>app.use("/recipes", recipeRouter);
app.use("/supplies", supplyRouter);
</code>```

All my test passed. However, when I change the order of when I call app.use() the test would fail.

```<code>app.use("/supplies", supplyRouter);
app.use("/recipes", recipeRouter);
</code>```

The test would fail with the error Cannot set headers after they are sent to the client for the POST /supplies method. I have no clear understanding why this happens. Appreciate any insight. Thank you!

答:
I cannot pass my test correctly because I didn't have proper understanding of the flow of the code.

```<code>router.post("/", async (req, res, next) => {
  try {
    await createSupplyItem(req.body);
  } catch (err) {
    next(err);
  }
  const respObj = {};
  respObj.name = req.body.name;
  respObj.qty = req.body.qty;
  res.status(201).send(respObj);
});

</code>```

For the above code, when there is an error, express will run two paths of the code namely the path inside the catch block  and the last line of the code
res.status(201).send(respObj);

Because it is trying to run two paths, I received the error Cannot set headers after they are sent to the client.

The correct code is written below.

```<code>router.post("/", async (req, res, next) => {
  try {
    await createSupplyItem(req.body);
    const respObj = {};
    respObj.name = req.body.name;
    respObj.qty = req.body.qty;
    res.status(201).send(respObj);
  } catch (err) {
    if (err.name === "ValidationError") {
      err.statusCode = 400;
    } else if (err.name === "MongoError") {
      err.statusCode = 400;
    }
    next(err);
  }
});
</code>```

Body:
I am practicing my knowledge in Express.js .

I have one recipe router with the code below:

const express = require("express");
const router = express.Router();

const Recipe = require("../models/recipe.model");

const createRecipeItem = async recipeData => {
  await Recipe.init();
  const doc = Recipe(recipeData);
  await doc.save();
};

router.post("/", async (req, res, next) => {
  try {
    await createRecipeItem(req.body);
  } catch (err) {
    next(err);
  }
  res.status(201).send(req.body);
});

module.exports = router;

I have another supply router, the code is below:

const express = require("express");
const router = express.Router();

const Supply = require("../models/supply.model");

const createSupplyItem = async supplyData => {
  await Supply.init();
  const doc = Supply(supplyData);
  await doc.save();
};

const updateItem = async (name, itemData) => {
  const result = await Supply.findOneAndUpdate({ name }, itemData, {
    new: true
  });
  return result;
};

router.post("/", async (req, res, next) => {
  try {
    await createSupplyItem(req.body);
  } catch (err) {
    next(err);
  }
  const respObj = {};
  respObj.name = req.body.name;
  respObj.qty = req.body.qty;
  res.status(201).send(respObj);
});

router.patch("/:name", async (req, res, next) => {
  const updatedItem = await updateItem(req.params.name, req.body);
  const response = {};
  response.name = updatedItem.name;
  response.qty = updatedItem.qty;
  res.status(200).send(response);
});

module.exports = router;

I wrote tests for the two routers using supertest

Inside my app.js my code is written like this:

const supplyRouter = require("./routes/supply.route");
const recipeRouter = require("./routes/recipe.route");

app.use("/recipes", recipeRouter);
app.use("/supplies", supplyRouter);

when the code is written like this:

app.use("/recipes", recipeRouter);
app.use("/supplies", supplyRouter);

All my test passed. However, when I change the order of when I call app.use() the test would fail.

app.use("/supplies", supplyRouter);
app.use("/recipes", recipeRouter);

The test would fail with the error Cannot set headers after they are sent to the client for the POST /supplies method. I have no clear understanding why this happens. Appreciate any insight. Thank you!

Body:
I cannot pass my test correctly because I didn't have proper understanding of the flow of the code.

router.post("/", async (req, res, next) => {
  try {
    await createSupplyItem(req.body);
  } catch (err) {
    next(err);
  }
  const respObj = {};
  respObj.name = req.body.name;
  respObj.qty = req.body.qty;
  res.status(201).send(respObj);
});

For the above code, when there is an error, express will run two paths of the code namely the path inside the catch block  and the last line of the code
res.status(201).send(respObj);

Because it is trying to run two paths, I received the error Cannot set headers after they are sent to the client.

The correct code is written below.

router.post("/", async (req, res, next) => {
  try {
    await createSupplyItem(req.body);
    const respObj = {};
    respObj.name = req.body.name;
    respObj.qty = req.body.qty;
    res.status(201).send(respObj);
  } catch (err) {
    if (err.name === "ValidationError") {
      err.statusCode = 400;
    } else if (err.name === "MongoError") {
      err.statusCode = 400;
    }
    next(err);
  }
});


问:
What is the idiomatic way to do styling in Material-UI?
There are a few ways to do styling in Material-UI.

Use makeStyles:

```<code>import Box from '@material-ui/core/Box'
const useStyles = makeStyles(theme => ({
  testStyled: (props: isBoolean) => ({
    width: props ? '1px' : '2px',
  })
}))

<Box className={useStyles(true).root}></Box>
</code>```

Use MuiBoxProps:

```<code>import Box, { MuiBoxProps } from '@material-ui/core/Box'
let isTrue = true
let props: MuiBoxProps  = {
    style: {
        marginBottom: isTrue ? '1px' : '2px'
    }
}
<Box {...props}></Box>
</code>```

In the second way, I can put a special input for each individual component. For example:

```<code>let props: MuiBoxProps = {
   mb: '1px'
}
</code>```

Type inference can be used to see compilation errors.

However, this method is not applicable to makeStyles because its return type is always CSSProperties.

In the first case, however, I can style them internally by adding props.

So, in conclusion:

Type inference is impossible for a specific component. Can apply props in batch.

Type inference is possible for a specific component. Can't apply props in batch.

What is the official recommendation?

答:
Actually, doesn't matter which way you are choosing because both the have in official documents. the matter is that in which method or way you are comfortable with.

But Yes, I think the best way is withSyles which is also I use in my professional development code.

Here is the Example:

```<code>import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';

const styles = {
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
};

function HigherOrderComponent(props) {
  const { classes } = props;
  return <Button className={classes.root}>Higher-order component</Button>;
}

HigherOrderComponent.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(HigherOrderComponent);
</code>```

Body:
There are a few ways to do styling in Material-UI.

Use makeStyles:

import Box from '@material-ui/core/Box'
const useStyles = makeStyles(theme => ({
  testStyled: (props: isBoolean) => ({
    width: props ? '1px' : '2px',
  })
}))

<Box className={useStyles(true).root}></Box>

Use MuiBoxProps:

import Box, { MuiBoxProps } from '@material-ui/core/Box'
let isTrue = true
let props: MuiBoxProps  = {
    style: {
        marginBottom: isTrue ? '1px' : '2px'
    }
}
<Box {...props}></Box>

In the second way, I can put a special input for each individual component. For example:

let props: MuiBoxProps = {
   mb: '1px'
}

Type inference can be used to see compilation errors.

However, this method is not applicable to makeStyles because its return type is always CSSProperties.

In the first case, however, I can style them internally by adding props.

So, in conclusion:

Type inference is impossible for a specific component. Can apply props in batch.

Type inference is possible for a specific component. Can't apply props in batch.

What is the official recommendation?

Body:
Actually, doesn't matter which way you are choosing because both the have in official documents. the matter is that in which method or way you are comfortable with.

But Yes, I think the best way is withSyles which is also I use in my professional development code.

Here is the Example:

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';

const styles = {
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
};

function HigherOrderComponent(props) {
  const { classes } = props;
  return <Button className={classes.root}>Higher-order component</Button>;
}

HigherOrderComponent.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(HigherOrderComponent);


问:
Android buttons equal width
I need to have 2 buttons which wrap content but always stay same equal in width.

I want BUTTON 1 stretch to the width of BUTTON 2. Or if BUTTON 1 Would be wider I would need BUTTON 2 to stretch to the width of BUTTON 1

How can I achieve this? I tried using LinearLayout with weights, but it only works if linear layout width matched parent, which makes buttons unnecessary wide.

答:
I'm answering an old question, but there exist a one line solution.

Add android:layout_width="0dip" to both (i.e. all) buttons definitions in .xml file.

Another (alternative) solution is to add android:layout_width="fill_parent" to both (all) buttons definitions.

ContentLicense: CC BY-SA 3.0

Title: Android buttons equal width


问:
Using context in a fragment
How can I get the context in a fragment?

I need to use my database whose constructor takes in the context, but getApplicationContext() and FragmentClass.this don't work so what can I do?

Database constructor

```<code>public Database(Context ctx)
{
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);
}
</code>```

答:
Inside fragment for kotlin sample would help someone

```<code>textViewStatus.setTextColor(ContextCompat.getColor(context!!, R.color.red))
</code>```

if you use databinding;

```<code>bindingView.textViewStatus.setTextColor(ContextCompat.getColor(context!!, R.color.red))
</code>```

Where bindingView is initialized in onCreateView like this

```<code>private lateinit var bindingView: FragmentBookingHistoryDetailBinding

bindingView = DataBindingUtil.inflate(inflater, R.layout.your_layout_xml, container, false)
</code>```

Title: Using context in a fragment

Body:
How can I get the context in a fragment?

I need to use my database whose constructor takes in the context, but getApplicationContext() and FragmentClass.this don't work so what can I do?

Database constructor

public Database(Context ctx)
{
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);
}

Body:
Inside fragment for kotlin sample would help someone

textViewStatus.setTextColor(ContextCompat.getColor(context!!, R.color.red))

if you use databinding;

bindingView.textViewStatus.setTextColor(ContextCompat.getColor(context!!, R.color.red))

Where bindingView is initialized in onCreateView like this

private lateinit var bindingView: FragmentBookingHistoryDetailBinding

bindingView = DataBindingUtil.inflate(inflater, R.layout.your_layout_xml, container, false)


问:
gnome shell extension stylesheet not loading
i'm trying to develop a gnome shell extension and I've created the "Hello World" extension which is created automatically with gnome-shell-extension-tool --create-extension
It creates 3 files: example.js, metadata.json, stylesheet.css.

I reload gnome-shell and the extension works correcty. The problem is, the styling file is not working at all; here is the code:

```<code>// Sample extension code, makes clicking on the panel show a message
const St = imports.gi.St;
const Mainloop = imports.mainloop;

const Main = imports.ui.main;

function _showHello() {
    let text = new St.Label({  style_class: 'hello', text: "Hello, world!" });
    let monitor = global.get_primary_monitor();
    global.stage.add_actor(text);
    text.set_position(Math.floor (monitor.width / 2 - text.width / 2), Math.floor(monitor.height / 2 - text.height / 2));
    text.add_style_class_name("hello");
    Mainloop.timeout_add(6000, function () { text.destroy(); });
}

// Put your extension initialization code here
function main() {
    Main.panel.actor.reactive = true;
    Main.panel.actor.connect('button-release-event', _showHello);
}
</code>```

And here stylesheet.css:

```<code>/* Example stylesheet */
.hello {
    font-size: 360px;
    font-weight: bold;
    color: #ffffff;
    background-color: rgba(10,10,10,0.7);
    border-radius: 5px;
}
</code>```

I didn't know how to even get more information about this....any idea?

答:
Try the following stylesheet:</p>

```<code>.hello {
   font-size: 36px;
   font-weight: bold;
   color: #ffffff;
   background-color: rgba(10,10,10,0.7);
   border-radius: 15px;
   margin: 50px;
   padding: 50px;
}
</code>```

Body:
i'm trying to develop a gnome shell extension and I've created the "Hello World" extension which is created automatically with gnome-shell-extension-tool --create-extension
It creates 3 files: example.js, metadata.json, stylesheet.css.

I reload gnome-shell and the extension works correcty. The problem is, the styling file is not working at all; here is the code:

// Sample extension code, makes clicking on the panel show a message
const St = imports.gi.St;
const Mainloop = imports.mainloop;

const Main = imports.ui.main;

function _showHello() {
    let text = new St.Label({  style_class: 'hello', text: "Hello, world!" });
    let monitor = global.get_primary_monitor();
    global.stage.add_actor(text);
    text.set_position(Math.floor (monitor.width / 2 - text.width / 2), Math.floor(monitor.height / 2 - text.height / 2));
    text.add_style_class_name("hello");
    Mainloop.timeout_add(6000, function () { text.destroy(); });
}

// Put your extension initialization code here
function main() {
    Main.panel.actor.reactive = true;
    Main.panel.actor.connect('button-release-event', _showHello);
}

And here stylesheet.css:

/* Example stylesheet */
.hello {
    font-size: 360px;
    font-weight: bold;
    color: #ffffff;
    background-color: rgba(10,10,10,0.7);
    border-radius: 5px;
}

I didn't know how to even get more information about this....any idea?

Body:
Try the following stylesheet:

.hello {
   font-size: 36px;
   font-weight: bold;
   color: #ffffff;
   background-color: rgba(10,10,10,0.7);
   border-radius: 15px;
   margin: 50px;
   padding: 50px;
}


问:
Chunk does not contains lazy-loaded components
I just finished splitting my Angular 9 app into 2 modules to optimize the loading time. Unfortunately the chunk produced by the compilation is very small and seems to contains only the code of my feature module and router. All the components included in this module are still in the main js file.

This is what i have done :

AppModule

```<code>@NgModule({
  declarations: [
    //List of components (21)
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule, // required animations module
    HttpClientModule,
    AppRoutingModule,
    SharedModule,
    ConfigModule // My feature Module
  ],
  providers: [
    AuthGuard,
    DpGuard,
    AITIGuard,
    ApiService,
    StatusSocketService,
    VideoSocketService,
    Title
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

SharedModule :

```<code>@NgModule({
  declarations: [
      // List of shared components (7)
  ],
  imports: [
    CommonModule,
    FormsModule,
    NgbModule,
    TreeModule,
    TranslateModule.forChild()
  ],
  exports: [
    PasswordStrengthBarComponent,
    CameraslistComponent,
    VideoComponent,
    MaskdrawerComponent,
    FilterselectorComponent,
    TranslateModule,
    NgbModule,
    FormsModule,
    TreeModule,
    ZonedrawerComponent
  ]
})
export class SharedModule { }
</code>```

Feature (ConfigModule) Module

```<code>@NgModule({
  declarations: [
    //LIST OF FEATURE COMPONENTS (47)
  ],
  imports: [
    SharedModule,
    CommonModule,
    ConfigRoutingModule,
    HttpClientModule
  ]
})
export class ConfigModule { }
</code>```

The feature module is lazy loaded in the routes of App with :

```<code>{
    path: 'config',
    canActivate: [AuthGuard],
    loadChildren:() => import('./config/config.module').then(m => m.ConfigModule)
}
</code>```

And finally the feature module define his own routes like this :

```<code>const routes: Routes = [{
    path: '',
    canActivate: [AuthGuard],
    children : [
      { path: '', component:MenuconfigComponent },
      { path: 'system',component: ConfigSystemComponent},
      ... ,
    ]
  }];
</code>```

What am i missing ?

I was expecting that the chunk contains every thing included in the feature module and not only a small part of code.

The results of compilation is :

5-es2015.js : 4KB

main-es2015.js : 3.1MB

polyfills-es2015 : 62KB

runtime-es2015 : 3KB

I'll understand that main should be bigger because of all dependencies but it should not contains the components of the feature module.

Thanks for your help

答:
@MikeOne was right in his comment , i shouldn't have included my feature module in my main module : </p>

```<code>@NgModule({
  declarations: [
    //List of components (21)
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule, // required animations module
    HttpClientModule,
    AppRoutingModule,
    SharedModule,
    ConfigModule // <== Remove this
  ],
  providers: [
    AuthGuard,
    DpGuard,
    AITIGuard,
    ApiService,
    StatusSocketService,
    VideoSocketService,
    Title
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Body:
I just finished splitting my Angular 9 app into 2 modules to optimize the loading time. Unfortunately the chunk produced by the compilation is very small and seems to contains only the code of my feature module and router. All the components included in this module are still in the main js file.

This is what i have done :

AppModule

@NgModule({
  declarations: [
    //List of components (21)
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule, // required animations module
    HttpClientModule,
    AppRoutingModule,
    SharedModule,
    ConfigModule // My feature Module
  ],
  providers: [
    AuthGuard,
    DpGuard,
    AITIGuard,
    ApiService,
    StatusSocketService,
    VideoSocketService,
    Title
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

SharedModule :

@NgModule({
  declarations: [
      // List of shared components (7)
  ],
  imports: [
    CommonModule,
    FormsModule,
    NgbModule,
    TreeModule,
    TranslateModule.forChild()
  ],
  exports: [
    PasswordStrengthBarComponent,
    CameraslistComponent,
    VideoComponent,
    MaskdrawerComponent,
    FilterselectorComponent,
    TranslateModule,
    NgbModule,
    FormsModule,
    TreeModule,
    ZonedrawerComponent
  ]
})
export class SharedModule { }

Feature (ConfigModule) Module

@NgModule({
  declarations: [
    //LIST OF FEATURE COMPONENTS (47)
  ],
  imports: [
    SharedModule,
    CommonModule,
    ConfigRoutingModule,
    HttpClientModule
  ]
})
export class ConfigModule { }

The feature module is lazy loaded in the routes of App with :

{
    path: 'config',
    canActivate: [AuthGuard],
    loadChildren:() => import('./config/config.module').then(m => m.ConfigModule)
}

And finally the feature module define his own routes like this :

const routes: Routes = [{
    path: '',
    canActivate: [AuthGuard],
    children : [
      { path: '', component:MenuconfigComponent },
      { path: 'system',component: ConfigSystemComponent},
      ... ,
    ]
  }];

What am i missing ?

I was expecting that the chunk contains every thing included in the feature module and not only a small part of code.

The results of compilation is :

5-es2015.js : 4KB

main-es2015.js : 3.1MB

polyfills-es2015 : 62KB

runtime-es2015 : 3KB

I'll understand that main should be bigger because of all dependencies but it should not contains the components of the feature module.

Thanks for your help

Body:
@MikeOne was right in his comment , i shouldn't have included my feature module in my main module :

@NgModule({
  declarations: [
    //List of components (21)
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule, // required animations module
    HttpClientModule,
    AppRoutingModule,
    SharedModule,
    ConfigModule // <== Remove this
  ],
  providers: [
    AuthGuard,
    DpGuard,
    AITIGuard,
    ApiService,
    StatusSocketService,
    VideoSocketService,
    Title
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }