问:
How can I make the content of a grid element not affect its size?
Basically i just want the four boxes in the snippet below to be the same size while still having the text centered inside the first box. Right now the text 'qwe' affects the size of the first box. Also it has to be using display: grid, like it is now.

.asd {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  display: grid;
  grid-template-columns: repeat(4 1fr);
  grid-template-rows: repeat(4 1fr);
}

.asd > div {
  border: 1px solid black;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box1 {
  grid-column: 1/2;
  grid-row: 1/2;
}

.box4 {
    grid-column: 2/3;
  grid-row: 2/3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="asd">
  <div class="box1">qwe</div>
  <div class="box2"></div>
  <div class="box3"></div>
  <div class="box4"></div>
</div></code>```

答:
Your css is invalid grid-template-columns: repeat(4 1fr);grid-template-rows: repeat(4 1fr);

use

grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr 1fr;

If the text grow out of the box use overflow: hidden;

.asd {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
}

.asd > div {
  border: 1px solid black;
  display: flex;
  justify-content: center;
  align-items: center;
overflow: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="asd">
  <div class="box1">qwe qwe qwe</div>
  <div class="box2"></div>
  <div class="box3"></div>
  <div class="box4"></div>
</div></code>```

Body:
Basically i just want the four boxes in the snippet below to be the same size while still having the text centered inside the first box. Right now the text 'qwe' affects the size of the first box. Also it has to be using display: grid, like it is now.

.asd {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  display: grid;
  grid-template-columns: repeat(4 1fr);
  grid-template-rows: repeat(4 1fr);
}

.asd > div {
  border: 1px solid black;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box1 {
  grid-column: 1/2;
  grid-row: 1/2;
}

.box4 {
    grid-column: 2/3;
  grid-row: 2/3;
}

qwe

Body:
Your css is invalid grid-template-columns: repeat(4 1fr);grid-template-rows: repeat(4 1fr);

use

grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr 1fr;

If the text grow out of the box use overflow: hidden;

.asd {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
}

.asd > div {
  border: 1px solid black;
  display: flex;
  justify-content: center;
  align-items: center;
overflow: hidden;
}

<div class="asd">
  <div class="box1">qwe qwe qwe</div>
  <div class="box2"></div>
  <div class="box3"></div>
  <div class="box4"></div>
</div>


来源: stackexchange

问:
Multiprocessing example giving AttributeError
I am trying to implement multiprocessing in my code, and so, I thought that I would start my learning with some examples.  I used the first example found in this documentation.

```<code>from multiprocessing import Pool
def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))
</code>```

When I run the above code I get an AttributeError: can't get attribute 'f' on <module '__main__' (built-in)>.  I do not know why I am getting this error.  I am also using Python 3.5 if that helps.

答: If you're using Jupyter notebook (like the OP), then defining the function in a separate cell and executing that cell first fixes the problem. The accepted answer works too, but it's more work. Defining the function before, i.e. above the pool, isn't adequate. It has to be in a completely different notebook cell which is executed first.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am trying to implement multiprocessing in my code, and so, I thought that I would start my learning with some examples.  I used the first example found in this documentation.

from multiprocessing import Pool
def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))

When I run the above code I get an AttributeError: can't get attribute 'f' on <module '__main__' (built-in)>.  I do not know why I am getting this error.  I am also using Python 3.5 if that helps.

ContentLicense: CC BY-SA 4.0


问:
How to escape '|' character in JBehave
I'm using JBehave 4.0.5

I need to escape the pipeline(|) from the JBehave tabular parameter verification.

As per this answer from Stack Overflow,  In Cucumber we can use '\|'  to escape the pipeline on tabular verification, but i couldn't find one for JBehave.

EX:

```<code>|Key 1      |Key 2  |
| |value 1| |value 2|
| |value 3| |value 4|
</code>```

答:
JBehave allows to specify custom separators for ExamplesTable-s: Tabular Parameters > Specifying inlined separators.</p>

```<code>{headerSeparator=!,valueSeparator=!}
!Key 1      !Key 2  !
! |value 1| !value 2!
! |value 3| !value 4!
</code>```

Title: How to escape '|' character in JBehave

Body:
I'm using JBehave 4.0.5

I need to escape the pipeline(|) from the JBehave tabular parameter verification.

As per this answer from Stack Overflow,  In Cucumber we can use '\|'  to escape the pipeline on tabular verification, but i couldn't find one for JBehave.

EX:

|Key 1      |Key 2  |
| |value 1| |value 2|
| |value 3| |value 4|

Body:
JBehave allows to specify custom separators for ExamplesTable-s: Tabular Parameters > Specifying inlined separators.

{headerSeparator=!,valueSeparator=!}
!Key 1      !Key 2  !
! |value 1| !value 2!
! |value 3| !value 4!


问:
how i can resolve the error Cannot read property 'prenom' of undefined?
I'm developing a user registration page and I'm using angular on the front side and spring boot side back, the problem I get is this error when starting my application:

this is my user class :

```<code>export class User {

   constructor (

    IDENTIFIANT: Number,
    EMPLOI: Number,
    ENTITE: Number,
    LOGIN: string,
    MOTDEPASSE: string,
    NOM: string,
    PRENOM: string,
    STATUT: string,
    DATEEFFET: Date,
    DATEFIN: Date,
    CREELE: Date,
    CREEPAR: Date,
    MOTIFDEDESACTIVATION: string,
    ANNULEPAR: number,
    ANNULELE: Date,
    EMAIL: string,
    CONFIRMATIONMOTDEPASSE: string
   ){}
}
</code>```

and this is my component.html :

```<code><div class="inscription">

    <!-- Default form register -->
    <form class="text-center border border-light p-5">

        <p class="h4 mb-4">Sign up</p>

        <div class="form-row mb-4">
            <div class="col">
                <!-- First name -->
                <input type="text" id="prenom" class="form-control" [(ngModel)]="user.prenom" placeholder="Votre prenom">
            </div>
            <div class="col">
                <!-- Last name -->
                <input type="text" id="nom" class="form-control" [(ngModel)]="user.nom" placeholder="Votre nom">
            </div>
        </div>

        <!-- E-mail -->
        <input type="email" id="email" class="form-control mb-4" [(ngModel)]="user.email" placeholder="Votre email">

        <!-- Login -->
        <input type="text" id="login" class="form-control mb-4" [(ngModel)]="user.login" placeholder="Votre login">

        <!-- Password -->
        <input type="password" id="password" class="form-control" [(ngModel)]="user.motdepasse" placeholder="Votre mot de passe"
            aria-describedby="defaultRegisterFormPasswordHelpBlock">

        <!-- Confirmation mot de passe -->
        <input type="password" id="password-confirmation" class="form-control"
            placeholder="Confirmez votre mot de passe" [(ngModel)]="user.confirmationmotdepasse" aria-describedby="defaultRegisterFormPasswordHelpBlock">

        <!-- Entite -->

            <select class="form-control" id="entite" [(ngModel)]="user.entite">
                <option value="" selected disabled>Votre entité</option>
                <option>1</option>
                <option>2</option>
                <option>3</option>
                <option>4</option>
                <option>5</option>
            </select>

        <!-- Emploi -->

        <select class="form-control" id="emploi" [(ngModel)]="user.emploi">
            <option value="" selected disabled >Votre emploi</option>
            <ul class="list-unstyled navbar-list">

                <li *ngFor="let tempAllEmploi of allEmploi">

                    <option>{{ tempAllEmploi.NOM}}</option>
                </li>
            </ul>

        </select>

        <!-- Sign up button -->
        <button mdbBtn color="info" block="true" class="my-4" type="submit" id="btn-inscription" class="btn-primary btn-lg" (click)="inscriptionts()">Valider</button>

    </form>
    <!-- Default form register -->

</div>
</code>```

focus more on this code :

```<code><input type="text" id="prenom" class="form-control" [(ngModel)]="user.prenom" placeholder="Votre prenom">
</code>```

you can see here that I created the user class which has a "first name" variable and that I used the ngModel with user.prenom in my html code, so I don't see where the error can come from  :/

this is my component.ts :

```<code>import { Component, OnInit } from '@angular/core';
import { User } from 'src/app/model/user';
import { RestapiService } from 'src/app/restapi.service';
import { Emploi } from 'src/app/model/emploi';

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

  allEmploi: Emploi[];
  user: any;
  //user: Users= new Users(0,0,0,"","","","","",new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),"",0,new Date("dd-mm-yyyy"),"","");

  constructor(private Userservice: RestapiService) { }

  ngOnInit(): void {

    this.getAllEmploi();
  }

  public getAllEmploi(){

    this.Userservice.getEmploi().subscribe(

      data => {
        this.allEmploi=data;
      }
    );
  }

  public inscriptionts(){

    let resp=this.Userservice.inscription(this.user);
    resp.subscribe((data)=> this.user=data);
  }
}
</code>```

and this is my service :

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Emploi } from './model/emploi';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class RestapiService {

  url_getAllEmploi="http://localhost:8484/emploi/getall";

  constructor(private http:HttpClient) { }

  public inscription(user) {

    return this.http.post("http://localhost:8484/addUser", user);
  }

  public getEmploi(): Observable<Emploi[]> {

    return this.http.get<Emploi[]>(this.url_getAllEmploi);
  }

  public login(username:string, password:string) {
    const headers = new HttpHeaders({Authorization: 'Basic ' + btoa(username+":"+password)})
    return this.http.get("http://localhost:8484/", {headers, responseType:'text' as 'json'});
  }

  public getUsers() {
    let username="hr";
    let password="hr";
    const headers = new HttpHeaders({Authorization: 'Basic ' + btoa(username+":"+password)});
    return this.http.get("http://localhost:8484/getUsers", {headers});
  }
}
</code>```

can someone help me please ?

答:
You are binding your form field to an undefined object (user).
You need to initialise user in ngOnInit().
If you don't have any function in your class you can simply use an Interface.

```<code>export interface User {
    identifiant: Number,
    emploi: Number,
    entite: Number,
    login: string,
    motdepasse: string,
    nom: string,
    prenom: string,
    statut: string,
    dateeffet: Date,
    datefin: Date,
    creele: Date,
    creepar: string,
    motifdedesactivation: string,
    annulepar: number,
    annulele: Date,
    email: string,
    confirmationmotdepasse: string
}
</code>```

Then

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

  allEmploi: Emploi[];
  user: User;

  ngOnInit(): void {
    this.getAllEmploi();
    this.user = {
        identifiant: null,
        emploi: null,
        entite: null,
        login: "",
        motdepasse: "",
        nom: "",
        prenom: "",
        statut: "",
        dateeffet: null,
        datefin: null,
        creele: null,
        creepar: "",
        motifdedesactivation: "",
        annulepar: null,
        annulele: null,
        email: "",
        confirmationmotdepasse: ""
  }
}
</code>```

