问:
Angular 4 Bind Multiple Component Inside ngFor
I'm using DevExtreme Range Slider and I want to iterate through my columns array to create range sliders dynamically.

I'm following the example here : DevExtreme Range Slider Angular Demo

I don't know how to bind each range slider to its start & end value text boxes.

component.html

```<code><ng-template ngFor let-column [ngForOf]="columns" let-i = index;>

<div class="dx-fieldset" *ngIf="column.is_integer" >
    <div class="dx-field">
        <div class="dx-field-label">{{column.name}}</div>
        <div class="dx-field-value">
            <dx-range-slider
                #rangeSlider
                [min]="column.min"
                [max]="column.max"
                [start]="column.min"
                [end]="column.max"
                [rtlEnabled]="false"
                [tooltip]="tooltip"
                (onValueChanged)="quick_filter($event, column.name)"
            ></dx-range-slider>
            <dx-number-box
                [min]="column.min"
                [max]="column.max"
                [(value)]="rangeSlider.min"
                [showSpinButtons]="true"
                name="{{column.name}}_start"
            ></dx-number-box>
            <dx-number-box
                [min]="column.min"
                [max]="column.max"
                [(value)]="rangeSlider.max"
                [showSpinButtons]="true"
                name="{{column.name}}_end"
            ></dx-number-box>
        </div>
    </div>
</div>

</ng-template>
</code>```

How to change the #rangeSlider to each column.name inside the ngFor and bind it to the start & end value text boxes?

答:
min and max - options of dxRangeSlider, specifiing a border values.

start and end - options of dxRangeSlider, specifiing a left and right value of the selected interval (handle positions).

Bindings will be the same, like in the example:

```<code><div class="dx-fieldset" *ngFor="let column of columns" >
    <div class="dx-field">
          <div class="dx-field-label">{{column.name}}</div>
          <div class="dx-field-value">
              <dx-range-slider
                  #rangeSlider
                  [min]="0"
                  [max]="100"
                  [start]="column.start"
                  [end]="column.end"
              ></dx-range-slider>
              <dx-number-box
                  [min]="0"
                  [max]="100"
                  [(value)]="rangeSlider.start"
                  [showSpinButtons]="true"
              ></dx-number-box>
              <dx-number-box
                  [min]="0"
                  [max]="100"
                  [(value)]="rangeSlider.end"
                  [showSpinButtons]="true"
              ></dx-number-box>
          </div>
      </div>
</div>
</code>```

Also, I prepared a working sample on Plunker with the ngFor directive.

Body:
I'm using DevExtreme Range Slider and I want to iterate through my columns array to create range sliders dynamically.

I'm following the example here : DevExtreme Range Slider Angular Demo

I don't know how to bind each range slider to its start & end value text boxes.

component.html

<ng-template ngFor let-column [ngForOf]="columns" let-i = index;>

{{column.name}}

            <dx-range-slider
                #rangeSlider
                [min]="column.min"
                [max]="column.max"
                [start]="column.min"
                [end]="column.max"
                [rtlEnabled]="false"
                [tooltip]="tooltip"
                (onValueChanged)="quick_filter($event, column.name)"
            ></dx-range-slider>
            <dx-number-box
                [min]="column.min"
                [max]="column.max"
                [(value)]="rangeSlider.min"
                [showSpinButtons]="true"
                name="{{column.name}}_start"
            ></dx-number-box>
            <dx-number-box
                [min]="column.min"
                [max]="column.max"
                [(value)]="rangeSlider.max"
                [showSpinButtons]="true"
                name="{{column.name}}_end"
            ></dx-number-box>

</ng-template>

How to change the #rangeSlider to each column.name inside the ngFor and bind it to the start & end value text boxes?

Body:
min and max - options of dxRangeSlider, specifiing a border values.

start and end - options of dxRangeSlider, specifiing a left and right value of the selected interval (handle positions).

Bindings will be the same, like in the example:

<div class="dx-fieldset" *ngFor="let column of columns" >
    <div class="dx-field">
          <div class="dx-field-label">{{column.name}}</div>
          <div class="dx-field-value">
              <dx-range-slider
                  #rangeSlider
                  [min]="0"
                  [max]="100"
                  [start]="column.start"
                  [end]="column.end"
              ></dx-range-slider>
              <dx-number-box
                  [min]="0"
                  [max]="100"
                  [(value)]="rangeSlider.start"
                  [showSpinButtons]="true"
              ></dx-number-box>
              <dx-number-box
                  [min]="0"
                  [max]="100"
                  [(value)]="rangeSlider.end"
                  [showSpinButtons]="true"
              ></dx-number-box>
          </div>
      </div>
</div>

Also, I prepared a working sample on Plunker with the ngFor directive.


来源: stackexchange

问:
How to install mingw32 on Ubuntu?
I would like to install mingw32 on my Ubuntu (16.10) cuz I would like to generate an x86 windows version of my application. The "i586-mingw32msvc-g++" executable is needed by my Makefile (CMake).

I tried "sudo apt install mingw32" but it doesn't work (I have a "package not found" error).

答:
Look more closely at what is actually available:

```<code>edd@max:~$ apt-cache search mingw-
libassuan-mingw-w64-dev - IPC library for the GnuPG components -- Windows port
libgcrypt-mingw-w64-dev - LGPL Crypto library - Windows development
libgpg-error-mingw-w64-dev - library of error values and messages in GnuPG (Windows development)
libksba-mingw-w64-dev - X.509 and CMS support library (Windows development)
libnpth-mingw-w64-dev - replacement for GNU Pth using system threads (Windows dev)
binutils-mingw-w64 - Cross-binutils for Win32 and Win64 using MinGW-w64
binutils-mingw-w64-i686 - Cross-binutils for Win32 (x86) using MinGW-w64
binutils-mingw-w64-x86-64 - Cross-binutils for Win64 (x64) using MinGW-w64
g++-mingw-w64 - GNU C++ compiler for MinGW-w64
g++-mingw-w64-i686 - GNU C++ compiler for MinGW-w64 targeting Win32
g++-mingw-w64-x86-64 - GNU C++ compiler for MinGW-w64 targeting Win64
gcc-mingw-w64 - GNU C compiler for MinGW-w64
gcc-mingw-w64-base - GNU Compiler Collection for MinGW-w64 (base package)
gcc-mingw-w64-i686 - GNU C compiler for MinGW-w64 targeting Win32
gcc-mingw-w64-x86-64 - GNU C compiler for MinGW-w64 targeting Win64
gdb-mingw-w64 - Cross-debugger for Win32 and Win64 using MinGW-w64
gdb-mingw-w64-target - Cross-debugger server for Win32 and Win64 using MinGW-w64
gfortran-mingw-w64 - GNU Fortran compiler for MinGW-w64
gfortran-mingw-w64-i686 - GNU Fortran compiler for MinGW-w64 targeting Win32
gfortran-mingw-w64-x86-64 - GNU Fortran compiler for MinGW-w64 targeting Win64
gnat-mingw-w64 - GNU Ada compiler for MinGW-w64
gnat-mingw-w64-base - GNU Ada compiler for MinGW-w64 (base package)
gnat-mingw-w64-i686 - GNU Ada compiler for MinGW-w64 targeting Win32
gnat-mingw-w64-x86-64 - GNU Ada compiler for MinGW-w64 targeting Win64
gobjc++-mingw-w64 - GNU Objective-C++ compiler for MinGW-w64
gobjc++-mingw-w64-i686 - GNU Objective-C++ compiler for MinGW-w64 targeting Win32
gobjc++-mingw-w64-x86-64 - GNU Objective-C++ compiler for MinGW-w64 targeting Win64
gobjc-mingw-w64 - GNU Objective-C compiler for MinGW-w64
gobjc-mingw-w64-i686 - GNU Objective-C compiler for MinGW-w64 targeting Win32
gobjc-mingw-w64-x86-64 - GNU Objective-C compiler for MinGW-w64 targeting Win64
libz-mingw-w64 - compression library - Windows runtime
libz-mingw-w64-dev - compression library - Windows development files
mingw-ocaml - ocaml-mingw-w64 transitional dummy package
mingw-w64 - Development environment targeting 32- and 64-bit Windows
mingw-w64-common - Common files for Mingw-w64
mingw-w64-i686-dev - Development files for MinGW-w64 targeting Win32
mingw-w64-tools - Development tools for 32- and 64-bit Windows
mingw-w64-x86-64-dev - Development files for MinGW-w64 targeting Win64
ocaml-mingw-w64 - OCaml cross-compiler based on mingw -- Meta-package
ocaml-mingw-w64-i686 - OCaml cross-compiler based on mingw -- 32 bit compiler
ocaml-mingw-w64-x86-64 - OCaml cross-compiler based on mingw -- 64 bit compiler
edd@max:~$
</code>```

So sudo apt-get install gcc-mingw-w64 is probably what you want, and
you should get a 32-bit executable built by setting the appropriate compiler option, likely -m32.

ContentLicense: CC BY-SA 3.0

Title: How to install mingw32 on Ubuntu?

Body:
Look more closely at what is actually available:

