问:
How to access parent attributes with a relation of belongsTo and hasMany within the same class?
I'm working with Laravel 8, so far I have two models that I want to relate

```<code>Role[1]---[n]Users

class Role extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
    ];

    public function users(): HasMany
    {
        return $this->hasMany(User::class,'user_id_fk5');
    }
}
</code>```

and the Users looks like this

```<code>class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'rol_id',
    ];

    public function role()
    {
        return $this->belongsTo(Role::class, 'rol_id_fk4');
    }

    public function hasRole($role): bool
    {
        Log::info('Checking role ' . $role->role()->first()->get());
        Log::info('Current User rolId ' . $this->rol_id);
        Log::info('Current User name ' . $this->name);
        if ($this->role()->where('id', $role)->first()) {
            return true;
        }
        return false;
    }
}
</code>```

I have read the documentation and it appears that I'm using the correct relationships but I'm not sure how can I query the data from within the same model.

This will result in an exception

```<code>$role->role()->first()->get()
</code>```

I checked this but they query the data from outside of the model and thus not sure how to access the data from the same instance, any clue?

Update

I workarounded the issue with this

```<code>public function hasRole(string $roleName): bool
{
    $role = Role::where('id', $this->rol_id)->first();
    if ($role->name == $roleName) {
        return true;
    }
    return false;
}
</code>```

at this point, I don't understand what we gain by adding the belongsTo

答:
Get user

```<code>$user = User::first();
</code>```

After that summoned the relationship and access a property that you want

```<code>$user->role->name
</code>```

Body:
I'm working with Laravel 8, so far I have two models that I want to relate

Role[1]---[n]Users

class Role extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
    ];

    public function users(): HasMany
    {
        return $this->hasMany(User::class,'user_id_fk5');
    }
}

and the Users looks like this

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'rol_id',
    ];

    public function role()
    {
        return $this->belongsTo(Role::class, 'rol_id_fk4');
    }

    public function hasRole($role): bool
    {
        Log::info('Checking role ' . $role->role()->first()->get());
        Log::info('Current User rolId ' . $this->rol_id);
        Log::info('Current User name ' . $this->name);
        if ($this->role()->where('id', $role)->first()) {
            return true;
        }
        return false;
    }
}

I have read the documentation and it appears that I'm using the correct relationships but I'm not sure how can I query the data from within the same model.

This will result in an exception

$role->role()->first()->get()

I checked this but they query the data from outside of the model and thus not sure how to access the data from the same instance, any clue?

Update

I workarounded the issue with this

public function hasRole(string $roleName): bool
{
    $role = Role::where('id', $this->rol_id)->first();
    if ($role->name == $roleName) {
        return true;
    }
    return false;
}

at this point, I don't understand what we gain by adding the belongsTo

Body:
Get user

$user = User::first();

After that summoned the relationship and access a property that you want

$user->role->name


来源: stackexchange

问:
Remove duplicate entries in a list
I have this data:

[
  { "name": "Eric", "origin": "Tristan da Cunha" },
  { "name": "Eric", "origin": "Tristan da Cunha" },
  { "name": "Adelaide", "origin": "Cayman Islands" }
]
```

There is a duplicated data, how do I remove it before converting to a list?

答:
Remove Item by it's name

```<code> final ids = uniqueLedgerList.map((e) => e["name"]).toSet();
 uniqueLedgerList.retainWhere((x) => ids.remove(x["name"]));

 log("Remove Duplicate Items--->$uniqueLedgerList");
</code>```

ContentLicense: CC BY-SA 4.0

Title: Remove duplicate entries in a list

Body:
I have this data:

[
  { "name": "Eric", "origin": "Tristan da Cunha" },
  { "name": "Eric", "origin": "Tristan da Cunha" },
  { "name": "Adelaide", "origin": "Cayman Islands" }
]

There is a duplicated data, how do I remove it before converting to a list?

Body:
Remove Item by it's name

 final ids = uniqueLedgerList.map((e) => e["name"]).toSet();
 uniqueLedgerList.retainWhere((x) => ids.remove(x["name"]));

 log("Remove Duplicate Items--->$uniqueLedgerList");


问:
JPA excesive querys for mapping an entity
I have the following entity:

```<code>    @Name("estructuraOrganica")
    @Entity
    @Table(name = "srht_estructuras_organicas")
    public class EstructuraOrganica extends EntidadBasica implements Auditable,
    Desplegable<EstructuraOrganica> {

private static final long serialVersionUID = 1L;

@NotNull
@Length(max = 50)
@Column(name = "codigo", nullable = false, length = 50)
private String codigo;

@Length(max = 300)
@Column(name = "nombre", nullable = true, length = 160)
private String nombre;

@Column(name = "institucion_id")
private Long institucionId;

@NotNull
@Length(max = 1)
@Column(name = "es_uarh", nullable = false, length = 1)
private String esUARH;

@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "catalogo_jerarquia_proceso_unidad_id", nullable = false)
@Fetch(FetchMode.SELECT)
private Catalogo catalogoJerarquiaProcesoUnidad;

@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "estatuto_id", nullable = false)
private Estatuto estatuto;

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
@JoinColumn(name = "estructura_organica_padre_id", nullable = true)
private EstructuraOrganica estructuraOrganicaPadre;

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
@JoinColumn(name = "padre_auxiliar_estructura_id", nullable = true)
private EstructuraOrganica estructuraOrganicaJerarquia;

@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "estado_id", nullable = false)
@Fetch(FetchMode.SELECT)
private Estado estado;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY,                             mappedBy                    =                           "estructuraOrganicaPadre")
@OrderBy(value = "codigo")
private List<EstructuraOrganica> estructurasOrganicas;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, mappedBy = "estructuraOrganica")
private List<OrganigramaPosicion> organigramasPosiciones;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, mappedBy = "estructuraOrganica")
@Where(clause = "estado_id=1")
private List<OrganigramaPosicion> organigramasPosicionesActivas;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, mappedBy = "estructuraOrganicaPadre")
@OrderBy(value = "codigo")
@Where(clause = "estado_id=1")
private List<EstructuraOrganica> estructurasOrganicasActivas;

@Column(name = "estado_plan_vacaciones")
private Integer estadoPlanVacaciones;

@Column(name = "tipo")
private Integer tipo;

@Column(name = "puesto_jefe_inmediato")
private Long puestoJefeInmediato;

@Length(max = 10)
@Column(name = "codigo_mef", nullable = true, length = 10)
private String codigoMef;

@Transient
private Boolean puedeEliminarse;

@Transient
private Boolean uarh;

@Transient
private Boolean puedeGrabarse;

@Transient
private RegimenDePersonal regimenDePersonal;

@Column(name="institucion_desconcentrada_id")
private Long institucionDesconcentradaId;

... Getters and Setters omitted...

   }
</code>```

Now the JPQL query to find a certain instance of this entity is the following:

```<code>   SELECT o FROM EstructuraOrganica o WHERE o.estatuto.institucion.id=:institucionId and        o.estructuraOrganicaPadre is null AND o.estado.id=1 ORDER BY o.codigo ASC")
</code>```

However, the problem is that this simple query is generating an excesive count of calls to the database... doing selects basically. A native sql for doing the same could be:

```<code>    SELECT * from sch_senres.srht_estructuras_organicas,
          sch_senres.srht_estatutos,
          sch_senres.srht_instituciones,
          sch_senres.srht_estados
    WHERE sch_senres.srht_estructuras_organicas.estatuto_id=sch_senres.srht_estatutos.id
    AND   sch_senres.srht_estructuras_organicas.estado_id=sch_senres.srht_estados.id
    AND   sch_senres.srht_estatutos.institucion_id=sch_senres.srht_instituciones.id
    AND   sch_senres.srht_instituciones.id=91122
    AND   sch_senres.srht_estados.id=1
    AND   sch_senres.srht_estructuras_organicas.estructura_organica_padre_id IS NULL
    ORDER BY sch_senres.srht_estructuras_organicas.codigo
</code>```

So the idea was to create a NativeQuery like this:

```<code>    Query query=entityManager.createNativeQuery("SELECT * from  sch_senres.srht_estructuras_organicas,"+                                                    "sch_senres.srht_estatutos,sch_senres.srht_instituciones,"+
                                                "sch_senres.srht_estados "+
                                                "WHERE sch_senres.srht_estructuras_organicas.estatuto_id=sch_senres.srht_estatutos.id "+
                                                "AND   sch_senres.srht_estructuras_organicas.estado_id=sch_senres.srht_estados.id "+
                                                "AND   sch_senres.srht_estatutos.institucion_id=sch_senres.srht_instituciones.id "+
                                                "AND   sch_senres.srht_instituciones.id= :institucionId "+
                                                "AND   sch_senres.srht_estados.id=1 "+
                                                "AND   sch_senres.srht_estructuras_organicas.estructura_organica_padre_id IS NULL "+
                                                "ORDER BY sch_senres.srht_estructuras_organicas.codigo", EstructuraOrganica.class);
    query.setParameter("institucionId", institucionId);
