问:
HLS live streaming from static files
I have a client with thousands of audio/video files that they stream internally, all are segmented (.ts) and saved in an S3 bucket with appropriate metadata in an SQL database. Now they've asked me to create two "live" streams, one for audio, one for video that they can set and forget.

Not wanting to re-segment everything or concatenate all the files I'm trying to hack in a "live" m3u8 that slides through the already existing files (they're all encoded the exact same way).

What I've done is generate a "radio playlist" that is saved into a database at 40-second intervals (x3 .ts per m3u8), each tagged with a start and end time and appropriate EXT-X-MEDIA-SEQUENCE. Then I select between NOW() and push the file.

It works but sometimes the timing is right and it hits the same grouping for the first and last file and buffers out. I have complete control over the player (VideoJS) and server to get this working.

This is the code I have so far...any way I could make this work? I haven't tried playing with buffers on vJS yet (don't know how to...)

All the basic file information is stored in the database like this

```<code>INSERT INTO `contenido_audio_hls` (`id`, `audio_s`, `duration`) VALUES ('f2z7dcwc0l7rleig', '["10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","4.100000"]', 10);
</code>```

When a playlist is generated, I pull out the required data

```<code>$radio = sql("SELECT lista_contenido.orden,lista_contenido.contenido,contenido_audio_hls.audio_s FROM lista_listas LEFT JOIN lista_contenido ON (lista_listas.id = lista_contenido.lista) LEFT JOIN contenido_audio_hls ON (lista_contenido.contenido = contenido_audio_hls.id) WHERE (lista_listas.tipo = 'radio') ORDER BY lista_contenido.orden ASC");
foreach($radio['data'] as $k=>$v) {
    $arreglo = json_decode($v['audio_s'],TRUE);
    foreach($arreglo as $kk=>$vv) {
        $puro[] = array("extinf"=>'#EXTINF:'.$vv.',',"id"=>$v['contenido'],"segment"=>$kk);
    }
}
</code>```

I loop through them to create groups

```<code>$segundos = 0;
$grupo = 1;
$contador = 1;
foreach($puro as $k=>$v) {
    if($segundos <= 30) {
        $m3u8[$grupo][] = $puro[$k];
        $contador++;
    } else {
        $m3u8[$grupo][] = $puro[$k];
        $grupo = $grupo + $contador;
        $segundos = 0;
    }
    $segundos = $segundos + 10;
}
</code>```

Then put them into their own table

```<code>$largo = 0;
foreach($m3u8 as $k=>$v) {
    $ini = sprintf('%02d:%02d:%02d',($largo/3600),($largo/60%60),$largo%60);
    $localfin = $largo + 40;
    $fin = sprintf('%02d:%02d:%02d',($localfin/3600),($localfin/60%60),$localfin%60);

    $query = "INSERT INTO lista_m3u8 (ini,fin,tipo,sequence,data) VALUES('".$ini."','".$fin."','radio','".$k."','".json_encode($v)."')";

    sql($query);

    $largo = $largo + 40;
}
</code>```

Which gives me this

```<code>INSERT INTO `lista_m3u8` (`ini`, `fin`, `tipo`, `sequence`, `data`) VALUES ('06:54:00', '06:54:40', 'radio', 580636, '[{"extinf":"#EXTINF:10.000000,","id":"f2z7de0quwgehw23","segment":14},{"extinf":"#EXTINF:10.000000,","id":"f2z7de0quwgehw23","segment":15},{"extinf":"#EXTINF:10.000000,","id":"f2z7de0quwgehw23","segment":16},{"extinf":"#EXTINF:10.000000,","id":"f2z7de0quwgehw23","segment":17}]');
INSERT INTO `lista_m3u8` (`ini`, `fin`, `tipo`, `sequence`, `data`) VALUES ('06:54:40', '06:55:20', 'radio', 582504, '[{"extinf":"#EXTINF:10.000000,","id":"f2z7de0quwgehw23","segment":18},{"extinf":"#EXTINF:10.000000,","id":"f2z7de0quwgehw23","segment":19},{"extinf":"#EXTINF:0.766667,","id":"f2z7de0quwgehw23","segment":20},{"extinf":"#EXTINF:10.000000,","id":"f2z7dft8c217xyp","segment":0}]');
INSERT INTO `lista_m3u8` (`ini`, `fin`, `tipo`, `sequence`, `data`) VALUES ('06:55:20', '06:56:00', 'radio', 584375, '[{"extinf":"#EXTINF:10.000000,","id":"f2z7dft8c217xyp","segment":1},{"extinf":"#EXTINF:10.000000,","id":"f2z7dft8c217xyp","segment":2},{"extinf":"#EXTINF:10.000000,","id":"f2z7dft8c217xyp","segment":3},{"extinf":"#EXTINF:10.000000,","id":"f2z7dft8c217xyp","segment":4}]');
INSERT INTO `lista_m3u8` (`ini`, `fin`, `tipo`, `sequence`, `data`) VALUES ('06:56:00', '06:56:40', 'radio', 586249, '[{"extinf":"#EXTINF:10.000000,","id":"f2z7dft8c217xyp","segment":5},{"extinf":"#EXTINF:10.000000,","id":"f2z7dft8c217xyp","segment":6},{"extinf":"#EXTINF:10.000000,","id":"f2z7dft8c217xyp","segment":7},{"extinf":"#EXTINF:10.000000,","id":"f2z7dft8c217xyp","segment":8}]');
</code>```

Then the m3u8 is generated

```<code>$audio = sql("SELECT sequence, data FROM lista_m3u8 WHERE tipo = 'radio' AND ini <= DATE_FORMAT(NOW(),'%H:%i:%s') AND fin >= DATE_FORMAT(NOW(),'%H:%i:%s')");

$sale = '#EXTM3U'.PHP_EOL;
$sale .= '#EXT-X-VERSION:3'.PHP_EOL;
$sale .= '#EXT-X-MEDIA-SEQUENCE:'.$audio['data'][0]['sequence'].PHP_EOL;
$sale .= '#EXT-X-TARGETDURATION:10'.PHP_EOL;

$arreglo = json_decode($audio['data'][0]['data'],TRUE);
foreach($arreglo as $k=>$v) {
    $sale .= $v['extinf'].PHP_EOL;
    $sale .= S3URL("bucket-audio",$v['id']."/segment".sprintf('%05d',$v['segment']).".ts",(count($arreglo) * 25)).PHP_EOL;
}

header("Content-type: application/x-mpegURL");
echo $sale.PHP_EOL;
</code>```

答:
You could also try something simple like this php script if you have a single video that you want to loop:</p>

```<code><?php
// lets assume that we have stream splitted to parts named testXXXXX.ts
// and all parts have 2.4 seconds and we want to play in loop part
// from test0.ts to test29.ts forever in a live stream
header('Content-Type: application/x-mpegURL');
$time = intval(time() / 2.40000);
$s1 = ($time + 1) % 30;
$s2 = ($time + 2) % 30;
$s3 = ($time + 3) % 30;
$s4 = ($time + 4) % 30;
?>
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:2
#EXT-X-MEDIA-SEQUENCE:<?php echo "$time\n"; ?>
#EXTINF:2.40000,
test<?php echo $s1; ?>.ts
<?php if ($s2 < $s1) echo "#EXT-X-DISCONTINUITY\n"; ?>
#EXTINF:2.40000,
test<?php echo $s2; ?>.ts
<?php if ($s3 < $s2) echo "#EXT-X-DISCONTINUITY\n"; ?>
#EXTINF:2.40000,
test<?php echo $s3; ?>.ts
<?php if ($s4 < $s3) echo "#EXT-X-DISCONTINUITY\n"; ?>
#EXTINF:2.40000,
test<?php echo $s4; ?>.ts
</code>```

Title: HLS live streaming from static files

Body:
I have a client with thousands of audio/video files that they stream internally, all are segmented (.ts) and saved in an S3 bucket with appropriate metadata in an SQL database. Now they've asked me to create two "live" streams, one for audio, one for video that they can set and forget.

Not wanting to re-segment everything or concatenate all the files I'm trying to hack in a "live" m3u8 that slides through the already existing files (they're all encoded the exact same way).

What I've done is generate a "radio playlist" that is saved into a database at 40-second intervals (x3 .ts per m3u8), each tagged with a start and end time and appropriate EXT-X-MEDIA-SEQUENCE. Then I select between NOW() and push the file.

It works but sometimes the timing is right and it hits the same grouping for the first and last file and buffers out. I have complete control over the player (VideoJS) and server to get this working.

This is the code I have so far...any way I could make this work? I haven't tried playing with buffers on vJS yet (don't know how to...)

All the basic file information is stored in the database like this

INSERT INTO `contenido_audio_hls` (`id`, `audio_s`, `duration`) VALUES ('f2z7dcwc0l7rleig', '["10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","10.000000","4.100000"]', 10);

When a playlist is generated, I pull out the required data

$radio = sql("SELECT lista_contenido.orden,lista_contenido.contenido,contenido_audio_hls.audio_s FROM lista_listas LEFT JOIN lista_contenido ON (lista_listas.id = lista_contenido.lista) LEFT JOIN contenido_audio_hls ON (lista_contenido.contenido = contenido_audio_hls.id) WHERE (lista_listas.tipo = 'radio') ORDER BY lista_contenido.orden ASC");
foreach($radio['data'] as $k=>$v) {
    $arreglo = json_decode($v['audio_s'],TRUE);
    foreach($arreglo as $kk=>$vv) {
        $puro[] = array("extinf"=>'#EXTINF:'.$vv.',',"id"=>$v['contenido'],"segment"=>$kk);
    }
}

I loop through them to create groups

$segundos = 0;
$grupo = 1;
$contador = 1;
foreach($puro as $k=>$v) {
    if($segundos <= 30) {
        $m3u8[$grupo][] = $puro[$k];
        $contador++;
    } else {
        $m3u8[$grupo][] = $puro[$k];
        $grupo = $grupo + $contador;
        $segundos = 0;
    }
    $segundos = $segundos + 10;
}

Then put them into their own table

$largo = 0;
foreach($m3u8 as $k=>$v) {
    $ini = sprintf('%02d:%02d:%02d',($largo/3600),($largo/60%60),$largo%60);
    $localfin = $largo + 40;
    $fin = sprintf('%02d:%02d:%02d',($localfin/3600),($localfin/60%60),$localfin%60);

    $query = "INSERT INTO lista_m3u8 (ini,fin,tipo,sequence,data) VALUES('".$ini."','".$fin."','radio','".$k."','".json_encode($v)."')";

    sql($query);

    $largo = $largo + 40;
}

Which gives me this