edd@max:~$ apt-cache search mingw-
libassuan-mingw-w64-dev - IPC library for the GnuPG components -- Windows port
libgcrypt-mingw-w64-dev - LGPL Crypto library - Windows development
libgpg-error-mingw-w64-dev - library of error values and messages in GnuPG (Windows development)
libksba-mingw-w64-dev - X.509 and CMS support library (Windows development)
libnpth-mingw-w64-dev - replacement for GNU Pth using system threads (Windows dev)
binutils-mingw-w64 - Cross-binutils for Win32 and Win64 using MinGW-w64
binutils-mingw-w64-i686 - Cross-binutils for Win32 (x86) using MinGW-w64
binutils-mingw-w64-x86-64 - Cross-binutils for Win64 (x64) using MinGW-w64
g++-mingw-w64 - GNU C++ compiler for MinGW-w64
g++-mingw-w64-i686 - GNU C++ compiler for MinGW-w64 targeting Win32
g++-mingw-w64-x86-64 - GNU C++ compiler for MinGW-w64 targeting Win64
gcc-mingw-w64 - GNU C compiler for MinGW-w64
gcc-mingw-w64-base - GNU Compiler Collection for MinGW-w64 (base package)
gcc-mingw-w64-i686 - GNU C compiler for MinGW-w64 targeting Win32
gcc-mingw-w64-x86-64 - GNU C compiler for MinGW-w64 targeting Win64
gdb-mingw-w64 - Cross-debugger for Win32 and Win64 using MinGW-w64
gdb-mingw-w64-target - Cross-debugger server for Win32 and Win64 using MinGW-w64
gfortran-mingw-w64 - GNU Fortran compiler for MinGW-w64
gfortran-mingw-w64-i686 - GNU Fortran compiler for MinGW-w64 targeting Win32
gfortran-mingw-w64-x86-64 - GNU Fortran compiler for MinGW-w64 targeting Win64
gnat-mingw-w64 - GNU Ada compiler for MinGW-w64
gnat-mingw-w64-base - GNU Ada compiler for MinGW-w64 (base package)
gnat-mingw-w64-i686 - GNU Ada compiler for MinGW-w64 targeting Win32
gnat-mingw-w64-x86-64 - GNU Ada compiler for MinGW-w64 targeting Win64
gobjc++-mingw-w64 - GNU Objective-C++ compiler for MinGW-w64
gobjc++-mingw-w64-i686 - GNU Objective-C++ compiler for MinGW-w64 targeting Win32
gobjc++-mingw-w64-x86-64 - GNU Objective-C++ compiler for MinGW-w64 targeting Win64
gobjc-mingw-w64 - GNU Objective-C compiler for MinGW-w64
gobjc-mingw-w64-i686 - GNU Objective-C compiler for MinGW-w64 targeting Win32
gobjc-mingw-w64-x86-64 - GNU Objective-C compiler for MinGW-w64 targeting Win64
libz-mingw-w64 - compression library - Windows runtime
libz-mingw-w64-dev - compression library - Windows development files
mingw-ocaml - ocaml-mingw-w64 transitional dummy package
mingw-w64 - Development environment targeting 32- and 64-bit Windows
mingw-w64-common - Common files for Mingw-w64
mingw-w64-i686-dev - Development files for MinGW-w64 targeting Win32
mingw-w64-tools - Development tools for 32- and 64-bit Windows
mingw-w64-x86-64-dev - Development files for MinGW-w64 targeting Win64
ocaml-mingw-w64 - OCaml cross-compiler based on mingw -- Meta-package
ocaml-mingw-w64-i686 - OCaml cross-compiler based on mingw -- 32 bit compiler
ocaml-mingw-w64-x86-64 - OCaml cross-compiler based on mingw -- 64 bit compiler
edd@max:~$

So sudo apt-get install gcc-mingw-w64 is probably what you want, and
you should get a 32-bit executable built by setting the appropriate compiler option, likely -m32.


问:
CakePHP : Read values of a radio form
I'd like to read the values of a form I'm trying to use :

```<code><!-- File: src/Template/Users/edit.ctp -->
<?php
    echo '<p>Question 1 text</p>';
    echo $this->Form->radio(
    'answer_1',
    [
    ['value' => 'true', 'text' => 'Radio 1 text'],
    ['value' => 'false', 'text' => 'Radio 2 text'],
    ['value' => 'false', 'text' => 'Radio 3 text'],
    ['value' => 'false', 'text' => 'Radio 4 text'],
    ]
    );

    echo '<p>Question 2 text</p>';
    echo $this->Form->radio(
    'answer_2',[
    ['value' => 'false', 'text' => 'Radio 1 text'],
    ['value' => 'false', 'text' => 'Radio 2 text'],
    ['value' => 'true', 'text' => 'Radio 3 text'],
    ['value' => 'false', 'text' => 'Radio 4 text'],
    ]
    );

    echo '<p>Question 3 text</p>';
    echo $this->Form->radio(
    'answer_3',[
    ['value' => 'false', 'text' => 'Radio 1 text'],
    ['value' => 'false', 'text' => 'Radio 2 text'],
    ['value' => 'false', 'text' => 'Radio 3 text'],
    ['value' => 'true', 'text' => 'Radio 4 text'],
    ]
    );

echo $this->Form->button(__("Save"));
echo $this->Form->end();
?>
</code>```

I would like in my edit function to read the values of the submitted radios, in order to calculate a score for each "true". Do you know how to do it in my controller ? Neither the questions nor the answers are stored in DB, they're hard-coded in the view.

Bonus point : I'd like to save a specific answer of the form in DB, in that possible ? For example, a bonus question :

```<code>echo '<p>Bonus question text</p>';
echo $this->Form->control('bonus_answer');
</code>```

Thanks

答:
You can find how to get request data here

3.0 - 3.3

What you're looking for is

```<code>$this->request->data('answer_1');
$this->request->data('answer_2');
$this->request->data('answer_3');
</code>```

AS OF 3.4

The use of $this->request->data() has been deprecated.

What you're looking for is

```<code>$this->request->getData('answer_1');
$this->request->getData('answer_2');
$this->request->getData('answer_3');
</code>```

The "name" of the inputs is the first param of the function, $this->Form->control('INPUTNAME');

Title: CakePHP : Read values of a radio form

Body:
I'd like to read the values of a form I'm trying to use :

<?php
    echo '
Question 1 text
';
    echo $this->Form->radio(
    'answer_1',
    [
    ['value' => 'true', 'text' => 'Radio 1 text'],
    ['value' => 'false', 'text' => 'Radio 2 text'],
    ['value' => 'false', 'text' => 'Radio 3 text'],
    ['value' => 'false', 'text' => 'Radio 4 text'],
    ]
    );

    echo '
Question 2 text
';
    echo $this->Form->radio(
    'answer_2',[
    ['value' => 'false', 'text' => 'Radio 1 text'],
    ['value' => 'false', 'text' => 'Radio 2 text'],
    ['value' => 'true', 'text' => 'Radio 3 text'],
    ['value' => 'false', 'text' => 'Radio 4 text'],
    ]
    );

    echo '
Question 3 text
';
    echo $this->Form->radio(
    'answer_3',[
    ['value' => 'false', 'text' => 'Radio 1 text'],
    ['value' => 'false', 'text' => 'Radio 2 text'],
    ['value' => 'false', 'text' => 'Radio 3 text'],
    ['value' => 'true', 'text' => 'Radio 4 text'],
    ]
    );

echo $this->Form->button(__("Save"));
echo $this->Form->end();
?>

I would like in my edit function to read the values of the submitted radios, in order to calculate a score for each "true". Do you know how to do it in my controller ? Neither the questions nor the answers are stored in DB, they're hard-coded in the view.

Bonus point : I'd like to save a specific answer of the form in DB, in that possible ? For example, a bonus question :

echo '
Bonus question text
';
echo $this->Form->control('bonus_answer');

Thanks

Body:
You can find how to get request data here

3.0 - 3.3

What you're looking for is

$this->request->data('answer_1');
$this->request->data('answer_2');
$this->request->data('answer_3');

AS OF 3.4

The use of $this->request->data() has been deprecated.

What you're looking for is

$this->request->getData('answer_1');
$this->request->getData('answer_2');
$this->request->getData('answer_3');

The "name" of the inputs is the first param of the function, $this->Form->control('INPUTNAME');


问:
Unable to merge android manifests. See the Console for more details
I got following error while making apk file from unity. I set minimum API level=19 and target 24. because I build a apk for Gear VR and I have Samsung S7 Edge.

CommandInvokationFailure: Unable to merge android manifests. See the
  Console for more details.  C:/Program
  Files/Java/jdk1.8.0_131\bin\java.exe -Xmx2048M
  -Dcom.android.sdkmanager.toolsdir="C:/Android/sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Users\saad asghar\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[ Error:Invalid command manifmerger ] stdout[

] exit code: 64 UnityEditor.Android.Command.Run
  (System.Diagnostics.ProcessStartInfo psi,
  UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit,
  System.String errorMsg)
  UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String
  javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand,
  Int32 memoryMB, System.String workingdir,
  UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit,
  System.String errorMsg)
  UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String
  javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand,
  Int32 memoryMB, System.String workingdir,
  UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit,
  System.String errorMsg) UnityEditor.HostView:OnGUI()

答:
You can try to rise up your minimum api level, usually when there is high diffrence between target devices and minimum api level Unity fail to merge android manifests.

I hope this will work your problem :)


问:
lifecycle hooks of input population from sibling component angular2
I have two siblings component like below

```<code><broker-list (onBrokerClicked)="onBrokerClicked= $event"></broker-list>
<station-list [(broker)]="onBrokerClicked" [(ngModel)]="stations"></station-list><!--broker is an input-->
</code>```

when user click on broker-list, in station-list component broker which is an @Input gets populated. ngModel in stationlist can be populated only after it's sibling component is clicked or in other words the input broker gets populated. I want the exact moment when the input gets populated form the sibling component which is not in ngOnInit. is there any event or something which is raised after input population that I can do some stuff in it???

答:
Add setter method to Input() property

station-list.component.ts