Also be careful about your use of [(ngModel)] within a form. You need to set the name attributes for your controls like this

```<code><input type="text" id="prenom" class="form-control" [(ngModel)]="user.prenom" name="prenom" placeholder="Votre prenom">
</code>```

Body:
I'm developing a user registration page and I'm using angular on the front side and spring boot side back, the problem I get is this error when starting my application:

this is my user class :

export class User {

   constructor (

    IDENTIFIANT: Number,
    EMPLOI: Number,
    ENTITE: Number,
    LOGIN: string,
    MOTDEPASSE: string,
    NOM: string,
    PRENOM: string,
    STATUT: string,
    DATEEFFET: Date,
    DATEFIN: Date,
    CREELE: Date,
    CREEPAR: Date,
    MOTIFDEDESACTIVATION: string,
    ANNULEPAR: number,
    ANNULELE: Date,
    EMAIL: string,
    CONFIRMATIONMOTDEPASSE: string
   ){}
}

and this is my component.html :

    <form class="text-center border border-light p-5">

Sign up

                <input type="text" id="prenom" class="form-control" [(ngModel)]="user.prenom" placeholder="Votre prenom">

                <input type="text" id="nom" class="form-control" [(ngModel)]="user.nom" placeholder="Votre nom">

        <input type="email" id="email" class="form-control mb-4" [(ngModel)]="user.email" placeholder="Votre email">

        <input type="text" id="login" class="form-control mb-4" [(ngModel)]="user.login" placeholder="Votre login">

        <input type="password" id="password" class="form-control" [(ngModel)]="user.motdepasse" placeholder="Votre mot de passe"
            aria-describedby="defaultRegisterFormPasswordHelpBlock">

        <input type="password" id="password-confirmation" class="form-control"
            placeholder="Confirmez votre mot de passe" [(ngModel)]="user.confirmationmotdepasse" aria-describedby="defaultRegisterFormPasswordHelpBlock">

            <select class="form-control" id="entite" [(ngModel)]="user.entite">
                <option value="" selected disabled>Votre entité</option>
                <option>1</option>
                <option>2</option>
                <option>3</option>
                <option>4</option>
                <option>5</option>
            </select>

        <select class="form-control" id="emploi" [(ngModel)]="user.emploi">
            <option value="" selected disabled >Votre emploi</option>

                    <option>{{ tempAllEmploi.NOM}}</option>

        </select>

        <button mdbBtn color="info" block="true" class="my-4" type="submit" id="btn-inscription" class="btn-primary btn-lg" (click)="inscriptionts()">Valider</button>

    </form>

focus more on this code :

<input type="text" id="prenom" class="form-control" [(ngModel)]="user.prenom" placeholder="Votre prenom">

you can see here that I created the user class which has a "first name" variable and that I used the ngModel with user.prenom in my html code, so I don't see where the error can come from  :/

this is my component.ts :

import { Component, OnInit } from '@angular/core';
import { User } from 'src/app/model/user';
import { RestapiService } from 'src/app/restapi.service';
import { Emploi } from 'src/app/model/emploi';

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

  allEmploi: Emploi[];
  user: any;
  //user: Users= new Users(0,0,0,"","","","","",new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),new Date("dd-mm-yyyy"),"",0,new Date("dd-mm-yyyy"),"","");

  constructor(private Userservice: RestapiService) { }

  ngOnInit(): void {

    this.getAllEmploi();
  }

  public getAllEmploi(){

    this.Userservice.getEmploi().subscribe(

      data => {
        this.allEmploi=data;
      }
    );
  }

  public inscriptionts(){

    let resp=this.Userservice.inscription(this.user);
    resp.subscribe((data)=> this.user=data);
  }
}

and this is my service :

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Emploi } from './model/emploi';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class RestapiService {

  url_getAllEmploi="http://localhost:8484/emploi/getall";

  constructor(private http:HttpClient) { }

  public inscription(user) {

    return this.http.post("http://localhost:8484/addUser", user);
  }

  public getEmploi(): Observable<Emploi[]> {

    return this.http.get<Emploi[]>(this.url_getAllEmploi);
  }

  public login(username:string, password:string) {
    const headers = new HttpHeaders({Authorization: 'Basic ' + btoa(username+":"+password)})
    return this.http.get("http://localhost:8484/", {headers, responseType:'text' as 'json'});
  }

  public getUsers() {
    let username="hr";
    let password="hr";
    const headers = new HttpHeaders({Authorization: 'Basic ' + btoa(username+":"+password)});
    return this.http.get("http://localhost:8484/getUsers", {headers});
  }
}

can someone help me please ?

Body:
You are binding your form field to an undefined object (user).
You need to initialise user in ngOnInit().
If you don't have any function in your class you can simply use an Interface.

export interface User {
    identifiant: Number,
    emploi: Number,
    entite: Number,
    login: string,
    motdepasse: string,
    nom: string,
    prenom: string,
    statut: string,
    dateeffet: Date,
    datefin: Date,
    creele: Date,
    creepar: string,
    motifdedesactivation: string,
    annulepar: number,
    annulele: Date,
    email: string,
    confirmationmotdepasse: string
}

Then

export class InscriptionComponent implements OnInit {

  allEmploi: Emploi[];
  user: User;