INSERT INTO `lista_m3u8` (`ini`, `fin`, `tipo`, `sequence`, `data`) VALUES ('06:54:00', '06:54:40', 'radio', 580636, '[{"extinf":"#EXTINF:10.000000,","id":"f2z7de0quwgehw23","segment":14},{"extinf":"#EXTINF:10.000000,","id":"f2z7de0quwgehw23","segment":15},{"extinf":"#EXTINF:10.000000,","id":"f2z7de0quwgehw23","segment":16},{"extinf":"#EXTINF:10.000000,","id":"f2z7de0quwgehw23","segment":17}]');
INSERT INTO `lista_m3u8` (`ini`, `fin`, `tipo`, `sequence`, `data`) VALUES ('06:54:40', '06:55:20', 'radio', 582504, '[{"extinf":"#EXTINF:10.000000,","id":"f2z7de0quwgehw23","segment":18},{"extinf":"#EXTINF:10.000000,","id":"f2z7de0quwgehw23","segment":19},{"extinf":"#EXTINF:0.766667,","id":"f2z7de0quwgehw23","segment":20},{"extinf":"#EXTINF:10.000000,","id":"f2z7dft8c217xyp","segment":0}]');
INSERT INTO `lista_m3u8` (`ini`, `fin`, `tipo`, `sequence`, `data`) VALUES ('06:55:20', '06:56:00', 'radio', 584375, '[{"extinf":"#EXTINF:10.000000,","id":"f2z7dft8c217xyp","segment":1},{"extinf":"#EXTINF:10.000000,","id":"f2z7dft8c217xyp","segment":2},{"extinf":"#EXTINF:10.000000,","id":"f2z7dft8c217xyp","segment":3},{"extinf":"#EXTINF:10.000000,","id":"f2z7dft8c217xyp","segment":4}]');
INSERT INTO `lista_m3u8` (`ini`, `fin`, `tipo`, `sequence`, `data`) VALUES ('06:56:00', '06:56:40', 'radio', 586249, '[{"extinf":"#EXTINF:10.000000,","id":"f2z7dft8c217xyp","segment":5},{"extinf":"#EXTINF:10.000000,","id":"f2z7dft8c217xyp","segment":6},{"extinf":"#EXTINF:10.000000,","id":"f2z7dft8c217xyp","segment":7},{"extinf":"#EXTINF:10.000000,","id":"f2z7dft8c217xyp","segment":8}]');

Then the m3u8 is generated

$audio = sql("SELECT sequence, data FROM lista_m3u8 WHERE tipo = 'radio' AND ini <= DATE_FORMAT(NOW(),'%H:%i:%s') AND fin >= DATE_FORMAT(NOW(),'%H:%i:%s')");

$sale = '#EXTM3U'.PHP_EOL;
$sale .= '#EXT-X-VERSION:3'.PHP_EOL;
$sale .= '#EXT-X-MEDIA-SEQUENCE:'.$audio['data'][0]['sequence'].PHP_EOL;
$sale .= '#EXT-X-TARGETDURATION:10'.PHP_EOL;

$arreglo = json_decode($audio['data'][0]['data'],TRUE);
foreach($arreglo as $k=>$v) {
    $sale .= $v['extinf'].PHP_EOL;
    $sale .= S3URL("bucket-audio",$v['id']."/segment".sprintf('%05d',$v['segment']).".ts",(count($arreglo) * 25)).PHP_EOL;
}

header("Content-type: application/x-mpegURL");
echo $sale.PHP_EOL;

Body:
You could also try something simple like this php script if you have a single video that you want to loop:

<?php
// lets assume that we have stream splitted to parts named testXXXXX.ts
// and all parts have 2.4 seconds and we want to play in loop part
// from test0.ts to test29.ts forever in a live stream
header('Content-Type: application/x-mpegURL');
$time = intval(time() / 2.40000);
$s1 = ($time + 1) % 30;
$s2 = ($time + 2) % 30;
$s3 = ($time + 3) % 30;
$s4 = ($time + 4) % 30;
?>
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:2
#EXT-X-MEDIA-SEQUENCE:<?php echo "$time\n"; ?>
#EXTINF:2.40000,
test<?php echo $s1; ?>.ts
<?php if ($s2 < $s1) echo "#EXT-X-DISCONTINUITY\n"; ?>
#EXTINF:2.40000,
test<?php echo $s2; ?>.ts
<?php if ($s3 < $s2) echo "#EXT-X-DISCONTINUITY\n"; ?>
#EXTINF:2.40000,
test<?php echo $s3; ?>.ts
<?php if ($s4 < $s3) echo "#EXT-X-DISCONTINUITY\n"; ?>
#EXTINF:2.40000,
test<?php echo $s4; ?>.ts


来源: stackexchange

问:
Upgrading the SQL Extensions Toolkit in netezza
How to upgrading the SQL Extensions Toolkit in Netezza? I don't want to have duplicate files I just want to upgrade from the SQL Ext I have currently.

Thanks.

答:
Latest packages are available in fix central
Install instructions ->
https://www.ibm.com/support/knowledgecenter/SSULQD_7.2.1/com.ibm.nz.sqltk.doc/t_sqlext_installing.html
and https://www.ibm.com/support/knowledgecenter/SSULQD_7.2.1/com.ibm.nz.sqltk.doc/t_sqlext_enabling.html

You might find it easier to install SQLToolkit in its own database and refer to the functions from that database.

ContentLicense: CC BY-SA 4.0


问:
C, dynamic array, segmentation fault
I wanted to allocate memory and scanf array in one function, but it gives segmentation fault (core dumped) error. Thank you for help.</p>

```<code>#include <stdio.h>
#include <stdlib.h>

void scanf_array (int **array_pp, int size);

int main ()
{
  int *array_p, size;
  scanf ("%d", &size);
  scanf_array (&array_p, size);
  for (int i = 0; i < size; i++)
  {
    printf ("%d", array_p[i]);
  }
  return 0;
}

void scanf_array (int **array_pp, int size)
{
  *array_pp = (int *)malloc (size * sizeof (int));
  for (int i = 0; i < size; i++)
  {
  scanf ("%d", array_pp[i]);
  }
}
</code>```

答: Is scanf ("%d", &(*array_pp)[i]); you're looking for?</p>

Title: C, dynamic array, segmentation fault

Body:
I wanted to allocate memory and scanf array in one function, but it gives segmentation fault (core dumped) error. Thank you for help.

#include <stdio.h>
#include <stdlib.h>

void scanf_array (int **array_pp, int size);

int main ()
{
  int *array_p, size;
  scanf ("%d", &size);
  scanf_array (&array_p, size);
  for (int i = 0; i < size; i++)
  {
    printf ("%d", array_p[i]);
  }
  return 0;
}

void scanf_array (int **array_pp, int size)
{
  *array_pp = (int *)malloc (size * sizeof (int));
  for (int i = 0; i < size; i++)
  {
  scanf ("%d", array_pp[i]);
  }
}


问:
How to auto insert foreign key when insert entity/object by Spring Boot JPA to MySQL
I tried to insert an entity that contains foreign key from Spring boot JPA to MYSQL. But get error:

```<code>java.sql.SQLIntegrityConstraintViolationException: Column 'role_role_id' cannot be null.
</code>```

I know it is an error when I insert null into a column that does not allow null. I know the fix(please see myMainController below) is get object Role (foreignkey) to set into my User object then insert User Object to DB (new row in DB) (the necessary data of Role is already in the DB). But I want when I insert User, it will auto insert Object Role because I have set the realtion clearly(more info please see my pictures in User Entity and Role Entity). Please see my Code.

This is ERR:

```<code>java.sql.SQLIntegrityConstraintViolationException: Column 'role_role_id' cannot be null.
</code>```

This is myMainRestController

```<code>@RestController
public class MyMainController {

@Autowired
private UserRepository service;

@RequestMapping("/i")
@ResponseBody
public String Welcome() {
    return "Welcome!";
}
@JsonIgnore
@RequestMapping(value = "/", //
        method = RequestMethod.GET, //
        produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public User initData() {

    User user = new User();
    user.setUserId(4);
    user.setPassword("1234");
    user.setFullname("Nguyễn Văn D");
    user.setPhonenumber("012345678");
    user.setAddress("2 đường Số 7 Bình Trị Dông");
    user.setFontIdCardImg("p2fontid.jpg");
    user.setBackIdCardImg("p2backid.jpg");
    user.setRoleId(2);
    user.setAreaId(2);

//      Role role = new Role();
//      role.setRoleId(user.getRoleId());   / My fix here
//      user.setRole(role);

    service.save(user);
    return user;
}
</code>```

}

This is my User Entity:

```<code>@Entity
@Table(name="user")
@NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="user_id", unique=true, nullable=false)
private Integer userId;

@Column(length=1000)
private String address;

@Column(name="area_id")
private Integer areaId;

@Column(name="back_id_card_img", length=200)
private String backIdCardImg;

@Column(name="font_id_card_img", length=200)
private String fontIdCardImg;

@Column(length=45)
private String fullname;

@Column(length=45)
private String password;

@Column(length=45)
private String phonenumber;

@Column(name="role_id")
private Integer roleId;

//bi-directional many-to-one association to Accident
@OneToMany(mappedBy="user")
private List<Accident> accidents;

//bi-directional many-to-one association to Area
@ManyToOne
@JoinColumn(name="area_area_id")
private Area area;

//bi-directional many-to-one association to Policeworktime
@ManyToOne
@JoinColumn(name="policeworktime_police_user_id")
private Policeworktime policeworktime;

//bi-directional many-to-one association to Role
@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="role_role_id", nullable=false)
private Role role;

public User() {
}

public Integer getUserId() {
    return this.userId;
}

public void setUserId(Integer userId) {
    this.userId = userId;
}

public String getAddress() {
    return this.address;
}

public void setAddress(String address) {
    this.address = address;
}

public Integer getAreaId() {
    return this.areaId;
}

public void setAreaId(Integer areaId) {
    this.areaId = areaId;
}

public String getBackIdCardImg() {
    return this.backIdCardImg;
}

public void setBackIdCardImg(String backIdCardImg) {
    this.backIdCardImg = backIdCardImg;
}

public String getFontIdCardImg() {
    return this.fontIdCardImg;
}

public void setFontIdCardImg(String fontIdCardImg) {
    this.fontIdCardImg = fontIdCardImg;
}

public String getFullname() {
    return this.fullname;
}

public void setFullname(String fullname) {
    this.fullname = fullname;
}

public String getPassword() {
    return this.password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getPhonenumber() {
    return this.phonenumber;
}

public void setPhonenumber(String phonenumber) {
    this.phonenumber = phonenumber;
}

public Integer getRoleId() {
    return this.roleId;
}

public void setRoleId(Integer roleId) {
    this.roleId = roleId;
}

public List<Accident> getAccidents() {
    return this.accidents;
}

public void setAccidents(List<Accident> accidents) {
    this.accidents = accidents;
}

public Accident addAccident(Accident accident) {
    getAccidents().add(accident);
    accident.setUser(this);

    return accident;
}

public Accident removeAccident(Accident accident) {
    getAccidents().remove(accident);
    accident.setUser(null);

    return accident;
}

public Area getArea() {
    return this.area;
}

public void setArea(Area area) {
    this.area = area;
}

public Policeworktime getPoliceworktime() {
    return this.policeworktime;
}

public void setPoliceworktime(Policeworktime policeworktime) {
    this.policeworktime = policeworktime;
}

public Role getRole() {
    return this.role;
}

public void setRole(Role role) {
    this.role = role;
}
</code>```

}

This is my Role Entity:

```<code>@Entity
@Table(name="role")
@NamedQuery(name="Role.findAll", query="SELECT r FROM Role r")
public class Role implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="role_id", unique=true, nullable=false)
private Integer roleId;

@Column(name="role_name", length=45)
private String roleName;

//bi-directional many-to-one association to User
@OneToMany(mappedBy="role", cascade={CascadeType.ALL})
private List<User> users;

public Role() {
}

public Integer getRoleId() {
    return this.roleId;
}

public void setRoleId(Integer roleId) {
    this.roleId = roleId;
}

public String getRoleName() {
    return this.roleName;
}

public void setRoleName(String roleName) {
    this.roleName = roleName;
}

public List<User> getUsers() {
    return this.users;
}

public void setUsers(List<User> users) {
    this.users = users;
}

public User addUser(User user) {
    getUsers().add(user);
    user.setRole(this);

    return user;
}

public User removeUser(User user) {
    getUsers().remove(user);
    user.setRole(null);

        return user;
    }

}
</code>```