```<code>private _broker;

@Input() set broker(value) {
     this._broker = value
     // do the stuff every time when broker value is changed
}

get broker(value) {
     return this._broker;
}
</code>```

Body:
I have two siblings component like below

<broker-list (onBrokerClicked)="onBrokerClicked= $event"></broker-list>
<station-list [(broker)]="onBrokerClicked" [(ngModel)]="stations"></station-list>

when user click on broker-list, in station-list component broker which is an @Input gets populated. ngModel in stationlist can be populated only after it's sibling component is clicked or in other words the input broker gets populated. I want the exact moment when the input gets populated form the sibling component which is not in ngOnInit. is there any event or something which is raised after input population that I can do some stuff in it???

Body:
Add setter method to Input() property

station-list.component.ts

private _broker;

@Input() set broker(value) {
     this._broker = value
     // do the stuff every time when broker value is changed
}

get broker(value) {
     return this._broker;
}


问:
Kubernetes has a ton of pods in error state that can't seem to be cleared
I was originally trying to run a Job that seemed to get stuck in a CrashBackoffLoop.  Here was the service file:

```<code>apiVersion: batch/v1
kind: Job
metadata:
  name: es-setup-indexes
  namespace: elk-test
spec:
  template:
    metadata:
      name: es-setup-indexes
    spec:
      containers:
      - name: es-setup-indexes
        image: appropriate/curl
        command: ['curl -H  "Content-Type: application/json" -XPUT http://elasticsearch.elk-test.svc.cluster.local:9200/_template/filebeat -d@/etc/filebeat/filebeat.template.json']
        volumeMounts:
        - name: configmap-volume
          mountPath: /etc/filebeat/filebeat.template.json
          subPath: filebeat.template.json
      restartPolicy: Never

      volumes:
        - name: configmap-volume
          configMap:
            name: elasticsearch-configmap-indexes
</code>```

I tried deleting the job but it would only work if I ran the following command:

```<code>kubectl delete job es-setup-indexes --cascade=false
</code>```

After that I noticed when running:

```<code>kubectl get pods -w
</code>```

I would get a TON of pods in an Error state and I see no way to clean them up.  Here is just a small sample of the output when I run get pods:

```<code>es-setup-indexes-zvx9c   0/1       Error     0         20h
es-setup-indexes-zw23w   0/1       Error     0         15h
es-setup-indexes-zw57h   0/1       Error     0         21h
es-setup-indexes-zw6l9   0/1       Error     0         16h
es-setup-indexes-zw7fc   0/1       Error     0         22h
es-setup-indexes-zw9bw   0/1       Error     0         12h
es-setup-indexes-zw9ck   0/1       Error     0         1d
es-setup-indexes-zwf54   0/1       Error     0         18h
es-setup-indexes-zwlmg   0/1       Error     0         16h
es-setup-indexes-zwmsm   0/1       Error     0         21h
es-setup-indexes-zwp37   0/1       Error     0         22h
es-setup-indexes-zwzln   0/1       Error     0         22h
es-setup-indexes-zx4g3   0/1       Error     0         11h
es-setup-indexes-zx4hd   0/1       Error     0         21h
es-setup-indexes-zx512   0/1       Error     0         1d
es-setup-indexes-zx638   0/1       Error     0         17h
es-setup-indexes-zx64c   0/1       Error     0         21h
es-setup-indexes-zxczt   0/1       Error     0         15h
es-setup-indexes-zxdzf   0/1       Error     0         14h
es-setup-indexes-zxf56   0/1       Error     0         1d
es-setup-indexes-zxf9r   0/1       Error     0         16h
es-setup-indexes-zxg0m   0/1       Error     0         14h
es-setup-indexes-zxg71   0/1       Error     0         1d
es-setup-indexes-zxgwz   0/1       Error     0         19h
es-setup-indexes-zxkpm   0/1       Error     0         23h
es-setup-indexes-zxkvb   0/1       Error     0         15h
es-setup-indexes-zxpgg   0/1       Error     0         20h
es-setup-indexes-zxqh3   0/1       Error     0         1d
es-setup-indexes-zxr7f   0/1       Error     0         22h
es-setup-indexes-zxxbs   0/1       Error     0         13h
es-setup-indexes-zz7xr   0/1       Error     0         12h
es-setup-indexes-zzbjq   0/1       Error     0         13h
es-setup-indexes-zzc0z   0/1       Error     0         16h
es-setup-indexes-zzdb6   0/1       Error     0         1d
es-setup-indexes-zzjh2   0/1       Error     0         21h
es-setup-indexes-zzm77   0/1       Error     0         1d
es-setup-indexes-zzqt5   0/1       Error     0         12h
es-setup-indexes-zzr79   0/1       Error     0         16h
es-setup-indexes-zzsfx   0/1       Error     0         1d
es-setup-indexes-zzx1r   0/1       Error     0         21h
es-setup-indexes-zzx6j   0/1       Error     0         1d
kibana-kq51v   1/1       Running   0         10h
</code>```

But if I look at the jobs I get nothing related to that anymore:

```<code>$ kubectl get jobs --all-namespaces
NAMESPACE     NAME               DESIRED   SUCCESSFUL   AGE
kube-system   configure-calico   1         1            46d
</code>```

I've also noticed that kubectl seems much slow to respond.  I don't know if the pods are continuously trying to be restarted or in some broken state but would be great if someone could let me know how to troubleshoot as I have not come across another issue like this in kubernetes.

Kube info:

```<code>$ kubectl version
Client Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.1", GitCommit:"b0b7a323cc5a4a2019b2e9520c21c7830b7f708e", GitTreeState:"clean", BuildDate:"2017-04-03T20:44:38Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.1", GitCommit:"b0b7a323cc5a4a2019b2e9520c21c7830b7f708e", GitTreeState:"clean", BuildDate:"2017-04-03T20:33:27Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"}
</code>```

答:
The solution was as @johnharris85 mentioned in the comment.  I had to manually delete all the pods.  To do that I ran the following:

```<code>kubectl get pods -w | tee all-pods.txt
</code>```

That dumped all my pods, then to filter and delete on only what I wanted.

```<code>kubectl delete pod $(more all-pods.txt | grep es-setup-index | awk '{print $1}')
</code>```

Note: I had about 9292 pods, it took about 1-2 hours to delete them all.

Body:
I was originally trying to run a Job that seemed to get stuck in a CrashBackoffLoop.  Here was the service file:

apiVersion: batch/v1
kind: Job
metadata:
  name: es-setup-indexes
  namespace: elk-test
spec:
  template:
    metadata:
      name: es-setup-indexes
    spec:
      containers:
      - name: es-setup-indexes
        image: appropriate/curl
        command: ['curl -H  "Content-Type: application/json" -XPUT http://elasticsearch.elk-test.svc.cluster.local:9200/_template/filebeat -d@/etc/filebeat/filebeat.template.json']
        volumeMounts:
        - name: configmap-volume
          mountPath: /etc/filebeat/filebeat.template.json
          subPath: filebeat.template.json
      restartPolicy: Never

      volumes:
        - name: configmap-volume
          configMap:
            name: elasticsearch-configmap-indexes

I tried deleting the job but it would only work if I ran the following command:

kubectl delete job es-setup-indexes --cascade=false

After that I noticed when running:

kubectl get pods -w

I would get a TON of pods in an Error state and I see no way to clean them up.  Here is just a small sample of the output when I run get pods:

es-setup-indexes-zvx9c   0/1       Error     0         20h
es-setup-indexes-zw23w   0/1       Error     0         15h
es-setup-indexes-zw57h   0/1       Error     0         21h
es-setup-indexes-zw6l9   0/1       Error     0         16h
es-setup-indexes-zw7fc   0/1       Error     0         22h
es-setup-indexes-zw9bw   0/1       Error     0         12h
es-setup-indexes-zw9ck   0/1       Error     0         1d
es-setup-indexes-zwf54   0/1       Error     0         18h
es-setup-indexes-zwlmg   0/1       Error     0         16h
es-setup-indexes-zwmsm   0/1       Error     0         21h
es-setup-indexes-zwp37   0/1       Error     0         22h
es-setup-indexes-zwzln   0/1       Error     0         22h
es-setup-indexes-zx4g3   0/1       Error     0         11h
es-setup-indexes-zx4hd   0/1       Error     0         21h
es-setup-indexes-zx512   0/1       Error     0         1d
es-setup-indexes-zx638   0/1       Error     0         17h
es-setup-indexes-zx64c   0/1       Error     0         21h
es-setup-indexes-zxczt   0/1       Error     0         15h
es-setup-indexes-zxdzf   0/1       Error     0         14h
es-setup-indexes-zxf56   0/1       Error     0         1d
es-setup-indexes-zxf9r   0/1       Error     0         16h
es-setup-indexes-zxg0m   0/1       Error     0         14h
es-setup-indexes-zxg71   0/1       Error     0         1d
es-setup-indexes-zxgwz   0/1       Error     0         19h
es-setup-indexes-zxkpm   0/1       Error     0         23h
es-setup-indexes-zxkvb   0/1       Error     0         15h
es-setup-indexes-zxpgg   0/1       Error     0         20h
es-setup-indexes-zxqh3   0/1       Error     0         1d
es-setup-indexes-zxr7f   0/1       Error     0         22h
es-setup-indexes-zxxbs   0/1       Error     0         13h
es-setup-indexes-zz7xr   0/1       Error     0         12h
es-setup-indexes-zzbjq   0/1       Error     0         13h
es-setup-indexes-zzc0z   0/1       Error     0         16h
es-setup-indexes-zzdb6   0/1       Error     0         1d
es-setup-indexes-zzjh2   0/1       Error     0         21h
es-setup-indexes-zzm77   0/1       Error     0         1d
es-setup-indexes-zzqt5   0/1       Error     0         12h
es-setup-indexes-zzr79   0/1       Error     0         16h
es-setup-indexes-zzsfx   0/1       Error     0         1d
es-setup-indexes-zzx1r   0/1       Error     0         21h
es-setup-indexes-zzx6j   0/1       Error     0         1d
kibana-kq51v   1/1       Running   0         10h