</code>```

However I got no result... hibernate continues doing like 50 calls to the database. Does anybody know why is this happening, and how could I avoid so many calls?. Thanks a lot.

答: You've got a lot of associations mapped in that class. I expect all the selects are happening when you're using, and therefore initializing, the lazy references. If it's not causing problems, just let it be. Otherwise read about Fetching Strategies to understand the different ways you can tune hibernate queries.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have the following entity:

    @Name("estructuraOrganica")
    @Entity
    @Table(name = "srht_estructuras_organicas")
    public class EstructuraOrganica extends EntidadBasica implements Auditable,
    Desplegable<EstructuraOrganica> {

private static final long serialVersionUID = 1L;

@NotNull
@Length(max = 50)
@Column(name = "codigo", nullable = false, length = 50)
private String codigo;

@Length(max = 300)
@Column(name = "nombre", nullable = true, length = 160)
private String nombre;

@Column(name = "institucion_id")
private Long institucionId;

@NotNull
@Length(max = 1)
@Column(name = "es_uarh", nullable = false, length = 1)
private String esUARH;

@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "catalogo_jerarquia_proceso_unidad_id", nullable = false)
@Fetch(FetchMode.SELECT)
private Catalogo catalogoJerarquiaProcesoUnidad;

@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "estatuto_id", nullable = false)
private Estatuto estatuto;

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
@JoinColumn(name = "estructura_organica_padre_id", nullable = true)
private EstructuraOrganica estructuraOrganicaPadre;

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
@JoinColumn(name = "padre_auxiliar_estructura_id", nullable = true)
private EstructuraOrganica estructuraOrganicaJerarquia;

@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "estado_id", nullable = false)
@Fetch(FetchMode.SELECT)
private Estado estado;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY,                             mappedBy                    =                           "estructuraOrganicaPadre")
@OrderBy(value = "codigo")
private List<EstructuraOrganica> estructurasOrganicas;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, mappedBy = "estructuraOrganica")
private List<OrganigramaPosicion> organigramasPosiciones;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, mappedBy = "estructuraOrganica")
@Where(clause = "estado_id=1")
private List<OrganigramaPosicion> organigramasPosicionesActivas;

@OneToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY, mappedBy = "estructuraOrganicaPadre")
@OrderBy(value = "codigo")
@Where(clause = "estado_id=1")
private List<EstructuraOrganica> estructurasOrganicasActivas;

@Column(name = "estado_plan_vacaciones")
private Integer estadoPlanVacaciones;

@Column(name = "tipo")
private Integer tipo;

@Column(name = "puesto_jefe_inmediato")
private Long puestoJefeInmediato;

@Length(max = 10)
@Column(name = "codigo_mef", nullable = true, length = 10)
private String codigoMef;

@Transient
private Boolean puedeEliminarse;

@Transient
private Boolean uarh;

@Transient
private Boolean puedeGrabarse;

@Transient
private RegimenDePersonal regimenDePersonal;

@Column(name="institucion_desconcentrada_id")
private Long institucionDesconcentradaId;

... Getters and Setters omitted...

   }

Now the JPQL query to find a certain instance of this entity is the following:

   SELECT o FROM EstructuraOrganica o WHERE o.estatuto.institucion.id=:institucionId and        o.estructuraOrganicaPadre is null AND o.estado.id=1 ORDER BY o.codigo ASC")

However, the problem is that this simple query is generating an excesive count of calls to the database... doing selects basically. A native sql for doing the same could be:

    SELECT * from sch_senres.srht_estructuras_organicas,
          sch_senres.srht_estatutos,
          sch_senres.srht_instituciones,
          sch_senres.srht_estados
    WHERE sch_senres.srht_estructuras_organicas.estatuto_id=sch_senres.srht_estatutos.id
    AND   sch_senres.srht_estructuras_organicas.estado_id=sch_senres.srht_estados.id
    AND   sch_senres.srht_estatutos.institucion_id=sch_senres.srht_instituciones.id
    AND   sch_senres.srht_instituciones.id=91122
    AND   sch_senres.srht_estados.id=1
    AND   sch_senres.srht_estructuras_organicas.estructura_organica_padre_id IS NULL
    ORDER BY sch_senres.srht_estructuras_organicas.codigo

So the idea was to create a NativeQuery like this:

    Query query=entityManager.createNativeQuery("SELECT * from  sch_senres.srht_estructuras_organicas,"+                                                    "sch_senres.srht_estatutos,sch_senres.srht_instituciones,"+
                                                "sch_senres.srht_estados "+
                                                "WHERE sch_senres.srht_estructuras_organicas.estatuto_id=sch_senres.srht_estatutos.id "+
                                                "AND   sch_senres.srht_estructuras_organicas.estado_id=sch_senres.srht_estados.id "+
                                                "AND   sch_senres.srht_estatutos.institucion_id=sch_senres.srht_instituciones.id "+
                                                "AND   sch_senres.srht_instituciones.id= :institucionId "+
                                                "AND   sch_senres.srht_estados.id=1 "+
                                                "AND   sch_senres.srht_estructuras_organicas.estructura_organica_padre_id IS NULL "+
                                                "ORDER BY sch_senres.srht_estructuras_organicas.codigo", EstructuraOrganica.class);
    query.setParameter("institucionId", institucionId);

However I got no result... hibernate continues doing like 50 calls to the database. Does anybody know why is this happening, and how could I avoid so many calls?. Thanks a lot.


问:
command to compile typescript in react-native?
I went through this tutorial

https://reactnative.dev/docs/typescript

However, I am using npm and the only command to compile typescript I see in that page is "yarn tsc"

I found another blog that said "npm start" does this but when I add this one line to my typescript, it still compiles and should not since I do not declare a variable something, nor a variable called blah ->

something = blah;

What command should I run to compile/type-check?  I am looking for it to fail because of the above line.

答: You can also use npx to run things you don't have globally: npx tsc


问:
How to install and enable php extension for tidy html on a beanstalk with amazon linux 2? (php ver. 7.4)
How to install php extension for tidy html on a beanstalk with amazon linux 2?

I have tried the following

```<code>commands:
  1-aml-extras-epel:
    command: "amazon-linux-extras install epel -y"
  2-epel:
    command: "yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm -y"
  3-yum-clean:
    command: "yum clean all"
  4-tidy-php:
    command: "yum install php74-php-tidy.x86_64 -y"
</code>```

All of the commands run correctly but I get the following error at runtime of php scripts:

Class 'tidy' not found

答:
You cannot pull a single package/extension from "remi" repository, you must take the full stack from the same repository.

For a proper configuration, simply follow the Wizard instructions.

Body:
How to install php extension for tidy html on a beanstalk with amazon linux 2?

I have tried the following

commands:
  1-aml-extras-epel:
    command: "amazon-linux-extras install epel -y"
  2-epel:
    command: "yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm -y"
  3-yum-clean:
    command: "yum clean all"
  4-tidy-php:
    command: "yum install php74-php-tidy.x86_64 -y"

All of the commands run correctly but I get the following error at runtime of php scripts:

Class 'tidy' not found


问:
Looping through websites and saving information to dataframe
Resubmitted for clarity.

I am trying use Python to loop through a list of websites and extract information (locations, $$$ under management, partners, etc) from each site in the form of a dataframe (i.e. each website will have its own dataframe).

However, when I place the code inside a for loop as shown below, it will only extract information from the first website in the list. I am not receiving any errors in my code, it simply terminates after the first loop. I am not sure why it doesn't move onto the second loop. I have tried moving the driver.quit() inside and outside the loop and neither worked.

Code below:

```<code>from bs4 import BeautifulSoup
import numpy as np
from time import sleep
from random import randint
from selenium import webdriver
import pandas as pd
import spacy
from spacy import displacy
import requests
import re
import en_core_web_sm
nlp = en_core_web_sm.load()
NER = spacy.load("en_core_web_sm")

final_list = ['https://www.google.com','https://www.bing.com', 'https://www.amazon.com']
pd.set_option("display.max_rows", None, "display.max_columns", None)

df = []

for i in range(0,2):
    driver = webdriver.Chrome("C:/Users/~~~/chromedriver.exe")
    url = final_list[i]
    driver.get(url)
    sleep(randint(5,15))
    soup = BeautifulSoup(driver.page_source, 'html.parser')
    body=soup.body.text
    body = ' '.join(body.split())
    text3= NER(body)
    displacy.render(text3,style="ent",jupyter=True)
    doc = NER(body)
    entities = [(e.label_,e.text) for e in doc.ents]

    df[i] = pd.DataFrame(entities, columns=['Entity','Identified'])

driver.quit()
</code>```

答:
Change:

```<code>df[i] = pd.DataFrame(entities, columns=['Entity','Identified'])
</code>```

to:

```<code>df.append(pd.DataFrame(entities, columns=['Entity','Identified']))
</code>```

Body:
Resubmitted for clarity.

I am trying use Python to loop through a list of websites and extract information (locations, $$$ under management, partners, etc) from each site in the form of a dataframe (i.e. each website will have its own dataframe).

However, when I place the code inside a for loop as shown below, it will only extract information from the first website in the list. I am not receiving any errors in my code, it simply terminates after the first loop. I am not sure why it doesn't move onto the second loop. I have tried moving the driver.quit() inside and outside the loop and neither worked.

Code below:

from bs4 import BeautifulSoup
import numpy as np
from time import sleep
from random import randint
from selenium import webdriver
import pandas as pd
import spacy
from spacy import displacy
import requests
import re
import en_core_web_sm
nlp = en_core_web_sm.load()
NER = spacy.load("en_core_web_sm")

final_list = ['https://www.google.com','https://www.bing.com', 'https://www.amazon.com']
pd.set_option("display.max_rows", None, "display.max_columns", None)

df = []

for i in range(0,2):
    driver = webdriver.Chrome("C:/Users/~~~/chromedriver.exe")
    url = final_list[i]
    driver.get(url)
    sleep(randint(5,15))
    soup = BeautifulSoup(driver.page_source, 'html.parser')
    body=soup.body.text
    body = ' '.join(body.split())
    text3= NER(body)
    displacy.render(text3,style="ent",jupyter=True)
    doc = NER(body)
    entities = [(e.label_,e.text) for e in doc.ents]

    df[i] = pd.DataFrame(entities, columns=['Entity','Identified'])

driver.quit()

Body:
Change:

df[i] = pd.DataFrame(entities, columns=['Entity','Identified'])

to:

df.append(pd.DataFrame(entities, columns=['Entity','Identified']))


问:
Transact SQL - VARCHAR(8000) Data Type
I've coded the Tran_GenerateColumnList stored procedure to dynamically create a comma delimited list of column values to be passed into an execution call where the columns exist in both the View and the Table. This database has a lot of columns on a particular table and I am exceeding the 8000 character limit for the VARCHAR data type. Any suggestions on a possible work around? Do I need to use LEN and create a second variable to concatenate to the first variable? Any input would be greatly appreciated.

http://pastebin.com/kRDevWTD

答: Are you on SQL Server 2005 or higher? If so, can't you use varchar(max)? See also SQL Server: When 8000 Characters Is Not Enough for ideas if you are indeed stuck on pre 2005

Title: Transact SQL - VARCHAR(8000) Data Type


问:
Convert JSON to Avro in Jmeter
I need to convert a JSON message to Avro so that I can send it to Kafka.

I have the sample JSON request and also the schema from an avsc file for Avro.

Any ideas how I can do this please?

Thanks

答:
You will need:

To download Avro Java libraries and put them (along with the dependencies) to JMeter Classpath

To restart JMeter to pick up the libraries

To add a suitable JSR223 Test Element with the relevant Groovy code to perform the conversion, a piece of example code is below:

```<code>String schemaJson = 'your schema here'
String genericRecordStr = 'your json payload here'
def schemaParser = new org.apache.avro.Schema.Parser()
def schema = schemaParser.parse(schemaJson)
def decoderFactory = new org.apache.avro.io.DecoderFactory()
def decoder = decoderFactory.jsonDecoder(schema, genericRecordStr)
def reader = new org.apache.avro.generic.GenericDatumReader()(schema)
def record = reader.read(null, decoder)
</code>```

To send the message to Kafka, out of box JMeter doesn't support Kafka a couple of options are described in the Apache Kafka - How to Load Test with JMeter article

Title: Convert JSON to Avro in Jmeter

Body:
You will need:

To download Avro Java libraries and put them (along with the dependencies) to JMeter Classpath

To restart JMeter to pick up the libraries

To add a suitable JSR223 Test Element with the relevant Groovy code to perform the conversion, a piece of example code is below:

String schemaJson = 'your schema here'
String genericRecordStr = 'your json payload here'
def schemaParser = new org.apache.avro.Schema.Parser()
def schema = schemaParser.parse(schemaJson)
def decoderFactory = new org.apache.avro.io.DecoderFactory()
def decoder = decoderFactory.jsonDecoder(schema, genericRecordStr)
def reader = new org.apache.avro.generic.GenericDatumReader()(schema)
def record = reader.read(null, decoder)

To send the message to Kafka, out of box JMeter doesn't support Kafka a couple of options are described in the Apache Kafka - How to Load Test with JMeter article


问:
Because calendar depends on table_calendar >=2.3.0 which requires Flutter SDK version >=1.17.0, version solving failed
I have this error while running pubget table_calendar (^3.0.3) in my Calendar app. Here is my pubspec file</p>
```<code>name: calendar
description: A new Flutter project.
version: 1.0.0+1
environment:
  sdk: ">=2.12.0 <3.0.0"
dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  table_calendar: ^3.0.3

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^1.0.0
flutter:
uses-material-design: true
</code>```

答:
i am not getting any error , its work totally fine with me with the same packages and sdk

you can try changing the sdk version to   sdk: ">=1.17.0 <3.0.0"

```<code>name: getx_test_1
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  get: ^4.6.1
  table_calendar: ^3.0.3

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^1.0.0

flutter:
  uses-material-design: true
</code>```

Body:
I have this error while running pubget table_calendar (^3.0.3) in my Calendar app. Here is my pubspec file

name: calendar
description: A new Flutter project.
version: 1.0.0+1
environment:
  sdk: ">=2.12.0 <3.0.0"
dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  table_calendar: ^3.0.3

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^1.0.0
flutter:
uses-material-design: true

Body:
i am not getting any error , its work totally fine with me with the same packages and sdk

you can try changing the sdk version to   sdk: ">=1.17.0 <3.0.0"

name: getx_test_1
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  get: ^4.6.1
  table_calendar: ^3.0.3

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^1.0.0

flutter:
  uses-material-design: true


问:
Some function for preparing string on Typescript There is a need for a more elegant solution
I have a function for preparing string for a search query. But it looks so difficult  There is a need for a more elegant solution. Maybe someone can take a look and provide something better?
It is original func.

```<code>export const transformedSortFunc = (sortingPath) => {
  let transformPath;
  if (sortingPath) {
    if (sortingPath[0] === '-') {
      const sortingValue = get(SORTING_PATH_MAP, sortingPath.slice(1));
      transformPath = sortingValue ? `-${sortingValue}` : undefined;
    } else {
      transformPath = get(SORTING_PATH_MAP, sortingPath);
    }
  }
  return transformPath || sortingPath;
};

const SORTING_PATH_MAP = {
    asset: 'asset.type'
}
</code>```

Input parameters can be

```<code>  const conditional = [
        'id', 'asset', 'conditional', '-id', '-asset', '-conditional' ,
    ]
</code>```

I am using lodash.

For some incoming lines, I need to add a continuation.
For some, no. Lines can be with a minus, so I added additional checks. It ends up looking very complicated

答:
Maybe this will work for you?

```<code>tsf=s=>SORTING_PATH_MAP[(s??"").replace(/^-/,"")] ?? s;
</code>```

tsf() will remove an optional leading - while looking in SORTING_PATH_MAP and will use the result if it exists, otherwise it will return s directly.

Body:
I have a function for preparing string for a search query. But it looks so difficult  There is a need for a more elegant solution. Maybe someone can take a look and provide something better?
It is original func.

export const transformedSortFunc = (sortingPath) => {
  let transformPath;
  if (sortingPath) {
    if (sortingPath[0] === '-') {
      const sortingValue = get(SORTING_PATH_MAP, sortingPath.slice(1));
      transformPath = sortingValue ? `-${sortingValue}` : undefined;
    } else {
      transformPath = get(SORTING_PATH_MAP, sortingPath);
    }
  }
  return transformPath || sortingPath;
};

const SORTING_PATH_MAP = {
    asset: 'asset.type'
}

Input parameters can be

  const conditional = [
        'id', 'asset', 'conditional', '-id', '-asset', '-conditional' ,
    ]

I am using lodash.

For some incoming lines, I need to add a continuation.
For some, no. Lines can be with a minus, so I added additional checks. It ends up looking very complicated

Body:
Maybe this will work for you?

tsf=s=>SORTING_PATH_MAP[(s??"").replace(/^-/,"")] ?? s;

tsf() will remove an optional leading - while looking in SORTING_PATH_MAP and will use the result if it exists, otherwise it will return s directly.


问:
Laravel pagination bootstrap broken?
I have been trying to find a fix for this problem.

I have included use Illuminate\Pagination\Paginator; in my AppServiceProvider and added Paginator::useBootstrap(); in my public function boot().

It comes out like the image above. Is anyone encountering this as well? Any help would be greatly appreciated.

答: are you using laravel/ui? if yes did you install the npm packages and compile them?</p>

Title: Laravel pagination bootstrap broken?


问:
How to add spacing between columns in Bootstrap 5?
screenshot

i want like this

As you can see in the picture, I can't put a space between the red and blue columns. I tried many Bootstrap classes, but I couldn't get the result I wanted. I added m-4 to the Navbar, Header and the sections below. When I add a few divs in the row, the left and right length (in m-4 equal) is distorted. I want to keep the left and right spacing fixed and adjust the spacing of the columns inside. How will I do this?

<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">

            example

            example

            example

            example

            example

            example

```

答:
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
  href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
  rel="stylesheet"
/>

With Proper Bootstrap - Structure

        example

        example

        example

        example

        example

        example

```

Body:
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
  href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
  rel="stylesheet"
/>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<header>
  <div
    class="m-4 px-4"
    style="background-color: white; border-radius: 10px"
  ></div>
</header>

<section class="container-fluid p-4">
  <h1>With Proper Bootstrap - Structure</h1>

  <div class="row" style="background-color: white; border-radius: 10px">
    <div class="col-lg-6 mb-4 mb-lg-0">
      <div class="p-4" style="background-color: red; border-radius: 10px">
        example
      </div>
    </div>
    <div class="col-lg-6 mb-4 mb-lg-0">
      <div class="p-4" style="background-color: blue; border-radius: 10px">
        example
      </div>
    </div>
  </div>
  <div class="row mt-4" style="background-color: white; border-radius: 10px">
    <div class="col-lg-3 mb-4 mb-lg-0">
      <div class="p-4" style="background-color: red; border-radius: 10px">
        example
      </div>
    </div>
    <div class="col-lg-3 mb-4 mb-lg-0">
      <div class="p-4" style="background-color: red; border-radius: 10px">
        example
      </div>
    </div>
    <div class="col-lg-3 mb-4 mb-lg-0">
      <div class="p-4" style="background-color: blue; border-radius: 10px">
        example
      </div>
    </div>
    <div class="col-lg-3 mb-4 mb-lg-0">
      <div class="p-4" style="background-color: blue; border-radius: 10px">
        example
      </div>
    </div>
  </div>
</section>


问:
I have data frame with two columns and I would like to Fill missing column B value based on the column A value Range
```<code>df = pd.DataFrame({"id":[123, 1232, 2233, 2233, 2233, 2233],
                   "result":['', '', '', '', '', True]})
</code>```

I would like to fill true in result column where ever the id is same in Column A values.

ex: I don't want to update the true for the id 123, 1232.

Could someone help me with this. I'm trying to use Bfill but true is getting updated for all the id's.

答:
One way using pandas.DataFrame.groupby with transform:

```<code>df["result"] = df["result"].replace("", np.nan)
df["result"] = df.groupby("id")["result"].transform("first").fillna("")
</code>```

Output:

```<code>     id result
0   123
1  1232
2  2233   True
3  2233   True
4  2233   True
5  2233   True
</code>```

Body:
df = pd.DataFrame({"id":[123, 1232, 2233, 2233, 2233, 2233],
                   "result":['', '', '', '', '', True]})

I would like to fill true in result column where ever the id is same in Column A values.

ex: I don't want to update the true for the id 123, 1232.

Could someone help me with this. I'm trying to use Bfill but true is getting updated for all the id's.

Body:
One way using pandas.DataFrame.groupby with transform:

df["result"] = df["result"].replace("", np.nan)
df["result"] = df.groupby("id")["result"].transform("first").fillna("")

Output:

     id result
0   123
1  1232
2  2233   True
3  2233   True
4  2233   True
5  2233   True


问:
Flutter Cannot run Project.afterEvaluate(Closure) when the project is already evaluated
Workaround way: Looks like there is dependecy of onesignal plugin on flutter_tools. The solution is to place onesignal plugin after it in the sequence in the "android/app/build.gradle":

```<code>apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
</code>```

After upgrading Flutter version from 2.8.1 to 2.10, I started getting the following error. I reinstalled Flutter but the result did not change. When I downgrade Flutter to 2.8.1, it works fine, but when I upgrade to 2.10 it doesn't.

```<code>
Running Gradle task 'assembleDebug'...

FAILURE: Build failed with an exception.

* Where:
Script '/Users/aksoyhlc/flutter/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 421

 What went wrong:
A problem occurred evaluating root project 'android'.
> A problem occurred configuring project ':app'.
   > **Cannot run Project.afterEvaluate(Closure) when the project is already evaluated.**

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUİLD FAILED in 798ms
Exception: Gradle task assembleDebug failed with exit code 1
</code>```

part of android/app/build.gradle file

```<code>buildscript {
    repositories {

        google()  // Google's Maven repository
        maven { url 'https://plugins.gradle.org/m2/' }
    }
    dependencies {

        classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.6, 0.99.99]'
        classpath 'com.google.gms:google-services:4.3.8'
    }
}
allprojects {

    repositories {
        // Check that you have the following line (if not, add it):
        google()  // Google's Maven repository

    }
}
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
</code>```

android/build.gradle file

```<code>buildscript {
    ext.kotlin_version = '1.6.10'
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.8'

    }

}

