问:
Maven project with local file dependency build error 501
I've got maven project with local dependencies, which doesn't compile because this 'improvement', introduced by maven:

Effective January 15, 2020, The Central Repository no longer supports
  insecure communication over plain HTTP and requires that all requests
  to the repository are encrypted over HTTPS.

Here is my pom.xml:

```<code>...
<repositories>
    <repository>
        <id>in-project</id>
        <name>In Project Repo</name>
        <url>file://${project.basedir}/libs</url>
    </repository>
</repositories>
...
</code>```

So now I'm receiving the following compile error:

Could not resolve dependencies for project ........:war:1.0: Failed to

  collect dependencies for [.........:jar:1.0 (compile),

  javax:javaee-web-api:jar:7.0 (provided), .........:jar:1.0

  (compile)]: Failed to read artifact descriptor for

  .........:jar:1.0: Could not transfer artifact

  .........:pom:1.0 from/to central

  (http://repo.maven.apache.org/maven2): Failed to transfer file:

  http://repo.maven.apache.org/maven2/com/..../..../1.0/.....-1.0.pom.

  Return code is: 501 , ReasonPhrase:HTTPS Required. -> [Help 1]

As you can see I'm using local jar file, but this doesn't compile anymore

Does anyone have idea how to configure local repository for successful compilation?

答:
The Maven server do not support HTTP anymore. You must configure the maven repositories with HTTPS url's in your local maven configuration file, in your home folder yourname/.m2/settings.xml.

Here is an example that you may copy:

```<code><?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
   <profiles>
      <profile>
         <id>artifactory</id>
         <repositories>
            <repository>
               <snapshots>
                  <enabled>false</enabled>
               </snapshots>
               <id>central</id>
               <name>libs-release</name>
               <url>https://repo1.maven.org/maven2/</url>
            </repository>
            <repository>
               <snapshots />
               <id>snapshots</id>
               <name>libs-snapshot</name>
               <url>https://repo1.maven.org/maven2/</url>
            </repository>
         </repositories>
         <pluginRepositories>
            <pluginRepository>
               <snapshots>
                  <enabled>false</enabled>
               </snapshots>
               <id>central</id>
               <name>plugins-release</name>
               <url>https://repo1.maven.org/maven2/</url>
            </pluginRepository>
            <pluginRepository>
               <snapshots />
               <id>snapshots</id>
               <name>plugins-snapshot</name>
               <url>https://repo1.maven.org/maven2/</url>
            </pluginRepository>
         </pluginRepositories>
      </profile>
   </profiles>
   <activeProfiles>
      <activeProfile>artifactory</activeProfile>
   </activeProfiles>
</settings>
</code>```

Body:
I've got maven project with local dependencies, which doesn't compile because this 'improvement', introduced by maven:

Effective January 15, 2020, The Central Repository no longer supports
  insecure communication over plain HTTP and requires that all requests
  to the repository are encrypted over HTTPS.

Here is my pom.xml:

...
<repositories>
    <repository>
        <id>in-project</id>
        <name>In Project Repo</name>
        <url>file://${project.basedir}/libs</url>
    </repository>
</repositories>
...

So now I'm receiving the following compile error:

Could not resolve dependencies for project ........:war:1.0: Failed to

  collect dependencies for [.........:jar:1.0 (compile),

  javax:javaee-web-api:jar:7.0 (provided), .........:jar:1.0

  (compile)]: Failed to read artifact descriptor for

  .........:jar:1.0: Could not transfer artifact

  .........:pom:1.0 from/to central

  (http://repo.maven.apache.org/maven2): Failed to transfer file:

  http://repo.maven.apache.org/maven2/com/..../..../1.0/.....-1.0.pom.

  Return code is: 501 , ReasonPhrase:HTTPS Required. -> [Help 1]

As you can see I'm using local jar file, but this doesn't compile anymore

Does anyone have idea how to configure local repository for successful compilation?

Body:
The Maven server do not support HTTP anymore. You must configure the maven repositories with HTTPS url's in your local maven configuration file, in your home folder yourname/.m2/settings.xml.

Here is an example that you may copy:

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
   <profiles>
      <profile>
         <id>artifactory</id>
         <repositories>
            <repository>
               <snapshots>
                  <enabled>false</enabled>
               </snapshots>
               <id>central</id>
               <name>libs-release</name>
               <url>https://repo1.maven.org/maven2/</url>
            </repository>
            <repository>
               <snapshots />
               <id>snapshots</id>
               <name>libs-snapshot</name>
               <url>https://repo1.maven.org/maven2/</url>
            </repository>
         </repositories>
         <pluginRepositories>
            <pluginRepository>
               <snapshots>
                  <enabled>false</enabled>
               </snapshots>
               <id>central</id>
               <name>plugins-release</name>
               <url>https://repo1.maven.org/maven2/</url>
            </pluginRepository>
            <pluginRepository>
               <snapshots />
               <id>snapshots</id>
               <name>plugins-snapshot</name>
               <url>https://repo1.maven.org/maven2/</url>
            </pluginRepository>
         </pluginRepositories>
      </profile>
   </profiles>
   <activeProfiles>
      <activeProfile>artifactory</activeProfile>
   </activeProfiles>
</settings>


来源: stackexchange

问:
Is there a way to distinguish between different `Rc`s of the same value?
Here's an example:

```<code>use std::rc::Rc;

#[derive(PartialEq, Eq)]
struct MyId;

pub fn main() {
    let rc_a_0 = Rc::new(MyId);
    let rc_a_1 = rc_a_0.clone();
    let rc_b_0 = Rc::new(MyId);
    let rc_b_1 = rc_b_0.clone();

    println!("rc_a_0 == rc_a_1: {:?}", rc_a_0 == rc_a_1);
    println!("rc_a_0 == rc_b_0: {:?}", rc_a_0 == rc_b_0);
}
</code>```

Both println!s above print true. Is there a way distinguish between the rc_a_* and rc_b_* pointers?

答:
2017 stabilization update (in 2020).

In Rust 1.17 and forward, you can use Rc::ptr_eq. It does the same as ptr::eq, without the need of converting the Rc to a reference or pointer.

Reference Equality

As the other answers mention Rc::ptr_eq (and ptr::eq) checks for reference equality, i.e. whether the two references "point" to the same address.

let five = Rc::new(5);
let same_five = Rc::clone(&five);
let other_five = Rc::new(5);

// five and same_five reference the same value in memory
assert!(Rc::ptr_eq(&five, &same_five));

// five and other_five does not reference the same value in memory
assert!(!Rc::ptr_eq(&five, &other_five));
```

<p><em>The example is from the Rust <code>Rc::ptr_eq</code> docs.</em></p>

<h3>Value Equality</h3>

<p><code>Rc</code> implements <code>PartialEq</code>, so simply use <code>==</code> as always, to perform value equality, i.e. whether the values are equal, irrelevant of whether they reference the same address in memory.</p>

<pre class="lang-rust prettyprint-override"><code>use std::rc::Rc;

let five = Rc::new(5);
let other_five = Rc::new(5);

let ten = Rc::new(10);

assert!(five == other_five);

assert!(ten != five);
assert!(ten != other_five);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here's an example:

use std::rc::Rc;

#[derive(PartialEq, Eq)]
struct MyId;

pub fn main() {
    let rc_a_0 = Rc::new(MyId);
    let rc_a_1 = rc_a_0.clone();
    let rc_b_0 = Rc::new(MyId);
    let rc_b_1 = rc_b_0.clone();

    println!("rc_a_0 == rc_a_1: {:?}", rc_a_0 == rc_a_1);
    println!("rc_a_0 == rc_b_0: {:?}", rc_a_0 == rc_b_0);
}

Both println!s above print true. Is there a way distinguish between the rc_a_* and rc_b_* pointers?

Body:
2017 stabilization update (in 2020).

In Rust 1.17 and forward, you can use Rc::ptr_eq. It does the same as ptr::eq, without the need of converting the Rc to a reference or pointer.

Reference Equality

As the other answers mention Rc::ptr_eq (and ptr::eq) checks for reference equality, i.e. whether the two references "point" to the same address.

let five = Rc::new(5);
let same_five = Rc::clone(&five);
let other_five = Rc::new(5);

// five and same_five reference the same value in memory
assert!(Rc::ptr_eq(&five, &same_five));

// five and other_five does not reference the same value in memory
assert!(!Rc::ptr_eq(&five, &other_five));

The example is from the Rust Rc::ptr_eq docs.

Value Equality

Rc implements PartialEq, so simply use == as always, to perform value equality, i.e. whether the values are equal, irrelevant of whether they reference the same address in memory.

use std::rc::Rc;

let five = Rc::new(5);
let other_five = Rc::new(5);

let ten = Rc::new(10);

assert!(five == other_five);

assert!(ten != five);
assert!(ten != other_five);


问:
RISC-V disassembler doesn't match with spike running results?
I've set up a hello world program just for testing my riscv32-unknown-elf toolchain, spike, pk etc. Though I managed to get the hello world printed using spike --isa=RV32 pk hello.elf, I found out that if I added the -d flag for debugging, I was given following instructions (a section of the whole):

```<code>core   0: 0x0000000000001000 (0x7ffff297) auipc   t0, 0x7ffff
:
core   0: 0x0000000000001004 (0x00028067) jr      t0
:
core   0: 0xffffffff80000000 (0x1b00006f) j       pc + 0x1b0
:
core   0: 0xffffffff800001b0 (0x00000093) li      ra, 0
:
core   0: 0xffffffff800001b4 (0x00000113) li      sp, 0
:
core   0: 0xffffffff800001b8 (0x00000193) li      gp, 0
:
core   0: 0xffffffff800001bc (0x00000213) li      tp, 0
:
core   0: 0xffffffff800001c0 (0x00000293) li      t0, 0
:
core   0: 0xffffffff800001c4 (0x00000313) li      t1, 0
:
core   0: 0xffffffff800001c8 (0x00000393) li      t2, 0
:
core   0: 0xffffffff800001cc (0x00000413) li      s0, 0
:
core   0: 0xffffffff800001d0 (0x00000493) li      s1, 0
:
core   0: 0xffffffff800001d4 (0x00000513) li      a0, 0
:
core   0: 0xffffffff800001d8 (0x00000593) li      a1, 0
:
core   0: 0xffffffff800001dc (0x00000613) li      a2, 0
:
core   0: 0xffffffff800001e0 (0x00000693) li      a3, 0
:
core   0: 0xffffffff800001e4 (0x00000713) li      a4, 0
:
core   0: 0xffffffff800001e8 (0x00000793) li      a5, 0
:
core   0: 0xffffffff800001ec (0x00000813) li      a6, 0
:
core   0: 0xffffffff800001f0 (0x00000893) li      a7, 0
:
core   0: 0xffffffff800001f4 (0x00000913) li      s2, 0
:
core   0: 0xffffffff800001f8 (0x00000993) li      s3, 0
:
core   0: 0xffffffff800001fc (0x00000a13) li      s4, 0
:
core   0: 0xffffffff80000200 (0x00000a93) li      s5, 0
:
core   0: 0xffffffff80000204 (0x00000b13) li      s6, 0
:
core   0: 0xffffffff80000208 (0x00000b93) li      s7, 0
:
core   0: 0xffffffff8000020c (0x00000c13) li      s8, 0
:
core   0: 0xffffffff80000210 (0x00000c93) li      s9, 0
:
core   0: 0xffffffff80000214 (0x00000d13) li      s10, 0
:
core   0: 0xffffffff80000218 (0x00000d93) li      s11, 0
:
core   0: 0xffffffff8000021c (0x00000e13) li      t3, 0
:
core   0: 0xffffffff80000220 (0x00000e93) li      t4, 0
:
core   0: 0xffffffff80000224 (0x00000f13) li      t5, 0
:
core   0: 0xffffffff80000228 (0x00000f93) li      t6, 0
:
core   0: 0xffffffff8000022c (0x34001073) csrw    mscratch, zero
:
core   0: 0xffffffff80000230 (0x00000297) auipc   t0, 0x0
:
core   0: 0xffffffff80000234 (0xdd828293) addi    t0, t0, -552
:
core   0: 0xffffffff80000238 (0x30529073) csrw    mtvec, t0
:
core   0: 0xffffffff8000023c (0x30502373) csrr    t1, mtvec
:
core   0: 0xffffffff80000240 (0x00629063) bne     t0, t1, pc + 0
:
core   0: 0xffffffff80000244 (0x00012117) auipc   sp, 0x12
</code>```

Anyway it doesn't match the disassembler produced from riscv32-unknown-elf-objdump -d hello.elf > hello.dump (also a section on the beginning):

```<code>hello.elf:     file format elf32-littleriscv

Disassembly of section .text:

00010074 <_start>:
   10074:   00005197            auipc   gp,0x5
   10078:   fcc18193            addi    gp,gp,-52 # 15040 <_gp>
   1007c:   00004517            auipc   a0,0x4
   10080:   7d850513            addi    a0,a0,2008 # 14854 <_edata>
   10084:   00005617            auipc   a2,0x5
   10088:   83060613            addi    a2,a2,-2000 # 148b4 <_end>
   1008c:   40a60633            sub a2,a2,a0
   10090:   00000593            li  a1,0
   10094:   2c0000ef            jal ra,10354 <memset>
   10098:   00000517            auipc   a0,0x0
   1009c:   1bc50513            addi    a0,a0,444 # 10254 <__libc_fini_array>
   100a0:   16c000ef            jal ra,1020c <atexit>
   100a4:   210000ef            jal ra,102b4 <__libc_init_array>
   100a8:   00012503            lw  a0,0(sp)
   100ac:   00410593            addi    a1,sp,4
   100b0:   00000613            li  a2,0
   100b4:   124000ef            jal ra,101d8 <main>
   100b8:   1680006f            j   10220 <exit>

000100bc <_fini>:
   100bc:   00008067            ret

000100c0 <deregister_tm_clones>:
   100c0:   00015537            lui a0,0x15
   100c4:   000157b7            lui a5,0x15
   100c8:   84050713            addi    a4,a0,-1984 # 14840 <__TMC_END__>
   100cc:   84378793            addi    a5,a5,-1981 # 14843 <__TMC_END__+0x3>
   100d0:   40e787b3            sub a5,a5,a4
   100d4:   00600713            li  a4,6
   100d8:   00f77c63            bleu    a5,a4,100f0   <deregister_tm_clones+0x30>
   100dc:   00000337            lui t1,0x0
   100e0:   00030313            mv  t1,t1
   100e4:   00030663            beqz    t1,100f0 <deregister_tm_clones+0x30>
   100e8:   84050513            addi    a0,a0,-1984
   100ec:   00030067            jr  t1
   100f0:   00008067            ret

000100f4 <register_tm_clones>:
   100f4:   00015537            lui a0,0x15
   100f8:   000155b7            lui a1,0x15
   100fc:   84050793            addi    a5,a0,-1984 # 14840 <__TMC_END__>
   10100:   84058593            addi    a1,a1,-1984 # 14840 <__TMC_END__>
   10104:   40f585b3            sub a1,a1,a5
   10108:   4025d593            srai    a1,a1,0x2
   1010c:   01f5d793            srli    a5,a1,0x1f
   10110:   00b785b3            add a1,a5,a1
   10114:   4015d593            srai    a1,a1,0x1
   10118:   00058c63            beqz    a1,10130 <register_tm_clones+0x3c>
   1011c:   00000337            lui t1,0x0
   10120:   00030313            mv  t1,t1
   10124:   00030663            beqz    t1,10130 <register_tm_clones+0x3c>
   10128:   84050513            addi    a0,a0,-1984
   1012c:   00030067            jr  t1
   10130:   00008067            ret
</code>```

I am confused since there's a big difference between both the addresses and machine code. I'd really appreciate it if you could give me some thoughts. Thanks!

Best regards,
Cy

答:
If you start Spike like this

```<code>spike -d --isa=RV32 pk hello.elf
</code>```

your interactive debugging session starts at the first instruction of the proxy-kernel (pk) and not at the first instruction of your user-space program.

What you usually want to do is to continue executing the pk and then break on the first instruction of your program (see your objdump output for the start address), e.g.

```<code>: until pc 0 10074
</code>```

and then single step (ENTER) from there.

See also the Spike help command (h).

ContentLicense: CC BY-SA 3.0

Body:
I've set up a hello world program just for testing my riscv32-unknown-elf toolchain, spike, pk etc. Though I managed to get the hello world printed using spike --isa=RV32 pk hello.elf, I found out that if I added the -d flag for debugging, I was given following instructions (a section of the whole):

core   0: 0x0000000000001000 (0x7ffff297) auipc   t0, 0x7ffff
:
core   0: 0x0000000000001004 (0x00028067) jr      t0
:
core   0: 0xffffffff80000000 (0x1b00006f) j       pc + 0x1b0
:
core   0: 0xffffffff800001b0 (0x00000093) li      ra, 0
:
core   0: 0xffffffff800001b4 (0x00000113) li      sp, 0
:
core   0: 0xffffffff800001b8 (0x00000193) li      gp, 0
:
core   0: 0xffffffff800001bc (0x00000213) li      tp, 0
:
core   0: 0xffffffff800001c0 (0x00000293) li      t0, 0
:
core   0: 0xffffffff800001c4 (0x00000313) li      t1, 0
:
core   0: 0xffffffff800001c8 (0x00000393) li      t2, 0
:
core   0: 0xffffffff800001cc (0x00000413) li      s0, 0
:
core   0: 0xffffffff800001d0 (0x00000493) li      s1, 0
:
core   0: 0xffffffff800001d4 (0x00000513) li      a0, 0
:
core   0: 0xffffffff800001d8 (0x00000593) li      a1, 0
:
core   0: 0xffffffff800001dc (0x00000613) li      a2, 0
:
core   0: 0xffffffff800001e0 (0x00000693) li      a3, 0
:
core   0: 0xffffffff800001e4 (0x00000713) li      a4, 0
:
core   0: 0xffffffff800001e8 (0x00000793) li      a5, 0
:
core   0: 0xffffffff800001ec (0x00000813) li      a6, 0
:
core   0: 0xffffffff800001f0 (0x00000893) li      a7, 0
:
core   0: 0xffffffff800001f4 (0x00000913) li      s2, 0
:
core   0: 0xffffffff800001f8 (0x00000993) li      s3, 0
:
core   0: 0xffffffff800001fc (0x00000a13) li      s4, 0
:
core   0: 0xffffffff80000200 (0x00000a93) li      s5, 0
:
core   0: 0xffffffff80000204 (0x00000b13) li      s6, 0
:
core   0: 0xffffffff80000208 (0x00000b93) li      s7, 0
:
core   0: 0xffffffff8000020c (0x00000c13) li      s8, 0
:
core   0: 0xffffffff80000210 (0x00000c93) li      s9, 0
:
core   0: 0xffffffff80000214 (0x00000d13) li      s10, 0
:
core   0: 0xffffffff80000218 (0x00000d93) li      s11, 0
:
core   0: 0xffffffff8000021c (0x00000e13) li      t3, 0
:
core   0: 0xffffffff80000220 (0x00000e93) li      t4, 0
:
core   0: 0xffffffff80000224 (0x00000f13) li      t5, 0
:
core   0: 0xffffffff80000228 (0x00000f93) li      t6, 0
:
core   0: 0xffffffff8000022c (0x34001073) csrw    mscratch, zero
:
core   0: 0xffffffff80000230 (0x00000297) auipc   t0, 0x0
:
core   0: 0xffffffff80000234 (0xdd828293) addi    t0, t0, -552
:
core   0: 0xffffffff80000238 (0x30529073) csrw    mtvec, t0
:
core   0: 0xffffffff8000023c (0x30502373) csrr    t1, mtvec
:
core   0: 0xffffffff80000240 (0x00629063) bne     t0, t1, pc + 0
:
core   0: 0xffffffff80000244 (0x00012117) auipc   sp, 0x12

Anyway it doesn't match the disassembler produced from riscv32-unknown-elf-objdump -d hello.elf > hello.dump (also a section on the beginning):

hello.elf:     file format elf32-littleriscv

Disassembly of section .text:

00010074 <_start>:
   10074:   00005197            auipc   gp,0x5
   10078:   fcc18193            addi    gp,gp,-52 # 15040 <_gp>
   1007c:   00004517            auipc   a0,0x4
   10080:   7d850513            addi    a0,a0,2008 # 14854 <_edata>
   10084:   00005617            auipc   a2,0x5
   10088:   83060613            addi    a2,a2,-2000 # 148b4 <_end>
   1008c:   40a60633            sub a2,a2,a0
   10090:   00000593            li  a1,0
   10094:   2c0000ef            jal ra,10354 <memset>
   10098:   00000517            auipc   a0,0x0
   1009c:   1bc50513            addi    a0,a0,444 # 10254 <__libc_fini_array>
   100a0:   16c000ef            jal ra,1020c <atexit>
   100a4:   210000ef            jal ra,102b4 <__libc_init_array>
   100a8:   00012503            lw  a0,0(sp)
   100ac:   00410593            addi    a1,sp,4
   100b0:   00000613            li  a2,0
   100b4:   124000ef            jal ra,101d8
   100b8:   1680006f            j   10220 <exit>

000100bc <_fini>:
   100bc:   00008067            ret

000100c0 <deregister_tm_clones>:
   100c0:   00015537            lui a0,0x15
   100c4:   000157b7            lui a5,0x15
   100c8:   84050713            addi    a4,a0,-1984 # 14840 <__TMC_END__>
   100cc:   84378793            addi    a5,a5,-1981 # 14843 <__TMC_END__+0x3>
   100d0:   40e787b3            sub a5,a5,a4
   100d4:   00600713            li  a4,6
   100d8:   00f77c63            bleu    a5,a4,100f0   <deregister_tm_clones+0x30>
   100dc:   00000337            lui t1,0x0
   100e0:   00030313            mv  t1,t1
   100e4:   00030663            beqz    t1,100f0 <deregister_tm_clones+0x30>
   100e8:   84050513            addi    a0,a0,-1984
   100ec:   00030067            jr  t1
   100f0:   00008067            ret

000100f4 <register_tm_clones>:
   100f4:   00015537            lui a0,0x15
   100f8:   000155b7            lui a1,0x15
   100fc:   84050793            addi    a5,a0,-1984 # 14840 <__TMC_END__>
   10100:   84058593            addi    a1,a1,-1984 # 14840 <__TMC_END__>
   10104:   40f585b3            sub a1,a1,a5
   10108:   4025d593            srai    a1,a1,0x2
   1010c:   01f5d793            srli    a5,a1,0x1f
   10110:   00b785b3            add a1,a5,a1
   10114:   4015d593            srai    a1,a1,0x1
   10118:   00058c63            beqz    a1,10130 <register_tm_clones+0x3c>
   1011c:   00000337            lui t1,0x0
   10120:   00030313            mv  t1,t1
   10124:   00030663            beqz    t1,10130 <register_tm_clones+0x3c>
   10128:   84050513            addi    a0,a0,-1984
   1012c:   00030067            jr  t1
   10130:   00008067            ret

I am confused since there's a big difference between both the addresses and machine code. I'd really appreciate it if you could give me some thoughts. Thanks!

Best regards,
Cy

Body:
If you start Spike like this

spike -d --isa=RV32 pk hello.elf

your interactive debugging session starts at the first instruction of the proxy-kernel (pk) and not at the first instruction of your user-space program.

What you usually want to do is to continue executing the pk and then break on the first instruction of your program (see your objdump output for the start address), e.g.

: until pc 0 10074

and then single step (ENTER) from there.

See also the Spike help command (h).


问:
Problem with "list assignment index out of range" Python
I should replace the last element of a tuple in a list of tuples with and object given as input and I tried to write this code but I got a "list assignment index out of range" error at line 4. How should I fix it?</p>

```<code>def replaceLast (tupleList, object):
    for i, tup in enumerate(tupleList):
        lis = list(tup)
        lis[-1] = object
        tupleList[i] = tuple(lis)
    return tupleList

lT=[(1,),(2,3),(),(7,3)]
replaceLast(lT,11) #=> [(11,), (2, 11), (11,), (7, 11)] -> this should be the result
</code>```

答:
The problem is the empty tuple in your list lT, which does not have a last element, therefore you cannot access it with lst[-1].

Instead of changing lists, create new ones:

```<code>def replace_last(tuples, object):
    return [
        tup[:-1] + (object, )
        for tup in tuples
    ]
</code>```

Body:
I should replace the last element of a tuple in a list of tuples with and object given as input and I tried to write this code but I got a "list assignment index out of range" error at line 4. How should I fix it?

def replaceLast (tupleList, object):
    for i, tup in enumerate(tupleList):
        lis = list(tup)
        lis[-1] = object
        tupleList[i] = tuple(lis)
    return tupleList

lT=[(1,),(2,3),(),(7,3)]
replaceLast(lT,11) #=> [(11,), (2, 11), (11,), (7, 11)] -> this should be the result

Body:
The problem is the empty tuple in your list lT, which does not have a last element, therefore you cannot access it with lst[-1].

Instead of changing lists, create new ones:

def replace_last(tuples, object):
    return [
        tup[:-1] + (object, )
        for tup in tuples
    ]


问:
How to use variable that are set inside a function within a for loop or a if-block in python
I want to be able to use the BestELevator variable outside the findElevator function (In python)</p>

```<code>userPosition = int(input('Enter the position of the user: '))
userDirection = str(input('Enter the direction floor (up/down): '))

elevatorList = {
           1: {'position':'6', 'direction':'down', 'status':'move', 'gap':'', 'priority':''} ,
           2: {'position':'-6', 'direction':'up'  , 'status':'idle', 'gap':'', 'priority':''}
}

def findElevator(userPosition, userDirection):
  for i in elevatorList:
    elevatorPosition = int(elevatorList[i]['position'])
    elevatorDirection = str(elevatorList[i]['direction'])
    if (elevatorPosition == userPosition) & (elevatorDirection == userDirection):
      elevatorList[i]['priority'] = 55
      bestElevator = elevatorList[i]
      return bestElevator
    else:
      print('doesnt work ')

findElevator(userPosition, userDirection)
print(bestElevator)
</code>```

答:
```<code>bestElevator = findElevator(userPosition, userDirection)
print(bestElevator)
</code>```

The Variable bestElevator inside the if block is only accesible inside the function it was defined.

Body:
I want to be able to use the BestELevator variable outside the findElevator function (In python)

userPosition = int(input('Enter the position of the user: '))
userDirection = str(input('Enter the direction floor (up/down): '))

elevatorList = {
           1: {'position':'6', 'direction':'down', 'status':'move', 'gap':'', 'priority':''} ,
           2: {'position':'-6', 'direction':'up'  , 'status':'idle', 'gap':'', 'priority':''}
}

def findElevator(userPosition, userDirection):
  for i in elevatorList:
    elevatorPosition = int(elevatorList[i]['position'])
    elevatorDirection = str(elevatorList[i]['direction'])
    if (elevatorPosition == userPosition) & (elevatorDirection == userDirection):
      elevatorList[i]['priority'] = 55
      bestElevator = elevatorList[i]
      return bestElevator
    else:
      print('doesnt work ')

findElevator(userPosition, userDirection)
print(bestElevator)

Body:
bestElevator = findElevator(userPosition, userDirection)
print(bestElevator)

The Variable bestElevator inside the if block is only accesible inside the function it was defined.


问:
Find minimal set of subsets that covers a given set

General problem

Given a set N of X unique strings: {a1, a2, ... , aX}

And a set M of Y subsets of N:

```<code>{
  m1: { ... },
  m2: { ... },
      ...
  mY: { ... },
}
</code>```

How would you find the smallest subset of M where the union of those subsets equal N.

Example

Input form: a dictionary that maps each set in M to a list of a subset of N.

Output form: a list of the smallest subset of M.

Example input:

```<code>{
  "m1": [ "1", "4", "7" ],
  "m2": [ "1", "2" ],
  "m3": [ "2", "5", "6" ],
  "m4": [ "2", "3", "5" ],
  "m5": [ 3 ],
}
</code>```

Example output:

```<code>[ "m1", "m3", "m5" ]
</code>```

My current solution

Take the largest subset of M (first if more than one), i.e. "m1",

call this operation max(M), which should have time complexity O(Y)

Then remove m1 from M and all elements of m1 from the other subsets in M, giving us new M:

```<code>{
  "m2": [ "2" ],
  "m3": [ "2", "5", "6" ],
  "m4": [ "2", "3", "5" ],
  "m5": [ 3 ],
}
</code>```

Call this operation red(M,m), which should have time complexity O(Y*X),

Then the algorithm should be

```<code>iterative(M):
  answer = []
  while(len(M.keys()) != 0):
    m = max(M)
    answer.append(m)
    red(M,m)
  return answer
</code>```

Since the while loop will run maximum Y times, we get the time complexity

O(Y)+O(Y)+O(X*Y) = O(X*Y)

The Problem

I'm not sure if this is the optimal solution. Since I pick the first largest m I could switch around the order and end up with a different (and possibly suboptimal) answer.

So initially I thought "Ok, I'll just write it recursively and check them all":

max(M) will instead return a list of all m that had the most elements:

red(M,m) will return the new M

```<code>recursive(answer,M):
  if(len(M.keys() == 0):
    return answer
  m_list = max(M)
  for(m in m_list):
    new_answer = answer.copy()
    new_answer.append(m)
    return recursive(new_answer,red(M,m))
</code>```

But here I realised that in the worst case max(M) would return all possible lists (if all have the same size), and red(M,m) would reduce all lists by exactly one element each run, then it would run Y*(Y-1)*...=O(Y!) times!

答:
You should use actual sets to perform the operations.  For a brute force approach, a recursive function is easiest to program:

This one expects a list of sets and tries each one with a recursion on the remaining sets in the list.  It returns the shortest list of sets that it finds.

```<code>def setCover(setList,target=None):
    if not setList: return None
    if target  is None: target  = set.union(*setList)
    bestCover = []
    for i,values in enumerate(setList):
        remaining = target - values
        if remaining == target: continue
        if not remaining: return [values]
        subCover = setCover(setList[i+1:],remaining)
        if not subCover: continue
        if not bestCover or len(subCover)<len(bestCover)-1:
            bestCover = [values] + subCover
    return bestCover
</code>```

output:

```<code>M = [
  { "1", "4", "7" },
  { "1", "2" },
  { "2", "5", "6" },
  { "2", "5" },
  { "3" },
  { "8", "6" }
]

print(setCover(M))
# [{'7', '1', '4'}, {'6', '5', '2'}, {'3'}, {'6', '8'}]
</code>```

Brute fore is quite slow but it can be optimized.  The above function does skip sets that don't add more coverage but it performs in roughly O(n!).

There are several optimization strategies that will make it go faster.

Sort the set list in decreasing order of set length (combined with the other optimizations)

avoid memory allocation by not creating sub lists (i.e. pass the same list object with a starting index)

keep track of the current best result to constrain the recursion to a maximum count (i.e. skipping over sub-solutions that have more items than the current best)

isolate values that appear in only one set, the sets that contain them are mandatory and will always be part of the solution. Only analyse the remaining sets

compute the maximum coverage of remaining sets for each position in the list so that you can know in advance that there will not be a solution with the remaining items

Here is an optimized version of the function:

```<code>from itertools import accumulate
def setCover4(setList,start=0,target=None,maxCount=None,cumSets=None):

    # short circuit recursion when imposible to cover with fewer sets than current best
    if maxCount is None: maxCount = len(setList)
    if maxCount == 0: return None

    # sort sets in descending order of their size to maximize initial coverage
    if target  is None:
        target  = set.union(*setList)
        setList = sorted(setList,key=len,reverse=True)

    # values that exist in only one set make that set mandatory in the solution
    # set them apart and combine them with the solution for the remaining sets
    if start == 0:
        singletons = target
        foundOnce  = set()
        for s in setList:
            singletons = singletons - (s & foundOnce)
            foundOnce.update(s)
        if singletons:
            mandatorySets = [ s for s in setList if s&singletons ]
            remaining     = target - set.union(*mandatorySets)
            if not remaining: return mandatorySets
            setList = [s for s in setList if not s&singletons]
            subCover = setCover4(setList,0,remaining)
            if subCover : return mandatorySets + subCover
            return None

    # predetermine the remaining coverage from each position to the end of the list
    if cumSets is None:
        cumSets = [ u for u in accumulate(reversed(setList),set.union) ][::-1]

    # try sets at each position (from start to end) recursing with remaining sets
    bestCover = []
    for i in range(start,len(setList)):
        if not cumSets[i].issuperset(target): break # no solution in remaining sets
        values = setList[i]
        remaining = target - values
        if remaining == target: continue
        if not remaining: return [values]
        subCover = setCover4(setList,i+1,remaining,maxCount-1,cumSets)
        if not subCover: continue
        if not bestCover or len(subCover)<len(bestCover)-1:
            bestCover = [values] + subCover
            maxCount  = len(bestCover)
    return bestCover
</code>```

Performance tests show that setCover4 responds orders of magnitude faster than the original setCover function

```<code>from timeit import timeit
import random
samples = 10

values = list(range(100))
subsetSize  = 10
subsetCount = 20
M = [ set(random.sample(values,random.randrange(1,subsetSize))) for _ in range(subsetCount) ]

t = timeit(lambda:setCover(M),number=samples)
print("setCover ",f"{t:.5f}")
t = timeit(lambda:setCover4(M),number=samples)
print("setCover4",f"{t:.5f}")

# setCover  9.11923
# setCover4 0.00095
</code>```

More tests with varying numbers of sets and set sizes confirm the performance difference but it also shows that setCover4, despite being optimized, also has an exponential time pattern.

```<code>for subsetSize in (10,20,30):
    print("")
    for subsetCount in (10,15,18,19,20,25,30,35,40,45,50):
        t1 = t4 = 0
        for _ in range(samples):
            M = [ set(random.sample(values,random.randrange(1,subsetSize))) for _ in range(subsetCount) ]
            if subsetCount < 25: t1 += timeit(lambda:setCover(M),number=1)
            t4 += timeit(lambda:setCover4(M),number=1)
        print(f"subsetSize={subsetSize}",f"subsetCount={subsetCount}",
              f"  setCover:{t1:8.5f}" if t1 else "  setCover: -------",
              f"  setCover4:{t4:8.5f}")
</code>```

Results:

```<code>subsetSize=10 subsetCount=10   setCover: 0.01501   setCover4: 0.00039
subsetSize=10 subsetCount=15   setCover: 0.28903   setCover4: 0.00034
subsetSize=10 subsetCount=18   setCover: 2.05937   setCover4: 0.00042
subsetSize=10 subsetCount=19   setCover: 4.32700   setCover4: 0.00044
subsetSize=10 subsetCount=20   setCover: 8.08408   setCover4: 0.00045
subsetSize=10 subsetCount=25   setCover: -------   setCover4: 0.00101
subsetSize=10 subsetCount=30   setCover: -------   setCover4: 0.00158
subsetSize=10 subsetCount=35   setCover: -------   setCover4: 0.00215
subsetSize=10 subsetCount=40   setCover: -------   setCover4: 0.00813
subsetSize=10 subsetCount=45   setCover: -------   setCover4: 0.01751
subsetSize=10 subsetCount=50   setCover: -------   setCover4: 0.13528

subsetSize=20 subsetCount=10   setCover: 0.01878   setCover4: 0.00049
subsetSize=20 subsetCount=15   setCover: 0.35464   setCover4: 0.00050
subsetSize=20 subsetCount=18   setCover: 2.66359   setCover4: 0.00057
subsetSize=20 subsetCount=19   setCover: 4.73091   setCover4: 0.00074
subsetSize=20 subsetCount=20   setCover: 8.37055   setCover4: 0.00069
subsetSize=20 subsetCount=25   setCover: -------   setCover4: 0.00176
subsetSize=20 subsetCount=30   setCover: -------   setCover4: 0.00979
subsetSize=20 subsetCount=35   setCover: -------   setCover4: 0.05368
subsetSize=20 subsetCount=40   setCover: -------   setCover4: 0.32195
subsetSize=20 subsetCount=45   setCover: -------   setCover4: 5.34897
subsetSize=20 subsetCount=50   setCover: -------   setCover4:44.98202

subsetSize=30 subsetCount=10   setCover: 0.01798   setCover4: 0.00056
subsetSize=30 subsetCount=15   setCover: 0.32203   setCover4: 0.00058
subsetSize=30 subsetCount=18   setCover: 2.10538   setCover4: 0.00089
subsetSize=30 subsetCount=19   setCover: 4.31587   setCover4: 0.00121
subsetSize=30 subsetCount=20   setCover: 8.22864   setCover4: 0.00118
subsetSize=30 subsetCount=25   setCover: -------   setCover4: 0.01261
subsetSize=30 subsetCount=30   setCover: -------   setCover4: 0.05015
subsetSize=30 subsetCount=35   setCover: -------   setCover4: 0.38848
subsetSize=30 subsetCount=40   setCover: -------   setCover4: 3.29696
subsetSize=30 subsetCount=45   setCover: -------   setCover4: 8.22697
subsetSize=30 subsetCount=50   setCover: -------   setCover4:23.39054
</code>```

Body:
General problem

Given a set N of X unique strings: {a1, a2, ... , aX}

And a set M of Y subsets of N:

{
  m1: { ... },
  m2: { ... },
      ...
  mY: { ... },
}

How would you find the smallest subset of M where the union of those subsets equal N.

Example

Input form: a dictionary that maps each set in M to a list of a subset of N.

Output form: a list of the smallest subset of M.

Example input:

{
  "m1": [ "1", "4", "7" ],
  "m2": [ "1", "2" ],
  "m3": [ "2", "5", "6" ],
  "m4": [ "2", "3", "5" ],
  "m5": [ 3 ],
}

Example output:

[ "m1", "m3", "m5" ]

My current solution

Take the largest subset of M (first if more than one), i.e. "m1",

call this operation max(M), which should have time complexity O(Y)

Then remove m1 from M and all elements of m1 from the other subsets in M, giving us new M:

{
  "m2": [ "2" ],
  "m3": [ "2", "5", "6" ],
  "m4": [ "2", "3", "5" ],
  "m5": [ 3 ],
}

Call this operation red(M,m), which should have time complexity O(Y*X),

Then the algorithm should be

iterative(M):
  answer = []
  while(len(M.keys()) != 0):
    m = max(M)
    answer.append(m)
    red(M,m)
  return answer

Since the while loop will run maximum Y times, we get the time complexity

O(Y)+O(Y)+O(X*Y) = O(X*Y)

The Problem

I'm not sure if this is the optimal solution. Since I pick the first largest m I could switch around the order and end up with a different (and possibly suboptimal) answer.

So initially I thought "Ok, I'll just write it recursively and check them all":

max(M) will instead return a list of all m that had the most elements:

red(M,m) will return the new M

recursive(answer,M):
  if(len(M.keys() == 0):
    return answer
  m_list = max(M)
  for(m in m_list):
    new_answer = answer.copy()
    new_answer.append(m)
    return recursive(new_answer,red(M,m))

But here I realised that in the worst case max(M) would return all possible lists (if all have the same size), and red(M,m) would reduce all lists by exactly one element each run, then it would run Y*(Y-1)*...=O(Y!) times!

Body:
You should use actual sets to perform the operations.  For a brute force approach, a recursive function is easiest to program:

This one expects a list of sets and tries each one with a recursion on the remaining sets in the list.  It returns the shortest list of sets that it finds.

def setCover(setList,target=None):
    if not setList: return None
    if target  is None: target  = set.union(*setList)
    bestCover = []
    for i,values in enumerate(setList):
        remaining = target - values
        if remaining == target: continue
        if not remaining: return [values]
        subCover = setCover(setList[i+1:],remaining)
        if not subCover: continue
        if not bestCover or len(subCover)<len(bestCover)-1:
            bestCover = [values] + subCover
    return bestCover

output:

M = [
  { "1", "4", "7" },
  { "1", "2" },
  { "2", "5", "6" },
  { "2", "5" },
  { "3" },
  { "8", "6" }
]

print(setCover(M))
# [{'7', '1', '4'}, {'6', '5', '2'}, {'3'}, {'6', '8'}]

Brute fore is quite slow but it can be optimized.  The above function does skip sets that don't add more coverage but it performs in roughly O(n!).

There are several optimization strategies that will make it go faster.

Sort the set list in decreasing order of set length (combined with the other optimizations)

avoid memory allocation by not creating sub lists (i.e. pass the same list object with a starting index)

keep track of the current best result to constrain the recursion to a maximum count (i.e. skipping over sub-solutions that have more items than the current best)

isolate values that appear in only one set, the sets that contain them are mandatory and will always be part of the solution. Only analyse the remaining sets

compute the maximum coverage of remaining sets for each position in the list so that you can know in advance that there will not be a solution with the remaining items

Here is an optimized version of the function:

from itertools import accumulate
def setCover4(setList,start=0,target=None,maxCount=None,cumSets=None):

    # short circuit recursion when imposible to cover with fewer sets than current best
    if maxCount is None: maxCount = len(setList)
    if maxCount == 0: return None

    # sort sets in descending order of their size to maximize initial coverage
    if target  is None:
        target  = set.union(*setList)
        setList = sorted(setList,key=len,reverse=True)

    # values that exist in only one set make that set mandatory in the solution
    # set them apart and combine them with the solution for the remaining sets
    if start == 0:
        singletons = target
        foundOnce  = set()
        for s in setList:
            singletons = singletons - (s & foundOnce)
            foundOnce.update(s)
        if singletons:
            mandatorySets = [ s for s in setList if s&singletons ]
            remaining     = target - set.union(*mandatorySets)
            if not remaining: return mandatorySets
            setList = [s for s in setList if not s&singletons]
            subCover = setCover4(setList,0,remaining)
            if subCover : return mandatorySets + subCover
            return None

    # predetermine the remaining coverage from each position to the end of the list
    if cumSets is None:
        cumSets = [ u for u in accumulate(reversed(setList),set.union) ][::-1]

    # try sets at each position (from start to end) recursing with remaining sets
    bestCover = []
    for i in range(start,len(setList)):
        if not cumSets[i].issuperset(target): break # no solution in remaining sets
        values = setList[i]
        remaining = target - values
        if remaining == target: continue
        if not remaining: return [values]
        subCover = setCover4(setList,i+1,remaining,maxCount-1,cumSets)
        if not subCover: continue
        if not bestCover or len(subCover)<len(bestCover)-1:
            bestCover = [values] + subCover
            maxCount  = len(bestCover)
    return bestCover

Performance tests show that setCover4 responds orders of magnitude faster than the original setCover function

from timeit import timeit
import random
samples = 10

values = list(range(100))
subsetSize  = 10
subsetCount = 20
M = [ set(random.sample(values,random.randrange(1,subsetSize))) for _ in range(subsetCount) ]

t = timeit(lambda:setCover(M),number=samples)
print("setCover ",f"{t:.5f}")
t = timeit(lambda:setCover4(M),number=samples)
print("setCover4",f"{t:.5f}")

# setCover  9.11923
# setCover4 0.00095

More tests with varying numbers of sets and set sizes confirm the performance difference but it also shows that setCover4, despite being optimized, also has an exponential time pattern.

for subsetSize in (10,20,30):
    print("")
    for subsetCount in (10,15,18,19,20,25,30,35,40,45,50):
        t1 = t4 = 0
        for _ in range(samples):
            M = [ set(random.sample(values,random.randrange(1,subsetSize))) for _ in range(subsetCount) ]
            if subsetCount < 25: t1 += timeit(lambda:setCover(M),number=1)
            t4 += timeit(lambda:setCover4(M),number=1)
        print(f"subsetSize={subsetSize}",f"subsetCount={subsetCount}",
              f"  setCover:{t1:8.5f}" if t1 else "  setCover: -------",
              f"  setCover4:{t4:8.5f}")

Results:

subsetSize=10 subsetCount=10   setCover: 0.01501   setCover4: 0.00039
subsetSize=10 subsetCount=15   setCover: 0.28903   setCover4: 0.00034
subsetSize=10 subsetCount=18   setCover: 2.05937   setCover4: 0.00042
subsetSize=10 subsetCount=19   setCover: 4.32700   setCover4: 0.00044
subsetSize=10 subsetCount=20   setCover: 8.08408   setCover4: 0.00045
subsetSize=10 subsetCount=25   setCover: -------   setCover4: 0.00101
subsetSize=10 subsetCount=30   setCover: -------   setCover4: 0.00158
subsetSize=10 subsetCount=35   setCover: -------   setCover4: 0.00215
subsetSize=10 subsetCount=40   setCover: -------   setCover4: 0.00813
subsetSize=10 subsetCount=45   setCover: -------   setCover4: 0.01751
subsetSize=10 subsetCount=50   setCover: -------   setCover4: 0.13528

subsetSize=20 subsetCount=10   setCover: 0.01878   setCover4: 0.00049
subsetSize=20 subsetCount=15   setCover: 0.35464   setCover4: 0.00050
subsetSize=20 subsetCount=18   setCover: 2.66359   setCover4: 0.00057
subsetSize=20 subsetCount=19   setCover: 4.73091   setCover4: 0.00074
subsetSize=20 subsetCount=20   setCover: 8.37055   setCover4: 0.00069
subsetSize=20 subsetCount=25   setCover: -------   setCover4: 0.00176
subsetSize=20 subsetCount=30   setCover: -------   setCover4: 0.00979
subsetSize=20 subsetCount=35   setCover: -------   setCover4: 0.05368
subsetSize=20 subsetCount=40   setCover: -------   setCover4: 0.32195
subsetSize=20 subsetCount=45   setCover: -------   setCover4: 5.34897
subsetSize=20 subsetCount=50   setCover: -------   setCover4:44.98202

subsetSize=30 subsetCount=10   setCover: 0.01798   setCover4: 0.00056
subsetSize=30 subsetCount=15   setCover: 0.32203   setCover4: 0.00058
subsetSize=30 subsetCount=18   setCover: 2.10538   setCover4: 0.00089
subsetSize=30 subsetCount=19   setCover: 4.31587   setCover4: 0.00121
subsetSize=30 subsetCount=20   setCover: 8.22864   setCover4: 0.00118
subsetSize=30 subsetCount=25   setCover: -------   setCover4: 0.01261
subsetSize=30 subsetCount=30   setCover: -------   setCover4: 0.05015
subsetSize=30 subsetCount=35   setCover: -------   setCover4: 0.38848
subsetSize=30 subsetCount=40   setCover: -------   setCover4: 3.29696
subsetSize=30 subsetCount=45   setCover: -------   setCover4: 8.22697
subsetSize=30 subsetCount=50   setCover: -------   setCover4:23.39054


问:
How does Laravel generate SQL?
I'm brand new to Laravel and am working my way through the Laravel 6 from Scratch course over at Laracasts. The course is free but I can't afford a Laracasts membership so I can't ask questions there.

I've finished Section 6 of the course, Controller Techniques, and am having unexpected problems trying to extend the work we've done so far to add a few new features. The course has students build pages that let a user show a list of articles, look at an individual article, create and save a new article, and update and save an existing article. The course work envisioned a very simple article containing just an ID (auto-incremented in the database and not visible to the web user), a title, an excerpt and a body and I got all of the features working for that. Now I'm trying to add two new fields: an author name and a path to a picture illustrating the article. I've updated the migration, rolled back and rerun the migration to include the new fields and got no errors from that. (I also ran a migrate:free and got no errors from that.) I've also updated the forms used to create and update the articles and added validations for the new fields. However, when I go to execute the revised create code, it fails because the SQL is wrong.

The error message complains that the author field doesn't have a default, which is true, I didn't assign a default.  However, I did give it a value on the form. What perplexes me most is the SQL that it has generated: the column list doesn't show the two new columns. And that's not all: the values list is missing apostrophes around any of the string/text values. (All of the columns are defined as string or text.)

As I said, I'm completely new to Laravel so I don't know how to persuade Laravel to add the two new columns to the Insert statement nor how to make it put apostrophes around the strings in the values list. That hasn't come up in the course and I'm not sure if it will come up later. I was hoping someone could tell me how to fix this. All of my functionality was working fine before I added the  two new fields/columns.

Here is the error message:

```<code>    SQLSTATE[HY000]: General error: 1364 Field 'author' doesn't have a default value (SQL: insert         into `articles` (`title`, `excerpt`, `body`, `updated_at`, `created_at`) values (Today in Canada, The ideal winter-beater, This car is the ideal winter-beater for the tough Canadian climate. It is designed to get you from A to B in style and without breaking the bank., 2020-02-15 17:37:54, 2020-02-15 17:37:54))
</code>```

Here is ArticlesController:

```<code><?php

namespace App\Http\Controllers;

use App\Article;
use Illuminate\Http\Request;

class ArticlesController extends Controller
{
public function index()
{
    $articles = Article::latest()->get();
    return view ('articles.index', ['articles' => $articles]);
}

public function show(Article $article)
{
    return view('articles.show', ['article' => $article]);
}

public function create()
{
    return view('articles.create');
}

public function store()
{
    //Stores a NEW article
    Article::create($this->validateArticle());
    return redirect('/articles');
}

public function edit(Article $article)
{
    return view('articles.edit', ['article' => $article]);
}

public function update(Article $article)
{
    //Updates an EXISTING article
    $article->update($this->validateArticle());
    return redirect('/articles/', $article->id);
}

public function validateArticle()
{
    return request()->validate([
        'title' => ['required', 'min:5', 'max:20'],
        'author' => ['required', 'min:5', 'max:30'],
        'photopath' => ['required', 'min:10', 'max:100'],
        'excerpt' => ['required', 'min:10', 'max:50'],
        'body' => ['required', 'min:50', 'max:500']
    ]);
}

public function destroy(Article $article)
{
    //Display existing record with "Are you sure you want to delete this? Delete|Cancel" option
    //If user chooses Delete, delete the record
    //If user chooses Cancel, return to the list of articles
}
}
</code>```

Is there anything else you need to see?

答:
It may be possible because of you don't have defined that column in fillable property, to use mass assignment you have to specify that columns.

Try after adding that columns in fillable property.

Laravel mass assignment

Hope this helps :)

Title: How does Laravel generate SQL?

Body:
I'm brand new to Laravel and am working my way through the Laravel 6 from Scratch course over at Laracasts. The course is free but I can't afford a Laracasts membership so I can't ask questions there.

I've finished Section 6 of the course, Controller Techniques, and am having unexpected problems trying to extend the work we've done so far to add a few new features. The course has students build pages that let a user show a list of articles, look at an individual article, create and save a new article, and update and save an existing article. The course work envisioned a very simple article containing just an ID (auto-incremented in the database and not visible to the web user), a title, an excerpt and a body and I got all of the features working for that. Now I'm trying to add two new fields: an author name and a path to a picture illustrating the article. I've updated the migration, rolled back and rerun the migration to include the new fields and got no errors from that. (I also ran a migrate:free and got no errors from that.) I've also updated the forms used to create and update the articles and added validations for the new fields. However, when I go to execute the revised create code, it fails because the SQL is wrong.

The error message complains that the author field doesn't have a default, which is true, I didn't assign a default.  However, I did give it a value on the form. What perplexes me most is the SQL that it has generated: the column list doesn't show the two new columns. And that's not all: the values list is missing apostrophes around any of the string/text values. (All of the columns are defined as string or text.)

As I said, I'm completely new to Laravel so I don't know how to persuade Laravel to add the two new columns to the Insert statement nor how to make it put apostrophes around the strings in the values list. That hasn't come up in the course and I'm not sure if it will come up later. I was hoping someone could tell me how to fix this. All of my functionality was working fine before I added the  two new fields/columns.

Here is the error message:

    SQLSTATE[HY000]: General error: 1364 Field 'author' doesn't have a default value (SQL: insert         into `articles` (`title`, `excerpt`, `body`, `updated_at`, `created_at`) values (Today in Canada, The ideal winter-beater, This car is the ideal winter-beater for the tough Canadian climate. It is designed to get you from A to B in style and without breaking the bank., 2020-02-15 17:37:54, 2020-02-15 17:37:54))

Here is ArticlesController:

<?php

namespace App\Http\Controllers;

use App\Article;
use Illuminate\Http\Request;

class ArticlesController extends Controller
{
public function index()
{
    $articles = Article::latest()->get();
    return view ('articles.index', ['articles' => $articles]);
}

public function show(Article $article)
{
    return view('articles.show', ['article' => $article]);
}

public function create()
{
    return view('articles.create');
}

public function store()
{
    //Stores a NEW article
    Article::create($this->validateArticle());
    return redirect('/articles');
}

public function edit(Article $article)
{
    return view('articles.edit', ['article' => $article]);
}

public function update(Article $article)
{
    //Updates an EXISTING article
    $article->update($this->validateArticle());
    return redirect('/articles/', $article->id);
}

public function validateArticle()
{
    return request()->validate([
        'title' => ['required', 'min:5', 'max:20'],
        'author' => ['required', 'min:5', 'max:30'],
        'photopath' => ['required', 'min:10', 'max:100'],
        'excerpt' => ['required', 'min:10', 'max:50'],
        'body' => ['required', 'min:50', 'max:500']
    ]);
}

public function destroy(Article $article)
{
    //Display existing record with "Are you sure you want to delete this? Delete|Cancel" option
    //If user chooses Delete, delete the record
    //If user chooses Cancel, return to the list of articles
}
}

Is there anything else you need to see?


问:
Fatal error: require_once(): Failed opening required 'C:/xampp/htdocs/system/system.php' (include_path='.;C:\xampp\php\pear')
```<code>Warning: require_once(C:/xampp/htdocs/system/system.php): failed to open stream: No such file or directory in C:\xampp\htdocs\qdinka\includes\autoload.php on line 9

Fatal error: require_once(): Failed opening required 'C:/xampp/htdocs/system/system.php' (include_path='.;C:\xampp\php\pear') in C:\xampp\htdocs\qdinka\includes\autoload.php on line 9

root is c:/xampp/htdocs pear path is c:/xampp/php/pear
</code>```

anybody have idea why getting error?
tried changing alloverrideall in httpd.conf
I already saw few posts related but nothing seems to work.

答: Actually this is laravel project,and you are executing it without having laravel in your pc.So,there is no issue with that project only thing you need to install the laravel and 2nd thing is that if you have already laravel in your pc then you should update your composer.</p>

Body:
Warning: require_once(C:/xampp/htdocs/system/system.php): failed to open stream: No such file or directory in C:\xampp\htdocs\qdinka\includes\autoload.php on line 9

Fatal error: require_once(): Failed opening required 'C:/xampp/htdocs/system/system.php' (include_path='.;C:\xampp\php\pear') in C:\xampp\htdocs\qdinka\includes\autoload.php on line 9

root is c:/xampp/htdocs pear path is c:/xampp/php/pear

anybody have idea why getting error?
tried changing alloverrideall in httpd.conf
I already saw few posts related but nothing seems to work.


问:
How do I add a record to a database with LINQ?
I have been utilizing Scott Gu's tutorials on LINQ to SQL to try to learn some LINQ.  I have been able to view, retrieve, and update records but I am unable to write new records into the database (MSSQL). Scott starts getting into inserting rows in the fourth section of the set of tutorials. As you can see on that page (or may already know), in order to add a record you must do the following (VB.NET):

```<code>Dim db as New LINQtoSQLDataContext

Dim oArticle as New article // table name
oArticle.Body = "Some Text"
oArticle.Title = "Some Title"
oArticle.Author = "Some Author"

db.articles.Add(oArticle) // this is the line that does not work.
</code>```

Visual Studio 2008 returns me "'add' is not a member of 'System.Data.Linq.Table(Of article)".

Can anyone give me a push in the right direction? Thanks!

OwnerDisplayName: Anders

ContentLicense: CC BY-SA 2.5

Body:
I have been utilizing Scott Gu's tutorials on LINQ to SQL to try to learn some LINQ.  I have been able to view, retrieve, and update records but I am unable to write new records into the database (MSSQL). Scott starts getting into inserting rows in the fourth section of the set of tutorials. As you can see on that page (or may already know), in order to add a record you must do the following (VB.NET):

Dim db as New LINQtoSQLDataContext

Dim oArticle as New article // table name
oArticle.Body = "Some Text"
oArticle.Title = "Some Title"
oArticle.Author = "Some Author"

db.articles.Add(oArticle) // this is the line that does not work.

Visual Studio 2008 returns me "'add' is not a member of 'System.Data.Linq.Table(Of article)".

Can anyone give me a push in the right direction? Thanks!

LastEditorDisplayName: Cade Roux

Body:
db.articles.InsertOnSubmit(oArticle)
db.SubmitChanges()

OwnerDisplayName: John Boker

LastEditorDisplayName: Steve Robbins


问:
Bootstrap modal coded inside forms - rendered with model then OUTSIDE the form
I have a standard Rails app form with nested attributes.  I have too many fields in the nested attributes so I figured I would create a modal window for these via Bootstrap.  It looks roughly like this:

```<code><body>
  <form>
    <div id="modal" class="modal">
      modal form input fields
    </div>
  </form>
</body>
</code>```

The issue I have is that when rendered in the browser I get this:

```<code><body>
  <form>
  </form>
  <div id="modal" class="modal">
    modal form input fields
  </div>
</body>
</code>```

The modal divs are all moved to the end of the body and hence the inputs not submitted with the form.  The modals work just fine.

After searching I came across this (position:fixed):

https://getbootstrap.com/docs/4.0/components/modal/

I don't know if it related but worth mentioning.  Anyone else seen this?  I can't seem to find another related issue but could easily be using the wrong search terms etc.

UPDATE

Hunted through the BS code:

```<code>   // Move modal to body
    // Fix Bootstrap backdrop issue with animation.css

    // MOD Keeps the modals in place so you can hide them in a form

    $('.modal').appendTo("body");
</code>```

Now - thoughts on how to prevent this?  If it was one modal I could just move it back.  The issue is I have multiple modals (one for each nested attribute which can be > 0).  I can conceive making this work (ie. moving them all back) but ideally suppressing this would be better (easier).

答:
Given my situation I choose to just move the divs back.  It was not that bad:

```<code><body>
  <form>
    <table>
      <tr>
        <td class="modal_id_1">
          <div id="modal_id_1" class="modal">
            modal form input fields
          </div>
        </td>
        <td class="modal_id_2">
          <div id="modal_id_2" class="modal">
            modal form input fields
          </div>
        </td>
      </tr>
    </table>
  </form>
</body>
</code>```

After age load the modal divs are moved to the end of the body.  I did this:

```<code>  $('.item_modal').each(function() {
    $(this).appendTo("td." + $(this).attr('id'));
</code>```

Open to better answers - thanks to those that commented

Body:
I have a standard Rails app form with nested attributes.  I have too many fields in the nested attributes so I figured I would create a modal window for these via Bootstrap.  It looks roughly like this:

  <form>

      modal form input fields

  </form>

The issue I have is that when rendered in the browser I get this:

  <form>
  </form>

    modal form input fields

The modal divs are all moved to the end of the body and hence the inputs not submitted with the form.  The modals work just fine.

After searching I came across this (position:fixed):

https://getbootstrap.com/docs/4.0/components/modal/

I don't know if it related but worth mentioning.  Anyone else seen this?  I can't seem to find another related issue but could easily be using the wrong search terms etc.

UPDATE

Hunted through the BS code:

   // Move modal to body
    // Fix Bootstrap backdrop issue with animation.css

    // MOD Keeps the modals in place so you can hide them in a form

    $('.modal').appendTo("body");

Now - thoughts on how to prevent this?  If it was one modal I could just move it back.  The issue is I have multiple modals (one for each nested attribute which can be > 0).  I can conceive making this work (ie. moving them all back) but ideally suppressing this would be better (easier).

Body:
Given my situation I choose to just move the divs back.  It was not that bad:

<body>
  <form>
    <table>
      <tr>
        <td class="modal_id_1">
          <div id="modal_id_1" class="modal">
            modal form input fields
          </div>
        </td>
        <td class="modal_id_2">
          <div id="modal_id_2" class="modal">
            modal form input fields
          </div>
        </td>
      </tr>
    </table>
  </form>
</body>

After age load the modal divs are moved to the end of the body.  I did this:

  $('.item_modal').each(function() {
    $(this).appendTo("td." + $(this).attr('id'));

Open to better answers - thanks to those that commented


问:
How does MT19937RNG generate a random number less than 32 bit?
We know that the random module in python use MT19937 to generate a 32-bit random number, for example:

```<code>>>> import random
>>> random.seed(123)
>>> random.getrandbits(32)
224899942L
>>> random.getrandbits(32)
1149664691L
>>> random.getrandbits(32)
374463918L
>>> random.getrandbits(32)
3302642556L
</code>```

The output is the same as the MT19937's output when I set the same seed.

However, if I want to generate a random number less than 32-bit, for example, if I want to use random.getrandbits(1) to generate a 1-bit random number, at first I thought the result is just random.getrandbits(32)&1, but when I put into practice, I found it's not so:

```<code>>>> import random
>>> random.seed(123)
>>> random.getrandbits(1)
0L
>>> random.getrandbits(1)
0L
>>> random.getrandbits(1)
0L
>>> random.getrandbits(1)
1L
</code>```

Now I have no idea why the output become 0,0,0,1..., Where do these numbers come from?

And as we all know, if we get 624 consecutive 32-bit random numbers generated by MT19937RNG, we can easily recover the seed and calculate any random number, but if we can only get consecutive random numbers less than 32-bit like 1-bit, can we still break the MT19937RNG?

答:
the output of random.getrandbits(1) become 0,0,0,1..., Where do these numbers come from?

These are the high-order bits of the results of random.getrandbits(32). Just look at the source in file Modules/_randommodule.c

```<code>if (k <= 32)  /* Fast path */
    return PyLong_FromUnsignedLong(genrand_int32(self) >> (32 - k));
</code>```

if we can only get consecutive random numbers less than 32-bit like 1-bit, can we still break the MT19937RNG?

Yes. Of course we need 32 times more values. Basically, we take the 19937 bits of the state as unknowns, write one linear equation of these variables for each bit that we know, and solve.

OwnerDisplayName: amphibian

Body:
We know that the random module in python use MT19937 to generate a 32-bit random number, for example:

>>> import random
>>> random.seed(123)
>>> random.getrandbits(32)
224899942L
>>> random.getrandbits(32)
1149664691L
>>> random.getrandbits(32)
374463918L
>>> random.getrandbits(32)
3302642556L

The output is the same as the MT19937's output when I set the same seed.

However, if I want to generate a random number less than 32-bit, for example, if I want to use random.getrandbits(1) to generate a 1-bit random number, at first I thought the result is just random.getrandbits(32)&1, but when I put into practice, I found it's not so:

>>> import random
>>> random.seed(123)
>>> random.getrandbits(1)
0L
>>> random.getrandbits(1)
0L
>>> random.getrandbits(1)
0L
>>> random.getrandbits(1)
1L

Now I have no idea why the output become 0,0,0,1..., Where do these numbers come from?

And as we all know, if we get 624 consecutive 32-bit random numbers generated by MT19937RNG, we can easily recover the seed and calculate any random number, but if we can only get consecutive random numbers less than 32-bit like 1-bit, can we still break the MT19937RNG?

Body:
the output of random.getrandbits(1) become 0,0,0,1..., Where do these numbers come from?

These are the high-order bits of the results of random.getrandbits(32). Just look at the source in file Modules/_randommodule.c

if (k <= 32)  /* Fast path */
    return PyLong_FromUnsignedLong(genrand_int32(self) >> (32 - k));

if we can only get consecutive random numbers less than 32-bit like 1-bit, can we still break the MT19937RNG?

Yes. Of course we need 32 times more values. Basically, we take the 19937 bits of the state as unknowns, write one linear equation of these variables for each bit that we know, and solve.

OwnerDisplayName: fgrieu


问:
How to toggle a single element from nested map iteration in react
I am new to react. I am working on a project to create shift rota for workers. Created a grid with cells. When you click on a cell it will change its value from day number to "Holiday" and if you click it again it will change back to day number. The problem is when I click a cell entire row of cells change their values. What to do to change the value only one cell ?

This is my code...

```<code>export default class DayNames extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isToggleOn: true
    };
  }

  handleClick = e => {
    this.setState(prevState => ({
      isToggleOn: { ...prevState.isToggleOn, [e]: !prevState.isToggleOn[e] }
    }));
  };

  render() {
    //Getting number of days of month
    const month = new Date().getMonth() + 1;
    const year = new Date().getFullYear();
    const numberDaysOfMonth = new Date(year, month, 0).getDate();

    let foo1 = [];
    for (let i = 1; i <= numberDaysOfMonth; i++) {
      foo1.push(i);
    }

    let foo2 = ["Ops1", "Ops2", "Ops3", "Ops4", "Ops5", "Ops6"];
    const ops = foo2.map((elem, index) => {
      return (
        <div className="ops_header" key={index}>
          {elem}
          {foo1.map((cell, i) => {
            return (
              <div
                className="operator"
                data-id={cell}
                key={i}
                onClick={() => this.handleClick(i)}
              >
                {this.state.isToggleOn[i] ? "Holiday" : cell}
              </div>
            );
          })}
        </div>
      );
    });

    return (
      <div>
        <div className="table">{ops}</div>
      </div>
    );
  }
}
</code>```

This is link to sandbox .../components/DayNames/DayNames.js
https://codesandbox.io/s/react-toggle-day-0rjop

答:
Seems like you when you were toggling in was getting all the indexes for cell, I added another parameter which is basically the index of your foo2 and changed the toggle condition from one index to both [i=foo1, i=foo2];

```<code>// This line changed from e => (e,index)
handleClick = (e, index) => {
// memories both index and put into one variable
    const target = [e, index];
    console.log(target);
    this.setState(prevState => ({
// update state
      isToggleOn: { ...prevState.isToggleOn, [target]: !prevState.isToggleOn[target] }
    }));
};
</code>```

```<code>    let foo2 = ["Ops1", "Ops2", "Ops3", "Ops4", "Ops5", "Ops6"];
    const ops = foo2.map((elem, index) => {
      return (
        <div className="ops_header" key={index}>
          {elem}
          {foo1.map((cell, i) => {
            return (
              <div
                className="operator"
                data-id={cell}
                key={i}
                // pass both indexes to handleClick();
                onClick={() => this.handleClick(i, index)}
              >
                // togle based on indexes;
                {this.state.isToggleOn[[i, index]] ? "Holiday" : cell}
              </div>
            );
          })}
        </div>
      );
    });
</code>```

Body:
I am new to react. I am working on a project to create shift rota for workers. Created a grid with cells. When you click on a cell it will change its value from day number to "Holiday" and if you click it again it will change back to day number. The problem is when I click a cell entire row of cells change their values. What to do to change the value only one cell ?

This is my code...

export default class DayNames extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isToggleOn: true
    };
  }

  handleClick = e => {
    this.setState(prevState => ({
      isToggleOn: { ...prevState.isToggleOn, [e]: !prevState.isToggleOn[e] }
    }));
  };

  render() {
    //Getting number of days of month
    const month = new Date().getMonth() + 1;
    const year = new Date().getFullYear();
    const numberDaysOfMonth = new Date(year, month, 0).getDate();

    let foo1 = [];
    for (let i = 1; i <= numberDaysOfMonth; i++) {
      foo1.push(i);
    }

    let foo2 = ["Ops1", "Ops2", "Ops3", "Ops4", "Ops5", "Ops6"];
    const ops = foo2.map((elem, index) => {
      return (

          {elem}
          {foo1.map((cell, i) => {
            return (

 this.handleClick(i)}
              >
                {this.state.isToggleOn[i] ? "Holiday" : cell}

            );
          })}

      );
    });

    return (

{ops}

    );
  }
}

This is link to sandbox .../components/DayNames/DayNames.js
https://codesandbox.io/s/react-toggle-day-0rjop

Body:
Seems like you when you were toggling in was getting all the indexes for cell, I added another parameter which is basically the index of your foo2 and changed the toggle condition from one index to both [i=foo1, i=foo2];

// This line changed from e => (e,index)
handleClick = (e, index) => {
// memories both index and put into one variable
    const target = [e, index];
    console.log(target);
    this.setState(prevState => ({
// update state
      isToggleOn: { ...prevState.isToggleOn, [target]: !prevState.isToggleOn[target] }
    }));
};

    let foo2 = ["Ops1", "Ops2", "Ops3", "Ops4", "Ops5", "Ops6"];
    const ops = foo2.map((elem, index) => {
      return (
        <div className="ops_header" key={index}>
          {elem}
          {foo1.map((cell, i) => {
            return (
              <div
                className="operator"
                data-id={cell}
                key={i}
                // pass both indexes to handleClick();
                onClick={() => this.handleClick(i, index)}
              >
                // togle based on indexes;
                {this.state.isToggleOn[[i, index]] ? "Holiday" : cell}
              </div>
            );
          })}
        </div>
      );
    });


问:
Why does this PHP code not output property values?
I am trying to import a tab delimited file after upload. The meat of this is done with the following function. I'm trying to build an array of class instances. The code follows:

Import Function

```<code>$AddedProducts;
function importList($filename)
{
    global $AddedProducts;
    $AddedProducts=array();
    $fileHandle = fopen($filename, "r");
    $currentProduct = new productImport();

      $line=fgets($fileHandle); $line=fgets($fileHandle); //throw away top 2 lines
    echo '<hr>';
    while(true)
    {
        $line = fgets($fileHandle);
        if($line == null)   break;

        $cells=explode('    ', $line);
        $i=0;

        foreach($currentProduct as $ProductProperty)
        {
            if(isset($cells[$i]))
            {
                $ProductProperty = $cells[$i];
                echo $i . '. ' . $cells[$i] . "<br>";
            }
            else return false;
            $i++;
        }
        echo "<hr>";
        $AddedProducts[]=$currentProduct;
    }
    fclose($fileHandle);
    return true;
}
</code>```

Array Output

```<code><?
$i=0;
foreach($AddedProducts as $AddedProduct)
{
    $i++;
    echo "<hr>" . $i . "<br>";
    foreach($AddedProduct as $key=>$value)
    {
        echo $key . ' = ' . $value . '<br>';
    }
}
?>
</code>```

Breakdown of Known Info

The final array length/size is correct. (Should be lines in file - 2)

It doesn't particularly matter how many properties are in the productImport class so long as it equates to the same number of tabs per line in the file being read.

importList function echos proper values for $cells[$i] which are the same values I'm missing in the array output.

The problem seems to be either the values aren't being assigned to the properties or the properties are not being read. I'm not sure of why either would be the case but I assume it is because PHP is not my primary language and likely something obvious about the foreach loops ;)

I'm using PHP v5.2.6

What's wrong with this code?

Answer:

```<code>foreach($currentProduct as $ProductProperty) becomes
foreach($currentProduct as &$ProductProperty)
</code>```

答:
In your foreach loops, the assigned variables such as $ProductProperty are not references, therefore they will not actually affect anything outside the loop.

i.e. $ProductProperty = $cells[$i] only affects the current iteration.

Body:
I am trying to import a tab delimited file after upload. The meat of this is done with the following function. I'm trying to build an array of class instances. The code follows:

Import Function

$AddedProducts;
function importList($filename)
{
    global $AddedProducts;
    $AddedProducts=array();
    $fileHandle = fopen($filename, "r");
    $currentProduct = new productImport();

      $line=fgets($fileHandle); $line=fgets($fileHandle); //throw away top 2 lines
    echo '
';
    while(true)
    {
        $line = fgets($fileHandle);
        if($line == null)   break;

        $cells=explode('    ', $line);
        $i=0;

        foreach($currentProduct as $ProductProperty)
        {
            if(isset($cells[$i]))
            {
                $ProductProperty = $cells[$i];
                echo $i . '. ' . $cells[$i] . "
";
            }
            else return false;
            $i++;
        }
        echo "
";
        $AddedProducts[]=$currentProduct;
    }
    fclose($fileHandle);
    return true;
}

Array Output

<?
$i=0;
foreach($AddedProducts as $AddedProduct)
{
    $i++;
    echo "
" . $i . "
";
    foreach($AddedProduct as $key=>$value)
    {
        echo $key . ' = ' . $value . '
';
    }
}
?>

Breakdown of Known Info

The final array length/size is correct. (Should be lines in file - 2)

It doesn't particularly matter how many properties are in the productImport class so long as it equates to the same number of tabs per line in the file being read.

importList function echos proper values for $cells[$i] which are the same values I'm missing in the array output.

The problem seems to be either the values aren't being assigned to the properties or the properties are not being read. I'm not sure of why either would be the case but I assume it is because PHP is not my primary language and likely something obvious about the foreach loops ;)

I'm using PHP v5.2.6

What's wrong with this code?

Answer:

foreach($currentProduct as $ProductProperty) becomes
foreach($currentProduct as &$ProductProperty)


问:
java.io.File.length() greater than 0 when actual file is 0 bytes
What:

My Android application is compressing a directory on rooted Android Devices (API 25+) and writing the zip to a removable USB stick.

Problem:

Java is telling my that the file is 97,993 bytes but when I take the USB stick out of the Android Device and plug it into my mac, mac is saying it's 0 bytes.

Code:

```<code>/// Where is the directory that we're compressing onto the USB stick?
File dir = new File(Environment.getExternalStorageDirectory(), "logs");
if (!dir.exists() || !dir.isDirectory()) throw new IOException("Invalid directory.");

/// Where on the USB stick is the logs.zip going to go?
File zip = new File("/storage/FD91-1317/logs.zip");

/// Delete the file if it already exists then recreate it
if (zip.exists() && !zip.delete()) throw new IOException("Failed to create zip file.");
zip.createNewFile();

/// Using try {} to manage our streams
try (FileOutputStream fileOutputStream = new FileOutputStream(zip); ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream)) {
    /// Get the list of files to enumerate through
    File[] files = dir.listFiles();

    // Enumerate through each file to be compressed
    for (File file : files) {
        /// If somehow a file was deleted throw an exception
        if (!file.exists()) throw new FileNotFoundException(file.getPath());

        /// Create the new zip entry
        zipOutputStream.putNextEntry(new ZipEntry(file.getName()));

        /// Copy the file into the zip
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            IOUtils.copy(fileInputStream, zipOutputStream);
        }

        /// Close the zip entry
        zipOutputStream.closeEntry();
    }
}