  ngOnInit(): void {
    this.getAllEmploi();
    this.user = {
        identifiant: null,
        emploi: null,
        entite: null,
        login: "",
        motdepasse: "",
        nom: "",
        prenom: "",
        statut: "",
        dateeffet: null,
        datefin: null,
        creele: null,
        creepar: "",
        motifdedesactivation: "",
        annulepar: null,
        annulele: null,
        email: "",
        confirmationmotdepasse: ""
  }
}

Also be careful about your use of [(ngModel)] within a form. You need to set the name attributes for your controls like this

<input type="text" id="prenom" class="form-control" [(ngModel)]="user.prenom" name="prenom" placeholder="Votre prenom">


问:
How to share state between reducers in react (using hooks) without redux
I have a react hooks application written in typescript that contains multiple reducers, and I am using them with the context API.

I need to share the error state between reducers, because I need only one error state displayed in the app, which can be cleared/set with the errorReducer.

The trouble is, I need to set the error part of the state from the 'other' reducers (by 'other' I mean not the errorReducer).

If I try to use the useReducer hook (or my own useAsyncReducer hook) inside the 'other' reducers to set an error, I get

Error: Invalid hook call. Hooks can only be called inside of the body
  of a function component

, as you can see below.

How can I share state between reducers in react? (please see the 'TODO: THIS IS WHAT I NEED' below).

Please note that I do not want to use redux.

export type Actor = {
    _id?: string,
    firstName?: string,
    lastName?: string,
    selectedForDelete?: boolean
}

// Compound state for 3 reducers (activeEntityTypeReducer, actorReducer, errorReducer)
export type State = {
    activeEntityType: string,
    actors: Actor[],
    error: string | null
}

export const EMPTY_INITIAL_STATE: State = {
    activeEntityType: EntityType.ACTOR,
    actors: [],
    error: null
};

// ERROR REDUCER:
export const errorReducer = async (state: string | null, action: ErrorActions) => {
    switch (action.type) {
        case ErrorActionType.SET_ERROR: {
            return action.payload;
        }

        default:
            return state;
    }
};

// ACTOR REDUCER:
export const actorReducer = async (state: Actor[], action: ActorActions) => {
  // I cannot use here a hook like this because it triggers: "Error: Invalid hook call. Hooks can only be called inside of the body of a function component"
  // const { dispatch: dispatchError } = useAsyncReducer(errorReducer, EMPTY_INITIAL_STATE);
  switch (action.type) {
    //... other actions

    case ActorActionType.SEARCH_ACTORS: {
      return fetch(
        "http://localhost:3000/api/actors?pagesize=100"
      ).then(response => response.json())
        .then(response => response['data']);
      /*  // TODO: THIS IS WHAT I NEED: continue the above line with a catch inside which I dispatch the error
      .catch((error) => dispatchError({
        type: ErrorActionType.SET_ERROR,
        payload: error
      }))
      */
    }

    default:
      return state;
  }
};

// MAIN (COMPOSED) REDUCER:
export const mainReducer = async ({ activeEntityType, actors, error }: State,
    action: ActiveEntityTypeActions | ActorActions | ErrorActions) => (
    {
        actors: await actorReducer(actors, action as ActorActions),
        activeEntityType: activeEntityTypeReducer(activeEntityType, action as ActiveEntityTypeActions),
        // more reducers here and all need to set the error
        error: await errorReducer(error, action as ErrorActions)
    });
```

答:
I found a solution:

I changed the actorReducer to update the error part of the state as well. This means that actorReducer receives now both the actors and the error parts of the state and returns both of them.

For simplicity, I renamed the action names to start with words that identify the reducers, so that I can easily decide to which reducer to forward an action in the mainReducer (which is the combined reducer) by just checking the prefix of an incoming action (so ActorActionType.SEARCH_ACTORS was renamed to ActorActionType.ACTOR__SEARCH, etc).

Here is a part of the code:

type State = {
    activeEntityType: string,
    actors: Actor[],
    error: string | null
}

// For actorReducer
enum ActorActionType {
  ACTOR__ADD = 'ACTOR__ADD',
  ACTOR__SELECT_FOR_DELETING = 'ACTOR__SELECT_FOR_DELETING',
  ACTOR__DELETE = 'ACTOR__DELETE',
  ACTOR__SEARCH = 'ACTOR__SEARCH'
}

// For errorReducer
enum ErrorActionType {
    ERROR__SET = 'ERROR__SET',
}

// for activeEntityTypeReducer
const ACTIVE_ENTITY_TYPE__SET: string = "ACTIVE_ENTITY_TYPE__SET";

const actorReducer = async (actors: Actor[], error: string | null, action: ActorActions) => {
  case ActorActionType.ACTOR__SEARCH: {
    // fetch and error handling and fill newActors and newOrOldError
    return { actors: newActors, error: newOrOldError};
  }
}

// The combined (main) reducer:
const mainReducer = async ({ activeEntityType, actors, error }: State,
    action: ActiveEntityTypeActions | ActorActions | ErrorActions) => {
        if (action.type.startsWith('ACTOR__')) {
            const actorsAndError = (await actorReducer(actors, error, action as ActorActions));
            return {...actorsAndError, activeEntityType};
        }

        if (action.type.startsWith('ACTIVE_ENTITY_TYPE__')) {
            // No need for now to pass in and return the error for activeEntityTypeReducer, as it can never error
            return {activeEntityType: activeEntityTypeReducer(activeEntityType, action as ActiveEntityTypeActions), actors, error};
        }

        // Can only be the errorReducer case:
        return {activeEntityType, actors, error: await errorReducer(error, action as ErrorActions)};
};
```


问:
Python string sequcence like excel
I want sequence like excel headers.

e.g :
A,B,C,..,Z,AA,AB....

My code

```<code>>>> s = 'A'
>>> chr(ord(s) + 1)
'B'
>>> s = 'Z'
>>> chr(ord(s) + 1)
'['
>>>
# I want AA after chr(ord('Z') + 1)
</code>```

答:
using itertools,</p>

```<code>import itertools

alpha = [chr(x) for x in range(65, 91)] # create a list of character's

print(alpha + [k + v for k,v in itertools.product(alpha, repeat=2)])
</code>```

Title: Python string sequcence like excel

Body:
I want sequence like excel headers.

e.g :
A,B,C,..,Z,AA,AB....

My code

>>> s = 'A'
>>> chr(ord(s) + 1)
'B'
>>> s = 'Z'
>>> chr(ord(s) + 1)
'['
>>>
# I want AA after chr(ord('Z') + 1)

Body:
using itertools,

import itertools

alpha = [chr(x) for x in range(65, 91)] # create a list of character's

print(alpha + [k + v for k,v in itertools.product(alpha, repeat=2)])


问:
Why would you not use PreserveReferencesHandling in Json.NET?
In a farm where there is a number of cows and a number of farmers who are responsible for some of those cows, PreserveReferencesHandling reduces the size of the resulting json dramatically (45% in this case).

```<code>public class Farm
{
    public List<Cow> cows;
    public List<Farmer> farmers;
    public List<List<Farmer>> teams;
    ...
}
public class Cow
{
    //Some properties...
}
public class Farmer
{
    public List<Cow> cows;
    ...
}
</code>```

If PreserveReferencesHandling is turned off, this may lead to tons of cows being needlessly duplicated in the json, which, depending on whatever implementation there might be, may in fact break the program e.g. because of equality checks failing.

For example:
Without PreserveReferencesHandling

```<code>// characters: 985
{
  "cows": [
    {"name":"SmallCow"},
    {"name":"Cow"},
    {"name":"BigCow"}
  ],
  "farmers":[
    {"name":"Joe", "cows":[{"name":"SmallCow"}, {"name":"Cow"}]},
    {"name":"Chris", "cows":[{"name":"SmallCow"}, {"name":"BigCow"}]},
    {"name":"Chris Junior", "cows":[{"name":"SmallCow"}, {"name":"BigCow"}]},
    {"name":"Bob", "cows":[{"name":"SmallCow"}, {"name":"Cow"}, {"name":"BigCow"}]}
  ],
  "teams": [
    [{"name":"Joe", "cows":[{"name":"SmallCow"}, {"name":"Cow"}]}, {"name":"Chris", "cows":[{"name":"SmallCow"}, {"name":"BigCow"}]}],
    [{"name":"Chris Junior", "cows":[{"name":"SmallCow"}, {"name":"BigCow"}]}, {"name":"Chris", "cows":[{"name":"SmallCow"}, {"name":"BigCow"}]}],
    [{"name":"Joe", "cows":[{"name":"SmallCow"}, {"name":"Cow"}]},
    {"name":"Chris", "cows":[{"name":"SmallCow"}, {"name":"BigCow"}]},
    {"name":"Chris Junior", "cows":[{"name":"SmallCow"}, {"name":"BigCow"}]},
    {"name":"Bob", "cows":[{"name":"SmallCow"}, {"name":"Cow"}, {"name":"BigCow"}]}]
  ]
}
</code>```

With PreserveReferencesHandling.Objects

```<code>// characters: 547
{
  "cows": [
    {"$id": 0, "name":"SmallCow"},
    {"$id": 1,"name":"Cow"},
    {"$id": 2,"name":"BigCow"}
  ],
  "farmers":[
    {"$id": 3, "name":"Joe", "cows":[{"$ref": 0}, {"$ref": 1}]},
    {"$id": 4, "name":"Chris", "cows":[{"$ref": 0}, {"$ref": 2}]},
    {"$id": 5, "name":"Chris Junior", "cows":[{"$ref": 0}, {"$ref": 2}]},
    {"$id": 6, "name":"Bob", "cows":[{"$ref": 0}, {"$ref": 1}, {"$ref": 2}]}
  ],
  "teams": [
    [{"$ref" : 3}, {"$ref" : 4}],
    [{"$ref" : 5}, {"$ref" : 4}],
    [{"$ref" : 3}, {"$ref" : 4}, {"$ref" : 5}, {"$ref" : 6}]
  ]
}
</code>```

This example is somewhat engineered to show the difference, but I would assume this memory saving would only get more pronounced the more complex and interconnected a data system becomes.

What are the pros and cons of PreserveReferenceHandling? Which setting is most useful, PreserveReferenceHandling.Objects, PreserveReferenceHandling.Arrays or PreserveReferenceHandling.All?

答:
Why would you not use PreserveReferencesHandling in Json.NET?

Some downsides of the PreserveReferencesHandling behaviour include:

It generates "weird" looking JSON that other JSON parsers will struggle to deserialise (this is particularly an issue when deserialising it in different languages).

There may be an explicit desire to not have reference handling (e.g. the consumer specifically wants each instance to be unique, not references to the same value).

If you want performance / conciseness then some form of binary format (e.g. protobuf) makes more sense. JSON has benefits of being human readable and largely interoperable across languages. Using PreserveReferencesHandling dampens both benefits considerably.

The very nature of software development is tradeoffs. Are there benefits to using PreserveReferencesHandling? Sure there are - which is why it exists. But the authors of the library, rightly, optimised for interoperability while providing the option if you need it.

In addition, the use of PreserveReferencesHandling does not always "play well" with other Json.NET features, and it may slow some serialising / deserialising due to the extra effort of tracking and comparing the object references. Profiling would be necessary to see what performance looks like for you.

Body:
In a farm where there is a number of cows and a number of farmers who are responsible for some of those cows, PreserveReferencesHandling reduces the size of the resulting json dramatically (45% in this case).

public class Farm
{
    public List<Cow> cows;
    public List<Farmer> farmers;
    public List<List<Farmer>> teams;
    ...
}
public class Cow
{
    //Some properties...
}
public class Farmer
{
    public List<Cow> cows;
    ...
}

If PreserveReferencesHandling is turned off, this may lead to tons of cows being needlessly duplicated in the json, which, depending on whatever implementation there might be, may in fact break the program e.g. because of equality checks failing.

For example:
Without PreserveReferencesHandling

// characters: 985
{
  "cows": [
    {"name":"SmallCow"},
    {"name":"Cow"},
    {"name":"BigCow"}
  ],
  "farmers":[
    {"name":"Joe", "cows":[{"name":"SmallCow"}, {"name":"Cow"}]},
    {"name":"Chris", "cows":[{"name":"SmallCow"}, {"name":"BigCow"}]},
    {"name":"Chris Junior", "cows":[{"name":"SmallCow"}, {"name":"BigCow"}]},
    {"name":"Bob", "cows":[{"name":"SmallCow"}, {"name":"Cow"}, {"name":"BigCow"}]}
  ],
  "teams": [
    [{"name":"Joe", "cows":[{"name":"SmallCow"}, {"name":"Cow"}]}, {"name":"Chris", "cows":[{"name":"SmallCow"}, {"name":"BigCow"}]}],
    [{"name":"Chris Junior", "cows":[{"name":"SmallCow"}, {"name":"BigCow"}]}, {"name":"Chris", "cows":[{"name":"SmallCow"}, {"name":"BigCow"}]}],
    [{"name":"Joe", "cows":[{"name":"SmallCow"}, {"name":"Cow"}]},
    {"name":"Chris", "cows":[{"name":"SmallCow"}, {"name":"BigCow"}]},
    {"name":"Chris Junior", "cows":[{"name":"SmallCow"}, {"name":"BigCow"}]},
    {"name":"Bob", "cows":[{"name":"SmallCow"}, {"name":"Cow"}, {"name":"BigCow"}]}]
  ]
}

With PreserveReferencesHandling.Objects

// characters: 547
{
  "cows": [
    {"$id": 0, "name":"SmallCow"},
    {"$id": 1,"name":"Cow"},
    {"$id": 2,"name":"BigCow"}
  ],
  "farmers":[
    {"$id": 3, "name":"Joe", "cows":[{"$ref": 0}, {"$ref": 1}]},
    {"$id": 4, "name":"Chris", "cows":[{"$ref": 0}, {"$ref": 2}]},
    {"$id": 5, "name":"Chris Junior", "cows":[{"$ref": 0}, {"$ref": 2}]},
    {"$id": 6, "name":"Bob", "cows":[{"$ref": 0}, {"$ref": 1}, {"$ref": 2}]}
  ],
  "teams": [
    [{"$ref" : 3}, {"$ref" : 4}],
    [{"$ref" : 5}, {"$ref" : 4}],
    [{"$ref" : 3}, {"$ref" : 4}, {"$ref" : 5}, {"$ref" : 6}]
  ]
}

This example is somewhat engineered to show the difference, but I would assume this memory saving would only get more pronounced the more complex and interconnected a data system becomes.

What are the pros and cons of PreserveReferenceHandling? Which setting is most useful, PreserveReferenceHandling.Objects, PreserveReferenceHandling.Arrays or PreserveReferenceHandling.All?


问:
Install odoo requirments
I am trying to learn odoo but when I try to install requirements from requirement.txt file  using the command sudo pip install -r requirements.txt I get the following error:

Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-7VpR4f/python-ldap/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-rosrtv-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-7VpR4f/python-ldap/
```

so please can any one help me ?!

答:
hossam aboouf

Installation Odoo with python3:

sudo apt-get install python3-pip

    sudo pip3 install -r requirements.txt

    sudo apt install python3-setuptools

    sudo apt install python3-dev

If you face any other library package than execute this cmd:

```<code>sudo apt-get install libpq-dev python-dev libxml2-dev libxslt1-dev libldap2-dev libsasl2-dev libffi-dev
</code>```

Title: Install odoo requirments

Body:
I am trying to learn odoo but when I try to install requirements from requirement.txt file  using the command sudo pip install -r requirements.txt I get the following error:

Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-7VpR4f/python-ldap/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-rosrtv-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-7VpR4f/python-ldap/

so please can any one help me ?!

Body:
hossam aboouf

Installation Odoo with python3:

sudo apt-get install python3-pip

    sudo pip3 install -r requirements.txt

    sudo apt install python3-setuptools

    sudo apt install python3-dev

If you face any other library package than execute this cmd:

sudo apt-get install libpq-dev python-dev libxml2-dev libxslt1-dev libldap2-dev libsasl2-dev libffi-dev


问:
integrating Git Bash with Visual Studio
I have a windows version of Git Bash, and I want to use it with my Visual Studio Projects. What I want is a way of tweaking some setting so that one click can get Bash opened with the directory on the current visual studio project.

It would be great if there's a way to set up short cut in Git Bash for directories, so that one command can get me to a preset directory.

答:
Visual Studio 2019 after v16.6 comes with an integrated terminal similar to the one in Visual Studio Code.  It also doesn't come with a preconfigured git bash, so in order to make it work you'll have to create the configuration.

Open a terminal ("View -> Terminal") and click on the gear icon in the terminal window.  Alternatively, go to "Tools -> Options" then "Environment -> Terminal"

Click the Add button.

Configure the bash shell: set the name to something you like (I use "git bash" because I'm boring), as executable use c:\program files\git\bin\bash.exe, as arguments use --login -i to get your default aliases and so on.  The shell will be started in your solution's base directory.  Note that the name in the list will not update before you close the dialog (as of VS 2022 17.3.1).

You should now be able to use bash in the integrated terminal via the default shortcut Ctrl + ` or via View -> Terminal in the menu.

As of VS 2022 17.3.1 there are two major bugs that I'm aware of:

if you try to open your new bash, and you get a Powershell instead, the only way I'm aware of to fix that and to actually be able to open the bash is to delete the Powershell configuration that was used instead.  If you need it, you should save its settings and restore them manually.

if the Shell Location is set to a full path including the bash.exe executable, clicking the button labelled "..." on the right, which opens a file selection dialog, will make Visual Studio crash hard.

Title: integrating Git Bash with Visual Studio


问:
Android Kotlin Coroutine used with function parameters acts odd
I'm using a coroutine to format a list.

This is how it looks

```<code>val job : Job? = null

private fun formatList(originalList:MutableList<MY_OBJECT>, callback : (MutableList<MY_OBJECT>) -> Unit){

    if(job != null && !job?.isCompleted!!){

        job?.cancel()
    }

    job = viewModelScope.launch(Dispatchers.IO) {

          originalList.foreach { item ->
               //do something with the item.
          }
    }
}
</code>```

This method can be called several times during runtime, and to avoid it from doing the samething, I added a cancel call if the job isn't done yet.

The problem is, in runtime, the stuffs inside the foreach block randomly produces some index related crashes.

Why is this happening? Is this something about things going behind coroutine execution? Or are there something I don't know about the foreach loop?

答:
Making your code cancellable

For job.cancel() to work properly, you need to make your code inside coroutine cancellable.

```<code>job = viewModelScope.launch(Dispatchers.IO) {
      originalList.foreach { item ->
           if(!isActive) return@launch
           //do something with the item.
      }
      if(!isActive) return@launch
      // do something
}
</code>```

Here the line if(!isActive) return@launch is checking if the coroutine is still active or not. Checking for isActive before and after computationally intensive code is good practice.

Note: if you are not doing any network or database calls, always try to use Dispatchers.Default which is optimized for computation instead of Dispatchers.IO.

Body:
I'm using a coroutine to format a list.

This is how it looks

val job : Job? = null

private fun formatList(originalList:MutableList<MY_OBJECT>, callback : (MutableList<MY_OBJECT>) -> Unit){

    if(job != null && !job?.isCompleted!!){

        job?.cancel()
    }

    job = viewModelScope.launch(Dispatchers.IO) {

          originalList.foreach { item ->
               //do something with the item.
          }
    }
}

This method can be called several times during runtime, and to avoid it from doing the samething, I added a cancel call if the job isn't done yet.

The problem is, in runtime, the stuffs inside the foreach block randomly produces some index related crashes.

Why is this happening? Is this something about things going behind coroutine execution? Or are there something I don't know about the foreach loop?

Body:
Making your code cancellable

For job.cancel() to work properly, you need to make your code inside coroutine cancellable.

job = viewModelScope.launch(Dispatchers.IO) {
      originalList.foreach { item ->
           if(!isActive) return@launch
           //do something with the item.
      }
      if(!isActive) return@launch
      // do something
}

Here the line if(!isActive) return@launch is checking if the coroutine is still active or not. Checking for isActive before and after computationally intensive code is good practice.

Note: if you are not doing any network or database calls, always try to use Dispatchers.Default which is optimized for computation instead of Dispatchers.IO.


问:
How to evaluate an equation with a function?
I'm trying to create a function which will solve for some numeric computation – which is given as a string.

Example:

def calculate(expression):
   # Solve the expression below
   return

# Result should be 19
calculate("5+8-3+9")
```

I have tried using .split() but got stuck.

答:
First of all, it's okay to be a beginner - I was in your exact shoes just a few years ago!

I'm going to attempt to provide an elementary/beginner approach to solving this problem, with just the basics.

So first we want to determine what the limits of our function input will be. For this, I'll assume we only accept mathematical expressions with basic addition/subtraction operators.

import re

def calculate(expression: str) -> int:
    if not re.match("^[0-9\+-]*$", expression):
        return None
```

<p>For this you'll see I opted for regex, which is a slightly more advanced concept, but think about it like a validity check for <code>expression</code>. Basically, the pattern I wrote checks that there is a fully qualified string that has only integers, plus sign, and minus sign. If you want to learn more about the expression <code>^[0-9\+-]*$</code>, I highly recommend https://regexr.com/.</p>

<p>For our purposes and understanding though, these test cases should suffice:</p>

<pre class="lang-py prettyprint-override"><code>>>> re.match("^[0-9\+-]*$", "abcs")
>>> re.match("^[0-9\+-]*$", "1+2")
<re.Match object; span=(0, 3), match='1+2'>
>>> re.match("^[0-9\+-]*$", "1+2/3")
>>>
</code>```

Now that we have verified our expression, we can get to work on calculating the final value.

Let's try your idea with str.split()! It won't be entirely straightforward because split by definition splits a string up according to a delimiter(s) but discards them in the output. Fear not, because there's another way! The re package I imported earlier can come into handy. So the re library comes with a handy function, split!

By using capture groups for our separator, we are able to split and keep our separators.

>>> re.split("(\d+)", "1+393958-3")
['', '1', '+', '393958', '-', '3', '']
```

<p>So, with this up our sleeve...</p>

<pre class="lang-py prettyprint-override"><code>import re

def calculate(expression: str) -> int:
    if not re.match("^[0-9\+-]*$", expression):
        return None
    expression_arr = re.split("(\d+)", expression)[1:-1]
    while len(expression_arr) > 1:
        # TODO stuff
    return int(expression[0])
</code>```

We can now move onto our while loop. It stands to reason that as long as the array has more than one item, there is some sort of operation left to do.

import re

def calculate(expression: str) -> int:
    if not re.match("^[0-9\+-]*$", expression):
        return None
    expression_arr = re.split("(\d+)", expression)[1:-1]
    while len(expression_arr) > 1:
        if expression_arr[1] == "+":
            eval = int(expression_arr[0]) + int(expression_arr[2])
        if expression_arr[1] == "-":
            eval = int(expression_arr[0]) - int(expression_arr[2])
        del expression_arr[:3]
        expression_arr.insert(0, eval)

    return int(expression_arr[0])
```

<p>It's pretty straightforward from there - we check the next operator (which always has to be at <code>expression_arr[1]</code>) and either add or subtract, and make the corresponding changes to <code>expression_arr</code>.</p>

<p>We can verify that it passes the test case you provided. (I added some logging to help with visualization)</p>

<pre class="lang-py prettyprint-override"><code>>>> calculate("5+8-3+9")
['5', '+', '8', '-', '3', '+', '9']
[13, '-', '3', '+', '9']
[10, '+', '9']
[19]
19
</code>```

Body:
I'm trying to create a function which will solve for some numeric computation – which is given as a string.

Example:

def calculate(expression):
   # Solve the expression below
   return

# Result should be 19
calculate("5+8-3+9")

I have tried using .split() but got stuck.

Body:
First of all, it's okay to be a beginner - I was in your exact shoes just a few years ago!

I'm going to attempt to provide an elementary/beginner approach to solving this problem, with just the basics.

So first we want to determine what the limits of our function input will be. For this, I'll assume we only accept mathematical expressions with basic addition/subtraction operators.

import re

def calculate(expression: str) -> int:
    if not re.match("^[0-9\+-]*$", expression):
        return None

For this you'll see I opted for regex, which is a slightly more advanced concept, but think about it like a validity check for expression. Basically, the pattern I wrote checks that there is a fully qualified string that has only integers, plus sign, and minus sign. If you want to learn more about the expression ^[0-9\+-]*$, I highly recommend https://regexr.com/.

For our purposes and understanding though, these test cases should suffice:

>>> re.match("^[0-9\+-]*$", "abcs")
>>> re.match("^[0-9\+-]*$", "1+2")
<re.Match object; span=(0, 3), match='1+2'>
>>> re.match("^[0-9\+-]*$", "1+2/3")
>>>

Now that we have verified our expression, we can get to work on calculating the final value.

Let's try your idea with str.split()! It won't be entirely straightforward because split by definition splits a string up according to a delimiter(s) but discards them in the output. Fear not, because there's another way! The re package I imported earlier can come into handy. So the re library comes with a handy function, split!

By using capture groups for our separator, we are able to split and keep our separators.

>>> re.split("(\d+)", "1+393958-3")
['', '1', '+', '393958', '-', '3', '']

So, with this up our sleeve...

import re

def calculate(expression: str) -> int:
    if not re.match("^[0-9\+-]*$", expression):
        return None
    expression_arr = re.split("(\d+)", expression)[1:-1]
    while len(expression_arr) > 1:
        # TODO stuff
    return int(expression[0])

We can now move onto our while loop. It stands to reason that as long as the array has more than one item, there is some sort of operation left to do.

import re

def calculate(expression: str) -> int:
    if not re.match("^[0-9\+-]*$", expression):
        return None
    expression_arr = re.split("(\d+)", expression)[1:-1]
    while len(expression_arr) > 1:
        if expression_arr[1] == "+":
            eval = int(expression_arr[0]) + int(expression_arr[2])
        if expression_arr[1] == "-":
            eval = int(expression_arr[0]) - int(expression_arr[2])
        del expression_arr[:3]
        expression_arr.insert(0, eval)

    return int(expression_arr[0])

It's pretty straightforward from there - we check the next operator (which always has to be at expression_arr[1]) and either add or subtract, and make the corresponding changes to expression_arr.

We can verify that it passes the test case you provided. (I added some logging to help with visualization)

>>> calculate("5+8-3+9")
['5', '+', '8', '-', '3', '+', '9']
[13, '-', '3', '+', '9']
[10, '+', '9']
[19]
19


问:
Hugo not generating the same styling as in development mode
This is my first time I'm trying to generate a static website.

Everything works fine in development mode with hugo server command.
The styling is great, but when I'm trying to generate the final static files with hugo command the theme seems not to be applied properly and I don't understand why.

I've tried two themes (what's in the quickstart and another one) but I get similar results with both.

These are the commands what I've entered into console in the later case:

```<code>hugo new site testsite
cd testsite
cd themes
git clone https://github.com/cowboysmall-tools/hugo-devresume-theme.git
cd ..
cp themes/hugo-devresume-theme/exampleSite/config.toml .

hugo server
# styling seems to work

hugo
# the opened public/index.html is broken
</code>```

Can anyone tell me what am I doing wrong?

I've followed these tutorials:

quick-start

hugo-devresume-theme

UPDATE

after checking the errors in chrome console I can see values like this:

```<code><link href="/dist/css/app.1cb140d8ba31d5b2f1114537dd04802a.css" rel="stylesheet">
</code>```

if I delete the / from the beginning of /dist/css/app.1cb140d8ba31d5b2f1114537dd04802a.css the style seems to be applied correctly.

Obviously I don't want to do this every time manually. Is there any solution for this in configuration?

答:
Meanwhile I've figured out that the problem originates from this setting in config.toml:

```<code>baseURL = "mywebsite.com"
#...
</code>```

Instead of the above setting I've tried this one and it seems to work now properly:

```<code>baseURL = ""
relativeURLs = "True"
#...
</code>```

Body:
This is my first time I'm trying to generate a static website.

Everything works fine in development mode with hugo server command.
The styling is great, but when I'm trying to generate the final static files with hugo command the theme seems not to be applied properly and I don't understand why.

I've tried two themes (what's in the quickstart and another one) but I get similar results with both.

These are the commands what I've entered into console in the later case:

hugo new site testsite
cd testsite
cd themes
git clone https://github.com/cowboysmall-tools/hugo-devresume-theme.git
cd ..
cp themes/hugo-devresume-theme/exampleSite/config.toml .

hugo server
# styling seems to work

hugo
# the opened public/index.html is broken

Can anyone tell me what am I doing wrong?

I've followed these tutorials:

quick-start

hugo-devresume-theme

UPDATE

after checking the errors in chrome console I can see values like this:

<link href="/dist/css/app.1cb140d8ba31d5b2f1114537dd04802a.css" rel="stylesheet">

if I delete the / from the beginning of /dist/css/app.1cb140d8ba31d5b2f1114537dd04802a.css the style seems to be applied correctly.

Obviously I don't want to do this every time manually. Is there any solution for this in configuration?

Body:
Meanwhile I've figured out that the problem originates from this setting in config.toml:

baseURL = "mywebsite.com"
#...

Instead of the above setting I've tried this one and it seems to work now properly:

baseURL = ""
relativeURLs = "True"
#...


问:
transform a curl get request to dart request
i would like to transform a curl get request into http request using the dart language, the curl code is there :

and here is the code i have tried to implement, it doesn't take all parameters :

```<code>     import 'package:http/http.dart' as http;