allprojects {
    repositories {
        google()
        mavenCentral()
       /* maven {
            url "${project(':background_fetch').projectDir}/libs"
        }*/
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

</code>```
```<code>[✓] Flutter (Channel stable, 2.10.0, on macOS 12.0.1 21A559 darwin-x64, locale
    tr-TR)
    • Flutter version 2.10.0 at /Users/aksoyhlc/flutter/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 5f105a6ca7 (4 days ago), 2022-02-01 14:15:42 -0800
    • Engine revision 776efd2034
    • Dart version 2.16.0
    • DevTools version 2.9.2

[✓] Android toolchain - develop for Android devices (Android SDK version
    32.1.0-rc1)
    • Android SDK at /Users/aksoyhlc/Library/Android/sdk
    • Platform android-32, build-tools 32.1.0-rc1
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • CocoaPods version 1.11.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)

[✓] VS Code (version 1.64.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.34.0

[✓] Connected device (2 available)
    • Redmi Note 8 Pro (mobile) • ------- • android-arm64  • Android 11
      (API 30)
    • Chrome (web)              • chrome           • web-javascript • Google
      Chrome 98.0.4758.80

[✓] HTTP Host Availability
    • All required HTTP hosts are available
</code>```

答:
Looks like there is dependecy of onesignal plugin on flutter_tools.
The solution is to place onesignal plugin after it in the sequence in the "android/app/build.gradle":</p>
```<code>apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
</code>```

Body:
Workaround way: Looks like there is dependecy of onesignal plugin on flutter_tools. The solution is to place onesignal plugin after it in the sequence in the "android/app/build.gradle":

apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'

After upgrading Flutter version from 2.8.1 to 2.10, I started getting the following error. I reinstalled Flutter but the result did not change. When I downgrade Flutter to 2.8.1, it works fine, but when I upgrade to 2.10 it doesn't.

Running Gradle task 'assembleDebug'...

FAILURE: Build failed with an exception.

* Where:
Script '/Users/aksoyhlc/flutter/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 421

 What went wrong:
A problem occurred evaluating root project 'android'.
> A problem occurred configuring project ':app'.
   > **Cannot run Project.afterEvaluate(Closure) when the project is already evaluated.**

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUİLD FAILED in 798ms
Exception: Gradle task assembleDebug failed with exit code 1

part of android/app/build.gradle file

buildscript {
    repositories {

        google()  // Google's Maven repository
        maven { url 'https://plugins.gradle.org/m2/' }
    }
    dependencies {

        classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.6, 0.99.99]'
        classpath 'com.google.gms:google-services:4.3.8'
    }
}
allprojects {

    repositories {
        // Check that you have the following line (if not, add it):
        google()  // Google's Maven repository

    }
}
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'

android/build.gradle file

buildscript {
    ext.kotlin_version = '1.6.10'
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.8'

    }

}

allprojects {
    repositories {
        google()
        mavenCentral()
       /* maven {
            url "${project(':background_fetch').projectDir}/libs"
        }*/
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

[✓] Flutter (Channel stable, 2.10.0, on macOS 12.0.1 21A559 darwin-x64, locale
    tr-TR)
    • Flutter version 2.10.0 at /Users/aksoyhlc/flutter/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 5f105a6ca7 (4 days ago), 2022-02-01 14:15:42 -0800
    • Engine revision 776efd2034
    • Dart version 2.16.0
    • DevTools version 2.9.2

[✓] Android toolchain - develop for Android devices (Android SDK version
    32.1.0-rc1)
    • Android SDK at /Users/aksoyhlc/Library/Android/sdk
    • Platform android-32, build-tools 32.1.0-rc1
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • CocoaPods version 1.11.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)

[✓] VS Code (version 1.64.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.34.0

[✓] Connected device (2 available)
    • Redmi Note 8 Pro (mobile) • ------- • android-arm64  • Android 11
      (API 30)
    • Chrome (web)              • chrome           • web-javascript • Google
      Chrome 98.0.4758.80

[✓] HTTP Host Availability
    • All required HTTP hosts are available


问:
electron: google 403 We're sorry, but you do not have access to this page. That’s all we know
I'm developing an electron application. When I load the google login page using iframe, I get an error: '403. That’s an error. We're sorry, but you do not have access to this page. That’s all we know.'

How can I skip this error and get the google login page?

Q: Why not use an electron window to load the google login page?

A: It's true that using an electron window to load the google login page doesn't have any errors! But electron window will consume more memory!

Please help me!

答:
Display external web content in an isolated frame and process.

Process: Renderer This class is not exported from the 'electron'
module. It is only available as a return value of other methods in the
Electron API.

Use the webview tag to embed 'guest' content (such as web pages) in
your Electron app. The guest content is contained within the webview
container. An embedded page within your app controls how the guest
content is laid out and rendered.

Unlike an iframe, the webview runs in a separate process than your
app. It doesn't have the same permissions as your web page and all
interactions between your app and embedded content will be
asynchronous. This keeps your app safe from embedded content.
Note: Most methods called on the webview from the host page require a
synchronous call to the main process.

Reference

if you are using iframe for google sign you will get a content security policy (CSP) error
A result like this

```<code><iframe style="display: flex ;height: 1000px" width="100%" height="100%"
        src="https://accounts.google.com/signin/v2/identifier?service=mail&passive=1209600&osid=1&continue=https%3A%2F%2Fmail.google.com%2Fmail%2Fu%2F0%2F&followup=https%3A%2F%2Fmail.google.com%2Fmail%2Fu%2F0%2F&emr=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin"></iframe>
</code>```

Solution:

Electron already introduced a webview tag

So The result may like this

```<code>    <webview style="
height: 500px;display: flex"  src="https://accounts.google.com/signin/v2/identifier?service=mail&passive=1209600&osid=1&continue=https%3A%2F%2Fmail.google.com%2Fmail%2Fu%2F0%2F&followup=https%3A%2F%2Fmail.google.com%2Fmail%2Fu%2F0%2F&emr=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin"  ></webview>
</code>```

NB:

You must add the webPreferences property in Browserwindow and the webview tag must be true otherwise the view tag will be hidden. The default webview tag is false .like this

So you must add like this

```<code> function createWindow() {
    win = new BrowserWindow({width: 800, height: 600, webPreferences: {webviewTag: true}})
    win.loadURL(url.format({
        pathname: path.join(__dirname, 'index.html'),
        protocol: 'file:',
        slashes: true
    }))
}
</code>```

Body:
Display external web content in an isolated frame and process.

Process: Renderer This class is not exported from the 'electron'
module. It is only available as a return value of other methods in the
Electron API.

Use the webview tag to embed 'guest' content (such as web pages) in
your Electron app. The guest content is contained within the webview
container. An embedded page within your app controls how the guest
content is laid out and rendered.

Unlike an iframe, the webview runs in a separate process than your
app. It doesn't have the same permissions as your web page and all
interactions between your app and embedded content will be
asynchronous. This keeps your app safe from embedded content.
Note: Most methods called on the webview from the host page require a
synchronous call to the main process.

Reference

if you are using iframe for google sign you will get a content security policy (CSP) error
A result like this

<iframe style="display: flex ;height: 1000px" width="100%" height="100%"
        src="https://accounts.google.com/signin/v2/identifier?service=mail&passive=1209600&osid=1&continue=https%3A%2F%2Fmail.google.com%2Fmail%2Fu%2F0%2F&followup=https%3A%2F%2Fmail.google.com%2Fmail%2Fu%2F0%2F&emr=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin"></iframe>

Solution:

Electron already introduced a webview tag

So The result may like this

    <webview style="
height: 500px;display: flex"  src="https://accounts.google.com/signin/v2/identifier?service=mail&passive=1209600&osid=1&continue=https%3A%2F%2Fmail.google.com%2Fmail%2Fu%2F0%2F&followup=https%3A%2F%2Fmail.google.com%2Fmail%2Fu%2F0%2F&emr=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin"  ></webview>

NB:

You must add the webPreferences property in Browserwindow and the webview tag must be true otherwise the view tag will be hidden. The default webview tag is false .like this

So you must add like this

 function createWindow() {
    win = new BrowserWindow({width: 800, height: 600, webPreferences: {webviewTag: true}})
    win.loadURL(url.format({
        pathname: path.join(__dirname, 'index.html'),
        protocol: 'file:',
        slashes: true
    }))
}


问:
How to check event scheduler status mysql
In MySQL, we can enable the event scheduler by following query:

```<code>SET GLOBAL event_scheduler = ON;
</code>```

Similarly, to turn off the scheduler:

```<code>SET GLOBAL event_scheduler = OFF;
</code>```

But, Is there any query/way to check the status of this event_scheduler whether it's on or off?

答:
Use below command to see event status , you can choose any of them.

```<code>SELECT @@global.event_scheduler
or
SHOW variables WHERE variable_name ='event_scheduler'
</code>```

To enable event temporarily ON or OFF

```<code>SET GLOBAL event_scheduler = OFF;
SET GLOBAL event_scheduler = ON;
</code>```

For permanent setup go to my.cnf or my.ini or inside /etc/my.cnf.d/server.cnf file and under [mysqld] set event_scheduler =ON or event_scheduler=OFF depending on your requirements.

Body:
In MySQL, we can enable the event scheduler by following query:

SET GLOBAL event_scheduler = ON;

Similarly, to turn off the scheduler:

SET GLOBAL event_scheduler = OFF;

But, Is there any query/way to check the status of this event_scheduler whether it's on or off?

Body:
Use below command to see event status , you can choose any of them.

SELECT @@global.event_scheduler
or
SHOW variables WHERE variable_name ='event_scheduler'

To enable event temporarily ON or OFF

SET GLOBAL event_scheduler = OFF;
SET GLOBAL event_scheduler = ON;

For permanent setup go to my.cnf or my.ini or inside /etc/my.cnf.d/server.cnf file and under [mysqld] set event_scheduler =ON or event_scheduler=OFF depending on your requirements.


问:
c# - cast generic class to its base non-generic class
I have following classes:

```<code>public abstract class CustomerBase
{
    public long CustomerNumber { get; set; }
    public string Name { get; set; }
}

public abstract class CustomerWithChildern<T> : CustomerBase
    where T: CustomerBase
{
    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

public class SalesOffice : CustomerWithChildern<NationalNegotiation>
{
}
</code>```

The SalesOffice is just one of few classes which represent different levels of customer hierarchy. Now I need to walk through this hierarchy from some point (CustomerBase). I can't figure out how to implement without using reflection. I'd like to implement something like:

```<code>    public void WalkHierarchy(CustomerBase start)
    {
        Print(start.CustomerNumber);
        if (start is CustomerWithChildern<>)
        {
            foreach(ch in start.Childern)
            {
                WalkHierarchy(ch);
            }
        }
    }
</code>```

Is there any chance I could get something like this working?

The solution based on suggested has-childern interface I implemented:

```<code>public interface ICustomerWithChildern
{
    IEnumerable ChildernEnum { get; }
}

public abstract class CustomerWithChildern<T> : CustomerBase, ICustomerWithChildern
    where T: CustomerBase
{
    public IEnumerable ChildernEnum { get { return Childern; } }

    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

    public void WalkHierarchy(CustomerBase start)
    {
        var x = start.CustomerNumber;
        var c = start as ICustomerWithChildern;
        if (c != null)
        {
            foreach(var ch in c.ChildernEnum)
            {
                WalkHierarchy((CustomerBase)ch);
            }
        }
    }
</code>```

答: Explicitly with that method, no. However you can achieve the same functionality with an interface. In fact, you could just have your generic class implement IEnumerable. It's also worth noting that your class should also have "where T : CustomerBase" in order to ensure type safety.</p>

OwnerDisplayName: Buthrakaur

ContentLicense: CC BY-SA 2.5

Body:
I have following classes:

public abstract class CustomerBase
{
    public long CustomerNumber { get; set; }
    public string Name { get; set; }
}

public abstract class CustomerWithChildern<T> : CustomerBase
    where T: CustomerBase
{
    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

public class SalesOffice : CustomerWithChildern<NationalNegotiation>
{
}

The SalesOffice is just one of few classes which represent different levels of customer hierarchy. Now I need to walk through this hierarchy from some point (CustomerBase). I can't figure out how to implement without using reflection. I'd like to implement something like:

    public void WalkHierarchy(CustomerBase start)
    {
        Print(start.CustomerNumber);
        if (start is CustomerWithChildern<>)
        {
            foreach(ch in start.Childern)
            {
                WalkHierarchy(ch);
            }
        }
    }

Is there any chance I could get something like this working?

The solution based on suggested has-childern interface I implemented:

public interface ICustomerWithChildern
{
    IEnumerable ChildernEnum { get; }
}

public abstract class CustomerWithChildern<T> : CustomerBase, ICustomerWithChildern
    where T: CustomerBase
{
    public IEnumerable ChildernEnum { get { return Childern; } }

    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

    public void WalkHierarchy(CustomerBase start)
    {
        var x = start.CustomerNumber;
        var c = start as ICustomerWithChildern;
        if (c != null)
        {
            foreach(var ch in c.ChildernEnum)
            {
                WalkHierarchy((CustomerBase)ch);
            }
        }
    }

LastEditorDisplayName: Buthrakaur

OwnerDisplayName: Adam Robinson


问:
Jfree chart Mouse Drag to Zoom
How to modify mouseDragged event of ChartPanel such that I want to do some processing before/after the zooming is done?
I have the following chartPanel,

```<code>JFreeChart chart = new JFreeChart(
                "Demo", JFreeChart.DEFAULT_TITLE_FONT,plot, true);
ChartPanel chartPanel = new ChartPanel(chart);
</code>```

Whenever the mouse is dragged, I want to call my function before/ after the mouseDragged() is called. How to do this ?

```<code>chartPanel.addMouseMotionListener(new MouseMotionListener() {

    @Override
    public void mouseDragged(MouseEvent e) {
        // TODO Auto-generated method stub
    }
</code>```

i am unable to see super.mouseDragged(e).
how to invoke my function after the chart is zoomed. Basically what i want to do is after the chart is zoomed, I want to get the range of x and y coordinates and add a suitable XYAnnotation. How can I do this ?

答:
You can override mouseDragged() in org.jfree.chart.ChartPanel and do your processing before or after super.mouseDragged(e).

Addendum: MouseMotionAdapter may be a convenient alternative:

```<code>chartPanel.addMouseMotionListener(new MouseMotionAdapter() {

    @Override
    public void mouseDragged(MouseEvent e) {
        // process before
        super.mouseDragged(e);
        // process after
    }
});
</code>```

Title: Jfree chart Mouse Drag to Zoom

Body:
How to modify mouseDragged event of ChartPanel such that I want to do some processing before/after the zooming is done?
I have the following chartPanel,

JFreeChart chart = new JFreeChart(
                "Demo", JFreeChart.DEFAULT_TITLE_FONT,plot, true);
ChartPanel chartPanel = new ChartPanel(chart);

Whenever the mouse is dragged, I want to call my function before/ after the mouseDragged() is called. How to do this ?

chartPanel.addMouseMotionListener(new MouseMotionListener() {

    @Override
    public void mouseDragged(MouseEvent e) {
        // TODO Auto-generated method stub
    }

i am unable to see super.mouseDragged(e).
how to invoke my function after the chart is zoomed. Basically what i want to do is after the chart is zoomed, I want to get the range of x and y coordinates and add a suitable XYAnnotation. How can I do this ?

Body:
You can override mouseDragged() in org.jfree.chart.ChartPanel and do your processing before or after super.mouseDragged(e).

Addendum: MouseMotionAdapter may be a convenient alternative:

chartPanel.addMouseMotionListener(new MouseMotionAdapter() {

    @Override
    public void mouseDragged(MouseEvent e) {
        // process before
        super.mouseDragged(e);
        // process after
    }
});


问:
How to fix pytorch 'RuntimeError: Expected object of type torch.cuda.LongTensor but found type torch.LongTensor'
I'm trying to get this code running using FloydHub's GPU.
When I run the train.py script under train_model folder, I'm getting the RuntimeError mentioned.

Here is the full traceback:

Traceback (most recent call last):

  File "./train_model/train.py", line 79, in

  answer = model(batch)

  File "/usr/local/lib/python3.6/site-packages/torch/nn/modules/module.py", line 477, in call

  result = self.forward(*input, **kwargs)

  File "/floyd/home/train_model/model.py", line 29, in forward

  vecs = self.embed(batch.text)

  File "/usr/local/lib/python3.6/site-packages/torch/nn/modules/module.py", line 477, in call

  result = self.forward(*input, **kwargs)

  File "/usr/local/lib/python3.6/site-packages/torch/nn/modules/sparse.py", line 110, in forward

  self.norm_type, self.scale_grad_by_freq, self.sparse)

  File "/usr/local/lib/python3.6/site-packages/torch/nn/functional.py", line 1110, in embedding

  return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse)

  RuntimeError: Expected object of type torch.cuda.LongTensor but found type torch.LongTensor for argument #3 'index'

I understand that parts of code are using GPU and other parts aren't but not knowing how to identify these and get all of the code to run on GPU.

Please help!

答: i resolved this error by running my code in Tensorflow 2 , so it might be a TF version issue</p>


问:
react : array state is not iterable
I have this array state :

```<code>  const [players, setPlayers] = useState([]);

</code>```

I want every time I add a player, to add the new value in addition to the previous ones
so I did this:

```<code>  const addPlayerHandler = (name) => {
    setPlayers({ players: [...players, name] });
  };
</code>```

when I add the first value works fine, but the second value it gives me error : players is not iterable, when did arrays become uniterable ?

答: I had the same issue, it was because I used useEffect() on window load to set state to the JSON.parse(localStorage.getItem("array") so my array was essentially turning into an Object and that's why it was not iterable</p>

Title: react : array state is not iterable

Body:
I have this array state :

  const [players, setPlayers] = useState([]);

I want every time I add a player, to add the new value in addition to the previous ones
so I did this:

  const addPlayerHandler = (name) => {
    setPlayers({ players: [...players, name] });
  };

when I add the first value works fine, but the second value it gives me error : players is not iterable, when did arrays become uniterable ?


问:
How to Combine Multiple Excel into one with Talend
I'm a new in Talend and need some help.

I want to write data in the same excel file containing different sheets, I have 2 tFileOuputExcel, I put the same file name and different sheet names,

In output the data is written only in the first sheet but not in the second sheet.

Below is the screenshot of my job.

答:
You can use tFileExcel-Components 13.3 by Jan Lolling on Talend Exchange. We have been using it in our project without any issues. You can use

tFileExcelWorkbookOpen - to open excel file (blank template file)

tFileExcelSheetOutput - to write to each sheet of the workbook opened above.

tFileExcelWorkbookSave - to save the excel file


问:
Build failed because of error spawn enomem in gatsby in amplify server. how to fix?
I have encountered the build error like this when deploying Gatsby project in AWS Amplify server.
Project is built successfully in local, but the build failed because of the following error in amplify server. Please let me know the solution.
enter image description here

答:
It's hard to say with 0 details. I've made a quick research and this is what I've found:

If you have extremely large images (up to 4000px wide for example), try to resize towards a lower number (1920px for example)

If you tweaked the build command adding some environment variables (GATSBY_CPU_COUNT for example), try lowering the number:

```<code>GATSBY_CPU_COUNT=1 npx gatsby build
</code>```

Check if the environment variables are defined in Amplify or in the corresponding configuration files

Related topics:

https://github.com/gatsbyjs/gatsby/issues/13980

https://github.com/gatsbyjs/gatsby/issues/16381

https://discuss.circleci.com/t/build-fails-with-error-spawn-enomem/30537/9

Body:
It's hard to say with 0 details. I've made a quick research and this is what I've found:

If you have extremely large images (up to 4000px wide for example), try to resize towards a lower number (1920px for example)

If you tweaked the build command adding some environment variables (GATSBY_CPU_COUNT for example), try lowering the number:

GATSBY_CPU_COUNT=1 npx gatsby build

Check if the environment variables are defined in Amplify or in the corresponding configuration files

Related topics:

https://github.com/gatsbyjs/gatsby/issues/13980

https://github.com/gatsbyjs/gatsby/issues/16381

https://discuss.circleci.com/t/build-fails-with-error-spawn-enomem/30537/9


问:
How To Save Data For Bookmarks?
I'm creating a very simple bookmarks menu for my app.  I just need to save 3 strings for each object.

I was thinking of using core data but I don't want this to be connected with my core database for various reasons.  Therefore what other easy options do I have?  NSUserDefaults or .plist?

I just need to save the 3 strings for each object then load them into a table view to be viewed.

答:
I'd recommend NSUserDefaults - is certainly easier. I tend to only use plist files for static data that I want to be editable as the developer, but from the application want it to be read-only (such as coordinates for objects on an embedded map image).

From your description, you would probably want to store an NSArray containing NSDictionary.

```<code>// Get the user defaults object
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

// Load your bookmarks (editable array)
NSMutableArray *bookmarks = [[NSMutableArray alloc]init];
NSArray *bookmarksLoaded = [userDefaults arrayForKey:@"bookmarks"];
if (bookmarksLoaded != nil) {
    [bookmarks initWithArray:bookmarksLoaded];
} else {
    [bookmarks init];
}

// Add a bookmark
NSMutableDictionary *bookmark = [NSMutableDictionary new];
[bookmark setValue:@"value" forKey:@"name"];
[bookmark setValue:@"value" forKey:@"description"];
[bookmark setValue:@"value" forKey:@"code"];
[bookmarks addObject:bookmark];

// Save your (updated) bookmarks
[userDefaults setObject:bookmarks forKey:@"bookmarks"];
[userDefaults synchronize];

// Memory cleanup
[bookmarks release];
</code>```

Title: How To Save Data For Bookmarks?

Body:
I'd recommend NSUserDefaults - is certainly easier. I tend to only use plist files for static data that I want to be editable as the developer, but from the application want it to be read-only (such as coordinates for objects on an embedded map image).

From your description, you would probably want to store an NSArray containing NSDictionary.

// Get the user defaults object
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

// Load your bookmarks (editable array)
NSMutableArray *bookmarks = [[NSMutableArray alloc]init];
NSArray *bookmarksLoaded = [userDefaults arrayForKey:@"bookmarks"];
if (bookmarksLoaded != nil) {
    [bookmarks initWithArray:bookmarksLoaded];
} else {
    [bookmarks init];
}

// Add a bookmark
NSMutableDictionary *bookmark = [NSMutableDictionary new];
[bookmark setValue:@"value" forKey:@"name"];
[bookmark setValue:@"value" forKey:@"description"];
[bookmark setValue:@"value" forKey:@"code"];
[bookmarks addObject:bookmark];

// Save your (updated) bookmarks
[userDefaults setObject:bookmarks forKey:@"bookmarks"];
[userDefaults synchronize];

// Memory cleanup
[bookmarks release];


问:
Entity Framework Core 6 - IEntityTypeConfiguration Separate Configuration Class
Using EF Core 6, a sequence can be set up in the model builder, and then use to generate values for properties following way.

```<code>//DBContex Class
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.HasSequence<int>("OrderNumbers");

    modelBuilder.Entity<Order>()
        .Property(o => o.OrderNo)
        .HasDefaultValueSql("NEXT VALUE FOR shared.OrderNumbers");
}
</code>```

I'm trying to move the DbConfigurations to a model-specific seperate configuration class:

```<code>//Seperate Configuration Class
public class OrdertEntityConfiguration : IEntityTypeConfiguration<Order>
{
    public void Configure(EntityTypeBuilder<Order> builder)
    {
        builder.HasSequence("OrderNumbers").StartsAt(1000);

    }
}
</code>```

But it gives following error:

Error CS1929  'EntityTypeBuilder' does not contain a definition
for 'HasSequence' and the best extension method overload
'RelationalModelBuilderExtensions.HasSequence(ModelBuilder, string,
string?)' requires a receiver of type 'ModelBuilder'

Any Solutions?

答: A sequence does not belong to an entity, you must keep in main DbContext</p>

Body:
Using EF Core 6, a sequence can be set up in the model builder, and then use to generate values for properties following way.

//DBContex Class
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.HasSequence<int>("OrderNumbers");

    modelBuilder.Entity<Order>()
        .Property(o => o.OrderNo)
        .HasDefaultValueSql("NEXT VALUE FOR shared.OrderNumbers");
}

I'm trying to move the DbConfigurations to a model-specific seperate configuration class:

//Seperate Configuration Class
public class OrdertEntityConfiguration : IEntityTypeConfiguration<Order>
{
    public void Configure(EntityTypeBuilder<Order> builder)
    {
        builder.HasSequence("OrderNumbers").StartsAt(1000);

    }
}

But it gives following error:

Error CS1929  'EntityTypeBuilder' does not contain a definition
for 'HasSequence' and the best extension method overload
'RelationalModelBuilderExtensions.HasSequence(ModelBuilder, string,
string?)' requires a receiver of type 'ModelBuilder'

Any Solutions?


问:
Trying to load messages from Azure Service Bus to ADLS with Apache Spark Databricks
I am trying to move messages in Azure Service Bus queues to ADLS with Databricks.

The code that I'm using is as follows:

```<code>from azure.servicebus import ServiceBusClient, ServiceBusMessage

CONNECTION_STR = "Endpoint=sb://carlsbus.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=2BIOtFdooJFIkhZF0qxtYEoK32hJa39DseStw="

QUEUE_NAME = "myqueue"

servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR, logging_enable=True)

receiver = servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME, max_wait_time=5)
</code>```

And when I execute the following:

```<code>mystream2 = spark.readStream.format(receiver).load("/mnt/lake/RAW/FormulaClassification/F1Area/F1Domain/flightStream/1")
</code>```

But I keep on getting the error:

```<code>'ServiceBusReceivedMessage' object has no attribute '_get_object_id'
</code>```

Any thoughts why I'm getting the error?

答:
Error - 'ServiceBusReceivedMessage' object has no attribute '_get_object_id'

Above error occurs when you try to use dataframe inside a function. In your case you have used receiver inside format() function.

You can not use dataframe inside function.

For more information Follow this SO thread and this article

Body:
I am trying to move messages in Azure Service Bus queues to ADLS with Databricks.

The code that I'm using is as follows:

from azure.servicebus import ServiceBusClient, ServiceBusMessage

CONNECTION_STR = "Endpoint=sb://carlsbus.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=2BIOtFdooJFIkhZF0qxtYEoK32hJa39DseStw="

QUEUE_NAME = "myqueue"

servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR, logging_enable=True)

receiver = servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME, max_wait_time=5)

And when I execute the following:

mystream2 = spark.readStream.format(receiver).load("/mnt/lake/RAW/FormulaClassification/F1Area/F1Domain/flightStream/1")

But I keep on getting the error:

'ServiceBusReceivedMessage' object has no attribute '_get_object_id'

Any thoughts why I'm getting the error?


问:
React - how to stop div onClick from changing sibling divs
I have 6 div elements that I want to be able to click one of and have the className change for just the div I've clicked on.  Currently, when I click on one div, ALL the div classNames change.  This idea came from a vanilla JS concept that I'm trying to convert into a React component.  I'm not sure where/what is going wrong, if anyone can tell me how to prevent the sibling divs' onClicks from being fired or if what I have is wrong fundamentally, I would be eternally grateful.  This is what I have so far:

```<code>import React, { useState} from "react";

import { Panels } from "../../components/index";
import { data } from "../../constants/index";
import "./gallery.css";

const Gallery = () => {
  const [isOpen, setIsOpen] = useState(false);

    const toggleOpen = () => {
        setIsOpen(!isOpen);
    };

  return (
    <div className="panels">
      {data.restaurants.map((restaurant, index) => (
        <div
          className={`panel panel${index} ${isOpen ? "open open-active" : ""}`}
          onClick={toggleOpen}
        >
          <Panels
            key={restaurant.name + index}
            description={restaurant.description}
            name={restaurant.name}
            website={restaurant.website}
          />
        </div>
      ))}
    </div>
  );
};

export default Gallery;
</code>```

This is my Panels Component code:

```<code>import React from "react";

const Panels = ({ name, description, website }) => {
    return (
  <div className="panel_text">
    <p>{description}</p>
    <p>{name}</p>
    <a href={website}>
      <p>Visit {name}</p>
    </a>
  </div>
)};

export default Panels;
</code>```

Aaaand this is my CSS code:

```<code>*, *:before, *:after {
    box-sizing: inherit;
}

.panels {
    min-height: 100vh;
    overflow: hidden;
    display: flex;
}

.panel, .panel_text {
    background: '#fff';
    box-shadow: inse 0 0 0 5px rgba(255, 255, 255, 0.1);
    color: var(--color-golden);
    text-align: center;
    align-items: center;
    transition:
        font-size 0.7s cubic-bezier(0.61, -0.19, 0.7, -0.11),
        flex 0.7s cubic-bezier(0.61, -0.19, 0.7, -0.11);
    font-size: 20px;
    background-size: cover;
    background-position: center;
    flex: 1;
    justify-content: center;
    display: flex;
    flex-direction: column;
}

.panel0 {background-image: url(../../assets/defuegocarousel.jpg);}
.panel1 {background-image: url(../../assets/HaydenslakeSz.jpg);}
.panel2 {background-image: url(../../assets/stonecliffSz.jpg);}
.panel3 {background-image: url(../../assets/shigezooutside.png);}
.panel4 {background-image: url(../../assets/southparkSz.jpeg);}
.panel5 {background-image: url(../../assets/lechonoutside.jpg);}

.panel > * {
    margin: 0;
    width: 100%;
    transition: transform 0.5s;
    flex: 1 0 auto;
    display: flex;
    justify-content: center;
    align-items: center;
}

.panel > *:first-child {transform: translateY(-100%);}
.panel.open-active > *:first-child {transform: translateY(0); }
.panel > *:last-child { transform: translateY(100%); }
.panel.open-active > *:last-child {transform: translateY(0); }

.panel_text p, a {
    text-transform: uppercase;

}

.panel p:nth-child(2) {
    font-size: 4rem;
}

.panel.open {
    flex: 5;
    font-size: 40px;
}

@media only screen and (max-width: 600px) {
    .panel p {
        font-size: 1rem;
    }
}
</code>```

答:
You're saving a boolean value as  a div element is open or not. So this value is considered for all div element's because there is no identifier which div element is open. You need to save a div element value to identify the open div element.

So you can use a div element's index instead of a boolean value. For example, try the below code.

```<code>import React, { useState} from "react";
import { Panels } from "../../components/index";
import { data } from "../../constants/index";
import "./gallery.css";

const Gallery = () => {
  const [isOpen, setIsOpen] = useState(null);

  return (
    <div className="panels">
      {data.restaurants.map((restaurant, index) => (
        <div
          className={`panel panel${index} ${isOpen === index ? "open open-active" : ""}`}
          onClick={() => setIsOpen(index)}
        >
          <Panels
            key={restaurant.name + index}
            description={restaurant.description}
            name={restaurant.name}
            website={restaurant.website}
          />
        </div>
      ))}
    </div>
  );
};

export default Gallery;
</code>```

Body:
I have 6 div elements that I want to be able to click one of and have the className change for just the div I've clicked on.  Currently, when I click on one div, ALL the div classNames change.  This idea came from a vanilla JS concept that I'm trying to convert into a React component.  I'm not sure where/what is going wrong, if anyone can tell me how to prevent the sibling divs' onClicks from being fired or if what I have is wrong fundamentally, I would be eternally grateful.  This is what I have so far:

import React, { useState} from "react";

import { Panels } from "../../components/index";
import { data } from "../../constants/index";
import "./gallery.css";

const Gallery = () => {
  const [isOpen, setIsOpen] = useState(false);

    const toggleOpen = () => {
        setIsOpen(!isOpen);
    };

  return (

      {data.restaurants.map((restaurant, index) => (
        <div
          className={`panel panel${index} ${isOpen ? "open open-active" : ""}`}
          onClick={toggleOpen}
        >
          <Panels
            key={restaurant.name + index}
            description={restaurant.description}
            name={restaurant.name}
            website={restaurant.website}
          />

      ))}

  );
};

export default Gallery;

This is my Panels Component code:

import React from "react";

const Panels = ({ name, description, website }) => {
    return (

{description}

{name}

Visit {name}

)};

export default Panels;

Aaaand this is my CSS code:

*, *:before, *:after {
    box-sizing: inherit;
}

.panels {
    min-height: 100vh;
    overflow: hidden;
    display: flex;
}

.panel, .panel_text {
    background: '#fff';
    box-shadow: inse 0 0 0 5px rgba(255, 255, 255, 0.1);
    color: var(--color-golden);
    text-align: center;
    align-items: center;
    transition:
        font-size 0.7s cubic-bezier(0.61, -0.19, 0.7, -0.11),
        flex 0.7s cubic-bezier(0.61, -0.19, 0.7, -0.11);
    font-size: 20px;
    background-size: cover;
    background-position: center;
    flex: 1;
    justify-content: center;
    display: flex;
    flex-direction: column;
}

.panel0 {background-image: url(../../assets/defuegocarousel.jpg);}
.panel1 {background-image: url(../../assets/HaydenslakeSz.jpg);}
.panel2 {background-image: url(../../assets/stonecliffSz.jpg);}
.panel3 {background-image: url(../../assets/shigezooutside.png);}
.panel4 {background-image: url(../../assets/southparkSz.jpeg);}
.panel5 {background-image: url(../../assets/lechonoutside.jpg);}

.panel > * {
    margin: 0;
    width: 100%;
    transition: transform 0.5s;
    flex: 1 0 auto;
    display: flex;
    justify-content: center;
    align-items: center;
}

.panel > *:first-child {transform: translateY(-100%);}
.panel.open-active > *:first-child {transform: translateY(0); }
.panel > *:last-child { transform: translateY(100%); }
.panel.open-active > *:last-child {transform: translateY(0); }

.panel_text p, a {
    text-transform: uppercase;

}

.panel p:nth-child(2) {
    font-size: 4rem;
}

.panel.open {
    flex: 5;
    font-size: 40px;
}

@media only screen and (max-width: 600px) {
    .panel p {
        font-size: 1rem;
    }
}

Body:
You're saving a boolean value as  a div element is open or not. So this value is considered for all div element's because there is no identifier which div element is open. You need to save a div element value to identify the open div element.

So you can use a div element's index instead of a boolean value. For example, try the below code.

import React, { useState} from "react";
import { Panels } from "../../components/index";
import { data } from "../../constants/index";
import "./gallery.css";

const Gallery = () => {
  const [isOpen, setIsOpen] = useState(null);

  return (
    <div className="panels">
      {data.restaurants.map((restaurant, index) => (
        <div
          className={`panel panel${index} ${isOpen === index ? "open open-active" : ""}`}
          onClick={() => setIsOpen(index)}
        >
          <Panels
            key={restaurant.name + index}
            description={restaurant.description}
            name={restaurant.name}
            website={restaurant.website}
          />
        </div>
      ))}
    </div>
  );
};

export default Gallery;


问:
Convert JSON to Avro in Jmeter
I need to convert a JSON message to Avro so that I can send it to Kafka.

I have the sample JSON request and also the schema from an avsc file for Avro.

Any ideas how I can do this please?

Thanks

答:
Assuming by "Avro", you are using the Schema Registry. If you're able to install the Kafka REST Proxy, you could send JSON events to it, then the proxy can be configured to integrate with the Registry to send Avro objects to the brokers

Or you can write a custom sampler, as linked in the other answer, but you'd swap the StringSerializer for an Avro Serializer implementation (you'd need to add that to the Jmeter classpath)

Title: Convert JSON to Avro in Jmeter


问:
Combine two dataframes into one by intercalating the columns of each one of the two original dataframes
So i have two dataframes, df1 and df2, both have the same number of columns (and with the same name) but different number of rows. I want to combine them into one big dataframe in which the first column is the first column of df1, the second column is the first column of df2, the third column is the second column of df1, the fourth column is the second column of df2, and so on.</p>

答:
Here's a step by step guide using the iris dataset

# Use iris dataframe used for both df1 and df2
df1 <- iris
df2 <- iris

tot_cols <- ncol(df1) + ncol(df2)
tot_rows <- nrow(df1) + nrow(df2)

# Create empty output data.frame with desired number of rows and cols
df <- data.frame(matrix(ncol=tot_cols, nrow=tot_rows))

# Assign columns to output data.frame
df[, c(seq(1, tot_cols, 2))] <- df1
df[, seq(2, tot_cols, 2)] <- df2

# Assign columns to output data.frame
colnames(df) <- c(rbind(colnames(df1), colnames(df2)))

# View output
head(df)

#   Sepal.Length Sepal.Length Sepal.Width Sepal.Width Petal.Length Petal.Length Petal.Width Petal.Width Species Species
# 1          5.1          5.1         3.5         3.5          1.4          1.4         0.2         0.2  setosa  setosa
# 2          4.9          4.9         3.0         3.0          1.4          1.4         0.2         0.2  setosa  setosa
# 3          4.7          4.7         3.2         3.2          1.3          1.3         0.2         0.2  setosa  setosa
# 4          4.6          4.6         3.1         3.1          1.5          1.5         0.2         0.2  setosa  setosa
# 5          5.0          5.0         3.6         3.6          1.4          1.4         0.2         0.2  setosa  setosa
# 6          5.4          5.4         3.9         3.9          1.7          1.7         0.4         0.4  setosa  setosa
```

Reference:

See How to merge 2 vectors alternating indexes? for more info on why we use rbind().

Body:
Here's a step by step guide using the iris dataset

# Use iris dataframe used for both df1 and df2
df1 <- iris
df2 <- iris

tot_cols <- ncol(df1) + ncol(df2)
tot_rows <- nrow(df1) + nrow(df2)

# Create empty output data.frame with desired number of rows and cols
df <- data.frame(matrix(ncol=tot_cols, nrow=tot_rows))

# Assign columns to output data.frame
df[, c(seq(1, tot_cols, 2))] <- df1
df[, seq(2, tot_cols, 2)] <- df2

# Assign columns to output data.frame
colnames(df) <- c(rbind(colnames(df1), colnames(df2)))

# View output
head(df)

#   Sepal.Length Sepal.Length Sepal.Width Sepal.Width Petal.Length Petal.Length Petal.Width Petal.Width Species Species
# 1          5.1          5.1         3.5         3.5          1.4          1.4         0.2         0.2  setosa  setosa
# 2          4.9          4.9         3.0         3.0          1.4          1.4         0.2         0.2  setosa  setosa
# 3          4.7          4.7         3.2         3.2          1.3          1.3         0.2         0.2  setosa  setosa
# 4          4.6          4.6         3.1         3.1          1.5          1.5         0.2         0.2  setosa  setosa
# 5          5.0          5.0         3.6         3.6          1.4          1.4         0.2         0.2  setosa  setosa
# 6          5.4          5.4         3.9         3.9          1.7          1.7         0.4         0.4  setosa  setosa

Reference:

See How to merge 2 vectors alternating indexes? for more info on why we use rbind().


问:
How to add spacing between columns in Bootstrap 5?
screenshot

i want like this

As you can see in the picture, I can't put a space between the red and blue columns. I tried many Bootstrap classes, but I couldn't get the result I wanted. I added m-4 to the Navbar, Header and the sections below. When I add a few divs in the row, the left and right length (in m-4 equal) is distorted. I want to keep the left and right spacing fixed and adjust the spacing of the columns inside. How will I do this?

<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">

            example

            example

            example

            example

            example

            example

```

答:
All you need to use gutter class like gx-1 for gap between two columns:

<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
  href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
  rel="stylesheet"
/>

With Proper Bootstrap - Structure

        example

        example

        example

        example

        example

        example

```

Body:
All you need to use gutter class like gx-1 for gap between two columns:

<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
  href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
  rel="stylesheet"
/>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<header>
  <div
    class="m-4 px-4"
    style="background-color: white; border-radius: 10px"
  ></div>
</header>

<section class="container-fluid p-4">
  <h1>With Proper Bootstrap - Structure</h1>

  <div class="row gx-4" style="background-color: white; border-radius: 10px">
    <div class="col-lg-6 mb-4 mb-lg-0">
      <div class="p-4" style="background-color: red; border-radius: 10px">
        example
      </div>
    </div>
    <div class="col-lg-6 mb-4 mb-lg-0">
      <div class="p-4" style="background-color: blue; border-radius: 10px">
        example
      </div>
    </div>
  </div>
  <div class="row mt-4" style="background-color: white; border-radius: 10px">
    <div class="col-lg-3 mb-4 mb-lg-0">
      <div class="p-4" style="background-color: red; border-radius: 10px">
        example
      </div>
    </div>
    <div class="col-lg-3 mb-4 mb-lg-0">
      <div class="p-4" style="background-color: red; border-radius: 10px">
        example
      </div>
    </div>
    <div class="col-lg-3 mb-4 mb-lg-0">
      <div class="p-4" style="background-color: blue; border-radius: 10px">
        example
      </div>
    </div>
    <div class="col-lg-3 mb-4 mb-lg-0">
      <div class="p-4" style="background-color: blue; border-radius: 10px">
        example
      </div>
    </div>
  </div>
</section>


问:
How to apply a user-defined function to a column in pandas dataframe?
I'm working on an NLP task. I defined a function to conduct aspect extraction and sentiment based on the aspect and dependency parsing. The function looks like:

```<code>import spacy
nlp = spacy.load('en_core_web_sm')

def aspect_sentiment(text):
    aspects = []
    for sentence in text:
        doc = nlp(sentence)
        descriptive_term = ''
        target = ''
        for token in doc:
            if token.dep_ == 'nsubj' and token.pos_ == 'NOUN':
                target = token.text
            if token.pos_ == 'ADJ':
                prepend = ''
                for child in token.children:
                    if child.pos_ != 'ADV':
                        continue
                    prepend += child.text + ' '
                descriptive_term = prepend + token.text
        aspects.append({'aspect': target, 'description': descriptive_term})

    for aspect in aspects:
        aspect['polarity'] = TextBlob(aspect['description']).sentiment.polarity
        aspect['subjectivity'] = TextBlob(aspect['description']).sentiment.subjectivity

    return(aspects)
</code>```

First I made a list of sentences for testing:

```<code>sentences = [
  'The food we had yesterday was delicious',
  'My time in Italy was very enjoyable',
  'I found the meal to be tasty',
  'The internet was slow.',
  'Our experience was suboptimal'
]
</code>```

And when I use aspect_sentiment(sentences) it returns the desired outcome:

```<code>[{'aspect': 'food',
  'description': 'delicious',
  'polarity': 1.0,
  'subjectivity': 1.0},
 {'aspect': 'time',
  'description': 'very enjoyable',
  'polarity': 0.65,
  'subjectivity': 0.78},
 {'aspect': 'meal',
  'description': 'tasty',
  'polarity': 0.0,
  'subjectivity': 0.0},
 {'aspect': 'internet',
  'description': 'slow',
  'polarity': -0.30000000000000004,
  'subjectivity': 0.39999999999999997},
 {'aspect': 'experience',
  'description': 'suboptimal',
  'polarity': 0.0,
  'subjectivity': 0.0}]
</code>```

But when I make the sentence list into a pandas dataframe and apply the function, the result column doesn't return the correct values:

```<code>text = pd.DataFrame(sentences, columns=['sentences'])
text['result'] = text['sentences'].map(aspect_sentiment)
</code>```

it returns:

How can I fix it? The output seems very wrong...

答: You can use df[col].apply(fn) instead, which will run the function once on each element in a pandas Series. Just need to adjust aspect_sentiment a bit to expect individual sentences instead of a list of sentences.

Body:
I'm working on an NLP task. I defined a function to conduct aspect extraction and sentiment based on the aspect and dependency parsing. The function looks like:

import spacy
nlp = spacy.load('en_core_web_sm')

def aspect_sentiment(text):
    aspects = []
    for sentence in text:
        doc = nlp(sentence)
        descriptive_term = ''
        target = ''
        for token in doc:
            if token.dep_ == 'nsubj' and token.pos_ == 'NOUN':
                target = token.text
            if token.pos_ == 'ADJ':
                prepend = ''
                for child in token.children:
                    if child.pos_ != 'ADV':
                        continue
                    prepend += child.text + ' '
                descriptive_term = prepend + token.text
        aspects.append({'aspect': target, 'description': descriptive_term})

    for aspect in aspects:
        aspect['polarity'] = TextBlob(aspect['description']).sentiment.polarity
        aspect['subjectivity'] = TextBlob(aspect['description']).sentiment.subjectivity

    return(aspects)

First I made a list of sentences for testing:

sentences = [
  'The food we had yesterday was delicious',
  'My time in Italy was very enjoyable',
  'I found the meal to be tasty',
  'The internet was slow.',
  'Our experience was suboptimal'
]

And when I use aspect_sentiment(sentences) it returns the desired outcome:

[{'aspect': 'food',
  'description': 'delicious',
  'polarity': 1.0,
  'subjectivity': 1.0},
 {'aspect': 'time',
  'description': 'very enjoyable',
  'polarity': 0.65,
  'subjectivity': 0.78},
 {'aspect': 'meal',
  'description': 'tasty',
  'polarity': 0.0,
  'subjectivity': 0.0},
 {'aspect': 'internet',
  'description': 'slow',
  'polarity': -0.30000000000000004,
  'subjectivity': 0.39999999999999997},
 {'aspect': 'experience',
  'description': 'suboptimal',
  'polarity': 0.0,
  'subjectivity': 0.0}]

But when I make the sentence list into a pandas dataframe and apply the function, the result column doesn't return the correct values:

text = pd.DataFrame(sentences, columns=['sentences'])
text['result'] = text['sentences'].map(aspect_sentiment)

it returns:

How can I fix it? The output seems very wrong...


问:
How to test that dispatch only gets called once
I have a custom hook that dispatches an action when a URL parameter changes:

```<code>export const useUser = (): void => {
  const dispatch = useDispatch();

  const { user } = useParams<{ user: string }>();

  useEffect(() => {dispatch(getUser(user));
  }, [dispatch, user]);
};
</code>```

I have a test that mocks useDispatch and useParams:

```<code>const dispatch = jest.fn();

const useDispatchSpy = jest.spyOn(reactRedux, 'useDispatch').mockImplementation(() => {
  return dispatch;
});

const useParamsSpy = jest.spyOn(reactRouter, 'useParams').mockImplementation(() => {
  return { user: 'test' };
});

const getUserSpy = jest.spyOn(slice, 'getUser');

renderHook(() => useRequestProfile());

expect(getUserSpy.mock.calls).toEqual([['test']]);
</code>```

Now, this works, in that I can determine that getUser('test') has been called, but the point of wrapping it in useEffect is to make sure that it only get's called once. How can I test this?

答:
You can put the useUser hook inside a component. Pass some props to this component and check. Later, pass the new props to re-render the component and check again if getUserSpy was called more than once.

Besides, we use MemoryRouter with initial entries instead of mocking useParams to provide URL parameters.

The expected result of our test is: regardless of how many times the component rendering, due to dispatch and user parameter are stable, the useEffect in the useUser hook will only be executed once.

E.g.

useUser.ts:

```<code>import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { useParams } from 'react-router-dom';
import * as slice from './slice';

export const useUser = (): void => {
  const dispatch = useDispatch();

  const { user } = useParams<{ user: string }>();
  useEffect(() => {
    dispatch(slice.getUser(user));
  }, [dispatch, user]);
};
</code>```

slice.ts:

```<code>export const getUser = (user) => ({ type: 'GET_USER', payload: user });
</code>```

useUser.test.tsx:

```<code>import { render } from '@testing-library/react';
import { renderHook } from '@testing-library/react-hooks';
import React from 'react';
import { Provider } from 'react-redux';
import { MemoryRouter, Route } from 'react-router-dom';
import { createStore } from 'redux';
import * as slice from './slice';
import { useUser } from './useUser';

describe('useUser', () => {
  test('should pass', () => {
    const getUserSpy = jest.spyOn(slice, 'getUser');
    function TestComp(props) {
      console.log(props);
      useUser();
      return null;
    }
    const store = createStore(() => ({}));

    const { rerender } = renderHook(TestComp, {
      initialProps: { data: '1' },
      wrapper: ({ children }) => (
        <Provider store={store}>
          <MemoryRouter initialEntries={['/test']}>
            <Route path="/:user">{children}</Route>
          </MemoryRouter>
        </Provider>
      ),
    });
    expect(getUserSpy).toBeCalledWith('test');
    rerender({ data: '2' });
    expect(getUserSpy).toBeCalledTimes(1);
  });
});
</code>```

Test result:

 PASS  stackoverflow/70928091/useUser.test.tsx (7.748 s)
  useUser
    ✓ should pass (39 ms)

  console.log
    { data: '1' }

      at TestComp (stackoverflow/70928091/useUser.test.tsx:14:15)

  console.log
    { data: '2' }

      at TestComp (stackoverflow/70928091/useUser.test.tsx:14:15)

------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------|---------|----------|---------|---------|-------------------
All files   |     100 |      100 |     100 |     100 |
 slice.ts   |     100 |      100 |     100 |     100 |
 useUser.ts |     100 |      100 |     100 |     100 |
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.253 s, estimated 9 s
```

Body:
I have a custom hook that dispatches an action when a URL parameter changes:

export const useUser = (): void => {
  const dispatch = useDispatch();

  const { user } = useParams<{ user: string }>();

  useEffect(() => {dispatch(getUser(user));
  }, [dispatch, user]);
};

I have a test that mocks useDispatch and useParams:

const dispatch = jest.fn();

const useDispatchSpy = jest.spyOn(reactRedux, 'useDispatch').mockImplementation(() => {
  return dispatch;
});

const useParamsSpy = jest.spyOn(reactRouter, 'useParams').mockImplementation(() => {
  return { user: 'test' };
});

const getUserSpy = jest.spyOn(slice, 'getUser');

renderHook(() => useRequestProfile());

expect(getUserSpy.mock.calls).toEqual([['test']]);

Now, this works, in that I can determine that getUser('test') has been called, but the point of wrapping it in useEffect is to make sure that it only get's called once. How can I test this?

Body:
You can put the useUser hook inside a component. Pass some props to this component and check. Later, pass the new props to re-render the component and check again if getUserSpy was called more than once.

Besides, we use MemoryRouter with initial entries instead of mocking useParams to provide URL parameters.

The expected result of our test is: regardless of how many times the component rendering, due to dispatch and user parameter are stable, the useEffect in the useUser hook will only be executed once.

E.g.

useUser.ts:

import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { useParams } from 'react-router-dom';
import * as slice from './slice';

export const useUser = (): void => {
  const dispatch = useDispatch();

  const { user } = useParams<{ user: string }>();
  useEffect(() => {
    dispatch(slice.getUser(user));
  }, [dispatch, user]);
};

slice.ts:

export const getUser = (user) => ({ type: 'GET_USER', payload: user });

useUser.test.tsx:

import { render } from '@testing-library/react';
import { renderHook } from '@testing-library/react-hooks';
import React from 'react';
import { Provider } from 'react-redux';
import { MemoryRouter, Route } from 'react-router-dom';
import { createStore } from 'redux';
import * as slice from './slice';
import { useUser } from './useUser';

describe('useUser', () => {
  test('should pass', () => {
    const getUserSpy = jest.spyOn(slice, 'getUser');
    function TestComp(props) {
      console.log(props);
      useUser();
      return null;
    }
    const store = createStore(() => ({}));

    const { rerender } = renderHook(TestComp, {
      initialProps: { data: '1' },
      wrapper: ({ children }) => (
        <Provider store={store}>
          <MemoryRouter initialEntries={['/test']}>
            <Route path="/:user">{children}</Route>
          </MemoryRouter>
        </Provider>
      ),
    });
    expect(getUserSpy).toBeCalledWith('test');
    rerender({ data: '2' });
    expect(getUserSpy).toBeCalledTimes(1);
  });
});

Test result:

 PASS  stackoverflow/70928091/useUser.test.tsx (7.748 s)
  useUser
    ✓ should pass (39 ms)

  console.log
    { data: '1' }

      at TestComp (stackoverflow/70928091/useUser.test.tsx:14:15)

  console.log
    { data: '2' }

      at TestComp (stackoverflow/70928091/useUser.test.tsx:14:15)

------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------|---------|----------|---------|---------|-------------------
All files   |     100 |      100 |     100 |     100 |
 slice.ts   |     100 |      100 |     100 |     100 |
 useUser.ts |     100 |      100 |     100 |     100 |
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.253 s, estimated 9 s