答:
You don't need to create Colunm roleId. You just put relational with tables. For example in my situation, I have OneToMany User with Role. I only established relational in my MySql DB. And then, you can create your own entities or use the JPA tool at your disposal. User entity has a object Role, Role entity has a List.

```<code>@Entity
@Table(name="role")
@NamedQuery(name="Role.findAll", query="SELECT r FROM Role r")
public class Role implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="role_id", unique=true, nullable=false)
private Integer roleId;

@Column(name="role_name", length=45)
private String roleName;

//bi-directional many-to-one association to User
@OneToMany(mappedBy="role")
private List<User> users;

public Role() {
}

public Integer getRoleId() {
    return this.roleId;
}

public void setRoleId(Integer roleId) {
    this.roleId = roleId;
}

public String getRoleName() {
    return this.roleName;
}

public void setRoleName(String roleName) {
    this.roleName = roleName;
}

public List<User> getUsers() {
    return this.users;
}

public void setUsers(List<User> users) {
    this.users = users;
}

public User addUser(User user) {
    getUsers().add(user);
    user.setRole(this);

    return user;
}

public User removeUser(User user) {
    getUsers().remove(user);
    user.setRole(null);

    return user;
}

 }

@Entity
@Table(name = "user")
@NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;

// bi-directional many-to-one association to Role
@ManyToOne
@JoinColumn(name = "role_role_id", nullable = false)
private Role role;

public Role getRole() {
    return this.role;
}

public void setRole(Role role) {
    this.role = role;
}

}
</code>```

Body:
I tried to insert an entity that contains foreign key from Spring boot JPA to MYSQL. But get error:

java.sql.SQLIntegrityConstraintViolationException: Column 'role_role_id' cannot be null.

I know it is an error when I insert null into a column that does not allow null. I know the fix(please see myMainController below) is get object Role (foreignkey) to set into my User object then insert User Object to DB (new row in DB) (the necessary data of Role is already in the DB). But I want when I insert User, it will auto insert Object Role because I have set the realtion clearly(more info please see my pictures in User Entity and Role Entity). Please see my Code.

This is ERR:

java.sql.SQLIntegrityConstraintViolationException: Column 'role_role_id' cannot be null.

This is myMainRestController

@RestController
public class MyMainController {

@Autowired
private UserRepository service;

@RequestMapping("/i")
@ResponseBody
public String Welcome() {
    return "Welcome!";
}
@JsonIgnore
@RequestMapping(value = "/", //
        method = RequestMethod.GET, //
        produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public User initData() {

    User user = new User();
    user.setUserId(4);
    user.setPassword("1234");
    user.setFullname("Nguyễn Văn D");
    user.setPhonenumber("012345678");
    user.setAddress("2 đường Số 7 Bình Trị Dông");
    user.setFontIdCardImg("p2fontid.jpg");
    user.setBackIdCardImg("p2backid.jpg");
    user.setRoleId(2);
    user.setAreaId(2);

//      Role role = new Role();
//      role.setRoleId(user.getRoleId());   / My fix here
//      user.setRole(role);

    service.save(user);
    return user;
}

}

This is my User Entity:

@Entity
@Table(name="user")
@NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="user_id", unique=true, nullable=false)
private Integer userId;

@Column(length=1000)
private String address;

@Column(name="area_id")
private Integer areaId;

@Column(name="back_id_card_img", length=200)
private String backIdCardImg;

@Column(name="font_id_card_img", length=200)
private String fontIdCardImg;

@Column(length=45)
private String fullname;

@Column(length=45)
private String password;

@Column(length=45)
private String phonenumber;

@Column(name="role_id")
private Integer roleId;

//bi-directional many-to-one association to Accident
@OneToMany(mappedBy="user")
private List<Accident> accidents;

//bi-directional many-to-one association to Area
@ManyToOne
@JoinColumn(name="area_area_id")
private Area area;

//bi-directional many-to-one association to Policeworktime
@ManyToOne
@JoinColumn(name="policeworktime_police_user_id")
private Policeworktime policeworktime;

//bi-directional many-to-one association to Role
@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="role_role_id", nullable=false)
private Role role;

public User() {
}

public Integer getUserId() {
    return this.userId;
}

public void setUserId(Integer userId) {
    this.userId = userId;
}

public String getAddress() {
    return this.address;
}

public void setAddress(String address) {
    this.address = address;
}

public Integer getAreaId() {
    return this.areaId;
}

public void setAreaId(Integer areaId) {
    this.areaId = areaId;
}

public String getBackIdCardImg() {
    return this.backIdCardImg;
}

public void setBackIdCardImg(String backIdCardImg) {
    this.backIdCardImg = backIdCardImg;
}

public String getFontIdCardImg() {
    return this.fontIdCardImg;
}

public void setFontIdCardImg(String fontIdCardImg) {
    this.fontIdCardImg = fontIdCardImg;
}

public String getFullname() {
    return this.fullname;
}

public void setFullname(String fullname) {
    this.fullname = fullname;
}

public String getPassword() {
    return this.password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getPhonenumber() {
    return this.phonenumber;
}

public void setPhonenumber(String phonenumber) {
    this.phonenumber = phonenumber;
}

public Integer getRoleId() {
    return this.roleId;
}

public void setRoleId(Integer roleId) {
    this.roleId = roleId;
}

public List<Accident> getAccidents() {
    return this.accidents;
}

public void setAccidents(List<Accident> accidents) {
    this.accidents = accidents;
}

public Accident addAccident(Accident accident) {
    getAccidents().add(accident);
    accident.setUser(this);

    return accident;
}

public Accident removeAccident(Accident accident) {
    getAccidents().remove(accident);
    accident.setUser(null);

    return accident;
}

public Area getArea() {
    return this.area;
}

public void setArea(Area area) {
    this.area = area;
}

public Policeworktime getPoliceworktime() {
    return this.policeworktime;
}

public void setPoliceworktime(Policeworktime policeworktime) {
    this.policeworktime = policeworktime;
}

public Role getRole() {
    return this.role;
}

public void setRole(Role role) {
    this.role = role;
}

}

This is my Role Entity:

@Entity
@Table(name="role")
@NamedQuery(name="Role.findAll", query="SELECT r FROM Role r")
public class Role implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="role_id", unique=true, nullable=false)
private Integer roleId;

@Column(name="role_name", length=45)
private String roleName;

//bi-directional many-to-one association to User
@OneToMany(mappedBy="role", cascade={CascadeType.ALL})
private List<User> users;

public Role() {
}

public Integer getRoleId() {
    return this.roleId;
}

public void setRoleId(Integer roleId) {
    this.roleId = roleId;
}

public String getRoleName() {
    return this.roleName;
}

public void setRoleName(String roleName) {
    this.roleName = roleName;
}

public List<User> getUsers() {
    return this.users;
}

public void setUsers(List<User> users) {
    this.users = users;
}

public User addUser(User user) {
    getUsers().add(user);
    user.setRole(this);

    return user;
}

public User removeUser(User user) {
    getUsers().remove(user);
    user.setRole(null);

        return user;
    }

}

Body:
You don't need to create Colunm roleId. You just put relational with tables. For example in my situation, I have OneToMany User with Role. I only established relational in my MySql DB. And then, you can create your own entities or use the JPA tool at your disposal. User entity has a object Role, Role entity has a List.

@Entity
@Table(name="role")
@NamedQuery(name="Role.findAll", query="SELECT r FROM Role r")
public class Role implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="role_id", unique=true, nullable=false)
private Integer roleId;

@Column(name="role_name", length=45)
private String roleName;

//bi-directional many-to-one association to User
@OneToMany(mappedBy="role")
private List<User> users;

public Role() {
}

public Integer getRoleId() {
    return this.roleId;
}

public void setRoleId(Integer roleId) {
    this.roleId = roleId;
}

public String getRoleName() {
    return this.roleName;
}

public void setRoleName(String roleName) {
    this.roleName = roleName;
}

public List<User> getUsers() {
    return this.users;
}

public void setUsers(List<User> users) {
    this.users = users;
}

public User addUser(User user) {
    getUsers().add(user);
    user.setRole(this);

    return user;
}

public User removeUser(User user) {
    getUsers().remove(user);
    user.setRole(null);

    return user;
}

 }

@Entity
@Table(name = "user")
@NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;

// bi-directional many-to-one association to Role
@ManyToOne
@JoinColumn(name = "role_role_id", nullable = false)
private Role role;

public Role getRole() {
    return this.role;
}

public void setRole(Role role) {
    this.role = role;
}

}


问:
SQL retrieve all rows between two dates and a specific number of rows before the date ordered by date
As the title says, I have a table with a date column. I am trying to retrieve all rows between 2 dates as well as X number of rows before the beginning date ordered by date.

Take a select * from table order by date DSC

```<code>20200201
20200101
20191201
20191101
20191001
20190901
20190801
20190701
</code>```

I want between 20200201 and 20191201 and the previous 3 rows(not knowing the date)

```<code>result
20200201
20200101
20191201
20191101
20191001
20190901
</code>```

my current query returns a random set of high dates between the union for some reason:

```<code>(SELECT * FROM Table WHERE Date BETWEEN 20200201 AND 20191201 ORDER BY Date ASC)
UNION
(SELECT * FROM Table WHERE Date < 20191201 ORDER BY Date DESC LIMIT 3)
</code>```

Any idea where I am going wrong?

答:
I tried this query and it worked for me:

```<code>(SELECT * FROM Table WHERE Date BETWEEN  20191201 AND 20200201 ORDER BY Date ASC)
UNION
(SELECT * FROM Table WHERE Date < 20191201 ORDER BY Date DESC LIMIT 3)
</code>```

The first select shows me:

```<code>20191201
20200101
20200201
</code>```

The second select shows me:

```<code>20191101
20191001
20190901
</code>```

Body:
As the title says, I have a table with a date column. I am trying to retrieve all rows between 2 dates as well as X number of rows before the beginning date ordered by date.

Take a select * from table order by date DSC

20200201
20200101
20191201
20191101
20191001
20190901
20190801
20190701

I want between 20200201 and 20191201 and the previous 3 rows(not knowing the date)

result
20200201
20200101
20191201
20191101
20191001
20190901

my current query returns a random set of high dates between the union for some reason:

(SELECT * FROM Table WHERE Date BETWEEN 20200201 AND 20191201 ORDER BY Date ASC)
UNION
(SELECT * FROM Table WHERE Date < 20191201 ORDER BY Date DESC LIMIT 3)

Any idea where I am going wrong?

Body:
I tried this query and it worked for me:

(SELECT * FROM Table WHERE Date BETWEEN  20191201 AND 20200201 ORDER BY Date ASC)
UNION
(SELECT * FROM Table WHERE Date < 20191201 ORDER BY Date DESC LIMIT 3)

The first select shows me:

20191201
20200101
20200201

The second select shows me:

20191101
20191001
20190901