But if I look at the jobs I get nothing related to that anymore:

$ kubectl get jobs --all-namespaces
NAMESPACE     NAME               DESIRED   SUCCESSFUL   AGE
kube-system   configure-calico   1         1            46d

I've also noticed that kubectl seems much slow to respond.  I don't know if the pods are continuously trying to be restarted or in some broken state but would be great if someone could let me know how to troubleshoot as I have not come across another issue like this in kubernetes.

Kube info:

$ kubectl version
Client Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.1", GitCommit:"b0b7a323cc5a4a2019b2e9520c21c7830b7f708e", GitTreeState:"clean", BuildDate:"2017-04-03T20:44:38Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.1", GitCommit:"b0b7a323cc5a4a2019b2e9520c21c7830b7f708e", GitTreeState:"clean", BuildDate:"2017-04-03T20:33:27Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"}

Body:
The solution was as @johnharris85 mentioned in the comment.  I had to manually delete all the pods.  To do that I ran the following:

kubectl get pods -w | tee all-pods.txt

That dumped all my pods, then to filter and delete on only what I wanted.

kubectl delete pod $(more all-pods.txt | grep es-setup-index | awk '{print $1}')

Note: I had about 9292 pods, it took about 1-2 hours to delete them all.


问:
How do I modify WCF to process messages in a different (non SOAP) format?
I am working with WCF to exchange messages with a third party company. The messages need to be sent and received in an envelope that matches the ebXML specification. Ideally I would like to use as much of the WCF stack as possible and avoid the one method to process them all approach as in this case that would mean writing much of the infrastructure of WCF again.

As far as I can see from my initial research this would require me to write my own custom binding but I am struggling to find clarity in the documentation in MSDN.

I have been able to find lots of detailed documents about in individual implementations of each of these but very little about how to put it all together end to end. It would appear that the books I have are similarly light on these topics too with no mention of this in "Pro WCF" by Peiris and Mulder.

What I am aiming for is something like the following.

The messages being sent and received MUST be formatted like below where the name of the first element is the name of the operation that is to be executed and the child element is the payload of the request message would be of the form:

```<code><?xml version="1.0" encoding="UTF-8"?>
<op:DoSomething xmlns:op="http://my.ebXML.schema.com" xmlns:payload="http://payload.company.com">
    <op:AnObject>
        <payload:ImportantValue>42</payload:ImportantValue>
    </op:AnObject>
</op:DoSomething>
</code>```

And the response would be:

```<code><?xml version="1.0" encoding="UTF-8"?>
<op:AcknowledgementResponse xmlns:op="http://my.ebXML.schema.com" xmlns:payload="http://payload.company.com">
    <op:ResponseObject>
        <payload:Ok>True</payload:Ok>
    </op:ResponseObject>
</op:AcknowledgementResponse>
</code>```

As the messages are all described by XML schemas I have used XSD.exe to convert these to strongly typed objects. See https://gist.github.com/740303 for the schemas. Note that these are example schemas. I am not able to post the real schemas without breaching client confidentiality agreements (nor would you want me too as they are huge).

I would now like to be able to write the service implementation as follows:

```<code>public class MyEndpoint : IMyEndpoint
{
    public AcknowledgementResponse DoSomething(AnObject value)
    {
        return new AcknowledgementResponse
            {
                Ok = True;
            };
    }
}
</code>```

Any help would be much appreciated.

答:
For custom message format you need Custom MessageEncoder. MSDN contains example how to create custom encoder. If you use Reflector you will find several encoder implementations so you can learn how to write it.

You can also check what will happen if you try to use TextMessageEncoder with MessageVersion.None (I have never tryed it).

ContentLicense: CC BY-SA 2.5

Body:
I am working with WCF to exchange messages with a third party company. The messages need to be sent and received in an envelope that matches the ebXML specification. Ideally I would like to use as much of the WCF stack as possible and avoid the one method to process them all approach as in this case that would mean writing much of the infrastructure of WCF again.

As far as I can see from my initial research this would require me to write my own custom binding but I am struggling to find clarity in the documentation in MSDN.

I have been able to find lots of detailed documents about in individual implementations of each of these but very little about how to put it all together end to end. It would appear that the books I have are similarly light on these topics too with no mention of this in "Pro WCF" by Peiris and Mulder.

What I am aiming for is something like the following.

The messages being sent and received MUST be formatted like below where the name of the first element is the name of the operation that is to be executed and the child element is the payload of the request message would be of the form:

<?xml version="1.0" encoding="UTF-8"?>
<op:DoSomething xmlns:op="http://my.ebXML.schema.com" xmlns:payload="http://payload.company.com">
    <op:AnObject>
        <payload:ImportantValue>42</payload:ImportantValue>
    </op:AnObject>
</op:DoSomething>

And the response would be:

<?xml version="1.0" encoding="UTF-8"?>
<op:AcknowledgementResponse xmlns:op="http://my.ebXML.schema.com" xmlns:payload="http://payload.company.com">
    <op:ResponseObject>
        <payload:Ok>True</payload:Ok>
    </op:ResponseObject>
</op:AcknowledgementResponse>

As the messages are all described by XML schemas I have used XSD.exe to convert these to strongly typed objects. See https://gist.github.com/740303 for the schemas. Note that these are example schemas. I am not able to post the real schemas without breaching client confidentiality agreements (nor would you want me too as they are huge).

I would now like to be able to write the service implementation as follows:

public class MyEndpoint : IMyEndpoint
{
    public AcknowledgementResponse DoSomething(AnObject value)
    {
        return new AcknowledgementResponse
            {
                Ok = True;
            };
    }
}

Any help would be much appreciated.


问:
Python cPickle from a db field TypeError
In my project i save a list as a cPickle object in a byte field of my postgresql db like this:

```<code>my_list = list(self.outhtml)
bitRst = cPickle.dumps(my_list)
cur.execute("INSERT INTO frontend_t_test (test_id, test_data, test_creation, ip_addr) VALUES (%s, %s, %s, %s)",
                    (str(id(self)),
                     psycopg2.Binary(bitRst), dt, test_utils.return_ip()))
</code>```

All done, when i try to retrive my list i do:

```<code>cur = myconn.cursor()

cur.execute("""SELECT test_data FROM frontend_t_test WHERE test_id = %s""",(idTest,))
res = cur.fetchall()
with open(res, 'rb') as f:
    mynewlist = cPickle.load(f)
</code>```

but instead of the original list i get this error:

Traceback (most recent call last):
    File "", line 1, in
      with open(res, 'rb') as f:
  TypeError: coercing to Unicode: need string or buffer, list found

How can i retreive my pickled list from db?

Thanks in advance

答:
The pickle.load method expects to get a file object, but you are providing a list (res) instead. You need to write the result of cur.fetchall to a file and pass that in or use pickle.dump to write the list:

```<code>with open('outfile', 'wb') as f:
    pickle.dump(res, fp)
</code>```

and for reading:

```<code>with open('outfile', 'rb') as f:
    mynewlist = pickle.load(res)
</code>```

Body:
In my project i save a list as a cPickle object in a byte field of my postgresql db like this:

my_list = list(self.outhtml)
bitRst = cPickle.dumps(my_list)
cur.execute("INSERT INTO frontend_t_test (test_id, test_data, test_creation, ip_addr) VALUES (%s, %s, %s, %s)",
                    (str(id(self)),
                     psycopg2.Binary(bitRst), dt, test_utils.return_ip()))

All done, when i try to retrive my list i do:

cur = myconn.cursor()

cur.execute("""SELECT test_data FROM frontend_t_test WHERE test_id = %s""",(idTest,))
res = cur.fetchall()
with open(res, 'rb') as f:
    mynewlist = cPickle.load(f)

but instead of the original list i get this error:

Traceback (most recent call last):
    File "", line 1, in
      with open(res, 'rb') as f:
  TypeError: coercing to Unicode: need string or buffer, list found

How can i retreive my pickled list from db?

Thanks in advance

Body:
The pickle.load method expects to get a file object, but you are providing a list (res) instead. You need to write the result of cur.fetchall to a file and pass that in or use pickle.dump to write the list:

with open('outfile', 'wb') as f:
    pickle.dump(res, fp)

and for reading:

with open('outfile', 'rb') as f:
    mynewlist = pickle.load(res)


问:
google spreadsheet script editor: delete a project
I have two script projects for a spreadsheet. One was a temp one for development testing. I want to delete the temp one. When I click on script editor it shows both projects, and I can select one, but there is no option for deleting.

Also when I open the project itself there is no delete option.
I have seen other SO threads (such as this), but it seems the interface is changed since then.

Attached the screenshots.

Script Editor File menu:

答:
Make sure that you are the owner of the script.

I've tried to replicate your issue in other scripts which I don't own and it seems that I cannot see a Delete Project... option under File menu.

But with my owned script, there is a Delete Project... option. See screenshot.

Here's a reference post: How can I remove a project from a Google Spreadsheet?