        void main() async {
          var params = {
            'ad_format': 'DESKTOP_FEED_STANDARD',
            'access_token': '<ACCESS_TOKEN>',
          };
          var query = params.entries.map((p) => '${p.key}=${p.value}').join('&');

          var res = await http.get('https://graph.facebook.com/v2.11/act_AD_ACCOUNT_ID/generatepreviews?$query');
          if (res.statusCode != 200) throw Exception('http.get error: statusCode=${res.statusCode}');
          print(res.body);
        }
</code>```

答:
You are missing the creative query parameter that you add with --data-urlencode. Furthermore, avoid building the url with query parameters yourself. Use the Uri class.

```<code>final params = {
  'ad_format': 'DESKTOP_FEED_STANDARD',
  'access_token': '<ACCESS_TOKEN>',
  'creative': jsonEncode({
    'object_story_spec': {
      // fill in the rest here..
    },
  }),
};
final uri = Uri.https('graph.facebook.com', '/v2.11/act_AD_ACCOUNT_ID/generatepreviews', params);

var res = await http.get(uri);
if (res.statusCode != 200) throw Exception('http.get error: statusCode=${res.statusCode}');
print(res.body);
</code>```

Body:
i would like to transform a curl get request into http request using the dart language, the curl code is there :

and here is the code i have tried to implement, it doesn't take all parameters :

     import 'package:http/http.dart' as http;

        void main() async {
          var params = {
            'ad_format': 'DESKTOP_FEED_STANDARD',
            'access_token': '<ACCESS_TOKEN>',
          };
          var query = params.entries.map((p) => '${p.key}=${p.value}').join('&');

          var res = await http.get('https://graph.facebook.com/v2.11/act_AD_ACCOUNT_ID/generatepreviews?$query');
          if (res.statusCode != 200) throw Exception('http.get error: statusCode=${res.statusCode}');
          print(res.body);
        }

Body:
You are missing the creative query parameter that you add with --data-urlencode. Furthermore, avoid building the url with query parameters yourself. Use the Uri class.

final params = {
  'ad_format': 'DESKTOP_FEED_STANDARD',
  'access_token': '<ACCESS_TOKEN>',
  'creative': jsonEncode({
    'object_story_spec': {
      // fill in the rest here..
    },
  }),
};
final uri = Uri.https('graph.facebook.com', '/v2.11/act_AD_ACCOUNT_ID/generatepreviews', params);

var res = await http.get(uri);
if (res.statusCode != 200) throw Exception('http.get error: statusCode=${res.statusCode}');
print(res.body);


问:
Dotted border around ASP.NET Button

I have a problem with asp:button styling. I added following style:

```<code>.myAspButton    {
        background-image: url("image for button");
        width: 110px;
        height: 25px;
        color: white;
        font-weight: bold;
        vertical-align: middle;
    }
<asp:Button ID="btnAsp" runat="server" Text="hhh" CssClass="myAspButton" BackColor="Transparent" BorderStyle="None" />
</code>```

Problem is when I press button it gets that dotted border around how to remove this?

And also what property to use to change button style when button is pressed down?

答:
This is the outline css property. You can set it just like border.

However, the outline property can be beneficial for people tabbing through controls to see which control currently has focus.

As for the second part of your question, this is not possible with CSS alone. You will need to implement some javascript to change the class on mouse down.

Title: Dotted border around ASP.NET Button

Body:
I have a problem with asp:button styling. I added following style:

.myAspButton    {
        background-image: url("image for button");
        width: 110px;
        height: 25px;
        color: white;
        font-weight: bold;
        vertical-align: middle;
    }
<asp:Button ID="btnAsp" runat="server" Text="hhh" CssClass="myAspButton" BackColor="Transparent" BorderStyle="None" />

Problem is when I press button it gets that dotted border around how to remove this?

And also what property to use to change button style when button is pressed down?


问:
Xamarin : Adding multiple bindings to multiple collection views on the same page
I am currently trying to build two separate collection views on the same page in Xamarin. I keep getting the error that content is set more than once and also that I've set the content binding more than once. How do I add different bindings to two separate collection views on the same page?

ConsumerOrders.xaml page:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:viewmodels="clr-namespace:Shared.ViewModel"
             mc:Ignorable="d"
             x:Class="Shared.consumerOrders">

    <ContentPage.BindingContext>
        <viewmodels:AddedServicesViewModel />
    </ContentPage.BindingContext>

    <d:ContentPage.BindingContext>
        <viewmodels:PastOrderViewModel />
    </d:ContentPage.BindingContext>

    <ScrollView>

        <CollectionView ItemsSource="{Binding  ViewAddedServices}">
            <CollectionView.ItemsLayout>
                <GridItemsLayout Orientation="Vertical"/>
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid Padding="10">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="4"/>
                            <!--0-->
                            <RowDefinition Height="30"/>
                            <!--1-->
                            <RowDefinition Height="20"/>
                            <!--2-->
                            <RowDefinition Height=".25"/>
                            <!--3-->
                            <RowDefinition Height="4"/>
                            <!--4-->
                            <RowDefinition Height="Auto"/>
                            <!--5-->
                            <RowDefinition Height="Auto"/>
                            <!--6-->
                            <RowDefinition Height=".25"/>
                            <!--7-->
                            <RowDefinition Height="Auto"/>
                            <!--8-->
                            <RowDefinition Height="Auto"/>
                            <!--9-->
                            <RowDefinition Height=".25"/>
                            <!--10-->
                            <RowDefinition Height="Auto"/>
                            <!--11-->

                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="4"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="4"/>
                        </Grid.ColumnDefinitions>
                        <Label Text="Services added" FontAttributes="Bold" TextColor="#F65506" Grid.Row="6" Grid.Column="1" Grid.ColumnSpan="2" VerticalTextAlignment="End" HorizontalTextAlignment="Start" FontSize="18"/>
                        <Label Grid.Column="1" Grid.Row="7" BackgroundColor="#707070" Grid.ColumnSpan="3"/>
                        <!--This is a line-->
                        <BoxView BackgroundColor="#F0F0F0" Grid.Row="9" Grid.Column="1" Grid.ColumnSpan="3" CornerRadius="22"/>
                        <Label Grid.Column="1" Grid.Row="9" Padding="10" TextColor="Black" FontSize="18" Text="{Binding BusinessName}" VerticalOptions="CenterAndExpand" HorizontalOptions="StartAndExpand" Grid.ColumnSpan="2"/>
                        <Label Grid.Column="3" Grid.Row="9" Padding="0,0,20,0" TextColor="#F65506" FontAttributes="Bold" FontSize="18" Text="View" VerticalOptions="CenterAndExpand" HorizontalOptions="EndAndExpand" Grid.ColumnSpan="2"/>

                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>

        <CollectionView ItemsSource="{Binding  ViewQuoteStatus}">
            <CollectionView.ItemsLayout>
                <GridItemsLayout Orientation="Vertical"/>
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid Padding="10">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="4"/>
                            <!--0-->
                            <RowDefinition Height="30"/>
                            <!--1-->
                            <RowDefinition Height="20"/>
                            <!--2-->
                            <RowDefinition Height=".25"/>
                            <!--3-->
                            <RowDefinition Height="4"/>
                            <!--4-->
                            <RowDefinition Height="Auto"/>
                            <!--5-->
                            <RowDefinition Height="Auto"/>
                            <!--6-->
                            <RowDefinition Height=".25"/>
                            <!--7-->
                            <RowDefinition Height="Auto"/>
                            <!--8-->
                            <RowDefinition Height="Auto"/>
                            <!--9-->
                            <RowDefinition Height=".25"/>
                            <!--10-->
                            <RowDefinition Height="Auto"/>
                            <!--11-->

                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="4"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="4"/>
                        </Grid.ColumnDefinitions>
                        <Label Text="Past Orderrs" FontAttributes="Bold" TextColor="#F65506" Grid.Row="6" Grid.Column="1" Grid.ColumnSpan="2" VerticalTextAlignment="End" HorizontalTextAlignment="Start" FontSize="18"/>
                        <Label Grid.Column="1" Grid.Row="7" BackgroundColor="#707070" Grid.ColumnSpan="3"/>
                        <!--This is a line-->
                        <BoxView BackgroundColor="#F0F0F0" Grid.Row="9" Grid.Column="1" Grid.ColumnSpan="3" CornerRadius="22"/>
                        <Label Grid.Column="1" Grid.Row="9" Padding="10" TextColor="Black" FontSize="18" Text="{Binding BusinessName}" VerticalOptions="CenterAndExpand" HorizontalOptions="StartAndExpand" Grid.ColumnSpan="2"/>
                        <Label Grid.Column="3" Grid.Row="9" Padding="0,0,20,0" TextColor="#F65506" FontAttributes="Bold" FontSize="18" Text="View" VerticalOptions="CenterAndExpand" HorizontalOptions="EndAndExpand" Grid.ColumnSpan="2"/>

                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </ScrollView>
</ContentPage>
</code>```

AddedServicesViewModel.cs :

```<code>using Shared.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace Shared.ViewModel
{
    class AddedServicesViewModel
    {
        readonly IList<AddedServiceStatus> source;

        public ObservableCollection<AddedServiceStatus> ViewAddedServices { get; private set; }

        public AddedServicesViewModel()
        {
            source = new List<AddedServiceStatus>();
            CreateAddedServicesCollection();

        }

        void CreateAddedServicesCollection()
        {
            source.Add(new AddedServiceStatus
            {
                BusinessName = "Duck's Duct Cleaning"

            });

            source.Add(new AddedServiceStatus
            {
                BusinessName = "Rodney's Home Repair"

            });

            ViewAddedServices = new ObservableCollection<AddedServiceStatus>(source);
        }
    }
}
</code>```

PastOrderViewModel :

```<code>using Shared.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace Shared.ViewModel
{
    class PastOrderViewModel
    {

        readonly IList<PastOrderStatus> source;

        public ObservableCollection<PastOrderStatus> ViewPastOrders { get; private set; }

        public PastOrderViewModel()
        {
            source = new List<PastOrderStatus>();
            CreatePastOrderCollection();

        }

        void CreatePastOrderCollection()
        {
            source.Add(new PastOrderStatus
            {
                BusinessName = "Karen's Magnificent Dog Grooming"

            });

            source.Add(new PastOrderStatus
            {
                BusinessName = "Harry's In Home Haircuts"

            });

            source.Add(new PastOrderStatus
            {
                BusinessName = "Shelly's Floral Arrangements"

            });

            ViewPastOrders = new ObservableCollection<PastOrderStatus>(source);
        }
    }
}
</code>```

答:
You could also bind a ViewModel to each CollectionView separately.

like:

```<code><CollectionView ItemsSource="{Binding  ViewAddedServices}">
    <CollectionView.BindingContext>
      <viewmodels:AddedServicesViewModel/>
    </CollectionView.BindingContext>
     ...
</CollectionView>

<CollectionView ItemsSource="{Binding  ViewPastOrders}">
    <CollectionView.BindingContext>
      <viewmodels:PastOrderViewModel/>
    </CollectionView.BindingContext>
      ...
</CollectionView>
</code>```

Body:
I am currently trying to build two separate collection views on the same page in Xamarin. I keep getting the error that content is set more than once and also that I've set the content binding more than once. How do I add different bindings to two separate collection views on the same page?

ConsumerOrders.xaml page:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:viewmodels="clr-namespace:Shared.ViewModel"
             mc:Ignorable="d"
             x:Class="Shared.consumerOrders">