/// Validate that the zip has been created successfully
if (zip.length() == 0) throw new IOException("Zip failed to be created!!!!");
Log.v("logs", String.format("Logs collected: %s", zip.length());
</code>```

More Info:

My application is running as a system app in the /system/priv-app/ directory

My application has the android.permission.WRITE_MEDIA_STORAGE permission

The zip file on the USB stick is only 0 bytes when plugged into the mac, if I remove the USB stick within 5-10 seconds after Log.v(...) is called. If I wait longer than 10 seconds it'll always have bytes.

Log.v(...) also is logging Logs collected: 97993

org.apache.commons.io.FileUtils.readFileToByteArray(zip) is also returning a byte array with the length of 97993 and the byte array 100% has data in it and isn't empty.

ls -l /storage/FD91-1317 is also saying that logs.zip is 97993 bytes.

Closing:

I've tried literally everything I can think of at this point but still can't figure out why Java is saying that the zip contains data but when plugged into my mac it's saying the file is 0 bytes. Windows is telling me the same thing. The only thing I know for a fact is that if I wait more than 10 seconds before removing the USB from my Android device, then this problem will not occur but I worry that depending on the size of the zip, that might not be enough time in all cases. To my knowledge, once you write to a stream and close it, it should be 100% completed.

答:
In order to fix the issue, I had to run fileOutputStream.getFD().sync();

If anyone is wondering why running that had fixed it, here is a snippet from Java's docs to explain what sync(); does.

See: https://docs.oracle.com/javase/7/docs/api/java/io/FileDescriptor.html#sync() for more details.

Thanks so much to @CommonsWare for assisting!

Body:
What:

My Android application is compressing a directory on rooted Android Devices (API 25+) and writing the zip to a removable USB stick.

Problem:

Java is telling my that the file is 97,993 bytes but when I take the USB stick out of the Android Device and plug it into my mac, mac is saying it's 0 bytes.

Code:

/// Where is the directory that we're compressing onto the USB stick?
File dir = new File(Environment.getExternalStorageDirectory(), "logs");
if (!dir.exists() || !dir.isDirectory()) throw new IOException("Invalid directory.");

/// Where on the USB stick is the logs.zip going to go?
File zip = new File("/storage/FD91-1317/logs.zip");

/// Delete the file if it already exists then recreate it
if (zip.exists() && !zip.delete()) throw new IOException("Failed to create zip file.");
zip.createNewFile();

/// Using try {} to manage our streams
try (FileOutputStream fileOutputStream = new FileOutputStream(zip); ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream)) {
    /// Get the list of files to enumerate through
    File[] files = dir.listFiles();

    // Enumerate through each file to be compressed
    for (File file : files) {
        /// If somehow a file was deleted throw an exception
        if (!file.exists()) throw new FileNotFoundException(file.getPath());

        /// Create the new zip entry
        zipOutputStream.putNextEntry(new ZipEntry(file.getName()));

        /// Copy the file into the zip
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            IOUtils.copy(fileInputStream, zipOutputStream);
        }

        /// Close the zip entry
        zipOutputStream.closeEntry();
    }
}

/// Validate that the zip has been created successfully
if (zip.length() == 0) throw new IOException("Zip failed to be created!!!!");
Log.v("logs", String.format("Logs collected: %s", zip.length());

More Info:

My application is running as a system app in the /system/priv-app/ directory

My application has the android.permission.WRITE_MEDIA_STORAGE permission

The zip file on the USB stick is only 0 bytes when plugged into the mac, if I remove the USB stick within 5-10 seconds after Log.v(...) is called. If I wait longer than 10 seconds it'll always have bytes.

Log.v(...) also is logging Logs collected: 97993

org.apache.commons.io.FileUtils.readFileToByteArray(zip) is also returning a byte array with the length of 97993 and the byte array 100% has data in it and isn't empty.

ls -l /storage/FD91-1317 is also saying that logs.zip is 97993 bytes.

Closing:

I've tried literally everything I can think of at this point but still can't figure out why Java is saying that the zip contains data but when plugged into my mac it's saying the file is 0 bytes. Windows is telling me the same thing. The only thing I know for a fact is that if I wait more than 10 seconds before removing the USB from my Android device, then this problem will not occur but I worry that depending on the size of the zip, that might not be enough time in all cases. To my knowledge, once you write to a stream and close it, it should be 100% completed.


问:
Issue with scipy.io.wavfile.read and scipy.fftpack.fft
```<code>from os.path import dirname, join as pjoin
import scipy.io as sio
from scipy.io import wavfile
from scipy.fftpack import fft

data_dir = pjoin(dirname(sio.__file__), 'tests', 'data')
wav_fname = pjoin(data_dir, 'test-44100Hz-2ch-32bit-float-be.wav')
print(wav_fname)

def create_FFT(fn,size=1000):
    sample_rate, X = wavfile.read(fn)
    fft_features = abs(fft(X)[:size])
    return(sample_rate, X, fft_features)

for wav_fn in wav_fname :
    samplerate, data, fft_features = create_FFT(wav_fn)
    print(f"number of channels = {data.shape[1]}")
    print("fft features are: {}".format(fft_features))
</code>```

In the above code, if I don't include fft specific code in the create_FFT function, I could read the file and print the number of channels. However, as soon as I include fft specific code, I get an error "FileNotFoundError: [Errno 2] No such file or directory: 'C'"

Any help will be appreciated.

答: Found the answer. It was with the for loop at the bottom.</p>

Body:
from os.path import dirname, join as pjoin
import scipy.io as sio
from scipy.io import wavfile
from scipy.fftpack import fft

data_dir = pjoin(dirname(sio.__file__), 'tests', 'data')
wav_fname = pjoin(data_dir, 'test-44100Hz-2ch-32bit-float-be.wav')
print(wav_fname)

def create_FFT(fn,size=1000):
    sample_rate, X = wavfile.read(fn)
    fft_features = abs(fft(X)[:size])
    return(sample_rate, X, fft_features)

for wav_fn in wav_fname :
    samplerate, data, fft_features = create_FFT(wav_fn)
    print(f"number of channels = {data.shape[1]}")
    print("fft features are: {}".format(fft_features))

In the above code, if I don't include fft specific code in the create_FFT function, I could read the file and print the number of channels. However, as soon as I include fft specific code, I get an error "FileNotFoundError: [Errno 2] No such file or directory: 'C'"

Any help will be appreciated.


答:
your issue is generated when you have empty tuple, then your variable lst will be an empty list so will not make sense to use lst[-1], this will generate your error, a simple fix will be to check if is an empty list:

```<code>if lst:
    lst[-1] = object
else:
    lst.append(object)
</code>```

Title: Problem with "list assignment index out of range" Python

Body:
I should replace the last element of a tuple in a list of tuples with and object given as input and I tried to write this code but I got a "list assignment index out of range" error at line 4. How should I fix it?

def replaceLast (tupleList, object):
    for i, tup in enumerate(tupleList):
        lis = list(tup)
        lis[-1] = object
        tupleList[i] = tuple(lis)
    return tupleList

lT=[(1,),(2,3),(),(7,3)]
replaceLast(lT,11) #=> [(11,), (2, 11), (11,), (7, 11)] -> this should be the result

Body:
your issue is generated when you have empty tuple, then your variable lst will be an empty list so will not make sense to use lst[-1], this will generate your error, a simple fix will be to check if is an empty list:

if lst:
    lst[-1] = object
else:
    lst.append(object)


答:
I think the problem is in this section:

```<code>foreach($currentProduct as $ProductProperty)
        {
            if(isset($cells[$i]))
            {
                $ProductProperty = $cells[$i];        /* this seems to be the problem */
                echo $i . '. ' . $cells[$i] . "<br>";
            }
            else return false;
            $i++;
        }
</code>```

According to the php manual, Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. so the value you assign is discarded after the loop.

Edit: Apart from that, you are looping through object properties and although the manual does not explicitly state it, it seems you need foreach($class as $key => $value) instead of just foreach($class as $value)

Title: Why does this PHP code not output property values?

Body:
I think the problem is in this section:

foreach($currentProduct as $ProductProperty)
        {
            if(isset($cells[$i]))
            {
                $ProductProperty = $cells[$i];        /* this seems to be the problem */
                echo $i . '. ' . $cells[$i] . "<br>";
            }
            else return false;
            $i++;
        }

According to the php manual, Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. so the value you assign is discarded after the loop.

Edit: Apart from that, you are looping through object properties and although the manual does not explicitly state it, it seems you need foreach($class as $key => $value) instead of just foreach($class as $value)


问:
if condition using javascript
am trying to perform an if condition in javascript, but i cannot get the output. i tried the code below:

function myfunc(size){

    var m = parseInt(size);
    var size2 = (m).toString();
  if(m <= 2){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 1 node will be required for processing');

    }
  if(m > 2 || <= 4){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 3 nodes will be required for processing');

    }

  if(m > 4 || <= 6){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 5 nodes will be required for processing');

    }
  if(m > 6 || <= 8){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 7 nodes will be required for processing' );

    }
  if(m > 8){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 11 nodes will be required for processing');

    }

  }```

how can i solve this?

答:
The issue is that comparisons after || do not have a second operand.

Changes (Notice || m)

if(m > 2 || <= 4) to if(m > 2 || m <= 4)

if(m > 4 || <= 6) to if(m > 4 || m <= 6)

if(m > 6 || <= 8) to if(m > 6 || m <= 8)

Changes applied

```<code>function myfunc(size){
        var m = parseInt(size);
        var size2 = (m).toString();
        if(m <= 2){
                sweetAlert('dataset file is: '+size2 + 'a cluster of 1 node will be required for processing');
                }
        if(m > 2 || m <= 4){
                sweetAlert('dataset file is: '+size2 + 'a cluster of 3 nodes will be required for processing');

                }
        if(m > 4 || m <= 6){
                sweetAlert('dataset file is: '+size2 + 'a cluster of 5 nodes will be required for processing');

                }
        if(m > 6 || m <= 8){
                sweetAlert('dataset file is: '+size2 + 'a cluster of 7 nodes will be required for processing' );
                }
        if(m > 8){
                sweetAlert('dataset file is: '+size2 + 'a cluster of 11 nodes will be required for processing');
                }
        }
</code>```

Title: if condition using javascript

Body:
am trying to perform an if condition in javascript, but i cannot get the output. i tried the code below:

function myfunc(size){

    var m = parseInt(size);
    var size2 = (m).toString();
  if(m <= 2){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 1 node will be required for processing');

    }
  if(m > 2 || <= 4){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 3 nodes will be required for processing');

    }

  if(m > 4 || <= 6){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 5 nodes will be required for processing');

    }
  if(m > 6 || <= 8){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 7 nodes will be required for processing' );

    }
  if(m > 8){
    sweetAlert('dataset file is: '+size2 + 'a cluster of 11 nodes will be required for processing');

    }

  }

how can i solve this?

Body:
The issue is that comparisons after || do not have a second operand.

Changes (Notice || m)

if(m > 2 || <= 4) to if(m > 2 || m <= 4)

if(m > 4 || <= 6) to if(m > 4 || m <= 6)

if(m > 6 || <= 8) to if(m > 6 || m <= 8)

Changes applied

function myfunc(size){
        var m = parseInt(size);
        var size2 = (m).toString();
        if(m <= 2){
                sweetAlert('dataset file is: '+size2 + 'a cluster of 1 node will be required for processing');
                }
        if(m > 2 || m <= 4){
                sweetAlert('dataset file is: '+size2 + 'a cluster of 3 nodes will be required for processing');

                }
        if(m > 4 || m <= 6){
                sweetAlert('dataset file is: '+size2 + 'a cluster of 5 nodes will be required for processing');

                }
        if(m > 6 || m <= 8){
                sweetAlert('dataset file is: '+size2 + 'a cluster of 7 nodes will be required for processing' );
                }
        if(m > 8){
                sweetAlert('dataset file is: '+size2 + 'a cluster of 11 nodes will be required for processing');
                }
        }


问:
How do properly divide in a for loop? And how do I control the size of the result?
```<code>    printf("Enter the number of gallons used for tank#1: ");
    scanf("%.f", &number);
    while ((c = getchar() != '\n') && c != EOF);
    printf("Enter the number of miles driven:");
    scanf("%.f", &y);
    while ((c = getchar() != '\n') && c != EOF);
    div = number / y;
    printf("***The miles per gallon for this tank is %d\n\n", number, y, div);
</code>```

I am using a for loop here, the only problem I have with this section is the division of number and y.

Every time I try to do so the result isn't calculated, it'll give me a random number or an extremely long number.

答:
The printf() function is wrong, because the format code if %d instead of %f. Most probably all your variables are double, but you don't show us this important information.

```<code>printf("***The miles per gallon for this tank is %f\n\n", div);
</code>```

Please try it.

Body:
    printf("Enter the number of gallons used for tank#1: ");
    scanf("%.f", &number);
    while ((c = getchar() != '\n') && c != EOF);
    printf("Enter the number of miles driven:");
    scanf("%.f", &y);
    while ((c = getchar() != '\n') && c != EOF);
    div = number / y;
    printf("***The miles per gallon for this tank is %d\n\n", number, y, div);

I am using a for loop here, the only problem I have with this section is the division of number and y.

Every time I try to do so the result isn't calculated, it'll give me a random number or an extremely long number.

Body:
The printf() function is wrong, because the format code if %d instead of %f. Most probably all your variables are double, but you don't show us this important information.

printf("***The miles per gallon for this tank is %f\n\n", div);

Please try it.


问:
Bootstrap 4 collapse nav group
I am working on a documentation site with Table of contents in a right hand column and the content in the left hand column. The TOC has several groups containing code similar to below. Is there any way to collapse and expand the sub-menu nav by clicking on the anchor tag? So that the sub menus are are all collapsed when page loads and then the user can expand and collapse as needed.

Orgbrat

.doc-sub-menu {
  list-style: none;
  padding-left: 0;
}

.doc-sub-menu .nav-link {
  margin-bottom: 10px;
  font-size: 12px;
  display: block;
  color: #616670;
  padding: 0;
  padding-left: 34px;
  background: none;
}

.doc-sub-menu .nav-link:first-child {
  padding-top: 5px;
}

.doc-sub-menu .nav-link:hover {
  color: #494d55;
  text-decoration: none;
  background: none;
}

.doc-sub-menu .nav-link:focus {
  background: none;
}

.doc-sub-menu .nav-link.active {
  background: none;
  color: #40babd;
}

.body-blue .doc-sub-menu .nav-link.active {
  color: #58bbee;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
Adding and Managing Items
<nav class="doc-sub-menu nav flex-column">
  Medications
  Blood Sugars
  Pharmacies
  Physicians
  Family Members
  Appointments
  Medical Records
</nav>
<!--//nav--></code>```

答:
Yes you can use it default class (collapse) and data-toggle tag in Bootstrap 4. Please try below snippet :

.doc-sub-menu {
            list-style: none;
            padding-left: 0;
          }

          .doc-sub-menu .nav-link {
            margin-bottom: 10px;
            font-size: 12px;
            display: block;
            color: #616670;
            padding: 0;
            padding-left: 34px;
            background: none;
            cursor: pointer;
          }

          .doc-sub-menu .nav-link:first-child {
            padding-top: 5px;
          }

          .doc-sub-menu .nav-link:hover {
            color: #494d55;
            text-decoration: none;
            background: none;
          }

          .doc-sub-menu .nav-link:focus {
            background: none;
          }

          .doc-sub-menu .nav-link.active {
            background: none;
            color: #40babd;
          }

          .body-blue .doc-sub-menu .nav-link.active {
            color: #58bbee;
          }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

Adding and Managing Items
      <nav id="slide-submenu" class="doc-sub-menu nav flex-column collapse">
        <p>
          Medications
          Blood Sugars
          Pharmacies
          Physicians
          Family Members
          Appointments
          Medical Records
        </p>
      </nav></code>```

Title: Bootstrap 4 collapse nav group

Body:
I am working on a documentation site with Table of contents in a right hand column and the content in the left hand column. The TOC has several groups containing code similar to below. Is there any way to collapse and expand the sub-menu nav by clicking on the anchor tag? So that the sub menus are are all collapsed when page loads and then the user can expand and collapse as needed.

Orgbrat

.doc-sub-menu {
  list-style: none;
  padding-left: 0;
}

.doc-sub-menu .nav-link {
  margin-bottom: 10px;
  font-size: 12px;
  display: block;
  color: #616670;
  padding: 0;
  padding-left: 34px;
  background: none;
}

.doc-sub-menu .nav-link:first-child {
  padding-top: 5px;
}

.doc-sub-menu .nav-link:hover {
  color: #494d55;
  text-decoration: none;
  background: none;
}

.doc-sub-menu .nav-link:focus {
  background: none;
}

.doc-sub-menu .nav-link.active {
  background: none;
  color: #40babd;
}

.body-blue .doc-sub-menu .nav-link.active {
  color: #58bbee;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
Adding and Managing Items

  Medications
  Blood Sugars
  Pharmacies
  Physicians
  Family Members
  Appointments
  Medical Records

Body:
Yes you can use it default class (collapse) and data-toggle tag in Bootstrap 4. Please try below snippet :

.doc-sub-menu {
            list-style: none;
            padding-left: 0;
          }

          .doc-sub-menu .nav-link {
            margin-bottom: 10px;
            font-size: 12px;
            display: block;
            color: #616670;
            padding: 0;
            padding-left: 34px;
            background: none;
            cursor: pointer;
          }

          .doc-sub-menu .nav-link:first-child {
            padding-top: 5px;
          }

          .doc-sub-menu .nav-link:hover {
            color: #494d55;
            text-decoration: none;
            background: none;
          }

          .doc-sub-menu .nav-link:focus {
            background: none;
          }

          .doc-sub-menu .nav-link.active {
            background: none;
            color: #40babd;
          }

          .body-blue .doc-sub-menu .nav-link.active {
            color: #58bbee;
          }

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<a class="nav-link text-dark" asp-area="" asp-page="/UserGuide/Items" data-toggle="collapse" data-target="#slide-submenu">Adding and Managing Items</a>
      <nav id="slide-submenu" class="doc-sub-menu nav flex-column collapse">
        <p>
          <a class="nav-link scrollto" href="#html">Medications</a>
          <a class="nav-link scrollto" href="#css">Blood Sugars</a>
          <a class="nav-link scrollto" href="#sass">Pharmacies</a>
          <a class="nav-link scrollto" href="#less">Physicians</a>
          <a class="nav-link scrollto" href="#javascript">Family Members</a>
          <a class="nav-link scrollto" href="#python">Appointments</a>
          <a class="nav-link scrollto" href="#php">Medical Records</a>
        </p>
      </nav>