UPDATE (based from OP's comment):

You must be the owner of the spreadsheet to show the Delete Project... option.


问:
How do I use vector values as variables in R
I have a dataframe called repay and I have created a vector for the variables names of the variables I am interested in called variables.

```<code>variables<-names(repay)[22:36]
</code>```

I want to write a for loop that does some univariate analysis on each of the variables in variables. For example:

```<code>for (i in 1:length(variables))
{
model<-glm(Successful~ variables[i]
,data=repay
,family=binomial(link='logit'))
}
</code>```

However it doesn't recognize variables[i] as a variable, giving the following error message:

Error in model.frame.default(formula = Successful ~ variables[i], data
  = repay,  : variable lengths differ (found for 'variables[i]')

答:
Try using the formula function in R. It will allow correct interpretation of models as below:

```<code>for (i in 1:length(variables){
    myglm <- glm(formula(paste("Successful", "~", variables[i])),
                 data = repay, family = binomial(link = 'logit'))
</code>```

See my post here for more things you can do in this context.

Body:
I have a dataframe called repay and I have created a vector for the variables names of the variables I am interested in called variables.

variables<-names(repay)[22:36]

I want to write a for loop that does some univariate analysis on each of the variables in variables. For example:

for (i in 1:length(variables))
{
model<-glm(Successful~ variables[i]
,data=repay
,family=binomial(link='logit'))
}

However it doesn't recognize variables[i] as a variable, giving the following error message:

Error in model.frame.default(formula = Successful ~ variables[i], data
  = repay,  : variable lengths differ (found for 'variables[i]')

Body:
Try using the formula function in R. It will allow correct interpretation of models as below:

for (i in 1:length(variables){
    myglm <- glm(formula(paste("Successful", "~", variables[i])),
                 data = repay, family = binomial(link = 'logit'))

See my post here for more things you can do in this context.


问:
Still facing squid:S2095 in Sonar / How to upgrade SonarJava in Sonarqube
I freshly installed the newest version of Sonarqube and ran the inspection. I got warnings regarding squid:S2095 (closing of streams) which are false positives and which should be fixed with version 3.14 of SonarJava (see https://jira.sonarsource.com/browse/SONARJAVA-1478).</p>

答:
The LTS version of SonarQube comes with the versions of the analyzers that were current when the base version was released.

In your case, that means that your download of 5.6.6 included SonarJava 3.13.1, which was the current version when 5.6 was released. Analyzer versions are not bumped up with point releases because point releases only fix bugs and an analyzer upgrade would be a feature.

Because analyzers release so much more frequently than the platform, as a general policy you should always check your SonarQube update center for newer versions after you download a SonarQube version.


问:
What is the form collection in asp.net/html?
Simple question but one i need to clarify for myself. In terms of collections that can be accessed in the request object there is:

```<code>Cookies:    (whats in  a text file in the browser)
Querystring:   (whats passed in the url like [key=value&key=value etc])
Server Variables:  ?
Form Variables:    ?
</code>```

The ones with the ? next to are the ones that I dont really understand where in the http packet/html they are placed. I did a capture using wireshark:

```<code>POST /Security/HelixSessionAuth.aspx HTTP/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 391

ClientIP=192.168.20.31
Url=%2Fflash%2F56553550%5Fhi%2Emp4
Log=SESSIONSTART%20%5B13%2FDec%2F2010%3A16%3A31%3A23%20%2B0000%5D%20%20flash%2F56553550%5Fhi%2Emp4%200%20192%2E168%2E20%2E31%203%20%5B13%2FDec%2F2010%3A16%3A31%3A23%20%2B0000%5D%200%200%200%20%5B0%20No%20Error%5D%20%5B0%20No%20Error%5D%20%5Brtmp%3A%2F%2Fhelix%2Epete%2Evideolibraryserver%2Ecom%2Fflash%2F56553550%5Fhi%2Emp4%5D%0A
HTTP/1.1 404 Not Found
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
Date: Mon, 13 Dec 2010 16:31:23 GMT
Connection: close
Content-Length: 315

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
</code>```

Where abouts would they be in the above feed?

答:
First about your tool. WireShark is a low level packet analysis tool which you don't need for learning HTTP concepts. Instead use Fiddler.

ServerVariables:

This is an old object from asp classic. Now there are many aliases for their objects. For example Request.UserHostAddress is an alias for Request.ServerVariables("remote_addr").
Also Headers, Cookies, Session objects, ... are available from this object. This object is there more of backward compatibility.

Form Variables:

All controls in ASP.NET are tracked with an ID by ASP.NET and their state is hold within ViewState hidden field. view state, is the technique used by an ASP.NET Web page to persist changes to the state of a Web Form across PostBacks.
So, on every PostBack (form post, i.e click a button) ASP.NET at server side would repopulate form object and its children (controls inside the form) from post data. That's we call form collection.

Body:
Simple question but one i need to clarify for myself. In terms of collections that can be accessed in the request object there is:

Cookies:    (whats in  a text file in the browser)
Querystring:   (whats passed in the url like [key=value&key=value etc])
Server Variables:  ?
Form Variables:    ?

The ones with the ? next to are the ones that I dont really understand where in the http packet/html they are placed. I did a capture using wireshark:

POST /Security/HelixSessionAuth.aspx HTTP/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 391

ClientIP=192.168.20.31
Url=%2Fflash%2F56553550%5Fhi%2Emp4
Log=SESSIONSTART%20%5B13%2FDec%2F2010%3A16%3A31%3A23%20%2B0000%5D%20%20flash%2F56553550%5Fhi%2Emp4%200%20192%2E168%2E20%2E31%203%20%5B13%2FDec%2F2010%3A16%3A31%3A23%20%2B0000%5D%200%200%200%20%5B0%20No%20Error%5D%20%5B0%20No%20Error%5D%20%5Brtmp%3A%2F%2Fhelix%2Epete%2Evideolibraryserver%2Ecom%2Fflash%2F56553550%5Fhi%2Emp4%5D%0A
HTTP/1.1 404 Not Found
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
Date: Mon, 13 Dec 2010 16:31:23 GMT
Connection: close
Content-Length: 315

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Not Found

HTTP Error 404. The requested resource is not found.

Where abouts would they be in the above feed?


问:
Dynamically assigning variable names JavaScript
I am trying to dynamically assign variable names using the user's input. For example:

```<code>var input = document.querySelector('input');

for(var i = 0; i < 10; i++){
   var newVariableName = //input.value;
}
</code>```

Any help would be very much appreciated.

Thank you,
Scratch Cat

答:
You can use array in which the keys will be the input values and the value would be anything you want.

html

```<code><form>

<input type="text" value="demo1" class="example"><br />
<input type="text" value="demo2" class="example"><br />
<input type="text" value="demo3" class="example">

</form>
</code>```

js
First you declare array

```<code>var a = new Array();
</code>```

Then you use for loop to assign key names to array which will be the input values

```<code>for(var i = 0; i < 3; i++){
    a[x[i].value] = x[i].value;
}
</code>```

Finally you can use those key names to access the values

```<code>alert(a['demo1'] + ' ' +a['demo2'] + ' ' + a['demo3']);
</code>```

Here is a link to an example
https://jsfiddle.net/309fpsjn/1/

<form>

<input type="text" value="demo1" class="example">

<input type="text" value="demo2" class="example">

<input type="text" value="demo3" class="example">

</form>

```

Body:
I am trying to dynamically assign variable names using the user's input. For example:

var input = document.querySelector('input');

for(var i = 0; i < 10; i++){
   var newVariableName = //input.value;
}

Any help would be very much appreciated.

Thank you,
Scratch Cat

Body:
You can use array in which the keys will be the input values and the value would be anything you want.

html

<form>

<input type="text" value="demo1" class="example"><br />
<input type="text" value="demo2" class="example"><br />
<input type="text" value="demo3" class="example">

</form>

js
First you declare array

var a = new Array();

Then you use for loop to assign key names to array which will be the input values

for(var i = 0; i < 3; i++){
    a[x[i].value] = x[i].value;
}

Finally you can use those key names to access the values

alert(a['demo1'] + ' ' +a['demo2'] + ' ' + a['demo3']);

Here is a link to an example
https://jsfiddle.net/309fpsjn/1/

<html>
<form>

<input type="text" value="demo1" class="example"><br />
<input type="text" value="demo2" class="example"><br />
<input type="text" value="demo3" class="example">

</form>
<script>
var x = document.querySelectorAll(".example");

var a = new Array();

for(var i = 0; i < 3; i++){
    a[x[i].value] = x[i].value;
}

alert(a['demo1'] + ' ' +a['demo2'] + ' ' + a['demo3']);

</script>
</html>


问:
Remove particular category in Wordpress
I am trying to hide "Gyming" category from custom post with custom taxonomy. Tried very hard to get the result but unfortunatly it did'nt work with following code.

```<code>function cat_subcat(){
$thetax = 'product';
    $args = array(
        'taxonomy' => 'product',
        //'parent' => 0,
        'hierarchical'=>true,
        'order'=> 'ASC',
        'show_count'=>false,
        'show_option_all'=>'',
        'child_of'=>0,
        'depth'=>3,
        'title_li'=>'',
        'show_option_none'    => __( 'No categories' ),
    );
echo '<ul class="category">';
    wp_list_categories( $args );
echo '</ul>';
</code>```

}

kindly advice.

答:
If you want to exclude a category from the list you have created, you can add exclude to your args, where the value is an array of IDs of which categories you want to exclude. So if you wish to exclude the category 'Gyming', you will first have to find the ID of that category. If you're not sure how to find the ID, use the following guide https://www.wpwhitesecurity.com/wordpress-tutorial/find-wordpress-category-id/

If the ID is 42, your new code will be

```<code>function cat_subcat(){
$thetax = 'product';
    $args = array(
        'taxonomy' => 'product',
        //'parent' => 0,
        'hierarchical'=>true,
        'order'=> 'ASC',
        'show_count'=>false,
        'show_option_all'=>'',
        'child_of'=>0,
        'depth'=>3,
        'title_li'=>'',
        'show_option_none'    => __( 'No categories' ),
        'exclude'    => array( 42 ),
    );
echo '<ul class="category">';
    wp_list_categories( $args );
echo '</ul>';
}
</code>```

Title: Remove particular category in Wordpress

Body:
I am trying to hide "Gyming" category from custom post with custom taxonomy. Tried very hard to get the result but unfortunatly it did'nt work with following code.

function cat_subcat(){
$thetax = 'product';
    $args = array(
        'taxonomy' => 'product',
        //'parent' => 0,
        'hierarchical'=>true,
        'order'=> 'ASC',
        'show_count'=>false,
        'show_option_all'=>'',
        'child_of'=>0,
        'depth'=>3,
        'title_li'=>'',
        'show_option_none'    => __( 'No categories' ),
    );
echo '
';
    wp_list_categories( $args );
echo '
';

}

kindly advice.

Body:
If you want to exclude a category from the list you have created, you can add exclude to your args, where the value is an array of IDs of which categories you want to exclude. So if you wish to exclude the category 'Gyming', you will first have to find the ID of that category. If you're not sure how to find the ID, use the following guide https://www.wpwhitesecurity.com/wordpress-tutorial/find-wordpress-category-id/

If the ID is 42, your new code will be

function cat_subcat(){
$thetax = 'product';
    $args = array(
        'taxonomy' => 'product',
        //'parent' => 0,
        'hierarchical'=>true,
        'order'=> 'ASC',
        'show_count'=>false,
        'show_option_all'=>'',
        'child_of'=>0,
        'depth'=>3,
        'title_li'=>'',
        'show_option_none'    => __( 'No categories' ),
        'exclude'    => array( 42 ),
    );
echo '<ul class="category">';
    wp_list_categories( $args );
echo '</ul>';
}


问:
How get core get current user info?
how get current logged user on windows pc in new .net core framework ?

Old namespace

```<code>System.DirectoryServices;
System.DirectoryServices.AccountManagement;
</code>```

not implemented yeat :(
Advise the ported library novell.ldap but I still do not understand how to get information about the user.

I get short name from System.Security.Principal.WindowsIdentity.GetCurrent().Name
how get full name ? Example "Mary Ann"

答:
First, ASP.NET Core can run on Linux and Mac, where you have no "Windows" user at all.

But even if you will run you app on Windows only - what user you mean? If your website is running on server behind IIS - than IIS is started as a service, without any interactive user, and your app also started under some service account.

But if you will run your app only under Windows and only interactively (user will start dotnet run or similar) then easiest way - read environment variables USERDOMAIN and USERNAME. In command prompt run set and you will see all environment variables currently defined in your session. You may read them via Environment class or add to ConfigurationBuilder with AddEnvironmentVariables() in Startup.cs.

Title: How get core get current user info?

Body:
how get current logged user on windows pc in new .net core framework ?

Old namespace

System.DirectoryServices;
System.DirectoryServices.AccountManagement;

not implemented yeat :(
Advise the ported library novell.ldap but I still do not understand how to get information about the user.

I get short name from System.Security.Principal.WindowsIdentity.GetCurrent().Name
how get full name ? Example "Mary Ann"


问:
Send Messages without reload page using ajax in laravel
I am working on laravel and I want to send personally messages to the users using blade template. But when I press submit button it gets refreshed/reload the page every time. what to do? and please anyone tell me how to use ajax url, type, data

View file

```<code><form action="{{action('MessageController@sendmessagereply')}}" method="post">
            <div class="panel-footer">
                <div class="input-group">
                   <?php if(isset($data)){ ?>
                   <?php for($i=0;$i<count($data);$i++) {?>
                    <input type="hidden" name="_token" value="{{csrf_token()}}">
                    <input type="hidden" name="id" value="<?php echo $data[$i]->receivermsgid;?>">
                    <?php } }?>
                    <input type="text"  name="messages" class="form-control" placeholder="Enter Message" />
                    <span class="input-group-btn">
                       <button class="btn btn-info" type="submit">SEND</button>
                    </span>
                </div>
            </div>
          </form>
</code>```

Controller file

```<code> public function sendmessagereply(Request $request)
      {
            $post=$request->all();
            $id=$post['id'];
            $senderid=Session::get('login_userid');
            $receiverid = $id;
            $data=array(
                        'sendermsgid' => $senderid,
                        'receivermsgid' => $receiverid,
                        'message'=>$post['messages'],
                        'sdate'=> DB::raw('CURRENT_TIMESTAMP')
                        );
            $messages = DB::table('messages')->insert($data);
            if($messages){
                \Session::flash('msg','Your Message Has Been Sent Successfully');
                return redirect('messageschat/'.$id);
            } else {
                \Session::flash('msg','Error In Sending Message');
                return redirect('basicsearch');
            }

        }

  //i get the all messages between two users
  public function messageschat($id)
    {
       $senderid=Session::get('login_userid');
       $result=DB::table('messages')
                  ->join('user_register','messages.sendermsgid','=','user_register.id')
                  ->leftjoin('profilephoto','messages.receivermsgid','=','profilephoto.userid','messages.sendermsgid','=','profilephoto.userid')
                  ->where('sendermsgid', $senderid)->where('receivermsgid',$receivermsgid)
                  ->orwhere('sendermsgid',$receivermsgid)->where('receivermsgid',$senderid)
                  ->select('messages.message','messages.sendermsgid','messages.receivermsgid','user_register.first_name as fname','profilephoto.name')
                  ->orderby('messages.sdate')
                  ->get();

       $chatdata=DB::table('messages')
                     ->select('messages.message','messages.receivermsgid','messages.sendermsgid')
                     ->where('receivermsgid',$receivermsgid)
                     ->where('sendermsgid',$senderid)->get();

       return view('users.messageschat')->with('data',$chatdata)->with('data1',$result);
    }
</code>```

Route file

```<code>Route::any('messageschat/{id}','MessageController@messageschat');
</code>```

Javascript file

```<code><script>
$("#add").click(function() {

    $.ajax({
        type: 'post',
        url: 'messageschat/{id}',
        data: {
            '_token': $('input[name=_token]').val(),
            'messages': $('input[messages=messages]').val(),
            'id':$('input[name=_token]').val()
        },
        success: function(data) {
          alert(data)
            if ((data.errors)) {
                $('.error').removeClass('hidden');
                $('.error').text(data.errors.name);
            } else {
                $('.error').remove();
                $('#table').append("");
            }
        },
    });
    $('#name').val('');
});
    </script>
</code>```

答:
To submit a HTML form using ajax, first you need to disable the full reload submission. For that make following amendments in your code -

Use this -

```<code><button class="btn btn-info" type="button" id="add">SEND</button>
</code>```

instead of this -

```<code><button class="btn btn-info" type="submit" id="add">SEND</button>
</code>```

JavaScript-

event.preventDefault(); will disable the default full page reload based form submission and will allow you to create an ajax request delivering your payload to your MessageController@messageschat controller.

```<code>$("#add").click(function(event) {
    //Preventing the default form submission
    event.preventDefault();
    $.ajax({
    type: 'post',
    url: 'messageschat/{id}',
    data: {
        '_token': $('input[name=_token]').val(),
        'messages': $('input[messages=messages]').val(),
        'id':$('input[name=_token]').val()
    },
    success: function(data) {
        alert(data);
        if ((data.errors)) {
            $('.error').removeClass('hidden');
            $('.error').text(data.errors.name);
        } else {
            $('.error').remove();
            $('#table').append("");
        }
    },
  });
  $('#name').val('');
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working on laravel and I want to send personally messages to the users using blade template. But when I press submit button it gets refreshed/reload the page every time. what to do? and please anyone tell me how to use ajax url, type, data

View file

<form action="{{action('MessageController@sendmessagereply')}}" method="post">

                   <?php if(isset($data)){ ?>
                   <?php for($i=0;$i<count($data);$i++) {?>
                    <input type="hidden" name="_token" value="{{csrf_token()}}">
                    <input type="hidden" name="id" value="<?php echo $data[$i]->receivermsgid;?>">
                    <?php } }?>
                    <input type="text"  name="messages" class="form-control" placeholder="Enter Message" />

                       <button class="btn btn-info" type="submit">SEND</button>

          </form>

Controller file

 public function sendmessagereply(Request $request)
      {
            $post=$request->all();
            $id=$post['id'];
            $senderid=Session::get('login_userid');
            $receiverid = $id;
            $data=array(
                        'sendermsgid' => $senderid,
                        'receivermsgid' => $receiverid,
                        'message'=>$post['messages'],
                        'sdate'=> DB::raw('CURRENT_TIMESTAMP')
                        );
            $messages = DB::table('messages')->insert($data);
            if($messages){
                \Session::flash('msg','Your Message Has Been Sent Successfully');
                return redirect('messageschat/'.$id);
            } else {
                \Session::flash('msg','Error In Sending Message');
                return redirect('basicsearch');
            }

        }

  //i get the all messages between two users
  public function messageschat($id)
    {
       $senderid=Session::get('login_userid');
       $result=DB::table('messages')
                  ->join('user_register','messages.sendermsgid','=','user_register.id')
                  ->leftjoin('profilephoto','messages.receivermsgid','=','profilephoto.userid','messages.sendermsgid','=','profilephoto.userid')
                  ->where('sendermsgid', $senderid)->where('receivermsgid',$receivermsgid)
                  ->orwhere('sendermsgid',$receivermsgid)->where('receivermsgid',$senderid)
                  ->select('messages.message','messages.sendermsgid','messages.receivermsgid','user_register.first_name as fname','profilephoto.name')
                  ->orderby('messages.sdate')
                  ->get();

       $chatdata=DB::table('messages')
                     ->select('messages.message','messages.receivermsgid','messages.sendermsgid')
                     ->where('receivermsgid',$receivermsgid)
                     ->where('sendermsgid',$senderid)->get();

       return view('users.messageschat')->with('data',$chatdata)->with('data1',$result);
    }

Route file

Route::any('messageschat/{id}','MessageController@messageschat');

Javascript file

Body:
To submit a HTML form using ajax, first you need to disable the full reload submission. For that make following amendments in your code -

Use this -

<button class="btn btn-info" type="button" id="add">SEND</button>

instead of this -

<button class="btn btn-info" type="submit" id="add">SEND</button>

JavaScript-

event.preventDefault(); will disable the default full page reload based form submission and will allow you to create an ajax request delivering your payload to your MessageController@messageschat controller.

$("#add").click(function(event) {
    //Preventing the default form submission
    event.preventDefault();
    $.ajax({
    type: 'post',
    url: 'messageschat/{id}',
    data: {
        '_token': $('input[name=_token]').val(),
        'messages': $('input[messages=messages]').val(),
        'id':$('input[name=_token]').val()
    },
    success: function(data) {
        alert(data);
        if ((data.errors)) {
            $('.error').removeClass('hidden');
            $('.error').text(data.errors.name);
        } else {
            $('.error').remove();
            $('#table').append("");
        }
    },
  });
  $('#name').val('');
}


问:
How to control the opacity of a container's background in CSS?
How can i control the opacity of a picture or background color of a container or a button or a form in CSS?
Which property should use?</p>

答:
You can use the RGBA system. The A stands for Alpha which mean the opacity of the color. So let's say you want to have a transparency of 50% you have to use this code:</p>

```<code>background-color: rgba(0,0,0,0.5);
</code>```

Body:
You can use the RGBA system. The A stands for Alpha which mean the opacity of the color. So let's say you want to have a transparency of 50% you have to use this code:

background-color: rgba(0,0,0,0.5);


问:
Justifying text inside a TextView in android
So, as most of you know, there is no text justifying inside a TextView in Android. So, I built a custom TextView to get around the problem. However, for some reason, sometimes punctuation marks break the line for some reason in some devices. I tested on an LG G3 and emulator (Nexus 4 running latest version) and a comma "," for instance breaks the justification on the LG G3 but not on the emulator.

If I add a Padding start and end (or left and right) of at least 2, the problem is solved. This looks very arbitrary to me.

Basically, my logic was that in order to justify the text, I would need to know the width of the TextView itself, construct the text into lines that are at maximum that length. Then, by finding the number of spaces in the line and the remaining empty space, stretch the " " (space) characters to be scaled according to remaining pixels (or, space in the view).

It works almost perfectly, and most of the time it supports RTL text as well.

here're some pictures of the text (a simple lorem impsum) with and without the offending marks (first one is on emulator nexus 4 running 7.1.1, second one is on LG G3 running v5.0)

Here's the code:

```<code>public class DTextView extends AppCompatTextView {

    private boolean justify;

    public DTextView(Context context) {
        super(context);
    }

    public DTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public DTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void setJustify(boolean justify) {
        this.justify = justify;
        if (justify) {
            justify();
        }
    }

    private void init(@Nullable AttributeSet attrs) {
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.DTextView, 0, 0);
        justify = ta.getBoolean(R.styleable.DTextView_justify, false);

        ta.recycle();
    }

    private SpannableStringBuilder justifyText() {

        String[] words = getText().toString().split(" ");
        setText("");

        int maxLineWidth = getWidth() - getPaddingLeft() - getPaddingRight();

        SpannableStringBuilder justifiedTextSpannable = new SpannableStringBuilder();

        //This will build the new text with the lines rearranged so that they will have a width
        //bigger than the View's own width
        ArrayList<String> lines = new ArrayList<>(0);
        String line = "";
        for (String word : words) {
            if (getWordWidth(line + word) < maxLineWidth) {
                line += word + " ";
            } else {
                line = line.substring(0, line.length() - 1);
                lines.add(line);
                line = word + " ";
            }
        }
        //Add the last line
        lines.add(line);

        for (int i = 0; i < lines.size() - 1; i++) {
            justifiedTextSpannable.append(justifyLine(lines.get(i), maxLineWidth));
            justifiedTextSpannable.append("\n");
        }

        justifiedTextSpannable.append(lines.get(lines.size() - 1));

        return justifiedTextSpannable;
    }

    private SpannableString justifyLine(String line, float maxWidth) {

        SpannableString sLine = new SpannableString(line);
        float spaces = line.split(" ").length - 1;

        float spaceCharSize = getWordWidth(" ");
        float emptySpace = maxWidth - getWordWidth(line);
        float newSpaceSize = (emptySpace / spaces) + spaceCharSize;
        float scaleX = newSpaceSize / spaceCharSize;

        for (int i = 0; i < line.length(); i++) {
            if (line.charAt(i) == ' ') {
                sLine.setSpan(new ScaleXSpan(scaleX), i, i + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        return sLine;
    }

    private void justify() {
        justify = false;
        setText(justifyText());
        invalidate();
    }

    private float getWordWidth(String word) {
        return getPaint().measureText(word);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (!justify)
            super.onDraw(canvas);
        else
            justify();
    }
}
</code>```

I would very much appreciate anyone that can shed some light on this.

答:
So, after looking a bit more at this: https://github.com/ufo22940268/android-justifiedtextview and TextView in general, I discovered that my main problem was my approach.

Using the approach of scaling the width of the " " characters was sound in theory, but after doing so, the width of the line changes again, as it seems that the width of the line is NOT the sum of its parts.

I have changed my approach and took inspiration from the link above, and so in my new approach I draw each character by itself, instead of drawing the whole line. If the text needs to be justified (based on a custom "justify" boolean attribute) then it will draw the line and justify it, else it will just draw the line.

Edit: I have changed the code now so that it also supports RTL texts. I will upload the code somewhere in the next few days.

Here's the result:

Here's the code:

```<code>public class DTextView extends AppCompatTextView {

    private boolean justify;
    private float textAreaWidth;
    private float spaceCharSize;
    private float lineY;

    public DTextView(Context context) {
        super(context);
    }

    public DTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public DTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    /**
     * @param attrs the attributes from the xml
     *              This function loads all the parameters from the xml
     */
    private void init(AttributeSet attrs) {

        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.DTextView, 0, 0);

        justify = ta.getBoolean(R.styleable.DTextView_justify, false);

        ta.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        drawText(canvas);
    }

    private void drawText(Canvas canvas) {
        TextPaint paint = getPaint();
        paint.setColor(getCurrentTextColor());
        paint.drawableState = getDrawableState();
        textAreaWidth = getMeasuredWidth() - (getPaddingLeft() + getPaddingRight());

        spaceCharSize = paint.measureText(" ");

        String text = getText().toString();
        lineY = getTextSize();

        Layout textLayout = getLayout();

        if (textLayout == null)
            return;

        Paint.FontMetrics fm = paint.getFontMetrics();
        int textHeight = (int) Math.ceil(fm.descent - fm.ascent);
        textHeight = (int) (textHeight * getLineSpacingMultiplier() + textLayout.getSpacingAdd());

        for (int i = 0; i < textLayout.getLineCount(); i++) {

            int lineStart = textLayout.getLineStart(i);
            int lineEnd = textLayout.getLineEnd(i);

            float lineWidth = StaticLayout.getDesiredWidth(text, lineStart, lineEnd, paint);
            String line = text.substring(lineStart, lineEnd);

            if (line.charAt(line.length() - 1) == ' ') {
                line = line.substring(0, line.length() - 1);
            }

            if (justify && i < textLayout.getLineCount() - 1) {
                drawLineJustified(canvas, line, lineWidth);
            } else {
                canvas.drawText(line, 0, lineY, paint);
            }

            lineY += textHeight;
        }

    }

    private void drawLineJustified(Canvas canvas, String line, float lineWidth) {
        TextPaint paint = getPaint();

        float emptySpace = textAreaWidth - lineWidth;
        int spaces = line.split(" ").length - 1;
        float newSpaceSize = (emptySpace / spaces) + spaceCharSize;

        float charX = 0;

        for (int i = 0; i < line.length(); i++) {
            String character = String.valueOf(line.charAt(i));
            float charWidth = StaticLayout.getDesiredWidth(character, paint);
            if (!character.equals(" ")) {
                canvas.drawText(character, charX, lineY, paint);
            }

            if (character.equals(" ") && i != line.length() - 1)
                charX += newSpaceSize;
            else
                charX += charWidth;
        }

    }
}
</code>```

and the XML:

```<code><il.co.drapp.views.text.DTextView
                android:layout_width="match_parent"
                android:inputType="textMultiLine|textNoSuggestions"
                app:justify="true"
                android:id="@+id/justifyText"
                android:text="@string/article_dummy_text"
                android:layout_height="wrap_content" />
</code>```

Thanks to Aditya Vyas-Lakhan for the links

Body:
So, as most of you know, there is no text justifying inside a TextView in Android. So, I built a custom TextView to get around the problem. However, for some reason, sometimes punctuation marks break the line for some reason in some devices. I tested on an LG G3 and emulator (Nexus 4 running latest version) and a comma "," for instance breaks the justification on the LG G3 but not on the emulator.

If I add a Padding start and end (or left and right) of at least 2, the problem is solved. This looks very arbitrary to me.

Basically, my logic was that in order to justify the text, I would need to know the width of the TextView itself, construct the text into lines that are at maximum that length. Then, by finding the number of spaces in the line and the remaining empty space, stretch the " " (space) characters to be scaled according to remaining pixels (or, space in the view).

It works almost perfectly, and most of the time it supports RTL text as well.

here're some pictures of the text (a simple lorem impsum) with and without the offending marks (first one is on emulator nexus 4 running 7.1.1, second one is on LG G3 running v5.0)

Here's the code:

public class DTextView extends AppCompatTextView {

    private boolean justify;

    public DTextView(Context context) {
        super(context);
    }

    public DTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public DTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void setJustify(boolean justify) {
        this.justify = justify;
        if (justify) {
            justify();
        }
    }

    private void init(@Nullable AttributeSet attrs) {
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.DTextView, 0, 0);
        justify = ta.getBoolean(R.styleable.DTextView_justify, false);

        ta.recycle();
    }

    private SpannableStringBuilder justifyText() {

        String[] words = getText().toString().split(" ");
        setText("");

        int maxLineWidth = getWidth() - getPaddingLeft() - getPaddingRight();

        SpannableStringBuilder justifiedTextSpannable = new SpannableStringBuilder();

        //This will build the new text with the lines rearranged so that they will have a width
        //bigger than the View's own width
        ArrayList<String> lines = new ArrayList<>(0);
        String line = "";
        for (String word : words) {
            if (getWordWidth(line + word) < maxLineWidth) {
                line += word + " ";
            } else {
                line = line.substring(0, line.length() - 1);
                lines.add(line);
                line = word + " ";
            }
        }
        //Add the last line
        lines.add(line);

        for (int i = 0; i < lines.size() - 1; i++) {
            justifiedTextSpannable.append(justifyLine(lines.get(i), maxLineWidth));
            justifiedTextSpannable.append("\n");
        }

        justifiedTextSpannable.append(lines.get(lines.size() - 1));

        return justifiedTextSpannable;
    }

    private SpannableString justifyLine(String line, float maxWidth) {

        SpannableString sLine = new SpannableString(line);
        float spaces = line.split(" ").length - 1;

        float spaceCharSize = getWordWidth(" ");
        float emptySpace = maxWidth - getWordWidth(line);
        float newSpaceSize = (emptySpace / spaces) + spaceCharSize;
        float scaleX = newSpaceSize / spaceCharSize;

        for (int i = 0; i < line.length(); i++) {
            if (line.charAt(i) == ' ') {
                sLine.setSpan(new ScaleXSpan(scaleX), i, i + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        return sLine;
    }

    private void justify() {
        justify = false;
        setText(justifyText());
        invalidate();
    }

    private float getWordWidth(String word) {
        return getPaint().measureText(word);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (!justify)
            super.onDraw(canvas);
        else
            justify();
    }
}

I would very much appreciate anyone that can shed some light on this.

Body:
So, after looking a bit more at this: https://github.com/ufo22940268/android-justifiedtextview and TextView in general, I discovered that my main problem was my approach.

Using the approach of scaling the width of the " " characters was sound in theory, but after doing so, the width of the line changes again, as it seems that the width of the line is NOT the sum of its parts.

I have changed my approach and took inspiration from the link above, and so in my new approach I draw each character by itself, instead of drawing the whole line. If the text needs to be justified (based on a custom "justify" boolean attribute) then it will draw the line and justify it, else it will just draw the line.

Edit: I have changed the code now so that it also supports RTL texts. I will upload the code somewhere in the next few days.

Here's the result:

Here's the code:

public class DTextView extends AppCompatTextView {

    private boolean justify;
    private float textAreaWidth;
    private float spaceCharSize;
    private float lineY;

    public DTextView(Context context) {
        super(context);
    }

    public DTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public DTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    /**
     * @param attrs the attributes from the xml
     *              This function loads all the parameters from the xml
     */
    private void init(AttributeSet attrs) {

        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.DTextView, 0, 0);

        justify = ta.getBoolean(R.styleable.DTextView_justify, false);

        ta.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        drawText(canvas);
    }

    private void drawText(Canvas canvas) {
        TextPaint paint = getPaint();
        paint.setColor(getCurrentTextColor());
        paint.drawableState = getDrawableState();
        textAreaWidth = getMeasuredWidth() - (getPaddingLeft() + getPaddingRight());

        spaceCharSize = paint.measureText(" ");

        String text = getText().toString();
        lineY = getTextSize();

        Layout textLayout = getLayout();

        if (textLayout == null)
            return;

        Paint.FontMetrics fm = paint.getFontMetrics();
        int textHeight = (int) Math.ceil(fm.descent - fm.ascent);
        textHeight = (int) (textHeight * getLineSpacingMultiplier() + textLayout.getSpacingAdd());

        for (int i = 0; i < textLayout.getLineCount(); i++) {

            int lineStart = textLayout.getLineStart(i);
            int lineEnd = textLayout.getLineEnd(i);

            float lineWidth = StaticLayout.getDesiredWidth(text, lineStart, lineEnd, paint);
            String line = text.substring(lineStart, lineEnd);

            if (line.charAt(line.length() - 1) == ' ') {
                line = line.substring(0, line.length() - 1);
            }

            if (justify && i < textLayout.getLineCount() - 1) {
                drawLineJustified(canvas, line, lineWidth);
            } else {
                canvas.drawText(line, 0, lineY, paint);
            }

            lineY += textHeight;
        }

    }

    private void drawLineJustified(Canvas canvas, String line, float lineWidth) {
        TextPaint paint = getPaint();

        float emptySpace = textAreaWidth - lineWidth;
        int spaces = line.split(" ").length - 1;
        float newSpaceSize = (emptySpace / spaces) + spaceCharSize;

        float charX = 0;

        for (int i = 0; i < line.length(); i++) {
            String character = String.valueOf(line.charAt(i));
            float charWidth = StaticLayout.getDesiredWidth(character, paint);
            if (!character.equals(" ")) {
                canvas.drawText(character, charX, lineY, paint);
            }

            if (character.equals(" ") && i != line.length() - 1)
                charX += newSpaceSize;
            else
                charX += charWidth;
        }

    }
}

and the XML:

<il.co.drapp.views.text.DTextView
                android:layout_width="match_parent"
                android:inputType="textMultiLine|textNoSuggestions"
                app:justify="true"
                android:id="@+id/justifyText"
                android:text="@string/article_dummy_text"
                android:layout_height="wrap_content" />

Thanks to Aditya Vyas-Lakhan for the links


问:
How Can I Get A List of Available System Sounds in iOS?
I found this question, but it's a bit aged. It looks like that directory access is no longer available for the example app they recommend.

The Apple documentation doesn't seem to have what I need, either.

What I need is to be able to list the built-in sounds (not provide my own), and allow a user of my app to choose one to play.

Sounds simple enough, eh?

UPDATE:

Here is the relevant code in the example app mentioned below:

```<code>NSURL *directoryURL = [NSURL URLWithString:@"/System/Library/Audio/UISounds"];
NSArray *keys = [NSArray arrayWithObject:NSURLIsDirectoryKey];

NSDirectoryEnumerator *enumerator = [fileManager
                                     enumeratorAtURL:directoryURL
                                     includingPropertiesForKeys:keys
                                     options:0
                                     errorHandler:^(NSURL *url, NSError *error) {
                                         // Handle the error.
                                         // Return YES if the enumeration should continue after the error.
                                         return YES;
                                     }];

for (NSURL *url in enumerator) {
    NSError *error;
    NSNumber *isDirectory = nil;
    if (! [url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error]) {
        // handle error
    }
    else if (! [isDirectory boolValue]) {
        [audioFileList addObject:url];
    }
}
</code>```

The problem is that the enumerator is always empty. I suspect this may be a security/sandbox issue.

答:
Reading up on this, you can find code to get a list of system sound files - but only on a "jail break" device.

Based on this note on Apple's docs (link), it sounds like (sorry for the pun) we won't have much luck in trying to access the "internal" sound clips:

Note System-supplied alert sounds and system-supplied user-interface sound effects are not available to your iOS application. For example, using the kSystemSoundID_UserPreferredAlert constant as a parameter to the AudioServicesPlayAlertSound function will not play anything.

Body:
I found this question, but it's a bit aged. It looks like that directory access is no longer available for the example app they recommend.

The Apple documentation doesn't seem to have what I need, either.

What I need is to be able to list the built-in sounds (not provide my own), and allow a user of my app to choose one to play.

Sounds simple enough, eh?

UPDATE:

Here is the relevant code in the example app mentioned below:

NSURL *directoryURL = [NSURL URLWithString:@"/System/Library/Audio/UISounds"];
NSArray *keys = [NSArray arrayWithObject:NSURLIsDirectoryKey];

NSDirectoryEnumerator *enumerator = [fileManager
                                     enumeratorAtURL:directoryURL
                                     includingPropertiesForKeys:keys
                                     options:0
                                     errorHandler:^(NSURL *url, NSError *error) {
                                         // Handle the error.
                                         // Return YES if the enumeration should continue after the error.
                                         return YES;
                                     }];

for (NSURL *url in enumerator) {
    NSError *error;
    NSNumber *isDirectory = nil;
    if (! [url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error]) {
        // handle error
    }
    else if (! [isDirectory boolValue]) {
        [audioFileList addObject:url];
    }
}

The problem is that the enumerator is always empty. I suspect this may be a security/sandbox issue.