    <ContentPage.BindingContext>
        <viewmodels:AddedServicesViewModel />
    </ContentPage.BindingContext>

    <d:ContentPage.BindingContext>
        <viewmodels:PastOrderViewModel />
    </d:ContentPage.BindingContext>

    <ScrollView>

        <CollectionView ItemsSource="{Binding  ViewAddedServices}">
            <CollectionView.ItemsLayout>
                <GridItemsLayout Orientation="Vertical"/>
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid Padding="10">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="4"/>

                            <RowDefinition Height="30"/>

                            <RowDefinition Height="20"/>

                            <RowDefinition Height=".25"/>

                            <RowDefinition Height="4"/>

                            <RowDefinition Height="Auto"/>

                            <RowDefinition Height="Auto"/>

                            <RowDefinition Height=".25"/>

                            <RowDefinition Height="Auto"/>

                            <RowDefinition Height="Auto"/>

                            <RowDefinition Height=".25"/>

                            <RowDefinition Height="Auto"/>

                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="4"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="4"/>
                        </Grid.ColumnDefinitions>

                        <BoxView BackgroundColor="#F0F0F0" Grid.Row="9" Grid.Column="1" Grid.ColumnSpan="3" CornerRadius="22"/>

                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>

        <CollectionView ItemsSource="{Binding  ViewQuoteStatus}">
            <CollectionView.ItemsLayout>
                <GridItemsLayout Orientation="Vertical"/>
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid Padding="10">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="4"/>