问:
SAS YYMMDD10. works but YYMMDDn10 doesn't
This is my data (sorry for no script, it's just proc create table from mssql):

```<code>testdb.testtable
id - numeric
date_from - numeric (datetime from mssql)
date_to - numeric (datetime from mssql)
base_id - numeric
base_id2 - string (length 64)
</code>```

What I tried to do was:

```<code>proc sql;
update testdb.testtable tt
set base_id2 = CATX('_',
    ('data from other table'),
    put(datepart(date_from),yymmddn10.),
    put(datepart(date_to),yymmddn10.),
    put(base_id,z4.)
)
where (....)
;
quit;
</code>```

And I get this error:

```<code>The width value for YYMMDDN is out of bounds. It should be between 2 and 8.
The width value for YYMMDDN is out of bounds. It should be between 2 and 8.
</code>```

What I really don't understand is that when I use format with separators, YYMMDD10., it works.

When i run:

```<code>proc sql;
select datepart(date_from) format=yymmddn10. from testdb.testtable;
quit;
</code>```

It returns 20191227 - It's great. When I run

```<code>proc sql;
select put(datepart(date_from),yymmddn10.) from testdb.testtable;
quit;
</code>```

It fails with the same error.

What do I miss?

答:
There seems to be a bug in PROC SQL that allows you to attach a format that cannot work (the maximum width needed for a date without separators is 8 bytes).

It is also interesting that PROC PRINT (and the simple SELECT query in PROC SQL, like in your example) do not mind that the format width is invalid.

```<code>542   data test1;
543     now=date();
544   run;

NOTE: The data set WORK.TEST1 has 1 observations and 1 variables.

545
546   data test2 ;
547     set test1;
548     format now yymmddn10.;
                   ----------
                   29
ERROR 29-185: Width specified for format YYMMDDN is invalid.

549   run;

NOTE: The SAS System stopped processing this step because of errors.
WARNING: The data set WORK.TEST2 may be incomplete.  When this step was stopped there were 0 observations
         and 1 variables.
WARNING: Data set WORK.TEST2 was not replaced because this step was stopped.

550
551   proc sql;
552   create table test2 as select now format=yymmddn10. from test1;
NOTE: Table WORK.TEST2 created, with 1 rows and 1 columns.

553   select * from test2;
554   quit;

555
556   proc print data=test2;
557   run;

NOTE: There were 1 observations read from the data set WORK.TEST2.

558
559   data test3;
560     set test2;
561   run;

ERROR: Width specified for format YYMMDDN is invalid.
NOTE: The SAS System stopped processing this step because of errors.
WARNING: The data set WORK.TEST3 may be incomplete.  When this step was stopped there were 0 observations
         and 1 variables.
WARNING: Data set WORK.TEST3 was not replaced because this step was stopped.
</code>```

Also interesting is that if you use that format specification in PROC FREQ

```<code>proc freq data=test2; tables now; run;
</code>```

it adds a space and a 'F7'x character in front of the data string.

```<code>The FREQ Procedure

                                       Cumulative    Cumulative
       now    Frequency     Percent     Frequency      Percent
---------------------------------------------------------------
 ÷20200218           1      100.00             1       100.00
</code>```

Body:
This is my data (sorry for no script, it's just proc create table from mssql):

testdb.testtable
id - numeric
date_from - numeric (datetime from mssql)
date_to - numeric (datetime from mssql)
base_id - numeric
base_id2 - string (length 64)

What I tried to do was:

proc sql;
update testdb.testtable tt
set base_id2 = CATX('_',
    ('data from other table'),
    put(datepart(date_from),yymmddn10.),
    put(datepart(date_to),yymmddn10.),
    put(base_id,z4.)
)
where (....)
;
quit;

And I get this error:

The width value for YYMMDDN is out of bounds. It should be between 2 and 8.
The width value for YYMMDDN is out of bounds. It should be between 2 and 8.

What I really don't understand is that when I use format with separators, YYMMDD10., it works.

When i run:

proc sql;
select datepart(date_from) format=yymmddn10. from testdb.testtable;
quit;

It returns 20191227 - It's great. When I run

proc sql;
select put(datepart(date_from),yymmddn10.) from testdb.testtable;
quit;

It fails with the same error.

What do I miss?

Body:
There seems to be a bug in PROC SQL that allows you to attach a format that cannot work (the maximum width needed for a date without separators is 8 bytes).

It is also interesting that PROC PRINT (and the simple SELECT query in PROC SQL, like in your example) do not mind that the format width is invalid.

542   data test1;
543     now=date();
544   run;

NOTE: The data set WORK.TEST1 has 1 observations and 1 variables.

545
546   data test2 ;
547     set test1;
548     format now yymmddn10.;
                   ----------
                   29
ERROR 29-185: Width specified for format YYMMDDN is invalid.

549   run;

NOTE: The SAS System stopped processing this step because of errors.
WARNING: The data set WORK.TEST2 may be incomplete.  When this step was stopped there were 0 observations
         and 1 variables.
WARNING: Data set WORK.TEST2 was not replaced because this step was stopped.

550
551   proc sql;
552   create table test2 as select now format=yymmddn10. from test1;
NOTE: Table WORK.TEST2 created, with 1 rows and 1 columns.

553   select * from test2;
554   quit;

555
556   proc print data=test2;
557   run;

NOTE: There were 1 observations read from the data set WORK.TEST2.

558
559   data test3;
560     set test2;
561   run;

ERROR: Width specified for format YYMMDDN is invalid.
NOTE: The SAS System stopped processing this step because of errors.
WARNING: The data set WORK.TEST3 may be incomplete.  When this step was stopped there were 0 observations
         and 1 variables.
WARNING: Data set WORK.TEST3 was not replaced because this step was stopped.

Also interesting is that if you use that format specification in PROC FREQ

proc freq data=test2; tables now; run;

it adds a space and a 'F7'x character in front of the data string.

The FREQ Procedure

                                       Cumulative    Cumulative
       now    Frequency     Percent     Frequency      Percent
---------------------------------------------------------------
 ÷20200218           1      100.00             1       100.00


问:
Android: how to open a Google Map?
I have an activity which extends MapActivity. After running the activity, the Google Map should be shown on the emulator.
How can I do that?</p>

答:
You have to signup here and then insert the code provided in your layout like this:</p>

```<code><com.google.android.maps.MapView
    android:id="@+id/map_map"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:apiKey="***************************************"
/>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Android: how to open a Google Map?

Body:
You have to signup here and then insert the code provided in your layout like this:

<com.google.android.maps.MapView
    android:id="@+id/map_map"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:apiKey="***************************************"
/>


问:
How does [Authorize] attribute know if a user has a role?
Lets say I have a working implementation of authentication and authorization in an ASP.NET Core MVC app, and on an action I have [Authorize(Roles = "Admin")] attribute. I have just logged in and I'm about to call that action.

When that action is called, where does the [Authorize(Roles = "Admin")] attribute look to see if the user has the role of "Admin"? Where is "Admin" stored?

答:
If you are using the default implementation of ASP.NET Identity, the roles will be stored in the table AspNetRoles and the user role assignments on the AspNetUserRoles table.

The Authorize attribute is executed before the action is executed.
Check out the following link for more details on the request pipeline: Filters in ASP.NET Core


问:
Facebook Instant Game IAP on Android device
We are trying to integrate facebook instant game IAP in our game，but it only works on Browser.

There is a dialog presented on browser.
payment dialog on browser

But on Android device, the callback passed to FBInstant.payments.onReady is never called.

Sample Code we are using:

```<code>let supportedAPIs = FBInstant.getSupportedAPIs();
if (supportedAPIs.includes('payments.purchaseAsync'))
{
    console.log('payments supported...');

    FBInstant.payments.onReady(() => {
        console.log('payments ready...');

        FBInstant.payments.purchaseAsync({
            productID: 'test_product',
            developerPayload: 'payload',
        }).then(function (purchase) {
            console.log(purchase);
        });
    });
}
else
{
    console.log('payments not supported...');
}
</code>```

Is there any extra requirement I need to fulfill before I could test payment on Android device?

My test device model is Nexus 6P, and Android version is 8.0.

答:
Looks like you're no consuming your purchase. As long as you have everything good with your Business verification, IAP settings etc. from the Facebook Developers admin dashboard the code below is working for me:

```<code>FBInstant.payments.purchaseAsync({
    productID: 'gems50'
  }).then(function (purchase) {
    FBInstant.payments.consumePurhaseAsync(purchase.purchaseToken).then(function () {
      localStorage.gems = parseInt(localStorage.gems) + 50; // Add appropriate quantity of extra gems.
    }).catch(function (error) {
      // Handle errors...
    });
  }).catch(function (error) {
    // Handle errors...
});
</code>```

Keep in mind that alert and console.log won't help you with any interaction/logs when working on Android for Facebook Instant Games.

Body:
We are trying to integrate facebook instant game IAP in our game，but it only works on Browser.

There is a dialog presented on browser.
payment dialog on browser

But on Android device, the callback passed to FBInstant.payments.onReady is never called.

Sample Code we are using:

let supportedAPIs = FBInstant.getSupportedAPIs();
if (supportedAPIs.includes('payments.purchaseAsync'))
{
    console.log('payments supported...');

    FBInstant.payments.onReady(() => {
        console.log('payments ready...');

        FBInstant.payments.purchaseAsync({
            productID: 'test_product',
            developerPayload: 'payload',
        }).then(function (purchase) {
            console.log(purchase);
        });
    });
}
else
{
    console.log('payments not supported...');
}

Is there any extra requirement I need to fulfill before I could test payment on Android device?

My test device model is Nexus 6P, and Android version is 8.0.

Body:
Looks like you're no consuming your purchase. As long as you have everything good with your Business verification, IAP settings etc. from the Facebook Developers admin dashboard the code below is working for me:

FBInstant.payments.purchaseAsync({
    productID: 'gems50'
  }).then(function (purchase) {
    FBInstant.payments.consumePurhaseAsync(purchase.purchaseToken).then(function () {
      localStorage.gems = parseInt(localStorage.gems) + 50; // Add appropriate quantity of extra gems.
    }).catch(function (error) {
      // Handle errors...
    });
  }).catch(function (error) {
    // Handle errors...
});

Keep in mind that alert and console.log won't help you with any interaction/logs when working on Android for Facebook Instant Games.


问:
Compile Error: Method or data member not found, VBA
I am using a ActiveX Command Button in Microsoft Word to do the following tasks:

Add ActiveX labels to a series of tables

Rename the inserted ActiveX labels

Populate the captions of the ActiveX labels with data from an Excel workbook

I am renaming the ActiveX labels to "FY" & seq where seq is a sequence of numbers. For example, a renamed label could be "FY1". In Step 3 my code uses "FY1" (ThisDocument.FY1.Caption = rw.Cells(1).Value) but the code will not run and I receive a Compile Error: Method or data member not found message.

Do I have to call a new Sub for my labels to be recognized? Is there a way for the whole code to be ran with one click of an ActiveX button?

```<code>Private Sub CommandButton1_Click()

Dim objExcel As Excel.Application
Dim exWb As Excel.Workbook
Dim rng As Excel.Range, m, rw As Excel.Range
Dim num As Integer
Dim TableNo As Integer
Dim seq As Integer
Dim ctl As MSForms.Label
Dim ils As Word.InlineShape

Set objExcel = New Excel.Application
Set exWb = objExcel.Workbooks.Open("O:\Documents\Database.csv")
Set rng = exWb.Sheets("FY1819_DatabaseExtracted").Cells
TableNo = ActiveDocument.Tables.Count
num = 3
seq = 1

'' Now, create all FY labels
Do
    Set ils = ActiveDocument.Tables(num).cell(6, 2).Range.InlineShapes.AddOLEControl(ClassType:="Forms.Label.1")
    Set ctl = ils.OLEFormat.Object
    ctl.Name = "FY" & seq
    seq = seq + 1
    num = num + 1
Loop Until num = TableNo + 1

'''' Match to Excel Database
m = objExcel.Match(ThisDocument.Code1.Caption, rng.Columns(3), 0)

If Not IsError(m) Then
    Set rw = rng.Rows(m) '<< get the matching row as a Range
    ThisDocument.FY1.Caption = rw.Cells(1).Value 'value from colA
End If

Set exWb = Nothing

End Sub
</code>```

My error occurs at ThisDocument.FY1.Caption = rw.Cells(1).Value. The 'FY1' isn't recognized.

答:
Here's a simplified example of how to change your code:</p>

```<code>Private Sub CommandButton1_Click()

    Dim obj, ctl, ils As Word.InlineShape

    'add a control and set its name
    Set ils = ActiveDocument.Tables(1).Cell(1, 1).Range. _
                  InlineShapes.AddOLEControl(ClassType:="Forms.Label.1")
    Set ctl = ils.OLEFormat.Object
    ctl.Name = "FY1"
    'consider setting the caption here?

    'ThisDocument.FY1.Caption = "Hello" '<< will not compile

    'alternate approach
    Set obj = GetControl(ActiveDocument, "FY1")
    If Not obj Is Nothing Then
        obj.Caption = "Hello"
    End If

End Sub

'get a control by name
Function GetControl(doc As Document, conName As String) As Object
    Dim rv As Object, obj
    For Each obj In doc.InlineShapes
        If obj.OLEFormat.Object.Name = conName Then
            Set rv = obj.OLEFormat.Object
            Exit For
        End If
    Next obj
    Set GetControl = rv
End Function
</code>```

Body:
I am using a ActiveX Command Button in Microsoft Word to do the following tasks:

Add ActiveX labels to a series of tables

Rename the inserted ActiveX labels

Populate the captions of the ActiveX labels with data from an Excel workbook

I am renaming the ActiveX labels to "FY" & seq where seq is a sequence of numbers. For example, a renamed label could be "FY1". In Step 3 my code uses "FY1" (ThisDocument.FY1.Caption = rw.Cells(1).Value) but the code will not run and I receive a Compile Error: Method or data member not found message.

Do I have to call a new Sub for my labels to be recognized? Is there a way for the whole code to be ran with one click of an ActiveX button?

Private Sub CommandButton1_Click()

Dim objExcel As Excel.Application
Dim exWb As Excel.Workbook
Dim rng As Excel.Range, m, rw As Excel.Range
Dim num As Integer
Dim TableNo As Integer
Dim seq As Integer
Dim ctl As MSForms.Label
Dim ils As Word.InlineShape

Set objExcel = New Excel.Application
Set exWb = objExcel.Workbooks.Open("O:\Documents\Database.csv")
Set rng = exWb.Sheets("FY1819_DatabaseExtracted").Cells
TableNo = ActiveDocument.Tables.Count
num = 3
seq = 1

'' Now, create all FY labels
Do
    Set ils = ActiveDocument.Tables(num).cell(6, 2).Range.InlineShapes.AddOLEControl(ClassType:="Forms.Label.1")
    Set ctl = ils.OLEFormat.Object
    ctl.Name = "FY" & seq
    seq = seq + 1
    num = num + 1
Loop Until num = TableNo + 1

'''' Match to Excel Database
m = objExcel.Match(ThisDocument.Code1.Caption, rng.Columns(3), 0)

If Not IsError(m) Then
    Set rw = rng.Rows(m) '<< get the matching row as a Range
    ThisDocument.FY1.Caption = rw.Cells(1).Value 'value from colA
End If

Set exWb = Nothing

End Sub

My error occurs at ThisDocument.FY1.Caption = rw.Cells(1).Value. The 'FY1' isn't recognized.

Body:
Here's a simplified example of how to change your code:

Private Sub CommandButton1_Click()

    Dim obj, ctl, ils As Word.InlineShape

    'add a control and set its name
    Set ils = ActiveDocument.Tables(1).Cell(1, 1).Range. _
                  InlineShapes.AddOLEControl(ClassType:="Forms.Label.1")
    Set ctl = ils.OLEFormat.Object
    ctl.Name = "FY1"
    'consider setting the caption here?

    'ThisDocument.FY1.Caption = "Hello" '<< will not compile

    'alternate approach
    Set obj = GetControl(ActiveDocument, "FY1")
    If Not obj Is Nothing Then
        obj.Caption = "Hello"
    End If

End Sub

'get a control by name
Function GetControl(doc As Document, conName As String) As Object
    Dim rv As Object, obj
    For Each obj In doc.InlineShapes
        If obj.OLEFormat.Object.Name = conName Then
            Set rv = obj.OLEFormat.Object
            Exit For
        End If
    Next obj
    Set GetControl = rv
End Function


问:
When hovering/viewing Javascript Documentation in IntelliJ, what are all of the extra symbols?
So I'm trying out IntelliJ and possibly moving away from Eclipse.  I see I can hover over Javascript methods and actually see some info, which is great.  But how do I find out more about what is being shown to me?  In the pic below, what does the "?" mean?  Does 'void' mean there is not a 'return' statement?

Is this JSDoc?  This is old legacy code, so I know there is not any commenting above the function to give more info, so I'd like to know what's going on here.  Is this just IntelliJ extrapolating the function arguments and creating its own interpretation?

I assume there's a guide or legend out there for this.  But after searching around for a while I feel like I don't know the right search term to look for.  Any help is appreciated.

EDIT: We don't use TypeScript at all in our current app.

答:
Quick documentation is mostly based on comments in code. In this case the information comes from bundled definition files (In this case, a d.ts file which is a TypeScript type defintion file). For the methods defined in the project or in its dependencies, IDEA shows information from the JSDoc comments attached to functions.

Looks as if the function is defined in a d.ts file, because explicit type declarations are used, so ? indicates optional parameter, and void means that the function is not returning a value.


问:
Razor month dropdown to select current month
I've seen that there are plenty of ways to create a dropdown in razor that populates with a range of months and years. But, is there a lightweight way to autoselect the current month in that dropdown without resorting to js/jquery post page render? Let's say it's for a credit card form and I want to make sure that the dropdown autoselects the current month.

In case you need code, here's what I'm working with:

```<code>@{
   int[] months = Enumerable.Range(1, 12).ToArray();
}
@Html.DropDownListFor(x => x.ExpirationMonth,
                     months.Select(x =>
                          new SelectListItem {
                            Text = x.ToString(),
                            Value = x.ToString()
                          }
                     ))
</code>```

答:
```<code>@{

string curMonth = DateTime.Now.ToString("MMMM");

}
</code>```

Get the current month like this

```<code>@Html.DropDownListFor(model => model.SelectedMonth, Enumerable.Range(1, 12).Select(x => new SelectListItem { Value = x.ToString(), Text = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(x) }), curMonth, new { @class = "form-control" })
</code>```

Create a dropdown with the option label set to curMonth and SelectedMonth a string in your model/viewModel.

Body:
I've seen that there are plenty of ways to create a dropdown in razor that populates with a range of months and years. But, is there a lightweight way to autoselect the current month in that dropdown without resorting to js/jquery post page render? Let's say it's for a credit card form and I want to make sure that the dropdown autoselects the current month.

In case you need code, here's what I'm working with:

@{
   int[] months = Enumerable.Range(1, 12).ToArray();
}
@Html.DropDownListFor(x => x.ExpirationMonth,
                     months.Select(x =>
                          new SelectListItem {
                            Text = x.ToString(),
                            Value = x.ToString()
                          }
                     ))

Body:
@{

string curMonth = DateTime.Now.ToString("MMMM");

}

Get the current month like this

@Html.DropDownListFor(model => model.SelectedMonth, Enumerable.Range(1, 12).Select(x => new SelectListItem { Value = x.ToString(), Text = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(x) }), curMonth, new { @class = "form-control" })

Create a dropdown with the option label set to curMonth and SelectedMonth a string in your model/viewModel.


问:
Where to find a list of all jQuery events?
I really did try Google and jQuery documentation for this and I give up.

I need event names. No - I don't need to load them with code, I need them as HTML page, you know, to read and check what was the exact name of this event I've just forgotten. I'm sure there are hidden somwhere around the web laughing at me :)

It's pointless for me (or anyone) to ask here, "hey, how to attach a code when jQuery.ajax starts". I know, jQuery .ajax() triggers some global and local events, I know, if I'll waste another 15 minutes for reading whole .ajax() documentation I'll find it, but it's not my point. If you forget rarely used HTML tag name or syntax you just type "HTML tags" in google and find your tag in less than 10 seconds. Try it with jQuery event names :) "Window events" returns quite good documetation by Microsoft.

I'd rather waste my time for really good question: where to find a list of all jQuery events? It would be cool if they had some sort of description, but the most important are names.

I don't need any particular one of them. I need all of them in one place.

It's braindead easy when it comes to "class methods and properties". I know the code can define any number of custom events, but first: DOMDocument defines its defaults, JavaScript window defines its own and jQuery itself defines its own. Is there a list?

答:
Events in jQuery are just DOM events — except for a few exceptions that are provided for convenience — so you're not really looking for jQuery events.  That's the reason you're having a hard time finding them.

Since the events supported by each browser differ you really need to be looking at either a place like Quirksmode, for compatibility tables, or each vendor's support site like Mozilla Developer Network or MSDN.

Remove the on prefix for any event when binding with jQuery.


问:
Need help in Django 2x ,( FOREIGN KEY constraint failed )
hi everyone i made a simple modeland my problem is when i try to make a FOREIGN KEY in my model it shows me this error message , it would be awesome if you can help
here is the code

Model.py:

```<code>from django.db import models
from django.utils import timezone

# Create your models here.
class category(models.Model):
    title=models.CharField(max_length=100,default='')
    def __str__(self):
        return self.title
class gigpost(models.Model):

    title=models.CharField(default='',max_length=100)
    Category=models.OneToOneField(category,on_delete=True,default='')
    published_at=models.DateTimeField(auto_now_add=True)
    description=models.TextField(default='',max_length=None)
    mainphoto=models.ImageField(default='')
    photo=models.FileField()
    def __str__(self):
        return self.title
</code>```

Admin.py

```<code>from django.contrib import admin
from .models import gigpost , category

# Register your models here.
admin.site.register(gigpost)
admin.site.register(category)
</code>```

the error message :

```<code>IntegrityError at /admin/gigpost/category/add/
FOREIGN KEY constraint failed
Request Method: POST
Request URL:    http://127.0.0.1:8000/admin/gigpost/category/add/
Django Version: 2.2.5
Exception Type: IntegrityError
Exception Value:
FOREIGN KEY constraint failed
Exception Location: C:\Users\Madara\Miniconda3\envs\myEv\lib\site-packages\django\db\backends\base\base.py in _commit, line 240
Python Executable:  C:\Users\Madara\Miniconda3\envs\myEv\python.exe
Python Version: 3.7.6
Python Path:
['C:\\Users\\Madara\\Desktop\\empliya\\empliya',
 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv\\python37.zip',
 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv\\DLLs',
 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv\\lib',
 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv',
 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv\\lib\\site-packages']
Server time:    Tue, 18 Feb 2020 19:34:39 +0000
</code>```

答:
```<code>category=models.OneToOneField(Category, on_delete=models.PROTECT, default='')
</code>```

instead of

```<code>Category=models.OneToOneField(category,on_delete=True,default='')
</code>```

also class name should be in uppercase:

```<code>class Category(models.Model):
class Gigpost(models.Model):
</code>```

Body:
hi everyone i made a simple modeland my problem is when i try to make a FOREIGN KEY in my model it shows me this error message , it would be awesome if you can help
here is the code

Model.py:

from django.db import models
from django.utils import timezone

# Create your models here.
class category(models.Model):
    title=models.CharField(max_length=100,default='')
    def __str__(self):
        return self.title
class gigpost(models.Model):

    title=models.CharField(default='',max_length=100)
    Category=models.OneToOneField(category,on_delete=True,default='')
    published_at=models.DateTimeField(auto_now_add=True)
    description=models.TextField(default='',max_length=None)
    mainphoto=models.ImageField(default='')
    photo=models.FileField()
    def __str__(self):
        return self.title

Admin.py

from django.contrib import admin
from .models import gigpost , category

# Register your models here.
admin.site.register(gigpost)
admin.site.register(category)

the error message :

IntegrityError at /admin/gigpost/category/add/
FOREIGN KEY constraint failed
Request Method: POST
Request URL:    http://127.0.0.1:8000/admin/gigpost/category/add/
Django Version: 2.2.5
Exception Type: IntegrityError
Exception Value:
FOREIGN KEY constraint failed
Exception Location: C:\Users\Madara\Miniconda3\envs\myEv\lib\site-packages\django\db\backends\base\base.py in _commit, line 240
Python Executable:  C:\Users\Madara\Miniconda3\envs\myEv\python.exe
Python Version: 3.7.6
Python Path:
['C:\\Users\\Madara\\Desktop\\empliya\\empliya',
 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv\\python37.zip',
 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv\\DLLs',
 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv\\lib',
 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv',
 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv\\lib\\site-packages']
Server time:    Tue, 18 Feb 2020 19:34:39 +0000

Body:
category=models.OneToOneField(Category, on_delete=models.PROTECT, default='')

instead of

Category=models.OneToOneField(category,on_delete=True,default='')

also class name should be in uppercase:

class Category(models.Model):
class Gigpost(models.Model):


问:
Navbar functionality?
Please Help. I am trying to add functionality to my navbar so that if I click the menu button a side navbar pops out. It doesn't work. I have searched the web extensively. signedInLinks is a script that has the links used if someone is signed in. The boolean true is a place holder that will later contain auth.uid to check if a person is signed in (if you want to help me on this, please do as well - when I use this.state.links it throws an error.
How can I get my program to display a navbar with functionality (popping out menus etc)?

```<code>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import SignedInLinks from './SignedInLinks';
import SignedOutLinks from './SignedOutLinks';
import { connect } from 'react-redux';
import { NavLink } from 'react-router-dom';
import "materialize-css/dist/css/materialize.min.css"
import M from  'materialize-css/dist/js/materialize.min.js';

class Navbar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            auth : this.props,
            links : this.props.auth.uid ? <SignedInLinks /> : <SignedOutLinks />
        }
    }

    componentDidMount() {
        const M=window.M;
        document.addEventListener('DOMContentLoaded', function() {
            var elems = document.querySelectorAll('.sidenav');
            M.Sidenav.init(elems, {});
        });
    }

    render () {
        return (

            <div>

            <nav className="nav-wrapper blue darken-4">
                <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"></link>

                <div class='container'>
                <a href="/" className='brand-logo'>DSHS</a>
                <a href="/" className="sidenav-trigger" data-target="mobile links">
                    <i className="material-icons">menu</i>
                </a>
                    <ul className="right hide-on-med-and-down">

                        {true && <SignedInLinks />}
                    </ul>
                </div>
            </nav>
            <ul className="sidenav" id="mobile-links">
                {true && <SignedInLinks />}
            </ul>
            </div>
        );
    }

}

const mapStateToProps = (state) => {
    return {
        auth: state.firebase.auth
    }
}
export default connect(mapStateToProps)(Navbar);
</code>```

答:
You are not returning anything at:

```<code>               <ul className="right hide-on-med-and-down">
                    {true && <SignedInLinks />}
               </ul>
</code>```

Try something like this:

```<code>                <ul className="right hide-on-med-and-down">

                    {condition ? <SignedInLinks /> : null}
                </ul>
</code>```

The way above, you are going to check if your condition is true. If it is, it will return and render SignedLinks. Otherwise, you are going to render null.

Title: Navbar functionality?

Body:
Please Help. I am trying to add functionality to my navbar so that if I click the menu button a side navbar pops out. It doesn't work. I have searched the web extensively. signedInLinks is a script that has the links used if someone is signed in. The boolean true is a place holder that will later contain auth.uid to check if a person is signed in (if you want to help me on this, please do as well - when I use this.state.links it throws an error.
How can I get my program to display a navbar with functionality (popping out menus etc)?

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import SignedInLinks from './SignedInLinks';
import SignedOutLinks from './SignedOutLinks';
import { connect } from 'react-redux';
import { NavLink } from 'react-router-dom';
import "materialize-css/dist/css/materialize.min.css"
import M from  'materialize-css/dist/js/materialize.min.js';

class Navbar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            auth : this.props,
            links : this.props.auth.uid ? <SignedInLinks /> : <SignedOutLinks />
        }
    }

    componentDidMount() {
        const M=window.M;
        document.addEventListener('DOMContentLoaded', function() {
            var elems = document.querySelectorAll('.sidenav');
            M.Sidenav.init(elems, {});
        });
    }

    render () {
        return (

                <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"></link>

                DSHS

                    menu

                        {true && <SignedInLinks />}

                {true && <SignedInLinks />}

        );
    }

}

