问:
How to disable button when dynamic selected option value is zero?
Im having problems with this, I hope you can help me.

I have dynamic RadioButtons which fill from service.
When option 4 is selected, a combobox appears with more dynamic options and values.
By default the first option is "Select an Option" with value '0'.
When that ComboBox appears and the default option is '0', I need to disable the 'Continue' button. My problem is that the first time the ComboBox appears, doesn't recognize the value, So I can press the button.

This is what I have at the moment. (html)

```<code>    <div class="form-group row d-flex justify-content-center">
       <div class="card animated fadeIn" *ngIf="!loading && (!listModType.hasOwnProperty('ErrorDescription') || listModType.hasOwnProperty('error'))">
          <div class="card-body">
              <div *ngFor='let item of listModType; let idx = index'>
                   <input type="radio" id="{{ item.id }}" name="modifType" [value]="item.typeModif"
             [ngModel]="userSelection.chosenTipoMod" (change)='radioChecked( item.id, idx )' #selectedOp="ngModel">
                    <label class="form-check-label">   {{ item.typeModif }} </label>
               </div>
           </div>
        </div>
    </div>

    <div class="input-group justify-content-center" *ngIf="showSelect">
        <div class="col-sm-4 col-md-4 col-lg-4">
            <select class="form-control" id="selectedItem" (change)="onOptionsSelected($event)">
                <option [value]='userSelection.chonNumItem'>
                       Select an Item
                </option>
                <option value='{{ modifItem }}' *ngFor="let modifItem of modifiedItems">
                      Item {{ modifItem }}
                </option>
            </select>
         </div>
    </div>

    <div class="row">
        <div class="col-sm-6 col-md-6 col-lg-6" style="text-align:right;">
             <button (click)="modSelection(form)" [disabled]="selItem === '0'" class="btn btn-success" id="note-button">
                  Continue
            </button>
         </div>
    </div>
</code>```

And this is TS file.

```<code>export class ModificationComponent implements OnInit {

    objectItem: any;
    listModType: any = { ErrorDescription: '0' };
    modifiedItems: any = [];
    selItem: string;
    showSelect = false;
    userSelection = {
        chosenTipoMod: 'Datos de Cliente',
        chonNumItem: '0'
    };

    constructor() {
        this.searchModificationType();
        for (let i = 0; i < this.info.secures.item.length; i++) {
            this.modifiedItems.push(this.info.secures.item[i]['itemNumber']);
        }
        this.objectItem = this.modifiedItems.length;
    }

    onOptionsSelected(event: any) {
        this.selItem = event.target.value;
        console.log(this.selItem);
    }

    radioChecked(id, i) {
        this.listModType.forEach(item => {
            if (item.id === id) {
                console.log('Chosen Option', item.typeModif);
            }
            if (item.id === id && this.info.secures.item.length >= 1 && item.id === 'RB') {
                item.selected = false;
                this.showSelect = true;
                console.log('RB has been chosen');
            } else {
                item.selected = true;
                this.showSelect = false;
            }
        });
    }

}
</code>```

答:
Context

You should set the value of this.selItem to '0'.

Solutions

It could be done in two places:

a. When the select element appears.

And, as you described, it happens when the this.showSelect is set to true inside radioChecked.

Adding the assignment to selItem into your radioChecked function:

```<code>  ...
  this.showSelect = true;
  this.selItem = '0'; // <--
  ...
</code>```

If you want to preserve a possible previous value, use:

```<code>  ...
  this.showSelect = true;
  this.selItem = this.selItem ?? '0'; // <--
  ...
</code>```

Note: If you are using TypeScript < 3.7, then use || instead of the nullish coalescing operator ??:

```<code>this.selItem = this.selItem || '0';
</code>```

b. By default, setting it as the default value.

This option will work only if it does not change with each radio option. Otherwise, the solution a. is better suited.

```<code>    modifiedItems: any = [];
    selItem = '0';           // <---
    showSelect = false;
</code>```

Body:
Im having problems with this, I hope you can help me.

I have dynamic RadioButtons which fill from service.
When option 4 is selected, a combobox appears with more dynamic options and values.
By default the first option is "Select an Option" with value '0'.
When that ComboBox appears and the default option is '0', I need to disable the 'Continue' button. My problem is that the first time the ComboBox appears, doesn't recognize the value, So I can press the button.

This is what I have at the moment. (html)

                   <input type="radio" id="{{ item.id }}" name="modifType" [value]="item.typeModif"
             [ngModel]="userSelection.chosenTipoMod" (change)='radioChecked( item.id, idx )' #selectedOp="ngModel">
                       {{ item.typeModif }}

            <select class="form-control" id="selectedItem" (change)="onOptionsSelected($event)">
                <option [value]='userSelection.chonNumItem'>
                       Select an Item
                </option>
                <option value='{{ modifItem }}' *ngFor="let modifItem of modifiedItems">
                      Item {{ modifItem }}
                </option>
            </select>

             <button (click)="modSelection(form)" [disabled]="selItem === '0'" class="btn btn-success" id="note-button">
                  Continue
            </button>

And this is TS file.

export class ModificationComponent implements OnInit {

    objectItem: any;
    listModType: any = { ErrorDescription: '0' };
    modifiedItems: any = [];
    selItem: string;
    showSelect = false;
    userSelection = {
        chosenTipoMod: 'Datos de Cliente',
        chonNumItem: '0'
    };

    constructor() {
        this.searchModificationType();
        for (let i = 0; i < this.info.secures.item.length; i++) {
            this.modifiedItems.push(this.info.secures.item[i]['itemNumber']);
        }
        this.objectItem = this.modifiedItems.length;
    }

    onOptionsSelected(event: any) {
        this.selItem = event.target.value;
        console.log(this.selItem);
    }

    radioChecked(id, i) {
        this.listModType.forEach(item => {
            if (item.id === id) {
                console.log('Chosen Option', item.typeModif);
            }
            if (item.id === id && this.info.secures.item.length >= 1 && item.id === 'RB') {
                item.selected = false;
                this.showSelect = true;
                console.log('RB has been chosen');
            } else {
                item.selected = true;
                this.showSelect = false;
            }
        });
    }

}

Body:
Context

You should set the value of this.selItem to '0'.

Solutions

It could be done in two places:

a. When the select element appears.

And, as you described, it happens when the this.showSelect is set to true inside radioChecked.

Adding the assignment to selItem into your radioChecked function:

  ...
  this.showSelect = true;
  this.selItem = '0'; // <--
  ...

If you want to preserve a possible previous value, use:

  ...
  this.showSelect = true;
  this.selItem = this.selItem ?? '0'; // <--
  ...

Note: If you are using TypeScript < 3.7, then use || instead of the nullish coalescing operator ??:

this.selItem = this.selItem || '0';

b. By default, setting it as the default value.

This option will work only if it does not change with each radio option. Otherwise, the solution a. is better suited.

    modifiedItems: any = [];
    selItem = '0';           // <---
    showSelect = false;


来源: stackexchange

问:
symfony 5 - disable subscriber
I am using bugsnag in a symfony 5 project to keep track of exeptions. I also use symfony messenger with rabbit for heavy processing.

Everything works fine overall, except the fact that in some cases, inside a messenger middleware (RejectRedeliveredMessageMiddleware) an exception is thrown in some particular cases in order to trigger a message reque while avoiding a possible infinite loop (RejectRedeliveredMessageException).

The exception should be there, and the behavior is correct. For example if a process stopped unexpectedly (a hard reboot or a kill), the message is requed. The logic works well, autorecovery works perfectly.

The only problem is that bugsnag registers itself as a subscriber for all kernel events, treated or not (code below)

```<code>$listeners = [
    KernelEvents::REQUEST => ['onKernelRequest', 256],
    KernelEvents::EXCEPTION => ['onKernelException', 128],
</code>```

];

Normally exceptions are caught in our app before getting to the general event dispatcher and so they are not reported if they shouldn't. But, because that is in the middleware, and an event is risen it gets reported even though is already treated by the autoretry mechanism and because of that it generates a lot of noise and fake positives.

What I would need to do is unsubscribe for a particular event, but since I can't touch the 3rd party code (bugsnag and messenger) I can't find a way to do it.

Is there a way to programatically remove an event from a subscriber?

答:
It's hard to tell if this would work, but it's an angle - when you detect your Event is handled properly, you could invoke $event->stopPropagation(), perhaps from your own listener, which should: "... tell the dispatcher to stop all propagation of the event to future listeners (i.e. to not notify any more listeners)"

https://symfony.com/doc/current/components/event_dispatcher.html#stopping-event-flow-propagation

ContentLicense: CC BY-SA 4.0

Title: symfony 5 - disable subscriber

Body:
I am using bugsnag in a symfony 5 project to keep track of exeptions. I also use symfony messenger with rabbit for heavy processing.

Everything works fine overall, except the fact that in some cases, inside a messenger middleware (RejectRedeliveredMessageMiddleware) an exception is thrown in some particular cases in order to trigger a message reque while avoiding a possible infinite loop (RejectRedeliveredMessageException).

The exception should be there, and the behavior is correct. For example if a process stopped unexpectedly (a hard reboot or a kill), the message is requed. The logic works well, autorecovery works perfectly.

The only problem is that bugsnag registers itself as a subscriber for all kernel events, treated or not (code below)

$listeners = [
    KernelEvents::REQUEST => ['onKernelRequest', 256],
    KernelEvents::EXCEPTION => ['onKernelException', 128],

];

Normally exceptions are caught in our app before getting to the general event dispatcher and so they are not reported if they shouldn't. But, because that is in the middleware, and an event is risen it gets reported even though is already treated by the autoretry mechanism and because of that it generates a lot of noise and fake positives.

What I would need to do is unsubscribe for a particular event, but since I can't touch the 3rd party code (bugsnag and messenger) I can't find a way to do it.

Is there a way to programatically remove an event from a subscriber?


问:
Lists within dictionaries
I'm using Python and trying to access some items in a list within a dictionary.   I do not need to loop, just need the item value.   Please see this:

```<code>```
BROKER_INFO = {'AMERITRADE': {
           'file_info': {
             'broker_name'   : 'TD Ameritrade',
             'filename'      : 'ameritrade',
             'row_start'     : '1',
             'active'        : 'Y',
             'actions'       : 'Bought,Sold',
             'buy'           : 'Bought',
             'sell'          : 'Sold',
             'columns'       : [
               {'date': '0', 'action': '2', 'ticker': '4'}]
             }
```
</code>```

I'm looking to get the value to "date", "action", "ticker' within "columns", which is within "file_info" and "AMERITRADE".

I tried this:  BROKER_INFO[p_broker]['file_info']['columns']['action'], but no luck.

Many many thanks!

答:
Try</p>

```<code>BROKER_INFO[p_broker]['file_info']['columns'][0]['action']
</code>```

Title: Lists within dictionaries

Body:
I'm using Python and trying to access some items in a list within a dictionary.   I do not need to loop, just need the item value.   Please see this:

BROKER_INFO = {'AMERITRADE': {
           'file_info': {
             'broker_name'   : 'TD Ameritrade',
             'filename'      : 'ameritrade',
             'row_start'     : '1',
             'active'        : 'Y',
             'actions'       : 'Bought,Sold',
             'buy'           : 'Bought',
             'sell'          : 'Sold',
             'columns'       : [
               {'date': '0', 'action': '2', 'ticker': '4'}]
             }

I'm looking to get the value to "date", "action", "ticker' within "columns", which is within "file_info" and "AMERITRADE".

I tried this:  BROKER_INFO[p_broker]['file_info']['columns']['action'], but no luck.

Many many thanks!

Body:
Try

BROKER_INFO[p_broker]['file_info']['columns'][0]['action']


问:
How to transfer variables from a ts fie to another, angular
I defined a property here in my function

```<code>evs: string
...
openArticle(url){
    this.evs = url
    console.log(this.evs)
    this.navCtrl.navigateForward('/url-page')

  }
</code>```

And I a trying to pass the value of 'this.evs' to another ts file and use its value but I do not know how to do this. I tried exporting it like this.

```<code>export const webpage = this.evs
</code>```

but this.evs has no value until someone performs the openArticle function ad so I keep getting the error. "Cannot read property 'evs' of undefined"

What i need to do is tranfer the variable to the 'url-page' page and use the value of this.evs only after the openArticle function has bee called. How do I go about this?

答:
If the components have a parent/child relationship, You can share data between them via @Inpput() and @Output() decorators.

Sharing data from Parent to Child using @Input() :

```<code><h3>Parent Component</h3>

<label>Parent Component</label>c
<input type="number" [(ngModel)]='parentValue'/>

<p>Value of child component is: </p>
<app-child [value]='parentValue'></app-child>
</code>```

And in the child component, the 'parentValue' can be received as :

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

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

  @Input() value: number;
  constructor() { }

  ngOnInit() {
  }

}
</code>```

Now, in the case of sending data from Child to Parent, we can use an @Output() event emitter. So the parent would have a function to receive the emitted data from child as :

```<code>parent-app.component.html
    <app-child [value]="parentValue" (childEvent)="childEvent($event)"></app-child>

parent-app.component.ts

childEvent(event) {
console.log(event);
}

And, the child.component.ts would look like :

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

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

  @Input() PData: number;
  @Output() childEvent = new EventEmitter();
  constructor() { }
  onChange(value) {
    this.childEvent.emit(value);
  }

  ngOnInit() {
  }

}
</code>```

If the components do not have a parent/child relationship, a shared service can be used, say, SharedService which has a BehavioralSubject, that emits value from either component, and the other component can then catch the changed value.

Eg:

```<code>import { Injectable } from '@angular/core';
import { BehaviorSubject } from "rxjs/BehaviorSubject";

@Injectable()
export class SharedService {

  comp1Val: string;
  _comp1ValueBS = new BehaviorSubject<string>('');

  comp2Val: string;
  _comp2ValueBS = new BehaviorSubject<string>('');

  constructor() {
    this.comp1Val;
    this.comp2Val;

    this._comp1ValueBS.next(this.comp1Val);
    this._comp2ValueBS.next(this.comp2Val);
  }

  updateComp1Val(val) {
    this.comp1Val = val;
    this._comp1ValueBS.next(this.comp1Val);
  }

  updateComp2Val(val) {
    this.comp2Val = val;
    this._comp2ValueBS.next(this.comp2Val);
  }
</code>```

And component1 as follows :

```<code>import { Injectable } from '@angular/core';
import { BehaviorSubject } from "rxjs/BehaviorSubject";

@Injectable()
export class SharedService {

  comp1Val: string;
  _comp1ValueBS = new BehaviorSubject<string>('');

  comp2Val: string;
  _comp2ValueBS = new BehaviorSubject<string>('');

  constructor() {
    this.comp1Val;
    this.comp2Val;

    this._comp1ValueBS.next(this.comp1Val);
    this._comp2ValueBS.next(this.comp2Val);
  }

  updateComp1Val(val) {
    this.comp1Val = val;
    this._comp1ValueBS.next(this.comp1Val);
  }

  updateComp2Val(val) {
    this.comp2Val = val;
    this._comp2ValueBS.next(this.comp2Val);
  }
</code>```

Component 2 :

```<code>import { Component, AfterContentChecked } from '@angular/core';
import { SharedService } from "../../common/shared.service";

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

  comp1Val: string;
  comp2Val: string;

  constructor(private sharedService: SharedService) {
    this.sharedService.comp2Val = "Component 2 initial value";
  }

  ngAfterContentChecked() {
    this.comp1Val = this.sharedService.comp1Val;
  }

  addValue(str) {
    this.sharedService.updateComp2Val(str);
  }

}
</code>```

You can find more on different types of subjects here

Body:
I defined a property here in my function

evs: string
...
openArticle(url){
    this.evs = url
    console.log(this.evs)
    this.navCtrl.navigateForward('/url-page')

  }

And I a trying to pass the value of 'this.evs' to another ts file and use its value but I do not know how to do this. I tried exporting it like this.

export const webpage = this.evs

but this.evs has no value until someone performs the openArticle function ad so I keep getting the error. "Cannot read property 'evs' of undefined"

What i need to do is tranfer the variable to the 'url-page' page and use the value of this.evs only after the openArticle function has bee called. How do I go about this?

Body:
If the components have a parent/child relationship, You can share data between them via @Inpput() and @Output() decorators.

Sharing data from Parent to Child using @Input() :

<h3>Parent Component</h3>

<label>Parent Component</label>c
<input type="number" [(ngModel)]='parentValue'/>

<p>Value of child component is: </p>
<app-child [value]='parentValue'></app-child>

And in the child component, the 'parentValue' can be received as :

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

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

  @Input() value: number;
  constructor() { }

  ngOnInit() {
  }

}

Now, in the case of sending data from Child to Parent, we can use an @Output() event emitter. So the parent would have a function to receive the emitted data from child as :

parent-app.component.html
    <app-child [value]="parentValue" (childEvent)="childEvent($event)"></app-child>

parent-app.component.ts

childEvent(event) {
console.log(event);
}

And, the child.component.ts would look like :

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

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

  @Input() PData: number;
  @Output() childEvent = new EventEmitter();
  constructor() { }
  onChange(value) {
    this.childEvent.emit(value);
  }

  ngOnInit() {
  }

}

If the components do not have a parent/child relationship, a shared service can be used, say, SharedService which has a BehavioralSubject, that emits value from either component, and the other component can then catch the changed value.

Eg:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from "rxjs/BehaviorSubject";

@Injectable()
export class SharedService {

  comp1Val: string;
  _comp1ValueBS = new BehaviorSubject<string>('');

  comp2Val: string;
  _comp2ValueBS = new BehaviorSubject<string>('');

  constructor() {
    this.comp1Val;
    this.comp2Val;

    this._comp1ValueBS.next(this.comp1Val);
    this._comp2ValueBS.next(this.comp2Val);
  }

  updateComp1Val(val) {
    this.comp1Val = val;
    this._comp1ValueBS.next(this.comp1Val);
  }

  updateComp2Val(val) {
    this.comp2Val = val;
    this._comp2ValueBS.next(this.comp2Val);
  }

And component1 as follows :

import { Injectable } from '@angular/core';
import { BehaviorSubject } from "rxjs/BehaviorSubject";

@Injectable()
export class SharedService {

  comp1Val: string;
  _comp1ValueBS = new BehaviorSubject<string>('');

  comp2Val: string;
  _comp2ValueBS = new BehaviorSubject<string>('');

  constructor() {
    this.comp1Val;
    this.comp2Val;

    this._comp1ValueBS.next(this.comp1Val);
    this._comp2ValueBS.next(this.comp2Val);
  }

  updateComp1Val(val) {
    this.comp1Val = val;
    this._comp1ValueBS.next(this.comp1Val);
  }

  updateComp2Val(val) {
    this.comp2Val = val;
    this._comp2ValueBS.next(this.comp2Val);
  }

Component 2 :

import { Component, AfterContentChecked } from '@angular/core';
import { SharedService } from "../../common/shared.service";

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

  comp1Val: string;
  comp2Val: string;

  constructor(private sharedService: SharedService) {
    this.sharedService.comp2Val = "Component 2 initial value";
  }

  ngAfterContentChecked() {
    this.comp1Val = this.sharedService.comp1Val;
  }

  addValue(str) {
    this.sharedService.updateComp2Val(str);
  }

}

You can find more on different types of subjects here


问:
ORA-24805:LOB type mismatch
Let there be table A(text_1 varchar2(4000 CHAR), text_2 varchar(4000 CHAR))
And here is the select for this:

```<code>SELECT sys.dbms_crypto.hash(empty_clob() || text_1 || text_2, 2)  from A;
</code>```

I am getting error 24805. I am expecting casting text_1 and text_2 to  CLOB , and connecting to each other. After that I need to get hash_code using function below. This code will also be part of PL/SQL block ( part of insert statement in function).
If I will use this:

```<code>SELECT sys.dbms_crypto.hash(to_clob('') || text_1 || text_2, 2)  from A;
</code>```

Everything is ok now. So, what was the problem?

```<code> create table A(text_1 varchar2(4000 CHAR), text_2 varchar2(4000 CHAR));
 insert into A(text_1,text_2)values ('test1','test2');
 commit;
</code>```

Here is an example of creating data for A.

答:
Please try below query,</p>

```<code>SELECT sys.dbms_crypto.hash(to_clob(text_1 || text_2), 2)  from A;
</code>```

Title: ORA-24805:LOB type mismatch

Body:
Let there be table A(text_1 varchar2(4000 CHAR), text_2 varchar(4000 CHAR))
And here is the select for this:

SELECT sys.dbms_crypto.hash(empty_clob() || text_1 || text_2, 2)  from A;

I am getting error 24805. I am expecting casting text_1 and text_2 to  CLOB , and connecting to each other. After that I need to get hash_code using function below. This code will also be part of PL/SQL block ( part of insert statement in function).
If I will use this:

SELECT sys.dbms_crypto.hash(to_clob('') || text_1 || text_2, 2)  from A;

Everything is ok now. So, what was the problem?

 create table A(text_1 varchar2(4000 CHAR), text_2 varchar2(4000 CHAR));
 insert into A(text_1,text_2)values ('test1','test2');
 commit;

Here is an example of creating data for A.

Body:
Please try below query,

SELECT sys.dbms_crypto.hash(to_clob(text_1 || text_2), 2)  from A;


问:
xvfb bind to localhost instead of *
I have an XVFB service running as service and it binds to * instead of localhost. For security purposes, it is not recommended and I can't find a way to bind it to localhost. Does anyone know how to make xvfb to bind to localhost? Thanks</p>

```<code># cat /etc/systemd/system/xvfb.service
[Unit]
Description=XVFB Server
After=network.target

[Install]
WantedBy=multi-user.target

[Service]
Type=simple

Restart=always
RestartSec=10

TimeoutSec=30

User=xvfb
Group=xvfb

ExecStart=/usr/bin/Xvfb -screen 0, 1024x768x16
</code>```

```<code># systemctl status xvfb
● xvfb.service - XVFB Server
   Loaded: loaded (/etc/systemd/system/xvfb.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2020-05-28 18:13:57 UTC; 1min 4s ago
 Main PID: 11395 (Xvfb)
   Memory: 4.3M
   CGroup: /system.slice/xvfb.service
           └─11395 /usr/bin/Xvfb -screen 0, 1024x768x16

May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension MIT-SCREEN-SAVER
May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension DOUBLE-BUFFER
May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension RECORD
May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension DPMS
May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension Present
May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension X-Resource
May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension XVideo
May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension XVideo-MotionCompensation
May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension SELinux
May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension GLX
</code>```

```<code># lsof -Pi | grep -i 'listen'
Xvfb      11395        xvfb    0u  IPv6 2029253      0t0  TCP *:6000 (LISTEN)
Xvfb      11395        xvfb    1u  IPv4 2029254      0t0  TCP *:6000 (LISTEN)
</code>```

答:
The safest solution is to just close all the ports like this:</p>

```<code>Xvfb :0 -nolisten tcp
</code>```

Title: xvfb bind to localhost instead of *

Body:
I have an XVFB service running as service and it binds to * instead of localhost. For security purposes, it is not recommended and I can't find a way to bind it to localhost. Does anyone know how to make xvfb to bind to localhost? Thanks

# cat /etc/systemd/system/xvfb.service
[Unit]
Description=XVFB Server
After=network.target

[Install]
WantedBy=multi-user.target

[Service]
Type=simple

Restart=always
RestartSec=10

TimeoutSec=30

User=xvfb
Group=xvfb

ExecStart=/usr/bin/Xvfb -screen 0, 1024x768x16

# systemctl status xvfb
● xvfb.service - XVFB Server
   Loaded: loaded (/etc/systemd/system/xvfb.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2020-05-28 18:13:57 UTC; 1min 4s ago
 Main PID: 11395 (Xvfb)
   Memory: 4.3M
   CGroup: /system.slice/xvfb.service
           └─11395 /usr/bin/Xvfb -screen 0, 1024x768x16

May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension MIT-SCREEN-SAVER
May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension DOUBLE-BUFFER
May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension RECORD
May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension DPMS
May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension Present
May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension X-Resource
May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension XVideo
May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension XVideo-MotionCompensation
May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension SELinux
May 28 18:13:57 ip-10-73-36-143.ec2.internal Xvfb[11395]: Initializing built-in extension GLX

# lsof -Pi | grep -i 'listen'
Xvfb      11395        xvfb    0u  IPv6 2029253      0t0  TCP *:6000 (LISTEN)
Xvfb      11395        xvfb    1u  IPv4 2029254      0t0  TCP *:6000 (LISTEN)

Body:
The safest solution is to just close all the ports like this:

Xvfb :0 -nolisten tcp


问:
How to access specific element in json and compare the values
I am new to json and coding. I want to read a json file and flag the value in "data" to check if the value is below 50 (in python). I do not know how to access specific values and convert them to int.

Below is my code and error:

```<code>input = '{"data": 47.8,"code": "ABB","ID": "03"}'

var = json.loads(input)

for row in var:
    if input["data"] < 50:
        print(input["data"])

Error:
TypeError: string indices must be integers.
</code>```

答:
Please try following code, type is already float hence no need to convert it again before doing math operation

import json

input = '{"data": 47.8,"code": "ABB","ID": "03"}'
var = json.loads(input)
print(type(var['data']))
if var['data'] < 50:
    print(var['data'])
else:
    print('No Data')

print('Executing completed')
```

Body:
I am new to json and coding. I want to read a json file and flag the value in "data" to check if the value is below 50 (in python). I do not know how to access specific values and convert them to int.

Below is my code and error:

input = '{"data": 47.8,"code": "ABB","ID": "03"}'

var = json.loads(input)

for row in var:
    if input["data"] < 50:
        print(input["data"])

Error:
TypeError: string indices must be integers.


问:
DocuSign Webhooks Connect key integration
We are using DocuSign rest api to create and send DocuSign envelope. We attached event notification to it and get information related to Envelope status in Webhooks. We use SOAP Interface (SOAP Method: DocuSignConnectUpdate). We want to implement HMAC security on webhooks received from DocuSign.

I have created Custom Connect Configuration on our Demo account for testing but not sure how to implement it on Webhooks listener. Webhooks I'm getting after changing setting still do not have HMAC header in it.

Can you please let us know how to implement it ?

Our Webhooks listener is developed using c#

Thanks,
Dishant

答:
This guide on the DocuSign Developer center has the information about using HMAC to secure your webhook calls.

Here is the C# snippet showing you how to validate the HMAC:

```<code>public static class HMAC
{
    public static string ComputeHash(string secret, string payload)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(secret);
        System.Security.Cryptography.HMAC hmac = new System.Security.Cryptography.HMACSHA256(bytes);
        bytes = Encoding.UTF8.GetBytes(payload);
        bytes = hmac.ComputeHash(bytes);
        return Convert.ToBase64String(bytes);
    }

    public static bool HashIsValid(string secret, string payload, string verify)
    {
        return ComputeHash(secret, payload).Equals(verify);
    }
}
</code>```

Body:
This guide on the DocuSign Developer center has the information about using HMAC to secure your webhook calls.

Here is the C# snippet showing you how to validate the HMAC:

public static class HMAC
{
    public static string ComputeHash(string secret, string payload)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(secret);
        System.Security.Cryptography.HMAC hmac = new System.Security.Cryptography.HMACSHA256(bytes);
        bytes = Encoding.UTF8.GetBytes(payload);
        bytes = hmac.ComputeHash(bytes);
        return Convert.ToBase64String(bytes);
    }

    public static bool HashIsValid(string secret, string payload, string verify)
    {
        return ComputeHash(secret, payload).Equals(verify);
    }
}


问:
FILE *tmp = tmpfile() always generates NULL pointer in C?
I have the following code:

```<code>char buffer[8];

int main(int argc, char *argv[]) {
    FILE *input, *output, *tempFile;
    input = fopen(argv[1], "rb");
    if (input == NULL) {
        printf("%s", strerror(2));
        exit(EXIT_FAILURE);
    }
    else {
        output = fopen(argv[2], "wb");
        if (output == NULL) {
            printf("%s", strerror(2));
            exit(EXIT_FAILURE);
        }
    }
    tempFile = tmpfile();
    for (int i = 0; i < 8; i++) {
        fputc(buffer[i], tempFile);
        fillBuffer(tempFile);
        printf("%s", buffer);
    }
    if (tempFile == NULL) {
        printf("Unable to create temp file");
        return 0;
    }
}
</code>```

Some things have been left out but I believe that this is the relevant portion. The buffer[] array is valid. If in the for loop I use

fputc(buffer[i], output);

The correct info gets stored in the output file. Whenever I run this program I get a bunch of null results followed by "Unable to create temp file". Advice?

答:
The tmpfile function is standard C and is supposed to create temporary files in some abstract way the program shouldn't have to care about. If these files even have locations (no need for them to) in the filesystem, the location should be one that's suitable for temporary files.

It seems the MSVC implementation of tmpfile is buggy and tries to put files in "C:\" for h{istor,yster}ical reasons. If you'll be building on MSVC you need to either use a different nonstandard function or drop in a replacement to fix the problem by first creating a file safely in a valid location for temp files, then calling fopen on it.

It might be possible to fix this by setting an environment variable, but if it's broken by default that's probably not a suitable fix for a program you want to deploy/ship.

Body:
I have the following code:

char buffer[8];

int main(int argc, char *argv[]) {
    FILE *input, *output, *tempFile;
    input = fopen(argv[1], "rb");
    if (input == NULL) {
        printf("%s", strerror(2));
        exit(EXIT_FAILURE);
    }
    else {
        output = fopen(argv[2], "wb");
        if (output == NULL) {
            printf("%s", strerror(2));
            exit(EXIT_FAILURE);
        }
    }
    tempFile = tmpfile();
    for (int i = 0; i < 8; i++) {
        fputc(buffer[i], tempFile);
        fillBuffer(tempFile);
        printf("%s", buffer);
    }
    if (tempFile == NULL) {
        printf("Unable to create temp file");
        return 0;
    }
}

Some things have been left out but I believe that this is the relevant portion. The buffer[] array is valid. If in the for loop I use

fputc(buffer[i], output);

The correct info gets stored in the output file. Whenever I run this program I get a bunch of null results followed by "Unable to create temp file". Advice?


问:
MongoDB can't run MacOS
```<code>Murats-Air:~ murat$ mongod
2020-05-26T14:28:14.858-0400 I  CONTROL  [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
2020-05-26T14:28:14.862-0400 W  ASIO     [main] No TransportLayer configured during NetworkInterface startup
2020-05-26T14:28:14.863-0400 I  CONTROL  [initandlisten] MongoDB starting : pid=706 port=27017 dbpath=/data/db 64-bit host=Murats-Air.home
2020-05-26T14:28:14.863-0400 I  CONTROL  [initandlisten] db version v4.2.7
2020-05-26T14:28:14.863-0400 I  CONTROL  [initandlisten] git version: 51d9fe12b5d19720e72dcd7db0f2f17dd9a19212
2020-05-26T14:28:14.863-0400 I  CONTROL  [initandlisten] allocator: system
2020-05-26T14:28:14.863-0400 I  CONTROL  [initandlisten] modules: none
2020-05-26T14:28:14.863-0400 I  CONTROL  [initandlisten] build environment:
2020-05-26T14:28:14.863-0400 I  CONTROL  [initandlisten]     distarch: x86_64
2020-05-26T14:28:14.863-0400 I  CONTROL  [initandlisten]     target_arch: x86_64
2020-05-26T14:28:14.863-0400 I  CONTROL  [initandlisten] options: {}
2020-05-26T14:28:14.864-0400 I  STORAGE  [initandlisten] exception in initAndListen: NonExistentPath: Data directory /data/db not found. Create the missing directory or specify another path using (1) the --dbpath command line option, or (2) by adding the 'storage.dbPath' option in the configuration file., terminating
2020-05-26T14:28:14.865-0400 I  NETWORK  [initandlisten] shutdown: going to close listening sockets...
2020-05-26T14:28:14.865-0400 I  -        [initandlisten] Stopping further Flow Control ticket acquisitions.
2020-05-26T14:28:14.865-0400 I  CONTROL  [initandlisten] now exiting
2020-05-26T14:28:14.865-0400 I  CONTROL  [initandlisten] shutting down with code:100
</code>```

I cannot solve the problem. I had tried to kill all processes mongod there was no running processes on mongod.

I tried to create /data/db directory but I got an error that 'it is for read-only'. Can anybody tell what is the problem here.

答:
I solved my problem by using a manual run method:

```<code>mongod --dbpath /usr/local/var/mongodb --logpath/usr/local/var/log/mongodb/mongo.log --fork
</code>```

every time I run with this code and then I use mongo

Title: MongoDB can't run MacOS

Body:
Murats-Air:~ murat$ mongod
2020-05-26T14:28:14.858-0400 I  CONTROL  [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
2020-05-26T14:28:14.862-0400 W  ASIO     [main] No TransportLayer configured during NetworkInterface startup
2020-05-26T14:28:14.863-0400 I  CONTROL  [initandlisten] MongoDB starting : pid=706 port=27017 dbpath=/data/db 64-bit host=Murats-Air.home
2020-05-26T14:28:14.863-0400 I  CONTROL  [initandlisten] db version v4.2.7
2020-05-26T14:28:14.863-0400 I  CONTROL  [initandlisten] git version: 51d9fe12b5d19720e72dcd7db0f2f17dd9a19212
2020-05-26T14:28:14.863-0400 I  CONTROL  [initandlisten] allocator: system
2020-05-26T14:28:14.863-0400 I  CONTROL  [initandlisten] modules: none
2020-05-26T14:28:14.863-0400 I  CONTROL  [initandlisten] build environment:
2020-05-26T14:28:14.863-0400 I  CONTROL  [initandlisten]     distarch: x86_64
2020-05-26T14:28:14.863-0400 I  CONTROL  [initandlisten]     target_arch: x86_64
2020-05-26T14:28:14.863-0400 I  CONTROL  [initandlisten] options: {}
2020-05-26T14:28:14.864-0400 I  STORAGE  [initandlisten] exception in initAndListen: NonExistentPath: Data directory /data/db not found. Create the missing directory or specify another path using (1) the --dbpath command line option, or (2) by adding the 'storage.dbPath' option in the configuration file., terminating
2020-05-26T14:28:14.865-0400 I  NETWORK  [initandlisten] shutdown: going to close listening sockets...
2020-05-26T14:28:14.865-0400 I  -        [initandlisten] Stopping further Flow Control ticket acquisitions.
2020-05-26T14:28:14.865-0400 I  CONTROL  [initandlisten] now exiting
2020-05-26T14:28:14.865-0400 I  CONTROL  [initandlisten] shutting down with code:100

I cannot solve the problem. I had tried to kill all processes mongod there was no running processes on mongod.

I tried to create /data/db directory but I got an error that 'it is for read-only'. Can anybody tell what is the problem here.

Body:
I solved my problem by using a manual run method:

mongod --dbpath /usr/local/var/mongodb --logpath/usr/local/var/log/mongodb/mongo.log --fork

every time I run with this code and then I use mongo


问:
Trying to export a panda DataFrame to CSV, but it denies permission
So, I'm triyng to export a data frame with data on the recent pandemic:

```<code>df = pd.DataFrame({
    'Giorno': time_period,
    'Infetti': infected,
    'Morti': dead,
    'Guariti': recovered})
</code>```

where time_period, infected, dead and recovered are lists. When I use the command

```<code>df.to_csv(r'D:\Python\COVID-19\COVID-19.py', header = df.keys(), index = None, sep = ' ', mode = 'a')
</code>```

this is the error it returns:

```<code>Traceback (most recent call last):
  File "D:\Coding\Python\COVID-19\COVID-19.py", line 96, in <module>
    df.to_csv(r'D:\Coding\Python\COVID-19', header = df.keys(), index = None, sep = ' ', mode = 'a')
  File "C:\Users\39351\AppData\Roaming\Python\Python37\site-packages\pandas\core\generic.py", line 3204, in to_csv
    formatter.save()
  File "C:\Users\39351\AppData\Roaming\Python\Python37\site-packages\pandas\io\formats\csvs.py", line 188, in save
    compression=dict(self.compression_args, method=self.compression),
  File "C:\Users\39351\AppData\Roaming\Python\Python37\site-packages\pandas\io\common.py", line 428, in get_handle
    f = open(path_or_buf, mode, encoding=encoding, newline="")
PermissionError: [Errno 13] Permission denied: 'D:\\Coding\\Python\\COVID-19'
</code>```

I have tried running the script from the command prompt (opened as admin) but it raises the exact same error. I've tried a test script that writes a fifteen times in a newly created text file, and the test script works fine editing the file when it already exists (done this just to see if Python creates new files in this folder) and everything is fine. Am I doing something wrong with the original code?

答:
Try typing any name in the pd.to_csv(), without incluing the full path of the file. That will save the file in the folder of the script. Also, make sure to include ".csv" at the end of that name.

If it works, you can either try the full path or a relative path.

Hope I could help.

Body:
So, I'm triyng to export a data frame with data on the recent pandemic:

df = pd.DataFrame({
    'Giorno': time_period,
    'Infetti': infected,
    'Morti': dead,
    'Guariti': recovered})

where time_period, infected, dead and recovered are lists. When I use the command

df.to_csv(r'D:\Python\COVID-19\COVID-19.py', header = df.keys(), index = None, sep = ' ', mode = 'a')

this is the error it returns:

Traceback (most recent call last):
  File "D:\Coding\Python\COVID-19\COVID-19.py", line 96, in <module>
    df.to_csv(r'D:\Coding\Python\COVID-19', header = df.keys(), index = None, sep = ' ', mode = 'a')
  File "C:\Users\39351\AppData\Roaming\Python\Python37\site-packages\pandas\core\generic.py", line 3204, in to_csv
    formatter.save()
  File "C:\Users\39351\AppData\Roaming\Python\Python37\site-packages\pandas\io\formats\csvs.py", line 188, in save
    compression=dict(self.compression_args, method=self.compression),
  File "C:\Users\39351\AppData\Roaming\Python\Python37\site-packages\pandas\io\common.py", line 428, in get_handle
    f = open(path_or_buf, mode, encoding=encoding, newline="")
PermissionError: [Errno 13] Permission denied: 'D:\\Coding\\Python\\COVID-19'

I have tried running the script from the command prompt (opened as admin) but it raises the exact same error. I've tried a test script that writes a fifteen times in a newly created text file, and the test script works fine editing the file when it already exists (done this just to see if Python creates new files in this folder) and everything is fine. Am I doing something wrong with the original code?


问:
How do i restrict Text Prompt validator delegate to be called every time whenever there is a prompt?
I have a waterfall Dialog with 6 steps , each of them have a Text prompt to gather user input.

Text prompt

```<code>self.add_dialog(TextPrompt(TextPrompt.__name__,ChoiceDialog.text_prompt_validator))
self.add_dialog(
        WaterfallDialog(
            WaterfallDialog.__name__,
            [
                self.project_step,     #TextPrompt
                self.description_step, #TextPrompt
                self.name_step,        #TextPrompt
                self.date_step,
                self.confirm_step,
                self.final_step,
            ],
        )
    )
</code>```

When the user enters a value the Validator is invoked and we have an opportunity to check/change the outcome.

But, i don't want the validator to be called every time there is a TextPrompt. Or Maybe call the validator delegate with different validations for each step.

Is there a way to achieve this?

答:
Just construct multiple text prompts.</p>

```<code>self.add_dialog(TextPrompt("prompt:project", ChoiceDialog.project_validator))
self.add_dialog(TextPrompt("prompt:description", ChoiceDialog.description_validator))
self.add_dialog(TextPrompt("prompt:name", ChoiceDialog.name_validator))
</code>```

Body:
I have a waterfall Dialog with 6 steps , each of them have a Text prompt to gather user input.

Text prompt

self.add_dialog(TextPrompt(TextPrompt.__name__,ChoiceDialog.text_prompt_validator))
self.add_dialog(
        WaterfallDialog(
            WaterfallDialog.__name__,
            [
                self.project_step,     #TextPrompt
                self.description_step, #TextPrompt
                self.name_step,        #TextPrompt
                self.date_step,
                self.confirm_step,
                self.final_step,
            ],
        )
    )

When the user enters a value the Validator is invoked and we have an opportunity to check/change the outcome.

But, i don't want the validator to be called every time there is a TextPrompt. Or Maybe call the validator delegate with different validations for each step.

Is there a way to achieve this?

Body:
Just construct multiple text prompts.

self.add_dialog(TextPrompt("prompt:project", ChoiceDialog.project_validator))
self.add_dialog(TextPrompt("prompt:description", ChoiceDialog.description_validator))
self.add_dialog(TextPrompt("prompt:name", ChoiceDialog.name_validator))


问:
only getting a few attributes from HTML code and not all of them using Beautifulsoup Python
```<code>    names = []

for code in soup.find_all('li'):
    a_tag = code.find("a")
    if a_tag is not None and 'title' in a_tag.attrs:
        l = a_tag.get('title')
        names.append(l)
        time.sleep(1)
print(names)
</code>```

When I run the script, it returns only a few names (e.g. title attributes) out of 30 or so and all tags contain the title attribute.
Thank you!

Here's the html code for the one that worked:

```<code> <li class="wo9IH">
   <div class="uu6c_">
      <div class="t2ksc">
         <div class="RR-M- h5uC0 SAvC5" role="button" tabindex="0">
            <canvas class="CfWVH" height="40" width="40" style="position: absolute; top: -5px; left: -5px; width: 40px; height: 40px;"></canvas>
            <span class="_2dbep " role="link" tabindex="0" style="width: 30px; height: 30px;"><img alt="damla_dx's profile picture" class="_6q-tv" src="https://scontent-hbe1-1.cdninstagram.com/v/t51.2885-19/s150x150/100947324_584513555780923_3392957389983449088_n.jpg?_nc_ht=scontent-hbe1-1.cdninstagram.com&_nc_ohc=cpbHm-9Tg24AX-Y5ZTo&oh=523572e76dc634c387c1bce8f5ee24fd&oe=5EF8F269"></span>
         </div>
         <div class="enpQJ">
            <div class="d7ByH"><a class="FPmhX notranslate  _0imsa " title="damla_dx" href="/damla_dx/">damla_dx</a></div>
            <div class="wFPL8 "></div>
         </div>
      </div>
      <div class="Pkbci"><button class="sqdOP  L3NKy   y3zKF     " type="button">Follow</button></div>
   </div>
</li>
</code>```

and here's the code for the one that didn't:

```<code><li class="wo9IH">
   <div class="uu6c_">
      <div class="t2ksc">
         <div class="RR-M-  SAvC5" role="button" tabindex="0">
            <canvas class="CfWVH" height="40" width="40" style="position: absolute; top: -5px; left: -5px; width: 40px; height: 40px;"></canvas>
            <a class="_2dbep qNELH kIKUG" href="/connie_mario/" style="width: 30px; height: 30px;"><img alt="connie_mario's profile picture" class="_6q-tv" src="https://scontent-hbe1-1.cdninstagram.com/v/t51.2885-19/s150x150/25016555_1962725540720404_7523275851970904064_n.jpg?_nc_ht=scontent-hbe1-1.cdninstagram.com&_nc_ohc=AvK0clN2PSMAX-detNw&oh=6184a0c465a9bfcd04617d134cde4fe9&oe=5EFA793D"></a>
         </div>
         <div class="enpQJ">
            <div class="d7ByH"><a class="FPmhX notranslate  _0imsa " title="connie_mario" href="/connie_mario/">connie_mario</a></div>
            <div class="wFPL8 ">Connie_ Mario</div>
         </div>
      </div>
      <div class="Pkbci"><button class="sqdOP  L3NKy   y3zKF     " type="button">Follow</button></div>
   </div>
</li>
</code>```

答:
You can do something simpler with css selctors:

```<code>for artist in code.select('a[title]'):
    print(artist.text)
</code>```

For the two snippets in your question, the output should be:

```<code>connie_mario
damla_dx
</code>```

Body:
    names = []

for code in soup.find_all('li'):
    a_tag = code.find("a")
    if a_tag is not None and 'title' in a_tag.attrs:
        l = a_tag.get('title')
        names.append(l)
        time.sleep(1)
print(names)

When I run the script, it returns only a few names (e.g. title attributes) out of 30 or so and all tags contain the title attribute.
Thank you!

Here's the html code for the one that worked:

            <canvas class="CfWVH" height="40" width="40" style="position: absolute; top: -5px; left: -5px; width: 40px; height: 40px;"></canvas>

damla_dx

<button class="sqdOP  L3NKy   y3zKF     " type="button">Follow</button>

and here's the code for the one that didn't:

            <canvas class="CfWVH" height="40" width="40" style="position: absolute; top: -5px; left: -5px; width: 40px; height: 40px;"></canvas>

connie_mario

Connie_ Mario

<button class="sqdOP  L3NKy   y3zKF     " type="button">Follow</button>

Body:
You can do something simpler with css selctors:

for artist in code.select('a[title]'):
    print(artist.text)

For the two snippets in your question, the output should be:

connie_mario
damla_dx


问:
Assign route to a button
Hey guys i need to implement a button that will have a route assigned, i am writing on top of the existed code so I am a bit lost, there is a private route component wrapped in Switch component. How to i assign a route to my buttons onClick

```<code><Switch>

   <PrivateRoute exact path="/settings" component={Settings}/>
   <PrivateRoute exact path="/admin" component={AdminButton}/>
</code>```

The Private Route consist of the following

```<code>@inject('auth')
@observer
class PrivateRoute extends Component {

  render() {
    const {auth, component, ...rest} = this.props;
    const RouteComponent = component;
    const {authenticated, authenticating} = auth;
    return (
       <Route
          {...rest}
          render={props =>
             (authenticated || authenticating) ? (
                <RouteComponent {...props} />
             ) : (
                <Redirect to="/login" />
             )
          }
       />
</code>```

AdminButton component that needs to receive something to onClick i guess

```<code>export default class AdminButton extends React.Component {
    render() {
        return <QuestionButtonStyled onclick={}>Admin Panel</QuestionButtonStyled>
    }
}
</code>```

App.jsx

```<code> <DashboardLayout>
                            {this.props.auth.authenticated && <EpMenu/> }
                            <div style={{marginTop: '20px'}}>
                                <Switch>
                                    <Route exact path="/login/:token?" component={LoginPage}/>
                                    <PrivateRoute exact path="/welcome" component={Welcome}/>
                                    <PrivateRoute exact path="/monthly-payslip" component={MonthlyPayslip}/>
                                    <PrivateRoute exact path="/yearly-tax-overview" component={YearlyTaxStatementOverview}/>
                                    <PrivateRoute exact path="/social-security-documents" component={SocialSecurityDocuments}/>
                                    <PrivateRoute exact path="/central-information-documents" component={CentralDocuments}/>
                                    <PrivateRoute exact path="/settings" component={Settings}/>
                                    <PrivateRoute exact path="/admin" component={AdminButton}/>
                                    <Redirect from="/*" to="/login"/>
                                </Switch>
                            </div>
                        </DashboardLayout>
</code>```

答:
Since you want to change the route on onClick event, you can make use of history from props and pass on the new path like

```<code>export default class AdminButton extends React.Component {
    handleClick=() => {
       this.props.history.push('/settings');
    }
    render() {
        return <QuestionButtonStyled onClick={this.handleClick}>Admin Panel</QuestionButtonStyled>
    }
}
</code>```

Title: Assign route to a button

Body:
Hey guys i need to implement a button that will have a route assigned, i am writing on top of the existed code so I am a bit lost, there is a private route component wrapped in Switch component. How to i assign a route to my buttons onClick

<Switch>

   <PrivateRoute exact path="/settings" component={Settings}/>
   <PrivateRoute exact path="/admin" component={AdminButton}/>

The Private Route consist of the following

@inject('auth')
@observer
class PrivateRoute extends Component {

  render() {
    const {auth, component, ...rest} = this.props;
    const RouteComponent = component;
    const {authenticated, authenticating} = auth;
    return (
       <Route
          {...rest}
          render={props =>
             (authenticated || authenticating) ? (
                <RouteComponent {...props} />
             ) : (
                <Redirect to="/login" />
             )
          }
       />

AdminButton component that needs to receive something to onClick i guess

export default class AdminButton extends React.Component {
    render() {
        return <QuestionButtonStyled onclick={}>Admin Panel</QuestionButtonStyled>
    }
}

App.jsx

 <DashboardLayout>
                            {this.props.auth.authenticated && <EpMenu/> }

                                <Switch>
                                    <Route exact path="/login/:token?" component={LoginPage}/>
                                    <PrivateRoute exact path="/welcome" component={Welcome}/>
                                    <PrivateRoute exact path="/monthly-payslip" component={MonthlyPayslip}/>
                                    <PrivateRoute exact path="/yearly-tax-overview" component={YearlyTaxStatementOverview}/>
                                    <PrivateRoute exact path="/social-security-documents" component={SocialSecurityDocuments}/>
                                    <PrivateRoute exact path="/central-information-documents" component={CentralDocuments}/>
                                    <PrivateRoute exact path="/settings" component={Settings}/>
                                    <PrivateRoute exact path="/admin" component={AdminButton}/>
                                    <Redirect from="/*" to="/login"/>
                                </Switch>

                        </DashboardLayout>

Body:
Since you want to change the route on onClick event, you can make use of history from props and pass on the new path like

export default class AdminButton extends React.Component {
    handleClick=() => {
       this.props.history.push('/settings');
    }
    render() {
        return <QuestionButtonStyled onClick={this.handleClick}>Admin Panel</QuestionButtonStyled>
    }
}


问:
Flutter BLoC pattern - How can I navigate to another screen after a stream event?
My question is about navigation used with the BLoC pattern.

In my LoginScreen widget I have a button that adds an event into the EventSink of the bloc. The bloc calls the API and authenticates the user.
Where in the LoginScreen Widget do I have to listen to the stream, and how do I navigate to another screen after it returns a success status?

答:
First of all: if there isn't any business logic, then there isn't any need to go to YourBloc class.

But from time to time some user's activity is required to perform some logic in Bloc class and then the Bloc class has to decide what to do next: just rebuild widgets or show dialog or even navigate to next route. In such a case, you have to send some State to UI to finish the action.

Then another problem appears: what shall I do with widgets when Bloc sends State to show a toast?

And this is the main issue with all of this story.

A lot of answers and articles recommend to use flutter_block. This library has BlocBuilder and BlocListener. With those classes you can solve some issues, but not 100% of them.

In my case I used BlocConsumer which manages BlocBuilder and BlocListener and provides a brilliant way to manage states.

From the documentation:

```<code>BlocConsumer<BlocA, BlocAState>(
  listenWhen: (previous, current) {
    // Return true/false to determine whether or not
    // to invoke listener with state
  },
  listener: (context, state) {
    // Do stuff here based on BlocA's state
  },
  buildWhen: (previous, current) {
    // Return true/false to determine whether or not
    // to rebuild the widget with state
  },
  builder: (context, state) {
    // Return widget here based on BlocA's state
  }
)
</code>```

As you can see with BlocConsumer, you can filter states: you can easily define states to rebuild widgets and states to show some popups or navigate to the next screen.

Body:
First of all: if there isn't any business logic, then there isn't any need to go to YourBloc class.

But from time to time some user's activity is required to perform some logic in Bloc class and then the Bloc class has to decide what to do next: just rebuild widgets or show dialog or even navigate to next route. In such a case, you have to send some State to UI to finish the action.

Then another problem appears: what shall I do with widgets when Bloc sends State to show a toast?

And this is the main issue with all of this story.

A lot of answers and articles recommend to use flutter_block. This library has BlocBuilder and BlocListener. With those classes you can solve some issues, but not 100% of them.

In my case I used BlocConsumer which manages BlocBuilder and BlocListener and provides a brilliant way to manage states.

From the documentation:

BlocConsumer<BlocA, BlocAState>(
  listenWhen: (previous, current) {
    // Return true/false to determine whether or not
    // to invoke listener with state
  },
  listener: (context, state) {
    // Do stuff here based on BlocA's state
  },
  buildWhen: (previous, current) {
    // Return true/false to determine whether or not
    // to rebuild the widget with state
  },
  builder: (context, state) {
    // Return widget here based on BlocA's state
  }
)

As you can see with BlocConsumer, you can filter states: you can easily define states to rebuild widgets and states to show some popups or navigate to the next screen.


问:
Is it possible to select workers for specific tasks in Dask?
I have a process I'm running on my Kubernetes cluster with Dask that consists of two map-reduce phases, but both maps across the nodes download potentially numerous large files to each worker. In order to avoid having two different machines process the same subset of files on the two different map steps, is it possible to deterministically select which workers get which arguments for the same jobs? Conceptually, what I want might be something like:

workers : List = client.get_workers();
#                       ^^^^^^^^^^^
filenames : List[str] = get_filenames(); # input data to process

# map each file to a specific worker
file_to_worker = { filename : workers[hash(filename) % len(workers)] for filename in filenames }

# submit each file, specifying which worker should be assigned the task
futures = [client.submit(my_func, filename, worker=file_to_worker[filename]) for filename in filenames]
#                                           ^^^^^^
```

Something like this would allow me to direct different steps of computation for the same files to the same nodes, eliminating any need to do a second caching of files.

答:
yes, you can submit functions to specific workers:

c.run(func, workers=[WorkerA, WorkerB, WorkerC])

You can also attach metadata resources to workers and submit with those definition instead of the specific hostnames:

data = [client.submit(load, fn) for fn in filenames]
processed = [client.submit(process, d, resources={'GPU': 1}) for d in data]
final = client.submit(aggregate, processed, resources={'MEMORY': 70e9})
```

For setup info look at the resource docs

Body:
I have a process I'm running on my Kubernetes cluster with Dask that consists of two map-reduce phases, but both maps across the nodes download potentially numerous large files to each worker. In order to avoid having two different machines process the same subset of files on the two different map steps, is it possible to deterministically select which workers get which arguments for the same jobs? Conceptually, what I want might be something like:

workers : List = client.get_workers();
#                       ^^^^^^^^^^^
filenames : List[str] = get_filenames(); # input data to process

# map each file to a specific worker
file_to_worker = { filename : workers[hash(filename) % len(workers)] for filename in filenames }

# submit each file, specifying which worker should be assigned the task
futures = [client.submit(my_func, filename, worker=file_to_worker[filename]) for filename in filenames]
#                                           ^^^^^^

Something like this would allow me to direct different steps of computation for the same files to the same nodes, eliminating any need to do a second caching of files.

Body:
yes, you can submit functions to specific workers:

c.run(func, workers=[WorkerA, WorkerB, WorkerC])

You can also attach metadata resources to workers and submit with those definition instead of the specific hostnames:

data = [client.submit(load, fn) for fn in filenames]
processed = [client.submit(process, d, resources={'GPU': 1}) for d in data]
final = client.submit(aggregate, processed, resources={'MEMORY': 70e9})

For setup info look at the resource docs


问:
Kubeflow setup on baremetal setup?
Have been trying to setup Kubeflow on bare metal (on prem etc) on a shared server i.e. not my laptop. I followed the Kubeflow Deployment with kfctl_k8s_istio setup instructions which all well.

Under "Access Kubeflow Dashboard" it says

Refer Ingress Gateway guide.

which just leads to more questions I don't know the answer to coz i didn't write the setup i.e.

What is the ingress port for the UI? kubectl get svc istio-ingressgateway -n istio-system returns a hug list??

What do i do if the external IP is <none>? The server has an IP on the local network i.e. 192.168.1.69

I'm assuming kfctl didn't setup an external load balancer?

Whats the container that hosts the web UI? What should the Gateway and VirtualService yaml look like?

I want to use Kubeflow and have to learn how Istio works? Why?

答:
If you still want to give Kubeflow a chance here is how I got it up and running. I am running MicroK8s 1.18.2 + Kubeflow on Ubuntu 18.04.3 LTS natively (not in a VM environment).

My installation routine:

```<code>> # Install MicroK8s
> $ sudo snap install microk8s --classic --channel=1.18/stable

> # Set IP forwarding
> $ sudo apt-get update -qq
> $ sudo apt-get install -qq -y iptables-persistent
> $ sudo iptables -P FORWARD ACCEPT

> # Add xip.io adress to hosts
> $ sudo -- sh -c "echo '10.64.140.43\t10.64.140.43.xip.io' >>
> /etc/hosts"

> # Check if MicroK8s is Running
> $ microk8s status --wait-ready | grep microk8s
> $ microk8s kubectl get nodes
> $ microk8s kubectl get services

> # Set kubectl alias for MicroK8s
> $ sudo snap alias microk8s.kubectl kubectl

> # Activate MicroK8s Add-ons (DNS, Storage, K8s-Dashboard)
> $ microk8s.enable dns storage dashboard

> # (OPTIONAL) Activate GPU Devices for Nvidia GPUs
> $ microk8s.enable gpu

> # Activate Kubeflow
> $ microk8s.enable kubeflow

> # Check if MicroK8s Add-ons are Running
> $ microk8s status --wait-ready
</code>```

Depending on your hardware and internet connection, it might take some time until all services are ready. If all services are up, simply open http://10.64.140.43.xip.io in your browser and enter the user (admin) and your generated password.

Title: Kubeflow setup on baremetal setup?

Body:
If you still want to give Kubeflow a chance here is how I got it up and running. I am running MicroK8s 1.18.2 + Kubeflow on Ubuntu 18.04.3 LTS natively (not in a VM environment).

My installation routine:

> # Install MicroK8s
> $ sudo snap install microk8s --classic --channel=1.18/stable

> # Set IP forwarding
> $ sudo apt-get update -qq
> $ sudo apt-get install -qq -y iptables-persistent
> $ sudo iptables -P FORWARD ACCEPT

> # Add xip.io adress to hosts
> $ sudo -- sh -c "echo '10.64.140.43\t10.64.140.43.xip.io' >>
> /etc/hosts"

> # Check if MicroK8s is Running
> $ microk8s status --wait-ready | grep microk8s
> $ microk8s kubectl get nodes
> $ microk8s kubectl get services

> # Set kubectl alias for MicroK8s
> $ sudo snap alias microk8s.kubectl kubectl

> # Activate MicroK8s Add-ons (DNS, Storage, K8s-Dashboard)
> $ microk8s.enable dns storage dashboard

> # (OPTIONAL) Activate GPU Devices for Nvidia GPUs
> $ microk8s.enable gpu

> # Activate Kubeflow
> $ microk8s.enable kubeflow

> # Check if MicroK8s Add-ons are Running
> $ microk8s status --wait-ready

Depending on your hardware and internet connection, it might take some time until all services are ready. If all services are up, simply open http://10.64.140.43.xip.io in your browser and enter the user (admin) and your generated password.


问:
int array[10] = {1 , 2, 0, 3} . How can I find out that there are 4 elements here? I know how to find the size of array
I tried this code..As you can see the problem is the empty elements are zero. So, I tried to check with it but the thing is I can have 0 as an element. </p>

```<code>
int main()
{
    int array[10] = {1, 2, 0, 3, 4};

    printf("%d\n", sizeof(array)/ sizeof(*array)); // This is the size of array

    int i = 0;

    while(array[i] != 0  && i < 10) {
        i++;
    };

    printf("%d\n", i);

    return 0;
}```
</code>```

答:
First set the array to a number outside the range of your inputs. Like a negative number.

```<code>for(i = 0;i < 10;i++)
    array[i] = -1;
</code>```

or set it to INT_MAX or INT_MIN

Body:
I tried this code..As you can see the problem is the empty elements are zero. So, I tried to check with it but the thing is I can have 0 as an element.

int main()
{
    int array[10] = {1, 2, 0, 3, 4};

    printf("%d\n", sizeof(array)/ sizeof(*array)); // This is the size of array

    int i = 0;

    while(array[i] != 0  && i < 10) {
        i++;
    };

    printf("%d\n", i);

    return 0;
}```

Body:
First set the array to a number outside the range of your inputs. Like a negative number.

for(i = 0;i < 10;i++)
    array[i] = -1;

or set it to INT_MAX or INT_MIN


问:
Face Detection using Google Glass Enterprise Edition 2
Is OpenCV the most readily available way to get Face Detection working for offline, on-device use case with Google Glass Enterprise Edition 2?

I see three Google-provided libraries, ML Kit, ARCore and, Android-built-in Camera API's face detection, support offline face detection. However, they all seem they won't work for following reasons.

(1) ML Kit doesn't work since it requires Play Services
G. Glass EE 2 only ships with vanilla Android Oreo 8.0

Glass Tech Specs noting Android Oreo - https://www.google.com/glass/tech-specs/

MLKit requirements noting Play Services - https://firebase.google.com/docs/android/setup

(2) AR Core doesn't work because of the same reason, i.e. Play Services
ARCore requirements noting Play Services - https://developers.google.com/ar/discover/supported-devices#android_play

(3) Built-in Camera API for Face Detcetion is Accepted as not working as well
https://code.google.com/archive/p/google-glass-api/issues/282

答:
It looks like OpenCV may not be a good option after all since it's likely too slow on the CPU, and, hasn't been tested on GPU for the Snapdragon XR1 SoC that Google Glass EE2 relies on.
Reference: https://developer.qualcomm.com/forum/qdn-forums/software/fastcv-computer-vision-sdk/35734</p>


问:
Change button text Stripe Checkout?
is it possible to change button text in the strip checkout page?

Image

答:
Yes it's possible to partially customize the Checkout button text, but it depends on which mode of Checkout you're using:

In Checkout's subscription mode the button text is fixed to Subscribe.

If in subscription mode and the subscription has a trial the text is fixed to Start trial unless there is also a setup fee in which case it will be Pay {amount} and start trial.

In setup mode the button text is also fixed, and will equal Save card.

In payment mode the button text depends on the submit_type, for which there are three options:

pay: the submit button text will be Pay.

donate: the submit button text will be Donate.

book: the submit button text will be Book for.

It's not currently possible to enter in a custom string or customize the text beyond these options.

Title: Change button text Stripe Checkout?


问:
How can i access and change value of string variable which is declared in another class in FLUTTER/DART
basically i want to store name as sting in a seperate class and want to access that Sting name from any class of my project , Also i want to read and update the Sting name from any other class.</p>

答: This is not the way it's done in Flutter. You should have 'state' which is accessible in some way from all the widgets that are interested in reading and/or setting its value. When the value is set, it should produce a 'change' event that other widgets can react to. Read about state management and its various incarnations, like 'lifting state up', InheritedWidget, ValueListenable and the provider package.


问:
Generate Form from exist Entity Symfony4
I have a table in the database which has a large number of columns. I know that  EasyAdminBundle is out there and I used it in the past to create forms based on database tables. How can create this based on Entity? So that I can generate the forms automatically and no populate them manually.</p>

答:
As symfony 4.4 you can do :

./bin/console make:entity YourFormType \\Your\\Path\\To\\Entity

From the command help :

Description:
  Creates a new form class

Usage:

```<code>make:form [ <name> [<bound-class>]]
</code>```

Body:
As symfony 4.4 you can do :

./bin/console make:entity YourFormType \\Your\\Path\\To\\Entity

From the command help :

Description:
  Creates a new form class

Usage:

make:form [ <name> [<bound-class>]]


问:
Boostrap container overflow and not responsive (always displayed two columns)
I have created a form with two columns. But when I decrease the browser width, two columns are preserved even when their content overflows. I have tried to change the code to plain DIV with container class, specify cols count, set width but it resists.

Here is the codepen: https://codesandbox.io/s/stoic-goldberg-4ugt6

and the source code of the parent container:

```<code><div class="container flex-wrap pt-3 w-75 ml-auto mr-auto mt-auto mb-5">
  <div class="row">
    <div class="col">
      <b-card>
        <SeriesForm />
      </b-card>
    </div>
    <div class="col">
      <b-card :header="captions[1]">
        <SeriesForm :group="forms[1]" />
      </b-card>
    </div>
  </div>
  <div class="row">
    <div class="col text-center p-4">
      <b-button>Analyse</b-button>
    </div>
  </div>
</div>
</code>```

How can I make it two columns when there is enough space and single column otherwise?

答:
U can try class like col-sm-6 or col-xs-6 or col-md-6 or col-lg-6 according to your need.

```<code><div class="container flex-wrap pt-3 w-75 ml-auto mr-auto mt-auto mb-5">
  <div class="row">
    <div class="col-sm-6">
      <b-card>
        <SeriesForm />
      </b-card>
    </div>
    <div class="col-sm-6">
      <b-card :header="captions[1]">
        <SeriesForm :group="forms[1]" />
      </b-card>
    </div>
  </div>
  <div class="row">
    <div class="col text-center p-4">
      <b-button>Analyse</b-button>
    </div>
  </div>
</div>
</code>```

Body:
I have created a form with two columns. But when I decrease the browser width, two columns are preserved even when their content overflows. I have tried to change the code to plain DIV with container class, specify cols count, set width but it resists.

Here is the codepen: https://codesandbox.io/s/stoic-goldberg-4ugt6

and the source code of the parent container:

        <SeriesForm />

        <SeriesForm :group="forms[1]" />

      Analyse

How can I make it two columns when there is enough space and single column otherwise?

Body:
U can try class like col-sm-6 or col-xs-6 or col-md-6 or col-lg-6 according to your need.

<div class="container flex-wrap pt-3 w-75 ml-auto mr-auto mt-auto mb-5">
  <div class="row">
    <div class="col-sm-6">
      <b-card>
        <SeriesForm />
      </b-card>
    </div>
    <div class="col-sm-6">
      <b-card :header="captions[1]">
        <SeriesForm :group="forms[1]" />
      </b-card>
    </div>
  </div>
  <div class="row">
    <div class="col text-center p-4">
      <b-button>Analyse</b-button>
    </div>
  </div>
</div>


问:
Why does it not see the integer even though they are in the same class?
```<code>public class MainActivity extends AppCompatActivity {

    int loop = 1;
    int points = 0;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    for(loop == 1);{//the error is here

    }
    public void click(){
        points++;
    }

}
</code>```

it doesnt see loop(int) and I don`t know why.

I am trying to make a clicker game, so more tips would be really appreciated.

答:
You are writing your code outside the onCreate method. The code must either be within the onCreate() or inside another function.

```<code>public class MainActivity extends AppCompatActivity {

int loop = 1;
int points = 0;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    for(loop == 1){
        //write your code here
    }
}

public void click(){
    points++;
}
</code>```

}

Body:
public class MainActivity extends AppCompatActivity {

    int loop = 1;
    int points = 0;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    for(loop == 1);{//the error is here

    }
    public void click(){
        points++;
    }

}

it doesnt see loop(int) and I don`t know why.

I am trying to make a clicker game, so more tips would be really appreciated.

Body:
You are writing your code outside the onCreate method. The code must either be within the onCreate() or inside another function.

public class MainActivity extends AppCompatActivity {

int loop = 1;
int points = 0;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    for(loop == 1){
        //write your code here
    }
}

public void click(){
    points++;
}

}


问:
How do I make my own directory in QT QML?
I'm trying to make a directory of a singleton QML File "All.qml" which I can import anywhere else into my project so that I can access its objects (namely the drawer). I made a qmldir file, in the same folder as the "All.qml", and even add the directory to the .qrc file.
The contents of the directory is as follows:

```<code>Module App.Drawer

singleton All  1.0 All.qml
</code>```

But when I type in

```<code>import App.Drawer.   1.0
</code>```

It says "module 'App.Drawer' not installed". I can't find any other way to access that drawer, as the project is huge with multiple folders and directories. Can anyone help me?

Also, this project has C++ integrated with it. I tried going and finding some file where maybe the other directories (there are other custom directories, which were made beforehand) have been installed, but couldn't find any.

答:
You have to make sure that QEngine can find the qmldir file, and it has some specific requirements on where it will look.

First to make QEngine aware of the qmldir file you have to add an import path:

```<code>engine.addImportPath("qrc:/");
</code>```

Your path may vary, read on:

The qmldir file has to placed in the folder structure dictated by module name. In your case it is <rootPath>/App/Drawer/qmldir. The "rootPath" is unknown to me, but let's assume you have the following in your qrc file:

```<code><RCC>
    <qresource prefix="/ProjectX/App/Drawer">
        <file>Drawer.qml</file>
        <file>qmldir</file>
    </qresource>
</RCC>
</code>```

Then "rootPath" is qrc:/ProjectX and the import call becomes:

```<code>engine.addImportPath("qrc:/ProjectX");
</code>```

Also, the module declaration in qmldir should be the same as the folder structure where the qmldir file is placed. (And I think it should be lowercase)

```<code>module App.Drawer

singleton Drawer 1.0 Drawer.qml
</code>```

If you want Qt Creator to also find the stuff you can use the QML2_IMPORT_PATH environment variable and set it to the correct folder using the same logic.

You can also place the files in the <Qt_installation_folder>/qml/App/Drawer but this means every project can use it and you have to keep it up-to-date during development, which might be overdone.

Edit

To see if your files are lined up correctly, you can add this debug code:

```<code>QDirIterator it(":", QDirIterator::Subdirectories);
while (it.hasNext()) {
    qDebug() << it.next();
}
</code>```

Body:
I'm trying to make a directory of a singleton QML File "All.qml" which I can import anywhere else into my project so that I can access its objects (namely the drawer). I made a qmldir file, in the same folder as the "All.qml", and even add the directory to the .qrc file.
The contents of the directory is as follows:

Module App.Drawer

singleton All  1.0 All.qml

But when I type in

import App.Drawer.   1.0

It says "module 'App.Drawer' not installed". I can't find any other way to access that drawer, as the project is huge with multiple folders and directories. Can anyone help me?

Also, this project has C++ integrated with it. I tried going and finding some file where maybe the other directories (there are other custom directories, which were made beforehand) have been installed, but couldn't find any.

Body:
You have to make sure that QEngine can find the qmldir file, and it has some specific requirements on where it will look.

First to make QEngine aware of the qmldir file you have to add an import path:

engine.addImportPath("qrc:/");

Your path may vary, read on:

The qmldir file has to placed in the folder structure dictated by module name. In your case it is <rootPath>/App/Drawer/qmldir. The "rootPath" is unknown to me, but let's assume you have the following in your qrc file:

<RCC>
    <qresource prefix="/ProjectX/App/Drawer">
        <file>Drawer.qml</file>
        <file>qmldir</file>
    </qresource>
</RCC>

Then "rootPath" is qrc:/ProjectX and the import call becomes:

engine.addImportPath("qrc:/ProjectX");

Also, the module declaration in qmldir should be the same as the folder structure where the qmldir file is placed. (And I think it should be lowercase)

module App.Drawer

singleton Drawer 1.0 Drawer.qml

If you want Qt Creator to also find the stuff you can use the QML2_IMPORT_PATH environment variable and set it to the correct folder using the same logic.

You can also place the files in the <Qt_installation_folder>/qml/App/Drawer but this means every project can use it and you have to keep it up-to-date during development, which might be overdone.

Edit

To see if your files are lined up correctly, you can add this debug code:

QDirIterator it(":", QDirIterator::Subdirectories);
while (it.hasNext()) {
    qDebug() << it.next();
}


问:
Javascript. How can I access a variable outside of a function?
I'm trying to create a simple application that generates a random question with an onclick, and will generate a solution to said question with a different onclick.  I've been able to create the random question function simple enough, but what I'm having trouble with is the solution part.  Essentially I cant access the variables produced from the "generate question" function.

The following function generates a random question: "Convert 10mg/mL to mcg/mL"

```<code>const arr = ['mg/mL', 'mcg/mL', 'mg/L'];

function genConversion () {
  function clearBox(elementID){ //this resets the question
      document.getElementById(elementID).innerHTML = "";
  }

  clearBox('output');

  function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
  }

   function randomNum() {
    var number = Math.floor((Math.random() * 100) +1);
    return number
  }

  var num = randomNum()

  shuffle(arr);

  output.innerHTML += "Convert " + num + ' ' + arr[0] + ' to ' + arr[1]

}
</code>```

Now, when I try to create a function that will solve the generated problem (the actual logic will come once I can figure out how to access the question variables), I cant seem to access variable 'num'.  Interestingly, I am able to access the random array element arr[0].

```<code>function solveProb() {
  console.log(arr[0]);
  console.log(num);
}
</code>```

Im sure this has something to do with scope that Im having trouble with, but any advice would be appreciated.

答:
You don't actually want to access a variable outside a function. You're already thinking in functions, so you may benefit from my library, rubico. Here's your code in a functional, uni-directional data flow style. Also, use let and const instead of var to avoid unpredictable scope-related behavior.

import { pipe, fork } from 'https://deno.land/x/rubico/rubico.js'
// if you're in the browser, use script type='module' for the import to work

const clearBox = elementID => {
  document.getElementById(elementID).innerHTML = "";
}

const shuffle = a => {
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}

const randomNum = () => {
  const number = Math.floor((Math.random() * 100) +1);
  return number
}

const arr = ['mg/mL', 'mcg/mL', 'mg/L']

const randomUnits = () => {
  return shuffle(arr)
}

const addQuestionOutputHTML = question => {
  output.innerHTML += question
  return question
}

// () => string
const generateQuestion = pipe([
  fork({
    num: randomNum, // () => num
    units: randomUnits, // () => shuffledArr
  }), // () => { num, units }
  ({ num, units }) => `Convert ${num}${units[0]} to ${units[1]}`, // { num, units } => string
  addQuestionOutputHTML, // string => string
])

generateQuestion() // => 'Convert 10mg/mL to mcg/mL'
```

I've added some comments to the library specific code, but to really understand and start using rubico for yourself, read this intuition and then the docs

Body:
I'm trying to create a simple application that generates a random question with an onclick, and will generate a solution to said question with a different onclick.  I've been able to create the random question function simple enough, but what I'm having trouble with is the solution part.  Essentially I cant access the variables produced from the "generate question" function.

The following function generates a random question: "Convert 10mg/mL to mcg/mL"

const arr = ['mg/mL', 'mcg/mL', 'mg/L'];

function genConversion () {
  function clearBox(elementID){ //this resets the question
      document.getElementById(elementID).innerHTML = "";
  }

  clearBox('output');

  function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
  }

   function randomNum() {
    var number = Math.floor((Math.random() * 100) +1);
    return number
  }

  var num = randomNum()

  shuffle(arr);

  output.innerHTML += "Convert " + num + ' ' + arr[0] + ' to ' + arr[1]

}

Now, when I try to create a function that will solve the generated problem (the actual logic will come once I can figure out how to access the question variables), I cant seem to access variable 'num'.  Interestingly, I am able to access the random array element arr[0].

function solveProb() {
  console.log(arr[0]);
  console.log(num);
}

Im sure this has something to do with scope that Im having trouble with, but any advice would be appreciated.

Body:
You don't actually want to access a variable outside a function. You're already thinking in functions, so you may benefit from my library, rubico. Here's your code in a functional, uni-directional data flow style. Also, use let and const instead of var to avoid unpredictable scope-related behavior.

import { pipe, fork } from 'https://deno.land/x/rubico/rubico.js'
// if you're in the browser, use script type='module' for the import to work

const clearBox = elementID => {
  document.getElementById(elementID).innerHTML = "";
}

const shuffle = a => {
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}

const randomNum = () => {
  const number = Math.floor((Math.random() * 100) +1);
  return number
}

const arr = ['mg/mL', 'mcg/mL', 'mg/L']

const randomUnits = () => {
  return shuffle(arr)
}

const addQuestionOutputHTML = question => {
  output.innerHTML += question
  return question
}

// () => string
const generateQuestion = pipe([
  fork({
    num: randomNum, // () => num
    units: randomUnits, // () => shuffledArr
  }), // () => { num, units }
  ({ num, units }) => `Convert ${num}${units[0]} to ${units[1]}`, // { num, units } => string
  addQuestionOutputHTML, // string => string
])

generateQuestion() // => 'Convert 10mg/mL to mcg/mL'

I've added some comments to the library specific code, but to really understand and start using rubico for yourself, read this intuition and then the docs


问:
Initializing multiple subclassed sprites of the same kind in Cocos2D from Tiled
I'm trying to figure out the best way to initialize multiple sprites placed in Tiled that are the same type. I don't even know really how to start off in Tiled, because I'm only used to initializing one sprite by filling out the name field, and then in my CCLayer with the map I do something like

```<code>CCTMXObjectGroup *objects = [theMap objectGroupNamed:@"oj"];
NSMutableDictionary *startPoint = [objects objectNamed:@"StartPoint"];
int x = [[startPoint valueForKey:@"x"] intValue];
int y = [[startPoint valueForKey:@"y"] intValue];

hero = [[HeroClass alloc] init];

[self addChild:hero.heroSpriteSheet];

hero.heroSprite.position = ccp(x,y);
</code>```

As you can see, my "hero" is subclassed, and this goes for another sprite that is a bird, but I want an x amount of them. I import the header of HeroClass and create a pointer, make a property and synthesize that in my main file and finally release HeroClass in dealloc. I have a feeling that I will most likely end up use NSMutableArray, but I don't really know how in the case of subclassing. Also I'm not sure if I'll be using objectNamed:@"name" because I'll have x number of these sprites that I will be just duplicating throughout Tiled.

There's a helpful post here that shows how to add multiple sprites, but I don't know how to relate it to Tiled or subclassing:
http://www.iphonedevsdk.com/forum/iphone-sdk-game-development/58334-adding-sprites-screen-when-detecting-tap-cocos2d.html

Does anyone have any useful pointers or code examples relating how to resolve my issue? Thanks!

TLDR:

How do I initialize sprites from the same class in a CCLayer (that renders my map and other sprites) based upon definite object locations that were placed in a Tiled TMX map?

答: I'd suggesting creating an enemy class. Then, you create a bunch of them using a for loop. As far as spawnpoints, you would have each enemy set its own spawn point up based on rules. (Map borders, "safe areas", etc.)</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to figure out the best way to initialize multiple sprites placed in Tiled that are the same type. I don't even know really how to start off in Tiled, because I'm only used to initializing one sprite by filling out the name field, and then in my CCLayer with the map I do something like

CCTMXObjectGroup *objects = [theMap objectGroupNamed:@"oj"];
NSMutableDictionary *startPoint = [objects objectNamed:@"StartPoint"];
int x = [[startPoint valueForKey:@"x"] intValue];
int y = [[startPoint valueForKey:@"y"] intValue];

hero = [[HeroClass alloc] init];

[self addChild:hero.heroSpriteSheet];

hero.heroSprite.position = ccp(x,y);

As you can see, my "hero" is subclassed, and this goes for another sprite that is a bird, but I want an x amount of them. I import the header of HeroClass and create a pointer, make a property and synthesize that in my main file and finally release HeroClass in dealloc. I have a feeling that I will most likely end up use NSMutableArray, but I don't really know how in the case of subclassing. Also I'm not sure if I'll be using objectNamed:@"name" because I'll have x number of these sprites that I will be just duplicating throughout Tiled.

There's a helpful post here that shows how to add multiple sprites, but I don't know how to relate it to Tiled or subclassing:
http://www.iphonedevsdk.com/forum/iphone-sdk-game-development/58334-adding-sprites-screen-when-detecting-tap-cocos2d.html

Does anyone have any useful pointers or code examples relating how to resolve my issue? Thanks!

TLDR:

How do I initialize sprites from the same class in a CCLayer (that renders my map and other sprites) based upon definite object locations that were placed in a Tiled TMX map?


答:
You can't. int array[10] will always create an array of 10 elements and you can't ask the compiler which of them have been assigned.

What you could do is int array[] = {1, 2, 0, 3, 4} then the compiler will infer the number of elements for you and you'll have sizeof(array)/ sizeof(*array) == 5

Title: int array[10] = {1 , 2, 0, 3} . How can I find out that there are 4 elements here? I know how to find the size of array


问:
Would like a universal way to split different strings into multiple parts using PowerShell
I am working on a method of reading UninstallStrings for software from the registry. And then I'm trying to execute those strings to uninstall the software.

When I print out the variables that hold the string info, it prints the whole string (with the arguments) correctly, but I am unable to run those strings.
There are multiple parts to this issue.

Some install strings are formatted like so

```<code>c:\file path\blah\app.exe /uninstall
"c:\file path\blah\app.exe" /uninstall
c:\file path\blah\app.exe --uninstall
'c:\file path\blah\app.exe' /uninstall
</code>```

What I'm trying to do is figure out the best way to be able to run the uninstaller in a "universal" way.
Is there a way to do this effectively?

I tried executing the strings 2 different ways.

```<code>    & $uninstaller
</code>```

and

```<code>    Start-Process -FilePath cmd.exe -ArgumentList '/c', $uninstaller -Wait
</code>```

Neither of them seem to work. No errors, but they don't seem to run because when I check the app it's still installed.

And I tried splitting the text a few ways.

```<code>
    $Uninstaller.split("/")[0]
    $Uninstaller.split("/",2)[1]
    $($Uninstaller) | Invoke-Expression
    $Uninstaller.Substring(0,$Uninstaller.lastIndexOf('.exe '))
    $Uninstaller.split('^(*?\.exe) *')

</code>```

Thanks in advance!

答:
Try the following testing script, where simple console application CliParser.exe merely echoes command line arguments (written in C, inspired here). Used the exact copy with a space in name CliParser noPause.exe; it shows that . $Uninstaller $UninsParams should work even if a path $Uninstaller contains space(s).

No need to use Start-Process -FilePath cmd.exe …; just apply the dot-sourcing operator as . $Uninstaller $UninsParams…

The $lines collection contains an almost representative syntax patterns of uninstall strings (taken from my Windows 10):

```<code>$lines = @'
MsiExec.exe /X{FFC6E93A-B9AD-3F20-9B06-EE20E24AAEAF}
"D:\Program Files (x86)\Virtual Russian Keyboard\unins000.exe"
"C:\Windows10Upgrade\Windows10UpgraderApp.exe" /Uninstall
C:\Windows\SysWOW64\msiexec.exe /package {CFEF48A8-BFB8-3EAC-8BA5-DE4F8AA267CE} /uninstall {815F0BC1-7E54-300C-9ACA-C9460FDF6F78} /qb+ REBOOTPROMPT=""
C:\Program Files (x86)\InstallShield Installation Information\{8833FFB6-5B0C-4764-81AA-06DFEED9A476}\Setup.exe -runfromtemp -removeonly
"C:\WINDOWS\SysWOW64\RunDll32.EXE" "C:\Program Files\NVIDIA Corporation\Installer2\InstallerCore\NVI2.DLL",UninstallPackage Display.Driver
%windir%\system32\sdbinst.exe -u "C:\WINDOWS\AppPatch\CustomSDB\{9f4f4a9b-eec5-4906-92fe-d1f43ccf5c8d}.sdb"
'@ -split [System.Environment]::NewLine

$FakeUninstaller = "D:\bat\CLIParser noPause.exe"

foreach ( $line in $lines ) {
    # $line
    $aux = $line -split @('\.exe'),2,[System.StringSplitOptions]::None
    $Uninstaller = (cmd /c echo $($aux[0].TrimStart('"').TrimStart("'") + '.exe')).Trim('"')
    $UninsParams = $aux[1].TrimStart('"').TrimStart("'").Trim().split(' ',[System.StringSplitOptions]::RemoveEmptyEntries)

    ". $Uninstaller $UninsParams"
    . $FakeUninstaller $UninsParams | Where-Object { $_ -notlike "param 0 = *" }
}
</code>```

Output: D:\PShell\SO\62023960.ps1

```
. MsiExec.exe /X{FFC6E93A-B9AD-3F20-9B06-EE20E24AAEAF}
param 1 = /X{FFC6E93A-B9AD-3F20-9B06-EE20E24AAEAF}

. "D:\Program Files (x86)\Virtual Russian Keyboard\unins000.exe"

. C:\Windows10Upgrade\Windows10UpgraderApp.exe /Uninstall
param 1 = /Uninstall

. C:\Windows\SysWOW64\msiexec.exe /package {CFEF48A8-BFB8-3EAC-8BA5-DE4F8AA267CE} /uninstall {815F0BC1-7E54-300C-9ACA-C9460FDF6F78} /qb+ REBOOTPROMPT=""
param 1 = /package
param 2 = {CFEF48A8-BFB8-3EAC-8BA5-DE4F8AA267CE}
param 3 = /uninstall
param 4 = {815F0BC1-7E54-300C-9ACA-C9460FDF6F78}
param 5 = /qb+
param 6 = REBOOTPROMPT=""

. "C:\Program Files (x86)\InstallShield Installation Information\{8833FFB6-5B0C-4764-81AA-06DFEED9A476}\Setup.exe" -runfromtemp -removeonly
param 1 = -runfromtemp
param 2 = -removeonly

. C:\WINDOWS\SysWOW64\RunDll32.exe "C:\Program Files\NVIDIA Corporation\Installer2\InstallerCore\NVI2.DLL",UninstallPackage Display.Driver
param 1 = C:\Program Files\NVIDIA Corporation\Installer2\InstallerCore\NVI2.DLL,UninstallPackage
param 2 = Display.Driver

. C:\WINDOWS\system32\sdbinst.exe -u "C:\WINDOWS\AppPatch\CustomSDB\{9f4f4a9b-eec5-4906-92fe-d1f43ccf5c8d}.sdb"
param 1 = -u
param 2 = C:\WINDOWS\AppPatch\CustomSDB\{9f4f4a9b-eec5-4906-92fe-d1f43ccf5c8d}.sdb
```

Body:
I am working on a method of reading UninstallStrings for software from the registry. And then I'm trying to execute those strings to uninstall the software.

When I print out the variables that hold the string info, it prints the whole string (with the arguments) correctly, but I am unable to run those strings.
There are multiple parts to this issue.

Some install strings are formatted like so

c:\file path\blah\app.exe /uninstall
"c:\file path\blah\app.exe" /uninstall
c:\file path\blah\app.exe --uninstall
'c:\file path\blah\app.exe' /uninstall

What I'm trying to do is figure out the best way to be able to run the uninstaller in a "universal" way.
Is there a way to do this effectively?

I tried executing the strings 2 different ways.

    & $uninstaller

and

    Start-Process -FilePath cmd.exe -ArgumentList '/c', $uninstaller -Wait

Neither of them seem to work. No errors, but they don't seem to run because when I check the app it's still installed.

And I tried splitting the text a few ways.

    $Uninstaller.split("/")[0]
    $Uninstaller.split("/",2)[1]
    $($Uninstaller) | Invoke-Expression
    $Uninstaller.Substring(0,$Uninstaller.lastIndexOf('.exe '))
    $Uninstaller.split('^(*?\.exe) *')

Thanks in advance!

Body:
Try the following testing script, where simple console application CliParser.exe merely echoes command line arguments (written in C, inspired here). Used the exact copy with a space in name CliParser noPause.exe; it shows that . $Uninstaller $UninsParams should work even if a path $Uninstaller contains space(s).

No need to use Start-Process -FilePath cmd.exe …; just apply the dot-sourcing operator as . $Uninstaller $UninsParams…

The $lines collection contains an almost representative syntax patterns of uninstall strings (taken from my Windows 10):

$lines = @'
MsiExec.exe /X{FFC6E93A-B9AD-3F20-9B06-EE20E24AAEAF}
"D:\Program Files (x86)\Virtual Russian Keyboard\unins000.exe"
"C:\Windows10Upgrade\Windows10UpgraderApp.exe" /Uninstall
C:\Windows\SysWOW64\msiexec.exe /package {CFEF48A8-BFB8-3EAC-8BA5-DE4F8AA267CE} /uninstall {815F0BC1-7E54-300C-9ACA-C9460FDF6F78} /qb+ REBOOTPROMPT=&quot;&quot;
C:\Program Files (x86)\InstallShield Installation Information\{8833FFB6-5B0C-4764-81AA-06DFEED9A476}\Setup.exe -runfromtemp -removeonly
"C:\WINDOWS\SysWOW64\RunDll32.EXE" "C:\Program Files\NVIDIA Corporation\Installer2\InstallerCore\NVI2.DLL",UninstallPackage Display.Driver
%windir%\system32\sdbinst.exe -u "C:\WINDOWS\AppPatch\CustomSDB\{9f4f4a9b-eec5-4906-92fe-d1f43ccf5c8d}.sdb"
'@ -split [System.Environment]::NewLine

$FakeUninstaller = "D:\bat\CLIParser noPause.exe"

foreach ( $line in $lines ) {
    # $line
    $aux = $line -split @('\.exe'),2,[System.StringSplitOptions]::None
    $Uninstaller = (cmd /c echo $($aux[0].TrimStart('"').TrimStart("'") + '.exe')).Trim('"')
    $UninsParams = $aux[1].TrimStart('"').TrimStart("'").Trim().split(' ',[System.StringSplitOptions]::RemoveEmptyEntries)

    ". $Uninstaller $UninsParams"
    . $FakeUninstaller $UninsParams | Where-Object { $_ -notlike "param 0 = *" }
}

Output: D:\PShell\SO\62023960.ps1

. MsiExec.exe /X{FFC6E93A-B9AD-3F20-9B06-EE20E24AAEAF}
param 1 = /X{FFC6E93A-B9AD-3F20-9B06-EE20E24AAEAF}

. "D:\Program Files (x86)\Virtual Russian Keyboard\unins000.exe"

. C:\Windows10Upgrade\Windows10UpgraderApp.exe /Uninstall
param 1 = /Uninstall

. C:\Windows\SysWOW64\msiexec.exe /package {CFEF48A8-BFB8-3EAC-8BA5-DE4F8AA267CE} /uninstall {815F0BC1-7E54-300C-9ACA-C9460FDF6F78} /qb+ REBOOTPROMPT=""
param 1 = /package
param 2 = {CFEF48A8-BFB8-3EAC-8BA5-DE4F8AA267CE}
param 3 = /uninstall
param 4 = {815F0BC1-7E54-300C-9ACA-C9460FDF6F78}
param 5 = /qb+
param 6 = REBOOTPROMPT=""

. "C:\Program Files (x86)\InstallShield Installation Information\{8833FFB6-5B0C-4764-81AA-06DFEED9A476}\Setup.exe" -runfromtemp -removeonly
param 1 = -runfromtemp
param 2 = -removeonly

. C:\WINDOWS\SysWOW64\RunDll32.exe "C:\Program Files\NVIDIA Corporation\Installer2\InstallerCore\NVI2.DLL",UninstallPackage Display.Driver
param 1 = C:\Program Files\NVIDIA Corporation\Installer2\InstallerCore\NVI2.DLL,UninstallPackage
param 2 = Display.Driver

. C:\WINDOWS\system32\sdbinst.exe -u "C:\WINDOWS\AppPatch\CustomSDB\{9f4f4a9b-eec5-4906-92fe-d1f43ccf5c8d}.sdb"
param 1 = -u
param 2 = C:\WINDOWS\AppPatch\CustomSDB\{9f4f4a9b-eec5-4906-92fe-d1f43ccf5c8d}.sdb