                            <RowDefinition Height="30"/>

                            <RowDefinition Height="20"/>

                            <RowDefinition Height=".25"/>

                            <RowDefinition Height="4"/>

                            <RowDefinition Height="Auto"/>

                            <RowDefinition Height="Auto"/>

                            <RowDefinition Height=".25"/>

                            <RowDefinition Height="Auto"/>

                            <RowDefinition Height="Auto"/>

                            <RowDefinition Height=".25"/>

                            <RowDefinition Height="Auto"/>

                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="4"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="4"/>
                        </Grid.ColumnDefinitions>

                        <BoxView BackgroundColor="#F0F0F0" Grid.Row="9" Grid.Column="1" Grid.ColumnSpan="3" CornerRadius="22"/>

                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </ScrollView>
</ContentPage>

AddedServicesViewModel.cs :

using Shared.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace Shared.ViewModel
{
    class AddedServicesViewModel
    {
        readonly IList<AddedServiceStatus> source;

        public ObservableCollection<AddedServiceStatus> ViewAddedServices { get; private set; }

        public AddedServicesViewModel()
        {
            source = new List<AddedServiceStatus>();
            CreateAddedServicesCollection();

        }

        void CreateAddedServicesCollection()
        {
            source.Add(new AddedServiceStatus
            {
                BusinessName = "Duck's Duct Cleaning"

            });

            source.Add(new AddedServiceStatus
            {
                BusinessName = "Rodney's Home Repair"

            });

            ViewAddedServices = new ObservableCollection<AddedServiceStatus>(source);
        }
    }
}

PastOrderViewModel :

using Shared.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace Shared.ViewModel
{
    class PastOrderViewModel
    {

        readonly IList<PastOrderStatus> source;

        public ObservableCollection<PastOrderStatus> ViewPastOrders { get; private set; }

        public PastOrderViewModel()
        {
            source = new List<PastOrderStatus>();
            CreatePastOrderCollection();

        }

        void CreatePastOrderCollection()
        {
            source.Add(new PastOrderStatus
            {
                BusinessName = "Karen's Magnificent Dog Grooming"

            });

            source.Add(new PastOrderStatus
            {
                BusinessName = "Harry's In Home Haircuts"

            });

            source.Add(new PastOrderStatus
            {
                BusinessName = "Shelly's Floral Arrangements"

            });

            ViewPastOrders = new ObservableCollection<PastOrderStatus>(source);
        }
    }
}

Body:
You could also bind a ViewModel to each CollectionView separately.

like:

<CollectionView ItemsSource="{Binding  ViewAddedServices}">
    <CollectionView.BindingContext>
      <viewmodels:AddedServicesViewModel/>
    </CollectionView.BindingContext>
     ...
</CollectionView>

<CollectionView ItemsSource="{Binding  ViewPastOrders}">
    <CollectionView.BindingContext>
      <viewmodels:PastOrderViewModel/>
    </CollectionView.BindingContext>
      ...
</CollectionView>


问:
flutter doctor command failed to retrieve the Dart SDK on Ubuntu 18.04
```<code>$flutter doctor
</code>```

Running this command produces this output -

```<code>Downloading Dart SDK from Flutter engine bdc9708d235e582483d299642ad8682826ebb90d...
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:--  0:01:09 --:--:--     0
curl: (35) OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to storage.googleapis.com:443

Failed to retrieve the Dart SDK from: https://storage.googleapis.com/flutter_infra/flutter/bdc9708d235e582483d299642ad8682826ebb90d/dart-sdk-linux-x64.zip
If you're located in China, please see this page:
  https://flutter.dev/community/china
</code>```

I am not from China, and it's my first trial on setting up flutter so I can't understand why this isn't working.
Also I have added flutter to system variables using -

```<code>$nano ~/.bashrc
</code>```

答:
I later realized that storage.googleapis was blocked in Bangladesh that time, so just using a VPN worked.

Note: The site has been blocked yet again.

Body:
$flutter doctor

Running this command produces this output -

Downloading Dart SDK from Flutter engine bdc9708d235e582483d299642ad8682826ebb90d...
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:--  0:01:09 --:--:--     0
curl: (35) OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to storage.googleapis.com:443

Failed to retrieve the Dart SDK from: https://storage.googleapis.com/flutter_infra/flutter/bdc9708d235e582483d299642ad8682826ebb90d/dart-sdk-linux-x64.zip
If you're located in China, please see this page:
  https://flutter.dev/community/china

I am not from China, and it's my first trial on setting up flutter so I can't understand why this isn't working.
Also I have added flutter to system variables using -

$nano ~/.bashrc


问:
how to call different tables in if and else part of the same database in iphone?
I have a database. It has two tables in it. I want to call one table in if condition. If if conditions fails i wanted to call the second table in the else part.

Can any one help by providing the sample code.

Thanks in advance

答:
What kind of database is it? If sqlite, simply modify sql command with the condition.</p>

```<code>NSString* sql;
if (cond) {
    sql = @"SELECT id from foo;";
} else {
    sql = @"SELECT * from bar;";
}
</code>```

Body:
What kind of database is it? If sqlite, simply modify sql command with the condition.

NSString* sql;
if (cond) {
    sql = @"SELECT id from foo;";
} else {
    sql = @"SELECT * from bar;";
}


问:
MS-Teams , trying to send images (present on local machine) to Teams Channel webhook url
I'm trying to send images (present on local machine) to Teams Channel webhook url.

Is this supported in any type of card that is available ?

I see references on how to send images that is present  on other websites, but how to send images that is present on local machine ?

If this is not supported , can someone guide me how to upload image to azure blob container and how to post that image to teams using powershell

答:
You can not send an image from local machine. To display an image inside teams it has to be hosted publicly(Ex: Azure blob storage). You need to use the image URL.<br>
Please take a look into Message card for send image in a card to connector.  </p>

Body:
You can not send an image from local machine. To display an image inside teams it has to be hosted publicly(Ex: Azure blob storage). You need to use the image URL.

Please take a look into Message card for send image in a card to connector.


问:
How to set long click listener on items in BottomNavigationView?
As the title says, I have a BottomNavigationView with 3 Menu Items and want to assign a long click listener to each of them.

I have set an OnNavigationItemSelectedListener on the BottoNavigationView.

I have tried this answer
here
but that did not work out for me...

Any other way you guys recommend?

This is what I have...Regular clicks work btw

```<code>private void setUpNavigationListeners() {
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.add(R.id.fragment_container, new CalendarView()).commit();
    navigation.setOnNavigationItemSelectedListener(
            new BottomNavigationView.OnNavigationItemSelectedListener() {

                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                    Fragment fragment;
                    switch (item.getItemId()) {
                        case R.id.navigation_courses:
                            subtitle.setText(R.string.courses);
                            fragment = new CalendarView();
                            break;
                        case R.id.navigation_assignments:
                            subtitle.setText(R.string.assignments);
                            fragment = new AssignmentView();
                            break;
                        case R.id.navigation_professors:
                            subtitle.setText(R.string.professors);
                            return false;
                        default:
                            return false;
                    }

                    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                    ft.replace(R.id.fragment_container, fragment).commit();
                    return true;
                }

            });
    navigation.setItemIconTintList(null);

    Menu menu = navigation.getMenu();
    MenuItem courses = menu.findItem(R.id.navigation_courses);
    MenuItem assignments = menu.findItem(R.id.navigation_assignments);
    MenuItem prof = menu.findItem(R.id.navigation_professors);

    courses.setActionView(new ImageButton(this));
    courses.getActionView().setLongClickable(true);
    Log.d("Manage", "Is long clickable:" + courses.getActionView().isLongClickable());
    courses.getActionView().setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Log.d("Manage", "Long clicked");
            return true;
        }
    });

}
</code>```

答:
There are two ways to solve the problem.

By findViewById(int id);

bottomNavigationView.findViewById(R.id.action_home).setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            return true;
        }
    });