const mapStateToProps = (state) => {
    return {
        auth: state.firebase.auth
    }
}
export default connect(mapStateToProps)(Navbar);

Body:
You are not returning anything at:

               <ul className="right hide-on-med-and-down">
                    {true && <SignedInLinks />}
               </ul>

Try something like this:

                <ul className="right hide-on-med-and-down">

                    {condition ? <SignedInLinks /> : null}
                </ul>

The way above, you are going to check if your condition is true. If it is, it will return and render SignedLinks. Otherwise, you are going to render null.


问:
Make side bars reducing with max-width by degrees
How to make side parts of web page reduce they width with reducing width of whole page by degrees?

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .container {
            display: grid;
            grid-template-columns: 10% 80% 10%;
            min-height: 100vh;
        }
        .side-right {
            background: red;
        }
        .side-left {
            background: blue;
        }
        .main {
            background: green;
        }
        @media screen and (max-width: 1000px) {
            .container {
                grid-template-columns: 0 100% 0;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="side-right">
    </div>
    <div class="main">
    </div>
    <div class="side-left">
    </div>
</div>
</body>
</html>
</code>```

In example below after max-width = 1000px side elements are dissapearing instantly, but I want to make them reducing they width reacting by every pixel changed on max-width. How to make it?

答:
You can animate all with flex-box and just by changing some of your css.

```<code>.container {
  display: flex;
  min-height: 100vh;
  flex-direction: row-reverse;
}
.side-right {
  background: red;
  width: 100%;
}
.side-left {
  background: blue;
  width: 100%;
}
.main {
  background: green;
  min-width: 600px;
}
</code>```

Thats just a basic example. Consider reading more about flex-box.

Body:
How to make side parts of web page reduce they width with reducing width of whole page by degrees?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

In example below after max-width = 1000px side elements are dissapearing instantly, but I want to make them reducing they width reacting by every pixel changed on max-width. How to make it?

Body:
You can animate all with flex-box and just by changing some of your css.

.container {
  display: flex;
  min-height: 100vh;
  flex-direction: row-reverse;
}
.side-right {
  background: red;
  width: 100%;
}
.side-left {
  background: blue;
  width: 100%;
}
.main {
  background: green;
  min-width: 600px;
}

Thats just a basic example. Consider reading more about flex-box.


问:
Error while installing Zeppelin notebook on EC2 instance
I have created an AWS Glue development endpoint (without specifying VPC and Subnet). Then with same endpoint I have tried to create Apache Zeppelin Notebook on EC2 instance but getting an error as CloudFormation rollback is complete.

AWS uses CloudFormation template to launch EC2 instance with same role as same as Zeppelin notebook. I observed it takes too much time to create EC2 instance (crossing timeout limit) then it has terminated immediately, with no role attached to EC2 instance.

I assigned role to Zeppelin notebook with below mentioned permissions:

AWSGlueServiceNotebookRole

AmazonGleConsoleFullAccess

iam:PassRole

aws-glue*

Used references:

Creating a Notebook Server Associated with a Development Endpoint - AWS Glue

Creating a Notebook Server Hosted on Amazon EC2 - AWS Glue

Can anyone guide me to how I could troubleshoot the issue? Steps or references help would be really appreciated.

答: Skip cloudformation, launch a normal EC2 instance, and install zeppelin on it, then create an AMI from that instance. Use this new AMI for AWS Glue</p>


问:
$project: Is it possible to access a property of an expression result in just one single stage?
Is there any way to carry out the following operation in just one $project stage?

```<code>db.getCollection('users').aggregate([
    {
        $project : {
            firstEmail : { $arrayElemAt : ["$emails", 0] }
        }
    },
    {
        $project : {
            domain : "$firstEmail.domain"
        }
    }
])
</code>```

答:
When working with array of objects, you can automatically get array of objects's properties with the dot notation.
So the following will perfectly work :

```<code>db.getCollection('users').aggregate([
    {
        $project : {
            domain: { $arrayElemAt : ["$emails.domain", 0] }
        }
    },
])
</code>```

Mongo playground

Body:
Is there any way to carry out the following operation in just one $project stage?

db.getCollection('users').aggregate([
    {
        $project : {
            firstEmail : { $arrayElemAt : ["$emails", 0] }
        }
    },
    {
        $project : {
            domain : "$firstEmail.domain"
        }
    }
])

Body:
When working with array of objects, you can automatically get array of objects's properties with the dot notation.
So the following will perfectly work :

db.getCollection('users').aggregate([
    {
        $project : {
            domain: { $arrayElemAt : ["$emails.domain", 0] }
        }
    },
])

Mongo playground


问:
Wordpress stylesheet not loading
SOLUTION

The problem was that I didn't include the header on index.php

```<code><?php
    get_header();
?>
</code>```

I added this on the first line of index.php, removing the opening  and  tags and it started working.

ORIGINAL POST

I know this has been posted about already, but none of the solutions I try seem to be working.

I am trying to load a stylesheet for my wordpress theme, but it doesn't seem to be working. My stylesheet is named style.css and it resides in the root folder (the theme folder), alongside index.php, header.php, footer.php and functions.php.

Edit: Using the firefox debugger shows that the stylesheet is definitely not loading. The style editor section gives me a, "This page has no stylesheet."

Here are the contents of those files:

index.php

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css"/>
</head>
<body>

</body>
</html>
</code>```

style.css

```<code>body{
    background-color: green;
    background: green;
}
</code>```

header.php

```<code><!DOCTYPE html>
<html>
<head>
    <?php wp_head();?>
</head>
</html>
</code>```

footer.php

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <footer class="site-footer"></footer>
    <?php wp_footer(); ?>
</body>
</html>
</code>```

functions.php

```<code><?php
    function load_css(){
        wp_enqueue_style('styles',get_stylesheet_uri());
    }
    add_action('wp_enqueue_scripts', 'load_css');
?>
</code>```

答:
The stylesheet URI you are enqueueing in functions.php, doesn't look complete to me. This bit:

get_stylesheet_uri()

This will just get the directory of the of the stylesheet, which is usually the root directory of the theme. You need to point to the specific stylesheet, so your function would look like this:

```<code>function load_css(){
  wp_enqueue_style('styles', get_stylesheet_uri() . '/style.css' );
}
add_action('wp_enqueue_scripts', 'load_css');
</code>```

...where . '/styles.css' is completing the path to the stylesheet file. Make sure the file name matches.

Resource: https://developer.wordpress.org/reference/functions/get_stylesheet_uri/

Sorry I didnt see notice that the first time My other answer still applies for the templating issues I saw the first time.

Title: Wordpress stylesheet not loading

Body:
SOLUTION

The problem was that I didn't include the header on index.php

<?php
    get_header();
?>

I added this on the first line of index.php, removing the opening  and  tags and it started working.

ORIGINAL POST

I know this has been posted about already, but none of the solutions I try seem to be working.

I am trying to load a stylesheet for my wordpress theme, but it doesn't seem to be working. My stylesheet is named style.css and it resides in the root folder (the theme folder), alongside index.php, header.php, footer.php and functions.php.

Edit: Using the firefox debugger shows that the stylesheet is definitely not loading. The style editor section gives me a, "This page has no stylesheet."

Here are the contents of those files:

index.php

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css"/>

style.css

body{
    background-color: green;
    background: green;
}

header.php

<!DOCTYPE html>

    <?php wp_head();?>

footer.php

<!DOCTYPE html>

    <meta charset="UTF-8">

    <?php wp_footer(); ?>

functions.php

<?php
    function load_css(){
        wp_enqueue_style('styles',get_stylesheet_uri());
    }
    add_action('wp_enqueue_scripts', 'load_css');
?>

Body:
The stylesheet URI you are enqueueing in functions.php, doesn't look complete to me. This bit:

get_stylesheet_uri()

This will just get the directory of the of the stylesheet, which is usually the root directory of the theme. You need to point to the specific stylesheet, so your function would look like this:

function load_css(){
  wp_enqueue_style('styles', get_stylesheet_uri() . '/style.css' );
}
add_action('wp_enqueue_scripts', 'load_css');

...where . '/styles.css' is completing the path to the stylesheet file. Make sure the file name matches.

Resource: https://developer.wordpress.org/reference/functions/get_stylesheet_uri/

Sorry I didnt see notice that the first time My other answer still applies for the templating issues I saw the first time.


问:
Waiting for flash player to connect to debugger
Using Flex Builder 3 :

I have been getting this problem in every single debug launch for past few hours.

I used to get this earlier too, but once in a while, not with every debug launch.

I found out that flex debugger uses a certain 7935 port but I can't figure out

how to change it?

答:
Make sure there is a swf file with the proper name in your bin-debug directory and that name matches the swf name specified in index.template.html file for the project.

I had replaced index.template.html file by mistake with a similar one from another project. When I tried to debug, I got this "Waiting for flash player to connect to debugger…" status till it timed out.


问:
Bootstrap not working properly in Angular 6
I started learning Angular and I'm following a tutorial. I tried putting the code as in the tutorial for the navigation-bar:

```<code><nav class="navbar navbar-default">
  <div class="container-fluid">
     <div class="navbar-header">
         <a href="#" class="navbar-brand">Recipe book</a>
     </div>
     <div class="collapse navbar-collapse">
         <ul class="nav navbar-nav">
             <li> <a href="#">Recipe</a></li>
             <li> <a href="#">Shopping list</a></li>
         </ul>
         <ul class="nav navbar-nav navbar-right">
              <li class="dropdown">
                  <ul class="dropdown-menu">
                      <li><a href="#">Save data </a></li>
                      <li><a href="#">Fetch data </a></li>
                  </ul>
              </li>
         </ul>
     </div>
  </div>
</nav>
</code>```

But all I get is this:

If I remove bootstrap, I do get the other items.

I used npm install bootstrap --save and @import "~bootstrap/dist/css/bootstrap.css"; in styles.css to use bootstrap.

EDIT:

I did not wanted to open a question with two problem, but after looking at the answers so far ill describe another problem I had:

I also installed Jquery using nmp install jquery --save and added to angular.json:

```<code>"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.css",
          "src/styles.css"
        ],
        "scripts": [
          "node_modules/jquery/dist/jquery.min.js",
          "node_modules/tether/dist/js/tether.js",
          "node_modules/bootstrap/dist/js/bootstrap.min.js"
</code>```

In this case, after removing @import "~bootstrap/dist/css/bootstrap.css"; from styles.css`, bootstrap is not working at all.
The only way i got bootstrap to work is as i described in the question.

EDIT 2:

I started a new project and followed @HDJEMAI s answer instructions.
I now still get the same page as in the picture but its now working through the rows added to styles and scripts in angular.json and not through the @import "~bootstrap/dist/css/bootstrap.css" in the styles.css file . But the problem is still that is not the same as in the tutorial even though the code is the same.

This is what he gets in the tutorial:

答:
If you are adding the bootstrap path into the angular.json file, make sure it is the styles within the project\architect\build. Not the one in the project\architect\test.

```<code>{
"projects": {
        "architect": {
            "build": {
                    "styles": [
                        "node_modules/bootstrap/dist/bootstrap.min.css",
                         "src/styles.css"
                    ],
            "test": {
                    "styles": [
                         "src/styles.css"
                    ],
</code>```

Body:
I started learning Angular and I'm following a tutorial. I tried putting the code as in the tutorial for the navigation-bar:

         Recipe book

 Recipe

 Shopping list

Save data

Fetch data

But all I get is this:

If I remove bootstrap, I do get the other items.

I used npm install bootstrap --save and @import "~bootstrap/dist/css/bootstrap.css"; in styles.css to use bootstrap.

EDIT:

I did not wanted to open a question with two problem, but after looking at the answers so far ill describe another problem I had:

I also installed Jquery using nmp install jquery --save and added to angular.json:

"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.css",
          "src/styles.css"
        ],
        "scripts": [
          "node_modules/jquery/dist/jquery.min.js",
          "node_modules/tether/dist/js/tether.js",
          "node_modules/bootstrap/dist/js/bootstrap.min.js"

In this case, after removing @import "~bootstrap/dist/css/bootstrap.css"; from styles.css`, bootstrap is not working at all.
The only way i got bootstrap to work is as i described in the question.

EDIT 2:

I started a new project and followed @HDJEMAI s answer instructions.
I now still get the same page as in the picture but its now working through the rows added to styles and scripts in angular.json and not through the @import "~bootstrap/dist/css/bootstrap.css" in the styles.css file . But the problem is still that is not the same as in the tutorial even though the code is the same.

This is what he gets in the tutorial:

Body:
If you are adding the bootstrap path into the angular.json file, make sure it is the styles within the project\architect\build. Not the one in the project\architect\test.

{
"projects": {
        "architect": {
            "build": {
                    "styles": [
                        "node_modules/bootstrap/dist/bootstrap.min.css",
                         "src/styles.css"
                    ],
            "test": {
                    "styles": [
                         "src/styles.css"
                    ],


问:
Delete all lines after a specific line in PowerShell
I have this .txt file

```<code>ROTHSCHILD  = 81;        // Fondation Adolphe de Rothschild          ,                          2019
ONCOPOLE    = 82;        // Oncopole - Toulouse                      ,                          2019
GHRMSA      = 83;        // GHR  Mulhouse Sud-Alsace                 ,                          2019
CHDN        = 84;        // CH   du Nord - Luxembourg                ,                          2019
CAEN        = 85;        // CHU  de Caen                             ,                          2019
MONTELIMAR  = 86;        //                                          ,                          2019
PUYENVELAY  = 87;        //                                          ,                          2019
</code>```

I want delete all lines after

```<code>CHDN        = 84;        // CH   du Nord - Luxembourg                ,                          2019
</code>```

How can I do this ?

I tried this:

```<code>get-content txt.txt | % {$_ ; if($_ -eq "CHDN        = 84;        // CH   du Nord - Luxembourg                ,                          2019") {break }}
</code>```

but break end my program, how can I do this?

答:
You'll likely need to do something which tests each time.  I would use a Do..Until loop like this:

```<code>$txtData = get-content txt.txt
$stophere = 'CHDN        = 84;        // CH   du Nord - Luxembourg                ,                          2019'
$ctr = 0
Do
{
    $txtData[$ctr++] #Prints data line and increments counter
} Until ($txtData[$ctr] -eq $stophere)
</code>```

Body:
I have this .txt file

ROTHSCHILD  = 81;        // Fondation Adolphe de Rothschild          ,                          2019
ONCOPOLE    = 82;        // Oncopole - Toulouse                      ,                          2019
GHRMSA      = 83;        // GHR  Mulhouse Sud-Alsace                 ,                          2019
CHDN        = 84;        // CH   du Nord - Luxembourg                ,                          2019
CAEN        = 85;        // CHU  de Caen                             ,                          2019
MONTELIMAR  = 86;        //                                          ,                          2019
PUYENVELAY  = 87;        //                                          ,                          2019

I want delete all lines after

CHDN        = 84;        // CH   du Nord - Luxembourg                ,                          2019

How can I do this ?

I tried this:

get-content txt.txt | % {$_ ; if($_ -eq "CHDN        = 84;        // CH   du Nord - Luxembourg                ,                          2019") {break }}

but break end my program, how can I do this?

Body:
You'll likely need to do something which tests each time.  I would use a Do..Until loop like this:

$txtData = get-content txt.txt
$stophere = 'CHDN        = 84;        // CH   du Nord - Luxembourg                ,                          2019'
$ctr = 0
Do
{
    $txtData[$ctr++] #Prints data line and increments counter
} Until ($txtData[$ctr] -eq $stophere)


问:
Finding USB comport numbers using VID,PID,+SN
I am looking for example code in ansi c/c++ that will find usb devices by their pid/vid/sn# and then find the associated comport number.  I have multiple FTDI usb serial ports connected to a pc and need to identify each port by the known SN#.  This code I found will display the HWID info but how do I use it to get the comport number?  Here is a response to the below code for one of the devices: USB\VID_0403&PID_6001\FTAME7HK
Are there an online tutorial that runs through examples for this type of code?</p>

```<code>    #include <windows.h>
    #include <ansi_c.h>
    #include <Setupapi.h>
    #include <devguid.h>
    #include <Setupapi.h>
    HDEVINFO deviceInfoSet;
    GUID *guidDev = (GUID*) &GUID_DEVCLASS_USB;
    TCHAR buffer [4000];
    DWORD buffersize =4000;
    int memberIndex = 0;
    main()
    {
    deviceInfoSet = SetupDiGetClassDevs(guidDev, NULL, NULL, DIGCF_PRESENT | DIGCF_PROFILE);
    while (TRUE) {
    SP_DEVINFO_DATA deviceInfoData;
    ZeroMemory(&deviceInfoData, sizeof(SP_DEVINFO_DATA));
    deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
    if (SetupDiEnumDeviceInfo(deviceInfoSet, memberIndex, &deviceInfoData) == FALSE) {
      if (GetLastError() == ERROR_NO_MORE_ITEMS)
        {
        break;
        }
   }
   DWORD nSize=0 ;
   SetupDiGetDeviceInstanceId (deviceInfoSet, &deviceInfoData, buffer, sizeof(buffer), &nSize);
   buffer [nSize] ='\0';
   printf ("%s\n", buffer);
   memberIndex++;
   }
   if (deviceInfoSet) {
   SetupDiDestroyDeviceInfoList(deviceInfoSet);
   }
   getchar();
   return 0;
   }
</code>```

答:
If you want the friendly name, which typically includes the parenthesized com port number, this should do it:

```<code>{
    wchar_t friendly_name[128];
    if (!SetupDiGetDeviceRegistryPropertyW(device_list, &device_data, SPDRP_FRIENDLYNAME, nullptr, reinterpret_cast<PBYTE>(friendly_name), sizeof friendly_name, nullptr))
        return;
    StringCopyW(buffer, friendly_name);
}
</code>```

To get the two parameters device_list and device_data for the above call, I use this function:

```<code>void rescan_ports( void )
{
    SP_DEVINFO_DATA device_data = { sizeof device_data };
    HDEVINFO device_list = SetupDiGetClassDevsW(&GUID_DEVINTERFACE_COMPORT, nullptr, nullptr, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
    DWORD error = GetLastError();
    if (!device_list && device_list == INVALID_HANDLE_VALUE) return;

    bool ended = false;
    for( int i = 0; i < 6000 && !ended; i++ ) {
        if (SetupDiEnumDeviceInfo(device_list, i, &device_data))
            format_and_add_port_detail(device_list, device_data);
        else
            ended = (GetLastError() == ERROR_NO_MORE_ITEMS);
    }

    SetupDiDestroyDeviceInfoList(device_list);
}
</code>```

It's very similar to what you wrote, except that mine uses GUID_DEVINTERFACE_COMPORT to find only serial ports.

Body:
I am looking for example code in ansi c/c++ that will find usb devices by their pid/vid/sn# and then find the associated comport number.  I have multiple FTDI usb serial ports connected to a pc and need to identify each port by the known SN#.  This code I found will display the HWID info but how do I use it to get the comport number?  Here is a response to the below code for one of the devices: USB\VID_0403&PID_6001\FTAME7HK
Are there an online tutorial that runs through examples for this type of code?

    #include <windows.h>
    #include <ansi_c.h>
    #include <Setupapi.h>
    #include <devguid.h>
    #include <Setupapi.h>
    HDEVINFO deviceInfoSet;
    GUID *guidDev = (GUID*) &GUID_DEVCLASS_USB;
    TCHAR buffer [4000];
    DWORD buffersize =4000;
    int memberIndex = 0;
    main()
    {
    deviceInfoSet = SetupDiGetClassDevs(guidDev, NULL, NULL, DIGCF_PRESENT | DIGCF_PROFILE);
    while (TRUE) {
    SP_DEVINFO_DATA deviceInfoData;
    ZeroMemory(&deviceInfoData, sizeof(SP_DEVINFO_DATA));
    deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
    if (SetupDiEnumDeviceInfo(deviceInfoSet, memberIndex, &deviceInfoData) == FALSE) {
      if (GetLastError() == ERROR_NO_MORE_ITEMS)
        {
        break;
        }
   }
   DWORD nSize=0 ;
   SetupDiGetDeviceInstanceId (deviceInfoSet, &deviceInfoData, buffer, sizeof(buffer), &nSize);
   buffer [nSize] ='\0';
   printf ("%s\n", buffer);
   memberIndex++;
   }
   if (deviceInfoSet) {
   SetupDiDestroyDeviceInfoList(deviceInfoSet);
   }
   getchar();
   return 0;
   }

Body:
If you want the friendly name, which typically includes the parenthesized com port number, this should do it:

{
    wchar_t friendly_name[128];
    if (!SetupDiGetDeviceRegistryPropertyW(device_list, &device_data, SPDRP_FRIENDLYNAME, nullptr, reinterpret_cast<PBYTE>(friendly_name), sizeof friendly_name, nullptr))
        return;
    StringCopyW(buffer, friendly_name);
}

To get the two parameters device_list and device_data for the above call, I use this function:

void rescan_ports( void )
{
    SP_DEVINFO_DATA device_data = { sizeof device_data };
    HDEVINFO device_list = SetupDiGetClassDevsW(&GUID_DEVINTERFACE_COMPORT, nullptr, nullptr, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
    DWORD error = GetLastError();
    if (!device_list && device_list == INVALID_HANDLE_VALUE) return;

    bool ended = false;
    for( int i = 0; i < 6000 && !ended; i++ ) {
        if (SetupDiEnumDeviceInfo(device_list, i, &device_data))
            format_and_add_port_detail(device_list, device_data);
        else
            ended = (GetLastError() == ERROR_NO_MORE_ITEMS);
    }

    SetupDiDestroyDeviceInfoList(device_list);
}

It's very similar to what you wrote, except that mine uses GUID_DEVINTERFACE_COMPORT to find only serial ports.


问:
C, dynamic array, segmentation fault
I wanted to allocate memory and scanf array in one function, but it gives segmentation fault (core dumped) error. Thank you for help.</p>

```<code>#include <stdio.h>
#include <stdlib.h>

void scanf_array (int **array_pp, int size);

int main ()
{
  int *array_p, size;
  scanf ("%d", &size);
  scanf_array (&array_p, size);
  for (int i = 0; i < size; i++)
  {
    printf ("%d", array_p[i]);
  }
  return 0;
}

void scanf_array (int **array_pp, int size)
{
  *array_pp = (int *)malloc (size * sizeof (int));
  for (int i = 0; i < size; i++)
  {
  scanf ("%d", array_pp[i]);
  }
}
</code>```

答:
```<code>scanf ("%d", array_pp[i]);
</code>```

is wrong. int **array_pp is meant to be pointer to an array of ints. So you want to dereference the pointer, then pass the address of ith element to scanf:

```<code>scanf ("%d", &(*array_pp)[i]);
scanf ("%d", (*array_pp) + i);  // means the same
</code>```

Remember to free(array_p).

Because sometimes using pointer to pointer sematics is hard, it's sometimes clearer to use a temp pointer for me:

```<code>void scanf_array (int **array_pp, int size)
{
  int *array_p = malloc(size * sizeof (*array_p));
  for (int i = 0; i < size; i++) {
     scanf ("%d", &array_p[i]);
  }
  *array_pp = array_p;
}
</code>```

Title: C, dynamic array, segmentation fault

Body:
I wanted to allocate memory and scanf array in one function, but it gives segmentation fault (core dumped) error. Thank you for help.

#include <stdio.h>
#include <stdlib.h>

void scanf_array (int **array_pp, int size);

int main ()
{
  int *array_p, size;
  scanf ("%d", &size);
  scanf_array (&array_p, size);
  for (int i = 0; i < size; i++)
  {
    printf ("%d", array_p[i]);
  }
  return 0;
}

void scanf_array (int **array_pp, int size)
{
  *array_pp = (int *)malloc (size * sizeof (int));
  for (int i = 0; i < size; i++)
  {
  scanf ("%d", array_pp[i]);
  }
}

Body:
scanf ("%d", array_pp[i]);

is wrong. int **array_pp is meant to be pointer to an array of ints. So you want to dereference the pointer, then pass the address of ith element to scanf:

scanf ("%d", &(*array_pp)[i]);
scanf ("%d", (*array_pp) + i);  // means the same

Remember to free(array_p).

Because sometimes using pointer to pointer sematics is hard, it's sometimes clearer to use a temp pointer for me:

void scanf_array (int **array_pp, int size)
{
  int *array_p = malloc(size * sizeof (*array_p));
  for (int i = 0; i < size; i++) {
     scanf ("%d", &array_p[i]);
  }
  *array_pp = array_p;
}


问:
Login using java jsoup doesn't work on site rotowire
After trying several tutorials and reading many posts here, I still can't access the Rotowire site. This is my code.</p>

```<code>public static void main(String[] args) {

    final String USER_AGENT = "Mozilla/5.0";
    String loginFormUrl = "https://www.rotowire.com/users/login.php";
            String loginActionUrl = "https://www.rotowire.com/users/login.php";
    HashMap<String, String> cookies = new HashMap<String, String>();
    HashMap<String, String> formData = new HashMap<String, String>();

    try {

                Connection.Response loginForm = Jsoup.connect(loginFormUrl)

                        .method(Connection.Method.GET)
                        .userAgent(USER_AGENT)
                        .timeout(10 * 1000)
                        .followRedirects(true)
                        .execute();
                cookies.putAll(loginForm.cookies());
                String username = "****";
                String password = "****";
                formData.put("username",username);
                formData.put("password",password);
                formData.put("landingPage", "/");

                Connection.Response homePage = Jsoup.connect(loginActionUrl)
                        .cookies(cookies)
                        .data(formData)
                        .method(Connection.Method.POST)
                        .userAgent(USER_AGENT)
                        .timeout(10 * 1000)
                        .followRedirects(true)
                        .execute();
                Document doc = Jsoup.connect(loginFormUrl).cookies(homePage.cookies()).get();
                System.out.println(doc.html());
    } catch (IOException e) {
                // TODO Auto-generated catch block
                enter code heree.printStackTrace();
            }
}
</code>```

答:
Usually I do not use JSoup for login actions, since it does not handle javascript. Maybe you should move to HtmlUnit or Selenium to accomplish what you need.

EDIT: Adding an example using HtmlUnit

```<code>public void Login(String pass, String user) {
        try {
            HtmlPage p = navegador.getPage("https://www.somewebsite.com"); //The login webpage
            HtmlForm form = p.getFormByName("form-login"); //The login form name
            form.getInputByName("UserName").setValueAttribute(user);  //Setting username to the form
            form.getInputByName("Password").setValueAttribute(pass);  //Setting password to the form
            p = form.getInputByValue("Go").click(); //Clicking the form button by its input value and getting the next page
            System.out.println(p.asText()); //printing the page after being logged in
        }catch (FailingHttpStatusCodeException | IOException e) {
            e.printStackTrace();
        }
    }
</code>```

The navegador object is an instance of WebClient, which you can instantiate doing something like:

```<code>WebClient navegador = new WebClient(BrowserVersion.CHROME);
</code>```

Body:
After trying several tutorials and reading many posts here, I still can't access the Rotowire site. This is my code.

public static void main(String[] args) {

    final String USER_AGENT = "Mozilla/5.0";
    String loginFormUrl = "https://www.rotowire.com/users/login.php";
            String loginActionUrl = "https://www.rotowire.com/users/login.php";
    HashMap<String, String> cookies = new HashMap<String, String>();
    HashMap<String, String> formData = new HashMap<String, String>();

    try {

                Connection.Response loginForm = Jsoup.connect(loginFormUrl)

                        .method(Connection.Method.GET)
                        .userAgent(USER_AGENT)
                        .timeout(10 * 1000)
                        .followRedirects(true)
                        .execute();
                cookies.putAll(loginForm.cookies());
                String username = "****";
                String password = "****";
                formData.put("username",username);
                formData.put("password",password);
                formData.put("landingPage", "/");

                Connection.Response homePage = Jsoup.connect(loginActionUrl)
                        .cookies(cookies)
                        .data(formData)
                        .method(Connection.Method.POST)
                        .userAgent(USER_AGENT)
                        .timeout(10 * 1000)
                        .followRedirects(true)
                        .execute();
                Document doc = Jsoup.connect(loginFormUrl).cookies(homePage.cookies()).get();
                System.out.println(doc.html());
    } catch (IOException e) {
                // TODO Auto-generated catch block
                enter code heree.printStackTrace();
            }
}

Body:
Usually I do not use JSoup for login actions, since it does not handle javascript. Maybe you should move to HtmlUnit or Selenium to accomplish what you need.

EDIT: Adding an example using HtmlUnit

public void Login(String pass, String user) {
        try {
            HtmlPage p = navegador.getPage("https://www.somewebsite.com"); //The login webpage
            HtmlForm form = p.getFormByName("form-login"); //The login form name
            form.getInputByName("UserName").setValueAttribute(user);  //Setting username to the form
            form.getInputByName("Password").setValueAttribute(pass);  //Setting password to the form
            p = form.getInputByValue("Go").click(); //Clicking the form button by its input value and getting the next page
            System.out.println(p.asText()); //printing the page after being logged in
        }catch (FailingHttpStatusCodeException | IOException e) {
            e.printStackTrace();
        }
    }

The navegador object is an instance of WebClient, which you can instantiate doing something like:

WebClient navegador = new WebClient(BrowserVersion.CHROME);