By 'menuView';

```<code>private void overrideOnMenuItemLongClickListener(BottomNavigationView bottomNavigationView){

if(bottomNavigationView == null){
    return;
}

int count = bottomNavigationView.getChildCount();
if(count <= 0){
    return;
}

ViewGroup menuView = (ViewGroup) bottomNavigationView.getChildAt(0);
if(menuView == null){
    return;
}

int menuItemViewSize = menuView.getChildCount();
if(menuItemViewSize <= 0){
    return;
}

for(int i=0; i < menuItemViewSize; i++){
    menuView.getChildAt(i).setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            return true;
        }
    });
}
</code>```

}

Body:
As the title says, I have a BottomNavigationView with 3 Menu Items and want to assign a long click listener to each of them.

I have set an OnNavigationItemSelectedListener on the BottoNavigationView.

I have tried this answer
here
but that did not work out for me...

Any other way you guys recommend?

This is what I have...Regular clicks work btw

private void setUpNavigationListeners() {
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.add(R.id.fragment_container, new CalendarView()).commit();
    navigation.setOnNavigationItemSelectedListener(
            new BottomNavigationView.OnNavigationItemSelectedListener() {

                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                    Fragment fragment;
                    switch (item.getItemId()) {
                        case R.id.navigation_courses:
                            subtitle.setText(R.string.courses);
                            fragment = new CalendarView();
                            break;
                        case R.id.navigation_assignments:
                            subtitle.setText(R.string.assignments);
                            fragment = new AssignmentView();
                            break;
                        case R.id.navigation_professors:
                            subtitle.setText(R.string.professors);
                            return false;
                        default:
                            return false;
                    }

                    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                    ft.replace(R.id.fragment_container, fragment).commit();
                    return true;
                }

            });
    navigation.setItemIconTintList(null);

    Menu menu = navigation.getMenu();
    MenuItem courses = menu.findItem(R.id.navigation_courses);
    MenuItem assignments = menu.findItem(R.id.navigation_assignments);
    MenuItem prof = menu.findItem(R.id.navigation_professors);

    courses.setActionView(new ImageButton(this));
    courses.getActionView().setLongClickable(true);
    Log.d("Manage", "Is long clickable:" + courses.getActionView().isLongClickable());
    courses.getActionView().setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Log.d("Manage", "Long clicked");
            return true;
        }
    });

}

Body:
There are two ways to solve the problem.

By findViewById(int id);

bottomNavigationView.findViewById(R.id.action_home).setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            return true;
        }
    });

By 'menuView';

private void overrideOnMenuItemLongClickListener(BottomNavigationView bottomNavigationView){

if(bottomNavigationView == null){
    return;
}

int count = bottomNavigationView.getChildCount();
if(count <= 0){
    return;
}

ViewGroup menuView = (ViewGroup) bottomNavigationView.getChildAt(0);
if(menuView == null){
    return;
}

int menuItemViewSize = menuView.getChildCount();
if(menuItemViewSize <= 0){
    return;
}

for(int i=0; i < menuItemViewSize; i++){
    menuView.getChildAt(i).setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            return true;
        }
    });
}

}


问:
Update collection values in Form
How to update values from collection in ASP.NET Form.

My ViewModel:

public class FormVM
{
    public string Name { get; set; }
    public ICollection<OptionsVM> Options { get; set; }
}

```

<p>Controller:</p>

<pre class="lang-cs prettyprint-override"><code>public async Task<IActionResult> Edit(FormVM form) { }
</code>```

How to change values in Options? Now the controller always receive the "Name" but "Options" in always null???

答:
You can use a for loop instead in your form like below:

```<code>@for(int i = 0; i < Model.Options.Count; i++)
{
    <input asp-for="Options[i].Title" class="form-control" />
}
</code>```

For more details, check Expression names and Collections in the docs

Title: Update collection values in Form

Body:
How to update values from collection in ASP.NET Form.

My ViewModel:

public class FormVM
{
    public string Name { get; set; }
    public ICollection<OptionsVM> Options { get; set; }
}

Controller:

public async Task<IActionResult> Edit(FormVM form) { }

How to change values in Options? Now the controller always receive the "Name" but "Options" in always null???

Body:
You can use a for loop instead in your form like below:

@for(int i = 0; i < Model.Options.Count; i++)
{
    <input asp-for="Options[i].Title" class="form-control" />
}

For more details, check Expression names and Collections in the docs


问:
How to store PHP page with variables in DB for email use?
I have a question that someone may think sounds quite stupid, but I'm not a professional developer, just studying, the situation is following.

I'm developing the email system for my site, where I send emails on registration, updates to profile etc. I store the whole body of email in the MySQL DB.

When the user registers I invoke the following function:

```<code>function emailsend($category){
$db=new db();

$embodysql=$db->query("SELECT * FROM emailsys WHERE id=?","$category")->fetchArray();
$embody=$embodysql['body'];

echo "Получили $embody";

$fp=fopen("../emails/emailsent.php", "w") or die("Не могу открыть файл");
fwrite($fp, $embody);
fclose ($fp);
</code>```

As you may notice I write to the emailsent.php contents that I plan to send to the user later. However, I can't figure out, how do I process the contents of the body field in my DB that contains records like $name, $fname. I can pass these arguments when calling on the function, but how to do I tell PHP processor to replace these variables with real values before writing to file and after reading from DB. The example of DB record is following:

```<code><div class="body-text" style="font-family:Helvetica, Arial, sans-serif;font-size:14px;line-height:20px;text-align:left;color:#333333">
<?php
echo"$name $fname";?>Добро пожаловать в <a href="https://ikeen.com">Школу Айкин</a> - место, где вы получите современные и понятные знания, которые сможете применять сразу после обучения.<br><br>
Ваш логин:<?php echo"$login"?>
<br><br>
</div>
</code>```

At what exact stage after reading the contents from DB and creating the file and how do I process those variables?

Thank you in advance.

答:
I understood that you want to write $name and $fname while writing to the file.

There are 2 methods that come to my mind first

If you send value to the emailsend($category) function;

emailsend ($category, $name, $fname)

$date = date("YmdHis"); // I added

$Embody = $date. "\t". $name. "\t". $fname. "\t". $ Embodysql['body'];

$name and $fname are saved in the session.

$date = date("YmdHis"); // I added

$ Embody = $date. "\t". $_SESSION["name"]. "\t". $_SESSION ["fname"]. "\t". $ Embodysql['body'];

Body:
I have a question that someone may think sounds quite stupid, but I'm not a professional developer, just studying, the situation is following.

I'm developing the email system for my site, where I send emails on registration, updates to profile etc. I store the whole body of email in the MySQL DB.

When the user registers I invoke the following function:

function emailsend($category){
$db=new db();

$embodysql=$db->query("SELECT * FROM emailsys WHERE id=?","$category")->fetchArray();
$embody=$embodysql['body'];

echo "Получили $embody";

$fp=fopen("../emails/emailsent.php", "w") or die("Не могу открыть файл");
fwrite($fp, $embody);
fclose ($fp);

As you may notice I write to the emailsent.php contents that I plan to send to the user later. However, I can't figure out, how do I process the contents of the body field in my DB that contains records like $name, $fname. I can pass these arguments when calling on the function, but how to do I tell PHP processor to replace these variables with real values before writing to file and after reading from DB. The example of DB record is following:

<?php
echo"$name $fname";?>Добро пожаловать в Школу Айкин - место, где вы получите современные и понятные знания, которые сможете применять сразу после обучения.

Ваш логин:<?php echo"$login"?>

At what exact stage after reading the contents from DB and creating the file and how do I process those variables?

Thank you in advance.


问:
System.NullReferenceException: Object reference not set to an instance of an object

Possible Duplicates:
  What is a NullReferenceException in .NET?
  System.NullReferenceException: Object reference not set to an instance of an object

I am using the following code.

```<code>public partial class SectionControls_SingleBanners : SectionControlBaseClass
{
    private SingleBanners _section;

    protected void Page_PreRender(object sender, EventArgs e) {
        updateViews();

        if (RssCapable(this._section.GetType()) && _section.BannersEntries.Rows.Count > 0)  {
</code>```

So here on this code I am getting the error

```<code>this._section.GetType();
</code>```

How can this problem be fixed?

答:
Most likely, it means that _section is null and has not been set.  You either need

```<code>private SingleBanners _section = new SingleBanners(...);
</code>```

or

```<code>_section = ...
</code>```

somewhere else before you can use it.

Body:
Possible Duplicates:
  What is a NullReferenceException in .NET?
  System.NullReferenceException: Object reference not set to an instance of an object

I am using the following code.

public partial class SectionControls_SingleBanners : SectionControlBaseClass
{
    private SingleBanners _section;

    protected void Page_PreRender(object sender, EventArgs e) {
        updateViews();

        if (RssCapable(this._section.GetType()) && _section.BannersEntries.Rows.Count > 0)  {

So here on this code I am getting the error

this._section.GetType();

How can this problem be fixed?

Body:
Most likely, it means that _section is null and has not been set.  You either need

private SingleBanners _section = new SingleBanners(...);

or

_section = ...

somewhere else before you can use it.


问:
How does filter works for Struct property in spark dataframe?
I want to filter out some records from a dataframe using filter method. I have a address Array of Struct, which I am comparing with a column value. I am using below code:

```<code>entityJoinB_df.filter(col("addressstructm.streetName").cast(StringType) =!= (col("streetName")))
</code>```

I want to remove the element from address struct based on comparision. The sample schema is as below:

```<code>root
 |-- apartmentnumber: string (nullable = true)
 |-- streetName: string (nullable = true)
 |-- streetName2: string (nullable = true)
 |-- fullName: string (nullable = false)
 |-- address: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- id: string (nullable = true)
 |    |    |-- streetName: string (nullable = true)
 |    |    |-- streetName2: string (nullable = true)
 |    |    |-- buildingName: string (nullable = true)
 |    |    |-- type: string (nullable = true)
 |    |    |-- city: string (nullable = true)
 |-- isActive: boolean (nullable = false)
</code>```

But its not working. What can be the problem. Can anyone help?

Sample Input:

```<code>[
{
"apartmentnumber":  122,
"streetName": "ABC ABC",
"streetName2": "CBD",
"fullName": "MR. X"
"address": [{
            "streetName": "ABC ABC",
            "streetName2": "CBD",
            "buildingName": "ONE",
            "city":"NY"
           },
           {
            "streetName": "XYZ ABC",
            "streetName2": "XCB",
            "buildingName": "ONE",
            "city":"NY"
           }]
}
]
</code>```

Sample Output:

```<code>{
"apartmentnumber":  122,
"streetName": "ABC ABC",
"streetName2": "CBD",
"fullName": "MR. X"
"address": [
           {
            "streetName": "XYZ ABC",
            "streetName2": "XCB",
            "buildingName": "ONE",
            "city":"NY"
           }]
}
]
</code>```

Thanks,
Upen

答:
I think your problem can be solved by modifying the filter expression to

```<code>import org.apache.spark.sql.functions._
    entityJoinB_df.withColumn("address",
      expr("filter(addressstructm.address, x-> ( x.streetName != streetName AND x.streetName != 'Secondary' ) )"))
</code>```

assuming addressstructm is the alias of your Dataframe

Below is the sample struct similar to yours

```<code>import org.apache.spark.sql.functions._

object StructParsin {

  def main(args: Array[String]): Unit = {
    val spark = Constant.getSparkSess
    import spark.implicits._

    val df = List(
      Apartment(Array(Element("ABC ABC","123"),Element("XYZ ABC","123")),"ABC ABC"),
      Apartment(Array(Element("DEF","123"),Element("DEF1","123")),"XYZ")
    )
      .toDF

    df.printSchema()
    df.withColumn("newAddress",
      expr("filter(address, x -> ( x.streetName != streetName AND x.streetName != 'Secondary' ))"))
      .show()
  }
}

case class Element (streetName: String)

case class Apartment(address: Array[Element],streetName:String)

</code>```

Body:
I want to filter out some records from a dataframe using filter method. I have a address Array of Struct, which I am comparing with a column value. I am using below code:

entityJoinB_df.filter(col("addressstructm.streetName").cast(StringType) =!= (col("streetName")))

I want to remove the element from address struct based on comparision. The sample schema is as below:

root
 |-- apartmentnumber: string (nullable = true)
 |-- streetName: string (nullable = true)
 |-- streetName2: string (nullable = true)
 |-- fullName: string (nullable = false)
 |-- address: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- id: string (nullable = true)
 |    |    |-- streetName: string (nullable = true)
 |    |    |-- streetName2: string (nullable = true)
 |    |    |-- buildingName: string (nullable = true)
 |    |    |-- type: string (nullable = true)
 |    |    |-- city: string (nullable = true)
 |-- isActive: boolean (nullable = false)

But its not working. What can be the problem. Can anyone help?

Sample Input:

[
{
"apartmentnumber":  122,
"streetName": "ABC ABC",
"streetName2": "CBD",
"fullName": "MR. X"
"address": [{
            "streetName": "ABC ABC",
            "streetName2": "CBD",
            "buildingName": "ONE",
            "city":"NY"
           },
           {
            "streetName": "XYZ ABC",
            "streetName2": "XCB",
            "buildingName": "ONE",
            "city":"NY"
           }]
}
]

Sample Output:

{
"apartmentnumber":  122,
"streetName": "ABC ABC",
"streetName2": "CBD",
"fullName": "MR. X"
"address": [
           {
            "streetName": "XYZ ABC",
            "streetName2": "XCB",
            "buildingName": "ONE",
            "city":"NY"
           }]
}
]

Thanks,
Upen

Body:
I think your problem can be solved by modifying the filter expression to

import org.apache.spark.sql.functions._
    entityJoinB_df.withColumn("address",
      expr("filter(addressstructm.address, x-> ( x.streetName != streetName AND x.streetName != 'Secondary' ) )"))

assuming addressstructm is the alias of your Dataframe

Below is the sample struct similar to yours

import org.apache.spark.sql.functions._

object StructParsin {

  def main(args: Array[String]): Unit = {
    val spark = Constant.getSparkSess
    import spark.implicits._

    val df = List(
      Apartment(Array(Element("ABC ABC","123"),Element("XYZ ABC","123")),"ABC ABC"),
      Apartment(Array(Element("DEF","123"),Element("DEF1","123")),"XYZ")
    )
      .toDF

    df.printSchema()
    df.withColumn("newAddress",
      expr("filter(address, x -> ( x.streetName != streetName AND x.streetName != 'Secondary' ))"))
      .show()
  }
}

case class Element (streetName: String)

case class Apartment(address: Array[Element],streetName:String)


问:
Deserializing nested JSON in Unity
I have tried and exhausted many of the solutions I could find for simply being able to deserialize the follow response I am getting from my node server.

```<code>[{"treeData":"[{\"title\":\"GroupTitle\",\"nodeItemIds\":[5,1,3],\"children\":[]}] }]
</code>```

I have set up my classes as the following:

```<code>[Serializable]
public class Groups
{
    public string title { get; set; }
    public string tagClass { get; set; }
    public List<string> tagIds { get; set; }
    public List<Groups> children { get; set; }
}

[Serializable]
public class ResponseData
{
    public string treeData { get; set; }
}
</code>```

And I am attempting to use

```<code>ResponseData responseData = JsonUtility.FromJson<ResponseData>(www.downloadHandler.text);
string jsonString = Regex.Unescape(responseData.treeData);
List<Groups> groups = JsonConvert.DeserializeObject<List<Groups>>(jsonString);
</code>```

But this gives me the following error ArgumentException: JSON must represent an object type.

I don't know where I am going wrong. Any help on how I can deserialize this data into my classes is HUGELY appreciated.

答:
Your Json is broken.

[{"treeData":"[{\"title\":\"GroupTitle\",\"nodeItemIds\":[5,1,3],\"children\":[]}] }]

Even disregarding escaping properly, you are missing a doublequote. This is how it should look.

[{"treeData":"[{\"title\":\"GroupTitle\",\"nodeItemIds\":[5,1,3],\"children\":[]}]"}]

Other than that, your code looks like it ought to work.

Title: Deserializing nested JSON in Unity

Body:
I have tried and exhausted many of the solutions I could find for simply being able to deserialize the follow response I am getting from my node server.

[{"treeData":"[{\"title\":\"GroupTitle\",\"nodeItemIds\":[5,1,3],\"children\":[]}] }]

I have set up my classes as the following:

[Serializable]
public class Groups
{
    public string title { get; set; }
    public string tagClass { get; set; }
    public List<string> tagIds { get; set; }
    public List<Groups> children { get; set; }
}

[Serializable]
public class ResponseData
{
    public string treeData { get; set; }
}

And I am attempting to use

ResponseData responseData = JsonUtility.FromJson<ResponseData>(www.downloadHandler.text);
string jsonString = Regex.Unescape(responseData.treeData);
List<Groups> groups = JsonConvert.DeserializeObject<List<Groups>>(jsonString);

But this gives me the following error ArgumentException: JSON must represent an object type.

I don't know where I am going wrong. Any help on how I can deserialize this data into my classes is HUGELY appreciated.


问:
Room database onConflict = OnConflictStrategy.REPLACE not working
I am working on Room database and trying to insert list of items(eg. list of Quotes which contains author name and a quote in my case).

Following is the code I am using:

```<code>// view model
BaseApp.daoInstance?.appDao()?.insertQuotes(response!!)

// dao
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertQuotes(listData: MutableList<Quote>)
</code>```

When I try to insert the same data again, it always inserts as a new data instead of replacing with the current items.

I have researched a lot for this OnConflictStrategy.REPLACE but could not find any proper answer.

Is there anyone facing the same issue and found solution or am I doing anything wrong?

Thank you in advance...!!!

答:
Have you tried to index your main column and mark it as unique?</p>

```<code>@Index(value = {"quote"}, unique = true)}
</code>```

Body:
I am working on Room database and trying to insert list of items(eg. list of Quotes which contains author name and a quote in my case).

Following is the code I am using:

// view model
BaseApp.daoInstance?.appDao()?.insertQuotes(response!!)

// dao
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertQuotes(listData: MutableList<Quote>)

When I try to insert the same data again, it always inserts as a new data instead of replacing with the current items.

I have researched a lot for this OnConflictStrategy.REPLACE but could not find any proper answer.

Is there anyone facing the same issue and found solution or am I doing anything wrong?

Thank you in advance...!!!

Body:
Have you tried to index your main column and mark it as unique?

@Index(value = {"quote"}, unique = true)}