问:
How can I duplicate the Interrupt Vector Table using the linker script on a Cortex M0+?
First of all, I hope I'm not asking something that has already been asked before. I've searched as much as I can but I haven't found an answer to my specific problem or something useful.

I'm working on a FRDM-KL82Z board which runs a Cortex M0+ core. I'm using MCUXpresso IDE v10.0.2 and a Segger J-Link programmer, although I think this is not relevant for this question.

This project will need a custom bootloader and app coded by different developers, each block with its own flash memory space: 8K for the bootloader and 120K for the app (this may change in the future but it's no big deal at the moment).

Once the bootloader is completed, it will manage the jump to App space and the app will change de Vector Table Offset Register (VTOR) so that the Interrupt Vector Table changes form the Boot IVT to the App IVT. This has already been tested successfully.

My aim is to set up the linker script file so that the app developers can build and debug their project on the board before the bootloader is completed, as they will be developed at the same time. The reason for this is that they can work with the App space as it will be in the final version.

I think the Reset vector and the Config bits must be at their default position because the hardware will go to the same position every time it needs to read them.

My first idea consist in disabling the automatic linker script generation and modifying the MyProject_Debug.ld file.

What the script automatically generates:

```<code>INCLUDE "LEDTest_Debug_library.ld"
INCLUDE "LEDTest_Debug_memory.ld"

ENTRY(ResetISR)

SECTIONS
{
    /* MAIN TEXT SECTION */
    .text : ALIGN(4)
    {
        FILL(0xff)
    __vectors_start__ = ABSOLUTE(.) ;
    KEEP(*(.isr_vector))
    /* Global Section Table */
    . = ALIGN(4) ;
    __section_table_start = .;
    __data_section_table = .;
    LONG(LOADADDR(.data));
    LONG(    ADDR(.data));
    LONG(  SIZEOF(.data));
    LONG(LOADADDR(.data_RAM2));
    LONG(    ADDR(.data_RAM2));
    LONG(  SIZEOF(.data_RAM2));
    __data_section_table_end = .;
    __bss_section_table = .;
    LONG(    ADDR(.bss));
    LONG(  SIZEOF(.bss));
    LONG(    ADDR(.bss_RAM2));
    LONG(  SIZEOF(.bss_RAM2));
    __bss_section_table_end = .;
    __section_table_end = . ;
    /* End of Global Section Table */

    *(.after_vectors*)

    /* Kinetis Flash Configuration data */
    . = 0x400 ;
    PROVIDE(__FLASH_CONFIG_START__ = .) ;
    KEEP(*(.FlashConfig))
    PROVIDE(__FLASH_CONFIG_END__ = .) ;
    ASSERT(!(__FLASH_CONFIG_START__ == __FLASH_CONFIG_END__), "Linker Flash Config Support Enabled, but no .FlashConfig section provided within application");
    /* End of Kinetis Flash Configuration data */

    } >PROGRAM_FLASH

    .text : ALIGN(4)
    {
        *(.text*)
        *(.rodata .rodata.* .constdata .constdata.*)
        . = ALIGN(4);
    } > PROGRAM_FLASH
    /*
     * for exception handling/unwind - some Newlib functions (in common
     * with C++ and STDC++) use this.
     */
    .ARM.extab : ALIGN(4)
    {
        *(.ARM.extab* .gnu.linkonce.armextab.*)
    } > PROGRAM_FLASH
    __exidx_start = .;

    .ARM.exidx : ALIGN(4)
    {
        *(.ARM.exidx* .gnu.linkonce.armexidx.*)
    } > PROGRAM_FLASH
    __exidx_end = .;

    _etext = .;

    /* USB_RAM */
    .m_usb_data (NOLOAD) :
    {
        *(m_usb_bdt)
        *(m_usb_global)
    } > USB_RAM
    /* possible MTB section for USB_RAM */
    .mtb_buffer_RAM2 (NOLOAD) :
    {
        KEEP(*(.mtb.$RAM2*))
        KEEP(*(.mtb.$USB_RAM*))
    } > USB_RAM

    /* DATA section for USB_RAM */
    .data_RAM2 : ALIGN(4)
    {
         FILL(0xff)
        PROVIDE(__start_data_RAM2 = .) ;
        *(.ramfunc.$RAM2)
        *(.ramfunc.$USB_RAM)
        *(.data.$RAM2*)
        *(.data.$USB_RAM*)
        . = ALIGN(4) ;
        PROVIDE(__end_data_RAM2 = .) ;
     } > USB_RAM AT>PROGRAM_FLASH

    /* MAIN DATA SECTION */
        /* Default MTB section */
        .mtb_buffer_default (NOLOAD) :
        {
           KEEP(*(.mtb*))
        } > SRAM
    .uninit_RESERVED : ALIGN(4)
    {
        KEEP(*(.bss.$RESERVED*))
        . = ALIGN(4) ;
        _end_uninit_RESERVED = .;
    } > SRAM
    /* Main DATA section (SRAM) */
    .data : ALIGN(4)
    {
       FILL(0xff)
       _data = . ;
       *(vtable)
       *(.ramfunc*)
       *(.data*)
       . = ALIGN(4) ;
       _edata = . ;
    } > SRAM AT>PROGRAM_FLASH
    /* BSS section for USB_RAM */
    .bss_RAM2 : ALIGN(4)
    {
       PROVIDE(__start_bss_RAM2 = .) ;
       *(.bss.$RAM2*)
       *(.bss.$USB_RAM*)
       . = ALIGN (. != 0 ? 4 : 1) ; /* avoid empty segment */
       PROVIDE(__end_bss_RAM2 = .) ;
    } > USB_RAM
    /* MAIN BSS SECTION */
    .bss : ALIGN(4)
    {
        _bss = .;
        *(.bss*)
        *(COMMON)
        . = ALIGN(4) ;
        _ebss = .;
        PROVIDE(end = .);
    } > SRAM
    /* NOINIT section for USB_RAM */
     .noinit_RAM2 (NOLOAD) : ALIGN(4)
    {
       *(.noinit.$RAM2*)
       *(.noinit.$USB_RAM*)
       . = ALIGN(4) ;
    } > USB_RAM
    /* DEFAULT NOINIT SECTION */
    .noinit (NOLOAD): ALIGN(4)
    {
        _noinit = .;
        *(.noinit*)
         . = ALIGN(4) ;
        _end_noinit = .;
     } > SRAM
    .heap :  ALIGN(4)
    {
        _pvHeapStart = .;
        . += 0x1000;
        . = ALIGN(4);
        _pvHeapLimit = .;
    } > SRAM
       .heap2stackfill  :
    {
        . += 0x1000;
    } > SRAM
     .stack ORIGIN(SRAM) + LENGTH(SRAM) - 0x1000 - 0:  ALIGN(4)
    {
        _vStackBase = .;
        . = ALIGN(4);
        _vStackTop = . + 0x1000;
    } > SRAM
}
</code>```

I've tried to find information in this guide about de GNU linker but my ideas haven't worked so far.
What I've tried:

Setting the location counter to a different value after the Config Words and copying the ISR_vector code snipped before the text section:

```<code>...
/* End of Kinetis Flash Configuration data */

} >PROGRAM_FLASH

.text : ALIGN(4)
{
    /*  MODIFIED CODE   */

    . = 0x2000;     /*  First position of App code  */
     FILL(0xff)
    __vectors_start__ = ABSOLUTE(.) ;
    KEEP(*(.isr_vector))

    /*  END OF MODIFIED CODE    */

    *(.text*)
    *(.rodata .rodata.* .constdata .constdata.*)
     . = ALIGN(4);
} > PROGRAM_FLASH
...
</code>```

When I do this and I open the .hex file, the space between the Config Words (0x400) and the start of the App space (0x2000) is effectively empty (full of 0xFF) but the code after 0x2000 is nothing like the IVT table.

If I move location counter to 0x2000 before the IVT code lines it effectively moves the IVT adresses to the 0x2000 position. To do this, I move the Config Words part before the IVT part because de location counter can't move backwards.

I've tried creating a Bootloader section in the memory map, with the correct starting and length positions, and copying every line that by default gets placeD in the PROGRAM_FLASH section into a new one that goes to BOOTLOADER (the same code with ">BOOTLOADER" at the end). In this case de IVT only appears in the Boot space.

Is it possible that the linker script places de IVT only in the first place it is indicated and then ignores every other call? What am I doing wrong? Should I try another way to achieve this?

Thank you very much, I know it's quite a long!

答:
My experience with M4 application and bootloader shows that it is enough to set the Flash start at some offset address, and then in the application to initialize VTOR to this address.

From  linker script:

#

/* Specify the memory areas */

```<code>MEMORY
{
CLASSBRAM (rw)   : ORIGIN = 0x20000000, LENGTH = 0x80
/*RAM length = 192K - CLASSBRAM-length */
RAM (xrw)      : ORIGIN = 0x20000080, LENGTH = 0x2FF80
CCMRAM (rw)      : ORIGIN = 0x10000000, LENGTH = 64K
/* FLASH (rx)      : ORIGIN = 0x08000000, LENGTH = 512K */
FLASH (rx)      : ORIGIN = 0x08010000, LENGTH = 448K  /*in case of 64K for Bootloader*/
}

/* Define output sections */
SECTIONS
{
  /* The startup code goes first into FLASH */
  .isr_vector :
  {
    . = ALIGN(4);
    PROVIDE( _Rom_Start = . );
    KEEP(*(.isr_vector)) /* Startup code */
    . = ALIGN(4);
  } >FLASH
</code>```

.....

#

code:

```<code>extern const uint32_t _Rom_Start;
....
#define ROM_START ((uint32_t *)&_Rom_Start)
...
SCB->VTOR = (uint32_t)ROM_START;
</code>```

Body:
First of all, I hope I'm not asking something that has already been asked before. I've searched as much as I can but I haven't found an answer to my specific problem or something useful.

I'm working on a FRDM-KL82Z board which runs a Cortex M0+ core. I'm using MCUXpresso IDE v10.0.2 and a Segger J-Link programmer, although I think this is not relevant for this question.

This project will need a custom bootloader and app coded by different developers, each block with its own flash memory space: 8K for the bootloader and 120K for the app (this may change in the future but it's no big deal at the moment).

Once the bootloader is completed, it will manage the jump to App space and the app will change de Vector Table Offset Register (VTOR) so that the Interrupt Vector Table changes form the Boot IVT to the App IVT. This has already been tested successfully.

My aim is to set up the linker script file so that the app developers can build and debug their project on the board before the bootloader is completed, as they will be developed at the same time. The reason for this is that they can work with the App space as it will be in the final version.

I think the Reset vector and the Config bits must be at their default position because the hardware will go to the same position every time it needs to read them.

My first idea consist in disabling the automatic linker script generation and modifying the MyProject_Debug.ld file.

What the script automatically generates:

INCLUDE "LEDTest_Debug_library.ld"
INCLUDE "LEDTest_Debug_memory.ld"

ENTRY(ResetISR)

SECTIONS
{
    /* MAIN TEXT SECTION */
    .text : ALIGN(4)
    {
        FILL(0xff)
    __vectors_start__ = ABSOLUTE(.) ;
    KEEP(*(.isr_vector))
    /* Global Section Table */
    . = ALIGN(4) ;
    __section_table_start = .;
    __data_section_table = .;
    LONG(LOADADDR(.data));
    LONG(    ADDR(.data));
    LONG(  SIZEOF(.data));
    LONG(LOADADDR(.data_RAM2));
    LONG(    ADDR(.data_RAM2));
    LONG(  SIZEOF(.data_RAM2));
    __data_section_table_end = .;
    __bss_section_table = .;
    LONG(    ADDR(.bss));
    LONG(  SIZEOF(.bss));
    LONG(    ADDR(.bss_RAM2));
    LONG(  SIZEOF(.bss_RAM2));
    __bss_section_table_end = .;
    __section_table_end = . ;
    /* End of Global Section Table */

    *(.after_vectors*)

    /* Kinetis Flash Configuration data */
    . = 0x400 ;
    PROVIDE(__FLASH_CONFIG_START__ = .) ;
    KEEP(*(.FlashConfig))
    PROVIDE(__FLASH_CONFIG_END__ = .) ;
    ASSERT(!(__FLASH_CONFIG_START__ == __FLASH_CONFIG_END__), "Linker Flash Config Support Enabled, but no .FlashConfig section provided within application");
    /* End of Kinetis Flash Configuration data */

    } >PROGRAM_FLASH

    .text : ALIGN(4)
    {
        *(.text*)
        *(.rodata .rodata.* .constdata .constdata.*)
        . = ALIGN(4);
    } > PROGRAM_FLASH
    /*
     * for exception handling/unwind - some Newlib functions (in common
     * with C++ and STDC++) use this.
     */
    .ARM.extab : ALIGN(4)
    {
        *(.ARM.extab* .gnu.linkonce.armextab.*)
    } > PROGRAM_FLASH
    __exidx_start = .;

    .ARM.exidx : ALIGN(4)
    {
        *(.ARM.exidx* .gnu.linkonce.armexidx.*)
    } > PROGRAM_FLASH
    __exidx_end = .;

    _etext = .;

    /* USB_RAM */
    .m_usb_data (NOLOAD) :
    {
        *(m_usb_bdt)
        *(m_usb_global)
    } > USB_RAM
    /* possible MTB section for USB_RAM */
    .mtb_buffer_RAM2 (NOLOAD) :
    {
        KEEP(*(.mtb.$RAM2*))
        KEEP(*(.mtb.$USB_RAM*))
    } > USB_RAM

    /* DATA section for USB_RAM */
    .data_RAM2 : ALIGN(4)
    {
         FILL(0xff)
        PROVIDE(__start_data_RAM2 = .) ;
        *(.ramfunc.$RAM2)
        *(.ramfunc.$USB_RAM)
        *(.data.$RAM2*)
        *(.data.$USB_RAM*)
        . = ALIGN(4) ;
        PROVIDE(__end_data_RAM2 = .) ;
     } > USB_RAM AT>PROGRAM_FLASH

    /* MAIN DATA SECTION */
        /* Default MTB section */
        .mtb_buffer_default (NOLOAD) :
        {
           KEEP(*(.mtb*))
        } > SRAM
    .uninit_RESERVED : ALIGN(4)
    {
        KEEP(*(.bss.$RESERVED*))
        . = ALIGN(4) ;
        _end_uninit_RESERVED = .;
    } > SRAM
    /* Main DATA section (SRAM) */
    .data : ALIGN(4)
    {
       FILL(0xff)
       _data = . ;
       *(vtable)
       *(.ramfunc*)
       *(.data*)
       . = ALIGN(4) ;
       _edata = . ;
    } > SRAM AT>PROGRAM_FLASH
    /* BSS section for USB_RAM */
    .bss_RAM2 : ALIGN(4)
    {
       PROVIDE(__start_bss_RAM2 = .) ;
       *(.bss.$RAM2*)
       *(.bss.$USB_RAM*)
       . = ALIGN (. != 0 ? 4 : 1) ; /* avoid empty segment */
       PROVIDE(__end_bss_RAM2 = .) ;
    } > USB_RAM
    /* MAIN BSS SECTION */
    .bss : ALIGN(4)
    {
        _bss = .;
        *(.bss*)
        *(COMMON)
        . = ALIGN(4) ;
        _ebss = .;
        PROVIDE(end = .);
    } > SRAM
    /* NOINIT section for USB_RAM */
     .noinit_RAM2 (NOLOAD) : ALIGN(4)
    {
       *(.noinit.$RAM2*)
       *(.noinit.$USB_RAM*)
       . = ALIGN(4) ;
    } > USB_RAM
    /* DEFAULT NOINIT SECTION */
    .noinit (NOLOAD): ALIGN(4)
    {
        _noinit = .;
        *(.noinit*)
         . = ALIGN(4) ;
        _end_noinit = .;
     } > SRAM
    .heap :  ALIGN(4)
    {
        _pvHeapStart = .;
        . += 0x1000;
        . = ALIGN(4);
        _pvHeapLimit = .;
    } > SRAM
       .heap2stackfill  :
    {
        . += 0x1000;
    } > SRAM
     .stack ORIGIN(SRAM) + LENGTH(SRAM) - 0x1000 - 0:  ALIGN(4)
    {
        _vStackBase = .;
        . = ALIGN(4);
        _vStackTop = . + 0x1000;
    } > SRAM
}

I've tried to find information in this guide about de GNU linker but my ideas haven't worked so far.
What I've tried:

Setting the location counter to a different value after the Config Words and copying the ISR_vector code snipped before the text section:

...
/* End of Kinetis Flash Configuration data */

} >PROGRAM_FLASH

.text : ALIGN(4)
{
    /*  MODIFIED CODE   */

    . = 0x2000;     /*  First position of App code  */
     FILL(0xff)
    __vectors_start__ = ABSOLUTE(.) ;
    KEEP(*(.isr_vector))

    /*  END OF MODIFIED CODE    */

    *(.text*)
    *(.rodata .rodata.* .constdata .constdata.*)
     . = ALIGN(4);
} > PROGRAM_FLASH
...

When I do this and I open the .hex file, the space between the Config Words (0x400) and the start of the App space (0x2000) is effectively empty (full of 0xFF) but the code after 0x2000 is nothing like the IVT table.

If I move location counter to 0x2000 before the IVT code lines it effectively moves the IVT adresses to the 0x2000 position. To do this, I move the Config Words part before the IVT part because de location counter can't move backwards.

I've tried creating a Bootloader section in the memory map, with the correct starting and length positions, and copying every line that by default gets placeD in the PROGRAM_FLASH section into a new one that goes to BOOTLOADER (the same code with ">BOOTLOADER" at the end). In this case de IVT only appears in the Boot space.

Is it possible that the linker script places de IVT only in the first place it is indicated and then ignores every other call? What am I doing wrong? Should I try another way to achieve this?

Thank you very much, I know it's quite a long!

Body:
My experience with M4 application and bootloader shows that it is enough to set the Flash start at some offset address, and then in the application to initialize VTOR to this address.

From  linker script:

#

/* Specify the memory areas */

MEMORY
{
CLASSBRAM (rw)   : ORIGIN = 0x20000000, LENGTH = 0x80
/*RAM length = 192K - CLASSBRAM-length */
RAM (xrw)      : ORIGIN = 0x20000080, LENGTH = 0x2FF80
CCMRAM (rw)      : ORIGIN = 0x10000000, LENGTH = 64K
/* FLASH (rx)      : ORIGIN = 0x08000000, LENGTH = 512K */
FLASH (rx)      : ORIGIN = 0x08010000, LENGTH = 448K  /*in case of 64K for Bootloader*/
}

/* Define output sections */
SECTIONS
{
  /* The startup code goes first into FLASH */
  .isr_vector :
  {
    . = ALIGN(4);
    PROVIDE( _Rom_Start = . );
    KEEP(*(.isr_vector)) /* Startup code */
    . = ALIGN(4);
  } >FLASH

.....

#

code:

extern const uint32_t _Rom_Start;
....
#define ROM_START ((uint32_t *)&_Rom_Start)
...
SCB->VTOR = (uint32_t)ROM_START;


来源: stackexchange

问:
Can't link a stylesheet
I am building a web application and trying to link a stylesheet to my app. Here is my code

```<code><html>
    <head>
        <title>Bubble</title>
    </head>
    <link rel="stylesheet" href="./public/main.css">
<body>
</code>```

The app is located in the direct DrDenver/blog. The full style sheet is located in DrDenver/blog/public.

答:
I added this line to my app.js

```<code>app.use(express.static(__dirname +"/public"));
</code>```

And updated the code on my header.ejs to after moving the main.css to public/stylesheet directory.

```<code>link rel="stylesheet" href="/stylesheets/main.css"
</code>```

ContentLicense: CC BY-SA 3.0

Title: Can't link a stylesheet

Body:
I am building a web application and trying to link a stylesheet to my app. Here is my code

        <title>Bubble</title>

    <link rel="stylesheet" href="./public/main.css">

The app is located in the direct DrDenver/blog. The full style sheet is located in DrDenver/blog/public.

Body:
I added this line to my app.js

app.use(express.static(__dirname +"/public"));

And updated the code on my header.ejs to after moving the main.css to public/stylesheet directory.

link rel="stylesheet" href="/stylesheets/main.css"


问:
Is it possible to query an element in Firestore by key without knowing which collection it belongs to?
Using AngularFire2, Angular, Firebase Firestore, and one of my records models the relationship between a user and different types of objects.

```<code>/*
Represents a reaction that a user has towards some object in the system.
*/
export interface Reaction{

// The id of the user making that reaction
userId? : string;

// The id of the object that is being reacted to. Place, Org, List, Offer
objectId? : string;

}
</code>```

As you can see the only thing being stored is the key of an object and not its type or which collection it belongs to. I'm wondering how it would be possible at a later time, to query the reactions and then from there get the objects purely based on their key?

答: You must know the name of the collection (and possibly subcollection) of a document in order to obtain it.  There's no concept of a query that can get a document without knowledge of a collection.</p>

Body:
Using AngularFire2, Angular, Firebase Firestore, and one of my records models the relationship between a user and different types of objects.

/*
Represents a reaction that a user has towards some object in the system.
*/
export interface Reaction{

// The id of the user making that reaction
userId? : string;

// The id of the object that is being reacted to. Place, Org, List, Offer
objectId? : string;

}

As you can see the only thing being stored is the key of an object and not its type or which collection it belongs to. I'm wondering how it would be possible at a later time, to query the reactions and then from there get the objects purely based on their key?


问:
php: loop through json array
I have a json array:

```<code>[
    {
        "var1": "9",
        "var2": "16",
        "var3": "16"
    },
    {
        "var1": "8",
        "var2": "15",
        "var3": "15"
    }
]
</code>```

How can I loop through this array using php?

答:
Use json_decode to convert the JSON string to a PHP array, then use normal PHP array functions on it.

```<code>$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$data = json_decode($json);

var_dump($data[0]['var1']); // outputs '9'
</code>```

ContentLicense: CC BY-SA 2.5

Title: php: loop through json array

Body:
I have a json array:

[
    {
        "var1": "9",
        "var2": "16",
        "var3": "16"
    },
    {
        "var1": "8",
        "var2": "15",
        "var3": "15"
    }
]

How can I loop through this array using php?

Body:
Use json_decode to convert the JSON string to a PHP array, then use normal PHP array functions on it.

$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$data = json_decode($json);

var_dump($data[0]['var1']); // outputs '9'


问:
ACF multiple image sizes in repeater field
I want to use the repeater fields to display a block of content and images as a list. However, I don’t want to use one crop size for all images.

For example:

```<code>List item 1: Image size 1
List item 2: Image size 2
List item 3: Image size 2
List item 4: Image size 3
</code>```

Is this even possible?

The markup I am currently using is:

```<code><ul>

<?php while( have_rows('home-features') ): the_row();

    // vars
    $image = get_sub_field('image');
    $description = get_sub_field('description');
    $url = get_sub_field('url');

    ?>

    <li>

        <a href="<?php echo $url; ?>">
            <div>
                <h3><?php echo $description; ?></h3>
            </div>
        </a>

    </li>

<?php endwhile; ?>

</ul>
</code>```

答:
If you want to be able to assign a specific image size to each repeater element, why not just add another ACF sub-field in the repeater with a select for the image sizes?

Your new "Image Size" (image_size) Select sub-field Choices could go something like this:

```<code>thumbnail : Thumbnail
medium : Medium
medium_large : Medium Large
large : Large
full : Full Size
</code>```

You can substitute your own custom image sizes if you want above, as long as the value of each select item corresponds to the custom image size $name value (see codex for reference).

Then in your loop:

```<code><ul>

  <?php while( have_rows('home-features') ): the_row();

  // make sure the ACF return format is set to 'image array' on the image field
  $image = get_sub_field('image');

  // new select field described above
  $size = get_sub_field('image_size');

  // put the two together using the image array values
  $img_url = $image['sizes'][ $size ];

  $description = get_sub_field('description');
  $url = get_sub_field('url');

  ?>

  <li>

    <a href="<?php echo $url; ?>">
      <div>
        <img src="<?php echo $img_url; ?>">
        <h3><?php echo $description; ?></h3>
      </div>
    </a>

  </li>

  <?php endwhile; ?>

</ul>
</code>```

References

add_image_size

Post Thumbnails

ACF Image Field

Note:
I haven't tested this code so let me know if you have any trouble!

Body:
I want to use the repeater fields to display a block of content and images as a list. However, I don’t want to use one crop size for all images.

For example:

List item 1: Image size 1
List item 2: Image size 2
List item 3: Image size 2
List item 4: Image size 3

Is this even possible?

The markup I am currently using is:

<?php while( have_rows('home-features') ): the_row();

    // vars
    $image = get_sub_field('image');
    $description = get_sub_field('description');
    $url = get_sub_field('url');

    ?>

        <a href="<?php echo $url; ?>">

<?php echo $description; ?>

<?php endwhile; ?>

Body:
If you want to be able to assign a specific image size to each repeater element, why not just add another ACF sub-field in the repeater with a select for the image sizes?

Your new "Image Size" (image_size) Select sub-field Choices could go something like this:

thumbnail : Thumbnail
medium : Medium
medium_large : Medium Large
large : Large
full : Full Size

You can substitute your own custom image sizes if you want above, as long as the value of each select item corresponds to the custom image size $name value (see codex for reference).

Then in your loop:

<ul>

  <?php while( have_rows('home-features') ): the_row();

  // make sure the ACF return format is set to 'image array' on the image field
  $image = get_sub_field('image');

  // new select field described above
  $size = get_sub_field('image_size');

  // put the two together using the image array values
  $img_url = $image['sizes'][ $size ];

  $description = get_sub_field('description');
  $url = get_sub_field('url');

  ?>

  <li>

    <a href="<?php echo $url; ?>">
      <div>
        <img src="<?php echo $img_url; ?>">
        <h3><?php echo $description; ?></h3>
      </div>
    </a>

  </li>

  <?php endwhile; ?>

</ul>

References

add_image_size

Post Thumbnails

ACF Image Field

Note:
I haven't tested this code so let me know if you have any trouble!


问:
Web Scraping platform efficiency

Web scraping is efficient on windows or Ubuntu?

For scraping quotes from web which would be better scrapy or beautiful soap?

答:
Question1: Efficiency

This is very borad coverage question. Basically the efficiency depends on following criterias:

Computer Performance

Network Stability

Anti-antispider techniques

Extraction Method

Business purpose

Here are the way they affect your efficiency:

Computer Perfomace

If you are targeting big-ecommerce sites or if the site uses massive amount of javascript(like LinkedIn) then you should consider a moderate perfomace instance(computer) to finish your job. Note that if your computer memeory is too small, scrapy-splash's docker container will automatically stop and cause your spider to fail immediatly. Compared to Windows Home Edition, you'd better choose Ubuntu, because ubuntu uses less memory etc.. No matter which operation system you choose, Server-Edition is always better than Home-Edition.

Circumstance 1: (Using Scrapy® with Selenium Web Driver)

Example1: Linked-In Sales Navigator Spider

Example2: WeiFeng Spider with reCAPCHA crackted

Circumstance 2: (Using Scrapy with Scrapy-spalsh javascript rendering service)

Example1: INC5000 Spider

Network Stability

Network Stability counts when your instance(computer) is too far away from your targeting site. Your network speed and latency will directly affect your spider and sometimes causes disaster. Low network speed will slow down your request speed, while latency will sometimes cause your spider failed to load your target webpage. This will led to error in future content extraction. Your program may catch exceptions and quit immedialy and if you are not using modern spider framwork, the error page will not be re-fetched in the future, so you will lose some data. Compared to a home-network-spider, deploy a spider on public cloud is a better solution.

Some cloud VPS Provider that you can choose from: Link

You can use IP Location Detector to find the location of your target site: Link

Anti-antispider techniques

IP Rotation:

Method 1: Use Scrapy with Crawlera

Method 2: Proxy Pool

UA Rotation:

Scrapy with UA Rotation Framework

Download Delay:

Scrapy with Download Delay

Extraction Method

This is really a borad topic, You can use fast-performance-techniques to locate elements like xpaths, bs4, css.... while you can also use low-performance-techniques like Deep Learning or Search even regular expression

Beautiful Soup (aka bs4):

Intro-bs4

BeutifulSoup is not a good solution if you want to parse complicate website HTML. It does not support xpath or css selectors so that you will have to manually figure out the website's element hierarchic and result in some code likes this.

```<code>for level1 in bs_obj.find_all("div", {"id", "classname"})
    for level 2 in bs_obj.find_all("div", {"class", "classname"})
        for level3 in bs_obj.find_all("a", {"class", "classname"})
            for level4 ........
                ....
                    ....
</code>```

Xpath and CSS selectors:

Xpath tutorial by Oreilly

CSS tutorial by w3school

There is even a Xpath to CSS translator

Use Chrome Developer Mode to help you write xpath

Use Selector Gadget to automatically generate xpaths

Regular Expression (aka re):

This is a good way to extract content with a specified string pattern but it is slower than others.

Regular Expression Tutorial

Scrapy is integrated with xpath, css, re through parsel, you can check this tutorial to lean how to use them within scrapy

Question 2: Scrapy vs bs4 for scraping quotes from web

Scrapy is a scraping framwork while bs4 is a content extracting framework, so the answer is you can use BeautifulSoup in Scrapy.

There is also some User Friendly Scraping software

7 Tools for web scraping

Even scrapy company (scrapinghub) is developing their own open source H5 based scraper: Portia

Title: Web Scraping platform efficiency

Body:
Question1: Efficiency

This is very borad coverage question. Basically the efficiency depends on following criterias:

Computer Performance

Network Stability

Anti-antispider techniques

Extraction Method

Business purpose

Here are the way they affect your efficiency:

Computer Perfomace

If you are targeting big-ecommerce sites or if the site uses massive amount of javascript(like LinkedIn) then you should consider a moderate perfomace instance(computer) to finish your job. Note that if your computer memeory is too small, scrapy-splash's docker container will automatically stop and cause your spider to fail immediatly. Compared to Windows Home Edition, you'd better choose Ubuntu, because ubuntu uses less memory etc.. No matter which operation system you choose, Server-Edition is always better than Home-Edition.

Circumstance 1: (Using Scrapy® with Selenium Web Driver)

Example1: Linked-In Sales Navigator Spider

Example2: WeiFeng Spider with reCAPCHA crackted

Circumstance 2: (Using Scrapy with Scrapy-spalsh javascript rendering service)

Example1: INC5000 Spider

Network Stability

Network Stability counts when your instance(computer) is too far away from your targeting site. Your network speed and latency will directly affect your spider and sometimes causes disaster. Low network speed will slow down your request speed, while latency will sometimes cause your spider failed to load your target webpage. This will led to error in future content extraction. Your program may catch exceptions and quit immedialy and if you are not using modern spider framwork, the error page will not be re-fetched in the future, so you will lose some data. Compared to a home-network-spider, deploy a spider on public cloud is a better solution.

Some cloud VPS Provider that you can choose from: Link

You can use IP Location Detector to find the location of your target site: Link

Anti-antispider techniques

IP Rotation:

Method 1: Use Scrapy with Crawlera

Method 2: Proxy Pool

UA Rotation:

Scrapy with UA Rotation Framework

Download Delay:

Scrapy with Download Delay

Extraction Method

This is really a borad topic, You can use fast-performance-techniques to locate elements like xpaths, bs4, css.... while you can also use low-performance-techniques like Deep Learning or Search even regular expression

Beautiful Soup (aka bs4):

Intro-bs4

BeutifulSoup is not a good solution if you want to parse complicate website HTML. It does not support xpath or css selectors so that you will have to manually figure out the website's element hierarchic and result in some code likes this.

for level1 in bs_obj.find_all("div", {"id", "classname"})
    for level 2 in bs_obj.find_all("div", {"class", "classname"})
        for level3 in bs_obj.find_all("a", {"class", "classname"})
            for level4 ........
                ....
                    ....

Xpath and CSS selectors:

Xpath tutorial by Oreilly

CSS tutorial by w3school

There is even a Xpath to CSS translator

Use Chrome Developer Mode to help you write xpath

Use Selector Gadget to automatically generate xpaths

Regular Expression (aka re):

This is a good way to extract content with a specified string pattern but it is slower than others.

Regular Expression Tutorial

Scrapy is integrated with xpath, css, re through parsel, you can check this tutorial to lean how to use them within scrapy

Question 2: Scrapy vs bs4 for scraping quotes from web

Scrapy is a scraping framwork while bs4 is a content extracting framework, so the answer is you can use BeautifulSoup in Scrapy.

There is also some User Friendly Scraping software

7 Tools for web scraping

Even scrapy company (scrapinghub) is developing their own open source H5 based scraper: Portia


问:
Add a generic file in xv6 makefile
I'm currently studying the xv6 OS.
I found out here how to add a system call by modifying the MAKEFILE file.
My question is: how do we add simple text files or any other kind of file to be seen in the xv6 system once it boots?</p>

答:
README file in Xv6 is a generic file too. Searching for occurrences of README in the MakeFile and adding your required file will be sufficient.

Suppose new.txt is the file you want to add.

Parts of the MakeFile to be changed are:

1)

```<code>fs.img: mkfs README new.txt $(UPROGS)
./mkfs fs.img README new.txt $(UPROGS)
</code>```

2)

```<code>PRINT = runoff.list runoff.spec README new.txt toc.hdr toc.ftr $(FILES)
</code>```

3)

```<code>EXTRA=\
mkfs.c ulib.c user.h cat.c echo.c forktest.c grep.c kill.c\
ln.c ls.c mkdir.c rm.c stressfs.c usertests.c wc.c zombie.c\
printf.c umalloc.c\
README new.txt dot-bochsrc *.pl toc.* runoff runoff1 runoff.list\
.gdbinit.tmpl gdbutil\
</code>```

Title: Add a generic file in xv6 makefile

Body:
README file in Xv6 is a generic file too. Searching for occurrences of README in the MakeFile and adding your required file will be sufficient.

Suppose new.txt is the file you want to add.

Parts of the MakeFile to be changed are:

1)

fs.img: mkfs README new.txt $(UPROGS)
./mkfs fs.img README new.txt $(UPROGS)

2)

PRINT = runoff.list runoff.spec README new.txt toc.hdr toc.ftr $(FILES)

3)

EXTRA=\
mkfs.c ulib.c user.h cat.c echo.c forktest.c grep.c kill.c\
ln.c ls.c mkdir.c rm.c stressfs.c usertests.c wc.c zombie.c\
printf.c umalloc.c\
README new.txt dot-bochsrc *.pl toc.* runoff runoff1 runoff.list\
.gdbinit.tmpl gdbutil\


问:
jQuery wait for Ajax request until it's done doesn't work
I have a formular, when I press a button I have to handle a async Ajax request. The function nextButtonHandler() should be called after all processes from requestForTariff() are finished. I tried touse the following, but it didn't wait until the request processing is over.

```<code>$.when(requestForTariff(requestType.Street)).done(function(){
    nextButtonHandler()
});
</code>```

Here is my Ajax function:

```<code>function requestForTariff(requestParam) {
    $.ajax({
        type: 'POST',
        url: //...,
        data: getRequestJSON(requestParam),
        success: function(data, status) {
            if (status == "success") {
                if (requestParam == requestType.Street) {
                    handleResult(data);
                }
                //...
            }
        },
        contentType: "application/json",
        dataType: 'json',
        error: // ...
    });
</code>```

答:
Thanks to Adreas comment, changing my requestForTariff() function to

```<code>function requestForTariff(requestParam) {
    return $.ajax({
        type: 'POST',
        url: //...,
        data: getRequestJSON(requestParam),
        success: function(data, status) {
            if (status == "success") {
                if (requestParam == requestType.Street) {
                    handleResult(data);
                }
                //...
            }
        },
        contentType: "application/json",
        dataType: 'json',
        error: // ...
    });
</code>```

solved my problem.

Body:
I have a formular, when I press a button I have to handle a async Ajax request. The function nextButtonHandler() should be called after all processes from requestForTariff() are finished. I tried touse the following, but it didn't wait until the request processing is over.

$.when(requestForTariff(requestType.Street)).done(function(){
    nextButtonHandler()
});

Here is my Ajax function:

function requestForTariff(requestParam) {
    $.ajax({
        type: 'POST',
        url: //...,
        data: getRequestJSON(requestParam),
        success: function(data, status) {
            if (status == "success") {
                if (requestParam == requestType.Street) {
                    handleResult(data);
                }
                //...
            }
        },
        contentType: "application/json",
        dataType: 'json',
        error: // ...
    });

Body:
Thanks to Adreas comment, changing my requestForTariff() function to

function requestForTariff(requestParam) {
    return $.ajax({
        type: 'POST',
        url: //...,
        data: getRequestJSON(requestParam),
        success: function(data, status) {
            if (status == "success") {
                if (requestParam == requestType.Street) {
                    handleResult(data);
                }
                //...
            }
        },
        contentType: "application/json",
        dataType: 'json',
        error: // ...
    });

solved my problem.


问:
Superimposing the text from input form on top of an image
I want the text that I write on the input to be shown inside the "engrave-image" div. For some reason, I cannot get it to work. I appreciate your help.

function annotate(obj) {
  var typed = document.getElementById(obj).value;
  document.getElementById("engrave-image").innerHTML = typed;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="engrave-text" maxlength="15" onkeyup="count_up(this)" onkeyup="annotate(this);">
<div id="engrave-image"></div></code>```

答:
You can use obj directly to reference the input that called then onkeyup event. obj passed in is a reference to an element (an input element in this case) and not an id, so using document.getElementById(obj); doesn't make sense here.

Also you should have quotes around the id attribute in your input.

function annotate(obj) {
  var typed = obj.value;
  document.getElementById("engrave-image").innerHTML = typed;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="engrave-text" maxlength="15" onkeyup="annotate(this);">
<div id="engrave-image"></div></code>```

Body:
I want the text that I write on the input to be shown inside the "engrave-image" div. For some reason, I cannot get it to work. I appreciate your help.

function annotate(obj) {
  var typed = document.getElementById(obj).value;
  document.getElementById("engrave-image").innerHTML = typed;
}

<input id="engrave-text" maxlength="15" onkeyup="count_up(this)" onkeyup="annotate(this);">

Body:
You can use obj directly to reference the input that called then onkeyup event. obj passed in is a reference to an element (an input element in this case) and not an id, so using document.getElementById(obj); doesn't make sense here.

Also you should have quotes around the id attribute in your input.

function annotate(obj) {
  var typed = obj.value;
  document.getElementById("engrave-image").innerHTML = typed;
}

<input id="engrave-text" maxlength="15" onkeyup="annotate(this);">
<div id="engrave-image"></div>


问:
laravel eloquent resources api send status code
In Laravel 5.5 We can set API through resources (https://laracasts.com/series/whats-new-in-laravel-5-5/episodes/20), but how can we send STATUS CODE?

Also how should I set status dynamically which is defined in with()

```<code>//namespace App\Http\Resources;

//use Illuminate\Http\Resources\Json\Resource;

//class User extends Resource

public function with($request)
{
    return [
        'status' => 'success',
    ];
}
</code>```

答:
try this:

```<code>namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

class User extends Resource{

  public function toArray($request)
  {
               return[
                   'name' => $this->username,
                   'email'=> $this->email
               ];
  }

  public function with($request){
      return [
        'status'=>'success'
      ];
  }

}
</code>```

At Controller:

```<code>$resource = new UserResource($user);
return $resource->response()->setStatusCode(200);
</code>```

Body:
In Laravel 5.5 We can set API through resources (https://laracasts.com/series/whats-new-in-laravel-5-5/episodes/20), but how can we send STATUS CODE?

Also how should I set status dynamically which is defined in with()

//namespace App\Http\Resources;

//use Illuminate\Http\Resources\Json\Resource;

//class User extends Resource

public function with($request)
{
    return [
        'status' => 'success',
    ];
}

Body:
try this:

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

class User extends Resource{

  public function toArray($request)
  {
               return[
                   'name' => $this->username,
                   'email'=> $this->email
               ];
  }

  public function with($request){
      return [
        'status'=>'success'
      ];
  }

}

At Controller:

$resource = new UserResource($user);
return $resource->response()->setStatusCode(200);


问:
Reflection.TargetException problem
I want the EmployeeNumber property for an Employee to only be set by the database, but I need to be able to set the value for unit testing. Which is why I made the helper code below.

Can someone help me troubleshoot & fix this?

Cheers,

Berryl

Helper Code

```<code>public static void SetEmployeeNumberFor(Employee employee, EmployeeNumber employeeNumber)
    {
        var empNumberProperty = employee.GetType().GetProperty("EmployeeNumber", BindingFlags.Public | BindingFlags.Instance);

        Check.Invariant(empNumberProperty != null);
        Check.Invariant(empNumberProperty.PropertyType.Equals(typeof(EmployeeNumber)));

        empNumberProperty.SetValue(empNumberProperty, employeeNumber, null);
    }
</code>```

Full Exception

```<code>System.Reflection.TargetException : Object does not match target type.
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index)
TestableEmployee.cs(36,0): at Smack.ConstructionAdmin.TestingSupport.ResourceHelper.SetEmployeeNumberFor(Employee employee, EmployeeNumber employeeNumber)
TestableEmployee.cs(47,0): at Smack.ConstructionAdmin.TestingSupport.ResourceHelperTests.SetEmployeeNumberFor()
</code>```

EmployeeNumber property code

```<code>    public virtual EmployeeNumber EmployeeNumber {
        get { return _employeeNumber; }
        protected set {
            _employeeNumber = value;
            //base.BusinessId = _employeeNumber;
        }
    }
    private EmployeeNumber _employeeNumber;
</code>```

答:
```<code>empNumberProperty.SetValue(empNumberProperty, employeeNumber, null);
</code>```

<p>Should be </p>

```<code> empNumberProperty.SetValue(employee, employeeNumber, null);
</code>```

Title: Reflection.TargetException problem

Body:
I want the EmployeeNumber property for an Employee to only be set by the database, but I need to be able to set the value for unit testing. Which is why I made the helper code below.

Can someone help me troubleshoot & fix this?

Cheers,

Berryl

Helper Code

public static void SetEmployeeNumberFor(Employee employee, EmployeeNumber employeeNumber)
    {
        var empNumberProperty = employee.GetType().GetProperty("EmployeeNumber", BindingFlags.Public | BindingFlags.Instance);

        Check.Invariant(empNumberProperty != null);
        Check.Invariant(empNumberProperty.PropertyType.Equals(typeof(EmployeeNumber)));

        empNumberProperty.SetValue(empNumberProperty, employeeNumber, null);
    }

Full Exception

System.Reflection.TargetException : Object does not match target type.
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index)
TestableEmployee.cs(36,0): at Smack.ConstructionAdmin.TestingSupport.ResourceHelper.SetEmployeeNumberFor(Employee employee, EmployeeNumber employeeNumber)
TestableEmployee.cs(47,0): at Smack.ConstructionAdmin.TestingSupport.ResourceHelperTests.SetEmployeeNumberFor()

EmployeeNumber property code

    public virtual EmployeeNumber EmployeeNumber {
        get { return _employeeNumber; }
        protected set {
            _employeeNumber = value;
            //base.BusinessId = _employeeNumber;
        }
    }
    private EmployeeNumber _employeeNumber;

Body:
empNumberProperty.SetValue(empNumberProperty, employeeNumber, null);

Should be

 empNumberProperty.SetValue(employee, employeeNumber, null);


问:
Half transparent circle in another half circle
I have to make such contruction like this one on the picture. There is a bubble with some fancy ending and I don't know, how to make this half transparent circle inside it.
How can I do that?
I have some image as a background.

.bubble {
  background-color: #34bc74;
  border-top-right-radius: 0;
  border-radius: 10px;
  line-height: 18px;
  margin: 100px 0 0 0;
  padding: 15px 65px 25px 15px;
  position: relative;
  width: 200px;
}

.circle {
  background-color: #34bc74;
  border-bottom-right-radius: 140px;
  border-top-right-radius: 140px;
  border-left-color: transparent;
  width: 70px;
  height: 140px;
  position: absolute;
  z-index: 1;
  top: -70px;
  right: -70px;
  overflow: hidden;
}
.circle:after {
    height: 70px;
    width: 35px;
    left: -35px;
    z-index: 2;
    content: '';
    border-radius: 70px;
    position: absolute;
    // border: 35px solid $green;
    // box-shadow: 0px 300px 0px 300px #448CCB;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bubble">
  Donec viverra sodales imperdiet. Aliquam eget ante nec nulla hendrerit dignissim sit amet id Donec viverra sodales imperdiet. Aliquam eget ante nec nulla hendrerit dignissim sit amet id
  <div class="circle"></div>
</div></code>```

答:
Using a combination of pseudo-elements and box-shadow properties you can get close to the intended result.

Experiment and adjust height, width, and box-shadow values as required.

.bubble {
  background-color: #34bc74;
  border-top-right-radius: 0;
  border-radius: 10px;
  line-height: 18px;
  margin: 100px 0 0 0;
  padding: 15px 65px 25px 15px;
  position: relative;
  width: 200px;
}

.circle {
  width: 155px;
  height: 140px;
  border-radius: 100%;
  position: absolute;
  top: -70px;
  right: -45px;
  overflow: hidden;
  z-index: -1;
}

.circle:after {
  content: "";
  width: 112px;
  height: 87px;
  border-radius: 100%;
  box-shadow: 55px -15px 0 0 #34bc74;
  position: absolute;
  z-index: 9;
  overflow: hidden;
}

.circle:before {
  content: "";
  width: 112px;
  height: 88px;
  border-radius: 100%;
  box-shadow: 72px 52px 0 0 #34bc74;
  position: absolute;
  z-index: 9;
  overflow: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bubble">
  Donec viverra sodales imperdiet. Aliquam eget ante nec nulla hendrerit dignissim sit amet id Donec viverra sodales imperdiet. Aliquam eget ante nec nulla hendrerit dignissim sit amet id
  <div class="circle"></div>
</div></code>```

Body:
I have to make such contruction like this one on the picture. There is a bubble with some fancy ending and I don't know, how to make this half transparent circle inside it.
How can I do that?
I have some image as a background.

.bubble {
  background-color: #34bc74;
  border-top-right-radius: 0;
  border-radius: 10px;
  line-height: 18px;
  margin: 100px 0 0 0;
  padding: 15px 65px 25px 15px;
  position: relative;
  width: 200px;
}

.circle {
  background-color: #34bc74;
  border-bottom-right-radius: 140px;
  border-top-right-radius: 140px;
  border-left-color: transparent;
  width: 70px;
  height: 140px;
  position: absolute;
  z-index: 1;
  top: -70px;
  right: -70px;
  overflow: hidden;
}
.circle:after {
    height: 70px;
    width: 35px;
    left: -35px;
    z-index: 2;
    content: '';
    border-radius: 70px;
    position: absolute;
    // border: 35px solid $green;
    // box-shadow: 0px 300px 0px 300px #448CCB;
  }

  Donec viverra sodales imperdiet. Aliquam eget ante nec nulla hendrerit dignissim sit amet id Donec viverra sodales imperdiet. Aliquam eget ante nec nulla hendrerit dignissim sit amet id

Body:
Using a combination of pseudo-elements and box-shadow properties you can get close to the intended result.

Experiment and adjust height, width, and box-shadow values as required.

.bubble {
  background-color: #34bc74;
  border-top-right-radius: 0;
  border-radius: 10px;
  line-height: 18px;
  margin: 100px 0 0 0;
  padding: 15px 65px 25px 15px;
  position: relative;
  width: 200px;
}

.circle {
  width: 155px;
  height: 140px;
  border-radius: 100%;
  position: absolute;
  top: -70px;
  right: -45px;
  overflow: hidden;
  z-index: -1;
}

.circle:after {
  content: "";
  width: 112px;
  height: 87px;
  border-radius: 100%;
  box-shadow: 55px -15px 0 0 #34bc74;
  position: absolute;
  z-index: 9;
  overflow: hidden;
}

.circle:before {
  content: "";
  width: 112px;
  height: 88px;
  border-radius: 100%;
  box-shadow: 72px 52px 0 0 #34bc74;
  position: absolute;
  z-index: 9;
  overflow: hidden;
}

<div class="bubble">
  Donec viverra sodales imperdiet. Aliquam eget ante nec nulla hendrerit dignissim sit amet id Donec viverra sodales imperdiet. Aliquam eget ante nec nulla hendrerit dignissim sit amet id
  <div class="circle"></div>
</div>


问:
Comparing a value between two arrays and passing back
I have two tables that have an identical column structure where the information passed from a different department is put into the first template.

I want to look at the SKU from Table 1 and pass back everything that matches on that row in Table 2 - whilst ignoring any SKU code that is not on Table 1.

Graphical illustration of problem

The code is part of a larger sub (variables are declared prior etc.) which uses a scripting dictionary and then goes through a For loop - but this is not efficient:

    Set dlCD1 = CreateObject("Scripting.Dictionary")
    Row = 1
    On Error GoTo Error
    For Each cCD1 In Sheets("TABLE 2 SHEET").Range("c1:c" & MaxLineMPS)
        tmpCD1 = Trim(cCD1.Value)
        If Len(tmpCD1) < 10 Then tmpCD1 = "0" & tmpCD1
        If Len(tmpCD1) > 0 Then dlCD1(tmpCD1) = dlCD1(tmpCD1) + 1
    Next cCD1

    For Each kCD1 In dlCD1.keys

        With Sheets("TABLE 1 SHEET").Range("a2:x" & MaxLineMatrice)
            .AutoFilter Field:=3, Criteria1:=kCD1
        End With

        If Sheets("TABLE 1 SHEET").Range("A2:A" & MaxLineMatrice).SpecialCells(xlCellTypeVisible).Count > 1 Then
            With Sheets("TABLE 1 SHEET").Range("d$3:x" & "$" & MaxLineMatrice).SpecialCells(xlCellTypeVisible)
                .Value = Sheets("TABLE 2 SHEET").Range("$d" & "$" & Row & ":$x" & "$" & Row).Value
            End With
        Else: End If

        Row = Row + 1
        Debug.Print kCD1, dlCD1(kCD1)
    Next kCD1

    Worksheets("TABLE 1 SHEET").AutoFilterMode = False
    dlCD1.RemoveAll
```
<p>I have thousands of SKU codes and this takes time to loop through. I am told that by doing this outside of the sheet I can do the job faster.</p>
<p>Here's my whole code:</p>
<pre class="lang-vb prettyprint-override"><code>Sub Month_RiempiFuturo()
    Dim MinLineMatrice As Integer, MaxLineMatrice As Integer, MinLineMPS As Integer, MaxLineMPS As Integer, row As Integer
    Dim dlCD1 As Object, cCD1 As Range, kCD1, tmpCD1 As String, dlCD2 As Object, cCD2 As Range, kCD2, tmpCD2 As String
    Dim StartTime As Double, SecondsElapsed As Double
    Dim PT1 As PivotTable
    Application.EnableEvents = False
    Application.DisplayStatusBar = False
    Application.ScreenUpdating = False
    ActiveSheet.DisplayPageBreaks = False
    Application.Calculation = xlCalculationManual
    Worksheets("TABLE SHEET 1").AutoFilterMode = False
    Worksheets("TABLE SHEET 2").AutoFilterMode = False
    StartTime = Timer
    MinLineMatrice = 3
    MaxLineMatrice = Sheets("TABLE SHEET 1").Range("A" & Rows.Count).End(xlUp).Row
    MinLineMPS = 1
    MaxLineMPS = Sheets("TABLE SHEET 2").Range("C" & Rows.Count).End(xlUp).Row
    LastLineFINITY = Sheets("FINITY CAPACITY PLANNED").Range("A" & Rows.Count).End(xlUp).Row
    Set PT1 = Worksheets("shift").PivotTables("Tabella_pivot1")
    Worksheets("TABLE SHEET 1").Range("d3:x" & MaxLineMatrice).ClearContents
    Set dlCD1 = CreateObject("Scripting.Dictionary")
    Row = 1
    On Error GoTo Error
    For Each cCD1 In Sheets("TABLE SHEET 2").Range("c1:c" & MaxLineMPS)
        tmpCD1 = Trim(cCD1.Value)
        If Len(tmpCD1) < 10 Then tmpCD1 = "0" & tmpCD1
        If Len(tmpCD1) > 0 Then dlCD1(tmpCD1) = dlCD1(tmpCD1) + 1
    Next cCD1
    For Each kCD1 In dlCD1.keys
        With Worksheets("TABLE SHEET 1").Range("a2:x" & MaxLineMatrice)
            .AutoFilter Field:=3, Criteria1:=kCD1
        End With
        If Sheets("TABLE SHEET 1").Range("A2:A" & MaxLineMatrice).SpecialCells(xlCellTypeVisible).Count > 1 Then
            With Sheets("TABLE SHEET 1").Range("d$3:x" & "$" & MaxLineMatrice).SpecialCells(xlCellTypeVisible)
                .Value = Sheets("TABLE SHEET 2").Range("$d" & "$" & Row & ":$x" & "$" & Row).Value
            End With
        Else: End If
        Row = Row + 1
        Debug.Print kCD1, dlCD1(kCD1)
    Next kCD1
    Worksheets("TABLE SHEET 1").AutoFilterMode = False
    dlCD1.RemoveAll
    Set dlCD1 = CreateObject("Scripting.Dictionary")
    For Each cCD1 In Sheets("Finity capacity planned").Range("a2:a" & LastLineFINITY)
        tmpCD1 = Trim(cCD1.Value)
        If Len(tmpCD1) > 0 Then dlCD1(tmpCD1) = dlCD1(tmpCD1) + 1
    Next cCD1
    Set dlCD2 = CreateObject("Scripting.Dictionary")
    For Each cCD2 In Sheets("Finity capacity planned").Range("b2:b" & LastLineFINITY)
        tmpCD2 = Trim(cCD2.Value)
        If Len(tmpCD2) > 0 Then dlCD2(tmpCD2) = dlCD2(tmpCD2) + 1
    Next cCD2
    For Each kCD1 In dlCD1.keys
        With Sheets("Finity capacity planned").Range("A1:Ak" & LastLineFINITY)
            .AutoFilter Field:=1, Criteria1:=kCD1
            .AutoFilter Field:=2, Criteria1:=Array( _
              dlCD2.keys()(0), dlCD2.keys()(2), dlCD2.keys()(4), dlCD2.keys()(6), dlCD2.keys()(8), dlCD2.keys()(10)), Operator:=xlFilterValues
        End With
        With Sheets("Finity capacity planned").Range("A2:Ak" & LastLineFINITY).SpecialCells(xlCellTypeVisible)
            .Interior.ColorIndex = 15
        End With
        With Sheets("Finity capacity planned").Range("A1:Ak" & LastLineFINITY)
            .AutoFilter Field:=1, Criteria1:=kCD1
            .AutoFilter Field:=2, Criteria1:=Array( _
              dlCD2.keys()(1), dlCD2.keys()(3), dlCD2.keys()(5), dlCD2.keys()(7), dlCD2.keys()(9), dlCD2.keys()(11)), Operator:=xlFilterValues
        End With
        With Sheets("Finity capacity planned").Range("A2:Ak" & LastLineFINITY).SpecialCells(xlCellTypeVisible)
            .Interior.ColorIndex = 19
        End With
        Debug.Print kCD1, dlCD1(kCD1)
    Next kCD1
    Worksheets("Finity capacity planned").AutoFilterMode = False
    dlCD1.RemoveAll
    dlCD2.RemoveAll
    With PT1
        .RefreshTable
    End With
    Application.EnableEvents = True
    Application.DisplayStatusBar = True
    Application.ScreenUpdating = True
    ActiveSheet.DisplayPageBreaks = True
    Application.Calculation = xlCalculationAutomatic
    SecondsElapsed = Round(Timer - StartTime, 2)
    MsgBox "This code including the time for user prompts to be acknowledged took " & SecondsElapsed & " Seconds", vbInformation, "McManus automation speed testing"
    Exit Sub
Error:
    Application.EnableEvents = True
    Application.DisplayStatusBar = True
    Application.ScreenUpdating = True
    ActiveSheet.DisplayPageBreaks = True
    Application.Calculation = xlCalculationAutomatic
    MsgBox "Something went wrong"
End Sub
</code>```

答:
You can use Find function to find the row number you are looking for. Then using this row number, you can have the data from that row.

I didn't dig into your code too much, because it is a bit messy. So considering that:

Blank Lookup sheet name is "TABLE 1 SHEET",

Master Lookup sheet name is "TABLE 2 SHEET",

Results sheet name is "TABLE 3 SHEET",

then you can try the following:

```<code>Sub findmydata()
Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet
Dim i As Long, j As Long, foundrow As Long, lastrow1 As Long, lastrow2 As Long

Set ws1 = Sheets("TABLE 1 SHEET")
Set ws2 = Sheets("TABLE 2 SHEET")
Set ws3 = Sheets("TABLE 3 SHEET")

lastrow1 = ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row
lastrow2 = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row

For i = 1 To lastrow1
    On Error Resume Next
    foundrow = ws2.Range("A1:A" & lastrow2).Find(ws1.Cells(i, 1).Value).Row
    If Err.Number = 91 Then
        ws3.Cells(i, 1) = ws1.Cells(i, 1)
    Else
        For j = 1 To 4
            ws3.Cells(i, j) = ws2.Cells(foundrow, j)
        Next j
    End If
Next
End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two tables that have an identical column structure where the information passed from a different department is put into the first template.

I want to look at the SKU from Table 1 and pass back everything that matches on that row in Table 2 - whilst ignoring any SKU code that is not on Table 1.

Graphical illustration of problem

The code is part of a larger sub (variables are declared prior etc.) which uses a scripting dictionary and then goes through a For loop - but this is not efficient:

    Set dlCD1 = CreateObject("Scripting.Dictionary")
    Row = 1
    On Error GoTo Error
    For Each cCD1 In Sheets("TABLE 2 SHEET").Range("c1:c" & MaxLineMPS)
        tmpCD1 = Trim(cCD1.Value)
        If Len(tmpCD1) < 10 Then tmpCD1 = "0" & tmpCD1
        If Len(tmpCD1) > 0 Then dlCD1(tmpCD1) = dlCD1(tmpCD1) + 1
    Next cCD1

    For Each kCD1 In dlCD1.keys

        With Sheets("TABLE 1 SHEET").Range("a2:x" & MaxLineMatrice)
            .AutoFilter Field:=3, Criteria1:=kCD1
        End With

        If Sheets("TABLE 1 SHEET").Range("A2:A" & MaxLineMatrice).SpecialCells(xlCellTypeVisible).Count > 1 Then
            With Sheets("TABLE 1 SHEET").Range("d$3:x" & "$" & MaxLineMatrice).SpecialCells(xlCellTypeVisible)
                .Value = Sheets("TABLE 2 SHEET").Range("$d" & "$" & Row & ":$x" & "$" & Row).Value
            End With
        Else: End If

        Row = Row + 1
        Debug.Print kCD1, dlCD1(kCD1)
    Next kCD1

    Worksheets("TABLE 1 SHEET").AutoFilterMode = False
    dlCD1.RemoveAll

I have thousands of SKU codes and this takes time to loop through. I am told that by doing this outside of the sheet I can do the job faster.

Here's my whole code:

Sub Month_RiempiFuturo()
    Dim MinLineMatrice As Integer, MaxLineMatrice As Integer, MinLineMPS As Integer, MaxLineMPS As Integer, row As Integer
    Dim dlCD1 As Object, cCD1 As Range, kCD1, tmpCD1 As String, dlCD2 As Object, cCD2 As Range, kCD2, tmpCD2 As String
    Dim StartTime As Double, SecondsElapsed As Double
    Dim PT1 As PivotTable
    Application.EnableEvents = False
    Application.DisplayStatusBar = False
    Application.ScreenUpdating = False
    ActiveSheet.DisplayPageBreaks = False
    Application.Calculation = xlCalculationManual
    Worksheets("TABLE SHEET 1").AutoFilterMode = False
    Worksheets("TABLE SHEET 2").AutoFilterMode = False
    StartTime = Timer
    MinLineMatrice = 3
    MaxLineMatrice = Sheets("TABLE SHEET 1").Range("A" & Rows.Count).End(xlUp).Row
    MinLineMPS = 1
    MaxLineMPS = Sheets("TABLE SHEET 2").Range("C" & Rows.Count).End(xlUp).Row
    LastLineFINITY = Sheets("FINITY CAPACITY PLANNED").Range("A" & Rows.Count).End(xlUp).Row
    Set PT1 = Worksheets("shift").PivotTables("Tabella_pivot1")
    Worksheets("TABLE SHEET 1").Range("d3:x" & MaxLineMatrice).ClearContents
    Set dlCD1 = CreateObject("Scripting.Dictionary")
    Row = 1
    On Error GoTo Error
    For Each cCD1 In Sheets("TABLE SHEET 2").Range("c1:c" & MaxLineMPS)
        tmpCD1 = Trim(cCD1.Value)
        If Len(tmpCD1) < 10 Then tmpCD1 = "0" & tmpCD1
        If Len(tmpCD1) > 0 Then dlCD1(tmpCD1) = dlCD1(tmpCD1) + 1
    Next cCD1
    For Each kCD1 In dlCD1.keys
        With Worksheets("TABLE SHEET 1").Range("a2:x" & MaxLineMatrice)
            .AutoFilter Field:=3, Criteria1:=kCD1
        End With
        If Sheets("TABLE SHEET 1").Range("A2:A" & MaxLineMatrice).SpecialCells(xlCellTypeVisible).Count > 1 Then
            With Sheets("TABLE SHEET 1").Range("d$3:x" & "$" & MaxLineMatrice).SpecialCells(xlCellTypeVisible)
                .Value = Sheets("TABLE SHEET 2").Range("$d" & "$" & Row & ":$x" & "$" & Row).Value
            End With
        Else: End If
        Row = Row + 1
        Debug.Print kCD1, dlCD1(kCD1)
    Next kCD1
    Worksheets("TABLE SHEET 1").AutoFilterMode = False
    dlCD1.RemoveAll
    Set dlCD1 = CreateObject("Scripting.Dictionary")
    For Each cCD1 In Sheets("Finity capacity planned").Range("a2:a" & LastLineFINITY)
        tmpCD1 = Trim(cCD1.Value)
        If Len(tmpCD1) > 0 Then dlCD1(tmpCD1) = dlCD1(tmpCD1) + 1
    Next cCD1
    Set dlCD2 = CreateObject("Scripting.Dictionary")
    For Each cCD2 In Sheets("Finity capacity planned").Range("b2:b" & LastLineFINITY)
        tmpCD2 = Trim(cCD2.Value)
        If Len(tmpCD2) > 0 Then dlCD2(tmpCD2) = dlCD2(tmpCD2) + 1
    Next cCD2
    For Each kCD1 In dlCD1.keys
        With Sheets("Finity capacity planned").Range("A1:Ak" & LastLineFINITY)
            .AutoFilter Field:=1, Criteria1:=kCD1
            .AutoFilter Field:=2, Criteria1:=Array( _
              dlCD2.keys()(0), dlCD2.keys()(2), dlCD2.keys()(4), dlCD2.keys()(6), dlCD2.keys()(8), dlCD2.keys()(10)), Operator:=xlFilterValues
        End With
        With Sheets("Finity capacity planned").Range("A2:Ak" & LastLineFINITY).SpecialCells(xlCellTypeVisible)
            .Interior.ColorIndex = 15
        End With
        With Sheets("Finity capacity planned").Range("A1:Ak" & LastLineFINITY)
            .AutoFilter Field:=1, Criteria1:=kCD1
            .AutoFilter Field:=2, Criteria1:=Array( _
              dlCD2.keys()(1), dlCD2.keys()(3), dlCD2.keys()(5), dlCD2.keys()(7), dlCD2.keys()(9), dlCD2.keys()(11)), Operator:=xlFilterValues
        End With
        With Sheets("Finity capacity planned").Range("A2:Ak" & LastLineFINITY).SpecialCells(xlCellTypeVisible)
            .Interior.ColorIndex = 19
        End With
        Debug.Print kCD1, dlCD1(kCD1)
    Next kCD1
    Worksheets("Finity capacity planned").AutoFilterMode = False
    dlCD1.RemoveAll
    dlCD2.RemoveAll
    With PT1
        .RefreshTable
    End With
    Application.EnableEvents = True
    Application.DisplayStatusBar = True
    Application.ScreenUpdating = True
    ActiveSheet.DisplayPageBreaks = True
    Application.Calculation = xlCalculationAutomatic
    SecondsElapsed = Round(Timer - StartTime, 2)
    MsgBox "This code including the time for user prompts to be acknowledged took " & SecondsElapsed & " Seconds", vbInformation, "McManus automation speed testing"
    Exit Sub
Error:
    Application.EnableEvents = True
    Application.DisplayStatusBar = True
    Application.ScreenUpdating = True
    ActiveSheet.DisplayPageBreaks = True
    Application.Calculation = xlCalculationAutomatic
    MsgBox "Something went wrong"
End Sub

Body:
You can use Find function to find the row number you are looking for. Then using this row number, you can have the data from that row.

I didn't dig into your code too much, because it is a bit messy. So considering that:

Blank Lookup sheet name is "TABLE 1 SHEET",

Master Lookup sheet name is "TABLE 2 SHEET",

Results sheet name is "TABLE 3 SHEET",

then you can try the following:

Sub findmydata()
Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet
Dim i As Long, j As Long, foundrow As Long, lastrow1 As Long, lastrow2 As Long

Set ws1 = Sheets("TABLE 1 SHEET")
Set ws2 = Sheets("TABLE 2 SHEET")
Set ws3 = Sheets("TABLE 3 SHEET")

lastrow1 = ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row
lastrow2 = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row

For i = 1 To lastrow1
    On Error Resume Next
    foundrow = ws2.Range("A1:A" & lastrow2).Find(ws1.Cells(i, 1).Value).Row
    If Err.Number = 91 Then
        ws3.Cells(i, 1) = ws1.Cells(i, 1)
    Else
        For j = 1 To 4
            ws3.Cells(i, j) = ws2.Cells(foundrow, j)
        Next j
    End If
Next
End Sub


答:
Decode the JSON string using json_decode() and then loop through it using a regular loop:

```<code>$arr = json_decode('[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]');

foreach($arr as $item) { //foreach element in $arr
    $uses = $item['var1']; //etc
}
</code>```

Title: php: loop through json array

Body:
I have a json array:

[
    {
        "var1": "9",
        "var2": "16",
        "var3": "16"
    },
    {
        "var1": "8",
        "var2": "15",
        "var3": "15"
    }
]

How can I loop through this array using php?

Body:
Decode the JSON string using json_decode() and then loop through it using a regular loop:

$arr = json_decode('[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]');

foreach($arr as $item) { //foreach element in $arr
    $uses = $item['var1']; //etc
}


问:
Python 2.7 - I'm getting the wrong order of values after converting CSV to JSON
I want to convert CSV to JSON file by taking data from stdin and outputting it to stdout. The input data's format has a format (each line) like this:
    111117_055958,b8:27:eb:da:ef:6d,0,b8:27:eb:8f:ba:38,192.168.1.10,171110_163200,19,0,0,562,18.7,50.1,ON,OFF,44.0,6593,3697,-2.700629,X

My Python code is:

```<code>#!/usr/bin/env python
import csv, json , sys

fieldnames = ("Time","MAC_ETH","IP_ETH","MAC_WiFi","IP_WiFi","Up_time","Winsen","ADC_2","ADC_3","VOC","Temp","Humidity","Internet","Lampa_UV","CPU_temp","Amph_P1","Amph_P2","PT100","Brak",)
reader = csv.DictReader(sys.stdin, fieldnames)

for row in reader:
    print(json.dumps(row, sys.stdout))
    sys.stdout.write('\n')
</code>```

And my output looks like this:

```<code>{"ADC_2": "0", "ADC_3": "0", "Up_time": "171110_163200", "MAC_WiFi": "b8:27:eb:8f:ba:38", "CPU_temp": "44.0", "Temp": "18.7", "VOC": "562", "PT100": "-2.700629", "MAC_ETH": "b8:27:eb:da:ef:6d", "Internet": "ON", "Winsen": "19", "Humidity": "50.1", "Amph_P2": "3697", "Amph_P1": "6593", "IP_ETH": "0", "Time": "111117_055958", "Brak": "X", "Lampa_UV": "OFF", "IP_WiFi": "192.168.1.10"}
</code>```

So names and values of parameters are OK. But the order of parameters is different compared to the input string and order in the fieldnames value. Can you tell me what I am doing wrong?

I use Python 2.7.12 on Synology.

答:
json / dict does not preserve key order.

In python > 3.6 dict does support preserving key order by default.

However since reader has a .fieldnames which is order you could do the following (UNTESTED):

```<code>for row in reader:
    print(json.dumps({f: row[f] for f in reader.fieldnames}, sys.stdout))
    sys.stdout.write('\n')
</code>```

Or simply use your own declared fieldnames:

```<code>for row in reader:
    print(json.dumps({f: row[f] for f in fieldnames}, sys.stdout))
    sys.stdout.write('\n')
</code>```

Body:
I want to convert CSV to JSON file by taking data from stdin and outputting it to stdout. The input data's format has a format (each line) like this:
    111117_055958,b8:27:eb:da:ef:6d,0,b8:27:eb:8f:ba:38,192.168.1.10,171110_163200,19,0,0,562,18.7,50.1,ON,OFF,44.0,6593,3697,-2.700629,X

My Python code is:

#!/usr/bin/env python
import csv, json , sys

fieldnames = ("Time","MAC_ETH","IP_ETH","MAC_WiFi","IP_WiFi","Up_time","Winsen","ADC_2","ADC_3","VOC","Temp","Humidity","Internet","Lampa_UV","CPU_temp","Amph_P1","Amph_P2","PT100","Brak",)
reader = csv.DictReader(sys.stdin, fieldnames)

for row in reader:
    print(json.dumps(row, sys.stdout))
    sys.stdout.write('\n')

And my output looks like this:

{"ADC_2": "0", "ADC_3": "0", "Up_time": "171110_163200", "MAC_WiFi": "b8:27:eb:8f:ba:38", "CPU_temp": "44.0", "Temp": "18.7", "VOC": "562", "PT100": "-2.700629", "MAC_ETH": "b8:27:eb:da:ef:6d", "Internet": "ON", "Winsen": "19", "Humidity": "50.1", "Amph_P2": "3697", "Amph_P1": "6593", "IP_ETH": "0", "Time": "111117_055958", "Brak": "X", "Lampa_UV": "OFF", "IP_WiFi": "192.168.1.10"}

So names and values of parameters are OK. But the order of parameters is different compared to the input string and order in the fieldnames value. Can you tell me what I am doing wrong?

I use Python 2.7.12 on Synology.

Body:
json / dict does not preserve key order.

In python > 3.6 dict does support preserving key order by default.

However since reader has a .fieldnames which is order you could do the following (UNTESTED):

for row in reader:
    print(json.dumps({f: row[f] for f in reader.fieldnames}, sys.stdout))
    sys.stdout.write('\n')

Or simply use your own declared fieldnames:

for row in reader:
    print(json.dumps({f: row[f] for f in fieldnames}, sys.stdout))
    sys.stdout.write('\n')


问:
How to set limited access to some portion of code in Git?
I have a few developers on my team and I need to restrict each one access to some portions of our codes. we are using self-hosted version of GitLab.

For example I want to limit programmer1 to just has access to folder1 and won't be able to see or clone folder2 contents to his machine.

```<code>[RootFolder]
    -- folder1
         -- source.php
    -- folder2
         -- file.php
         -- image.jpg
</code>```

Should I use branch or what?

答: If the access controls for two directories are different, then your best bet is to put each in a separate git repository and control access at the repo level.  </p>

Body:
I have a few developers on my team and I need to restrict each one access to some portions of our codes. we are using self-hosted version of GitLab.

For example I want to limit programmer1 to just has access to folder1 and won't be able to see or clone folder2 contents to his machine.

[RootFolder]
    -- folder1
         -- source.php
    -- folder2
         -- file.php
         -- image.jpg

Should I use branch or what?


问:
(Nodejs + Restify) Can't set headers after they are sent - promise rejection warning
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.
This error happens when I hitting the API continuously or again hitting the API before the request got completed.
Referred many solutions but cant able to get the proper answer.pls, Help me to sort out.

```<code>exports.getRecords = function(req, res) {

        db.task(t => {
                return t.batch([
                    t.any(selectQuery),
                    t.any(recordCountQuery)
                ]);
            })
            .then(data => {

                //create a formatted object based on the two queries with recordCount
                var output = {};

                output.meta = data[1][0];
                let petData = data[0];

                /*
                 * Checks If the pet details available and then processing the pets Data
                 * To get the existing image URL.
                 */

                if (!util.isNullOrUndefined(petData)) {
                    //Iterating over the Array of pets and process each pets with promises()
                    Promise.all(petData.map(pet => {

                            //Processing each pet
                            return processUtil.getvalidData(pet)
                                .then(pet => pet);
                        }))
                        .then(results => {
                            //After processing all the pets send the output
                            output.data = results;
                            res.json(output);
                        })
                };
            })
            .catch(function(err) {
                if (util.isError(err)) {
                    res.error('NotFoundError', err);
                } // return 404
                else {
                    res.error('InternalServerError', err);
                }; //else 500

            });
    };
</code>```

Here is console log for the two responses

Response log for single hit

```<code>    "15" "TRACE" "services-data" "lynd-PC" "sr"  "4596ec40" "" "GET" "/data/2" "request received"
    "16" "TRACE" "services-data" "lynd-PC" ""    "4596ec40" "" "GET" "/data/2" ""
    "17" "TRACE" "services-data" "lynd-PC" ""    "4596ec40" "" "GET" "/data/2" ""
    "18" "TRACE" "services-data" "lynd-PC" "ss"  "4596ec40" "200" "GET" "/data/2" "response sent"
</code>```

Response log when we twice hitting the API before the request got completed.

```<code>"15" "TRACE" "services-data" "lynd-PC" "sr"  "1a85afb7" "" "GET" "/data/2" "request received"
"15" "TRACE" "services-data" "lynd-PC" ""    "1a85afb7" "" "GET" "/data/2" ""
"16" "TRACE" "services-data" "lynd-PC" ""    "1a85afb7" "" "GET" "/data/2" ""
"17" "TRACE" "services-data" "lynd-PC" "ss"  "1a85afb7" "500" "GET" "/data/2" "response sent"
"18" "TRACE" "services-data" "lynd-PC" ""    "1a85afb7" "" "GET" "/data/2" ""
(node:3860) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Can't set headers after they are sent.
</code>```

答:
For starters, there is no reject handler for the Promise.all() in your code.  You can chain it to the parent promise chain (which does have a reject handler) by just changing this:

```<code>Promise.all(petData.map(pet => {
</code>```

to this:

```<code>return Promise.all(petData.map(pet => {
</code>```

So, that will fix one opportunity for an unhandled rejection.  Or, you can add your own reject handle to the Promise.all() promise if you'd rather have a separate reject handler for it.

It also appears you have several code paths that would send no response.  If this condition:

```<code>if (!util.isNullOrUndefined(petData)) {
</code>```

is not satisified (meaning it does not go into the if block), then your code will not send any response which is typically a coding mistake since every request needs exactly one response to be sent.

Body:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.
This error happens when I hitting the API continuously or again hitting the API before the request got completed.
Referred many solutions but cant able to get the proper answer.pls, Help me to sort out.

exports.getRecords = function(req, res) {

        db.task(t => {
                return t.batch([
                    t.any(selectQuery),
                    t.any(recordCountQuery)
                ]);
            })
            .then(data => {

                //create a formatted object based on the two queries with recordCount
                var output = {};

                output.meta = data[1][0];
                let petData = data[0];

                /*
                 * Checks If the pet details available and then processing the pets Data
                 * To get the existing image URL.
                 */

                if (!util.isNullOrUndefined(petData)) {
                    //Iterating over the Array of pets and process each pets with promises()
                    Promise.all(petData.map(pet => {

                            //Processing each pet
                            return processUtil.getvalidData(pet)
                                .then(pet => pet);
                        }))
                        .then(results => {
                            //After processing all the pets send the output
                            output.data = results;
                            res.json(output);
                        })
                };
            })
            .catch(function(err) {
                if (util.isError(err)) {
                    res.error('NotFoundError', err);
                } // return 404
                else {
                    res.error('InternalServerError', err);
                }; //else 500

            });
    };

Here is console log for the two responses

Response log for single hit

    "15" "TRACE" "services-data" "lynd-PC" "sr"  "4596ec40" "" "GET" "/data/2" "request received"
    "16" "TRACE" "services-data" "lynd-PC" ""    "4596ec40" "" "GET" "/data/2" ""
    "17" "TRACE" "services-data" "lynd-PC" ""    "4596ec40" "" "GET" "/data/2" ""
    "18" "TRACE" "services-data" "lynd-PC" "ss"  "4596ec40" "200" "GET" "/data/2" "response sent"

Response log when we twice hitting the API before the request got completed.

"15" "TRACE" "services-data" "lynd-PC" "sr"  "1a85afb7" "" "GET" "/data/2" "request received"
"15" "TRACE" "services-data" "lynd-PC" ""    "1a85afb7" "" "GET" "/data/2" ""
"16" "TRACE" "services-data" "lynd-PC" ""    "1a85afb7" "" "GET" "/data/2" ""
"17" "TRACE" "services-data" "lynd-PC" "ss"  "1a85afb7" "500" "GET" "/data/2" "response sent"
"18" "TRACE" "services-data" "lynd-PC" ""    "1a85afb7" "" "GET" "/data/2" ""
(node:3860) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Can't set headers after they are sent.

Body:
For starters, there is no reject handler for the Promise.all() in your code.  You can chain it to the parent promise chain (which does have a reject handler) by just changing this:

Promise.all(petData.map(pet => {

to this:

return Promise.all(petData.map(pet => {

So, that will fix one opportunity for an unhandled rejection.  Or, you can add your own reject handle to the Promise.all() promise if you'd rather have a separate reject handler for it.

It also appears you have several code paths that would send no response.  If this condition:

if (!util.isNullOrUndefined(petData)) {

is not satisified (meaning it does not go into the if block), then your code will not send any response which is typically a coding mistake since every request needs exactly one response to be sent.


问:
How to build XMPP application using Monotouch?
can anyone help me to undertand how can I build XMPP appication using Monotouch? What library can I use? Are there some example?

Thanks.

答:
Well you could try to port one existing C# XMPP library like this one and try to make an iPhone library project with it then reference it on the iPhone App Project and try to work with it :)

Alex


问:
ImportError: No module named '_catboost'
I am using python 3.4 and have installed catboost library but when i try to import, it shows the following error.

```<code>ImportError                               Traceback (most recent call last)
c:\python34\lib\site-packages\catboost\core.py in <module>()
 17 try:
---> 18     from _catboost import _PoolBase, _CatBoostBase, CatboostError,
_cv, _set_logger, _reset_logger
 19 except ImportError:

ImportError: No module named '_catboost'

During handling of the above exception, another exception occurred:

ImportError                               Traceback (most recent call last)
<ipython-input-51-f6570a454eaf> in <module>()
----> 1 from catboost import CatBoostClassifier,cv, Pool

c:\python34\lib\site-packages\catboost\__init__.py in <module>()
----> 1 from .core import Pool, CatBoost, CatBoostClassifier,
CatBoostRegressor, CatboostError, cv  # noqa
  2 try:
  3     from .widget import CatboostIpythonWidget  # noqa
  4 except:
  5     pass

c:\python34\lib\site-packages\catboost\core.py in <module>()
 18     from _catboost import _PoolBase, _CatBoostBase, CatboostError, _cv,
_set_logger, _reset_logger
 19 except ImportError:
---> 20     from ._catboost import _PoolBase, _CatBoostBase, CatboostError,
_cv, _set_logger, _reset_logger
 21
 22 from contextlib import contextmanager

ImportError: DLL load failed: The specified module could not be found.
</code>```

答:
Because you're using python 3.x you need to use

```<code>pip3 install catboost
</code>```

not

```<code>pip install catboost
</code>```

Body:
I am using python 3.4 and have installed catboost library but when i try to import, it shows the following error.

ImportError                               Traceback (most recent call last)
c:\python34\lib\site-packages\catboost\core.py in <module>()
 17 try:
---> 18     from _catboost import _PoolBase, _CatBoostBase, CatboostError,
_cv, _set_logger, _reset_logger
 19 except ImportError:

ImportError: No module named '_catboost'

During handling of the above exception, another exception occurred:

ImportError                               Traceback (most recent call last)
<ipython-input-51-f6570a454eaf> in <module>()
----> 1 from catboost import CatBoostClassifier,cv, Pool

c:\python34\lib\site-packages\catboost\__init__.py in <module>()
----> 1 from .core import Pool, CatBoost, CatBoostClassifier,
CatBoostRegressor, CatboostError, cv  # noqa
  2 try:
  3     from .widget import CatboostIpythonWidget  # noqa
  4 except:
  5     pass

c:\python34\lib\site-packages\catboost\core.py in <module>()
 18     from _catboost import _PoolBase, _CatBoostBase, CatboostError, _cv,
_set_logger, _reset_logger
 19 except ImportError:
---> 20     from ._catboost import _PoolBase, _CatBoostBase, CatboostError,
_cv, _set_logger, _reset_logger
 21
 22 from contextlib import contextmanager

ImportError: DLL load failed: The specified module could not be found.

Body:
Because you're using python 3.x you need to use

pip3 install catboost

not

pip install catboost


问:
How to use IF OR & AND in excel formula
I am not a coder, but I'm trying to work on an excel sheet to make things more efficient at work.
I have two formulas that I need to combine and I can't figure it out! please help. I am trying to put this on my T2 cell.

This is the first one. I basically want to say if O2, R2, and S2 =yes, OR if Q2, R2, and S2 =yes, then "yes" otherwise leave blank. This is what I figured out and it is working!
=IF(OR(AND(O2="YES",R2="YES",S2="YES"),AND(Q2="YES",R2="YES",S2="YES")),"YES"," ")

However, If O2=NO and Q2=NO, then I want it to say No, otherwise leave blank. I have the two separate formulas but can't figure out how to combine.
IF(OR(AND(O2="NO", Q2="NO"),"NO", " ")

I was thinking maybe I can do this: =IF(OR(AND(O2="YES",R2="YES",S2="YES"),AND(Q2="YES",R2="YES",S2="YES")),"YES","NO") the only problem with this is that it automatically fills a NO, even if the cells are blank. I want it to skip it if its blank.
Link to spreadsheet image below:

答:
Test it first, then do the rest of the tests

```<code>If (AND(O2="NO",Q2="NO"),"NO",IF(AND(R2="YES", S2="YES",OR(O2="YES",Q2="YES")),"YES",""))
</code>```

I have also grouped the (R2="YES", S2="YES") as you were checking this twice and you don't need to.

Title: How to use IF OR & AND in excel formula

Body:
Test it first, then do the rest of the tests

If (AND(O2="NO",Q2="NO"),"NO",IF(AND(R2="YES", S2="YES",OR(O2="YES",Q2="YES")),"YES",""))

I have also grouped the (R2="YES", S2="YES") as you were checking this twice and you don't need to.


问:
Using WTForms with Enum
I have the following code:

```<code>class Company(enum.Enum):
    EnterMedia = 'EnterMedia'
    WhalesMedia = 'WhalesMedia'

    @classmethod
    def choices(cls):
        return [(choice.name, choice.name) for choice in cls]

    @classmethod
    def coerce(cls, item):
        print "Coerce", item, type(item)
        if item == 'WhalesMedia':
            return Company.WhalesMedia
        elif item == 'EnterMedia':
            return Company.EnterMedia
        else:
            raise ValueError
</code>```

And this is my wtform field:

```<code>company = SelectField("Company", choices=Company.choices(), coerce=Company.coerce)
</code>```

This is the html generated in my form:

```<code><select class="" id="company" name="company" with_label="">
    <option value="EnterMedia">EnterMedia</option>
    <option value="WhalesMedia">WhalesMedia</option>
</select>
</code>```

Somehow, when I click submit, I keep getting "Not a Valid Choice".

Any ideas why?

This is my terminal output:

When I look at my terminal I see the following:

```<code>Coerce None <type 'NoneType'>
Coerce EnterMedia <type 'unicode'>
Coerce EnterMedia <type 'str'>
Coerce WhalesMedia <type 'str'>
</code>```

答:
I've just been down the same rabbit hole. Not sure why, but coerce gets called with None when the form is initialised. After wasting a lot of time, I decided it's not worth coercing, and instead I just used:

```<code>field = SelectField("Label", choices=[(choice.name, choice.value) for choice in MyEnum])
</code>```

and to get the value:

```<code>selected_value = MyEnum[field.data]
</code>```

Title: Using WTForms with Enum

Body:
I have the following code:

class Company(enum.Enum):
    EnterMedia = 'EnterMedia'
    WhalesMedia = 'WhalesMedia'

    @classmethod
    def choices(cls):
        return [(choice.name, choice.name) for choice in cls]

    @classmethod
    def coerce(cls, item):
        print "Coerce", item, type(item)
        if item == 'WhalesMedia':
            return Company.WhalesMedia
        elif item == 'EnterMedia':
            return Company.EnterMedia
        else:
            raise ValueError

And this is my wtform field:

company = SelectField("Company", choices=Company.choices(), coerce=Company.coerce)

This is the html generated in my form:

<select class="" id="company" name="company" with_label="">
    <option value="EnterMedia">EnterMedia</option>
    <option value="WhalesMedia">WhalesMedia</option>
</select>

Somehow, when I click submit, I keep getting "Not a Valid Choice".

Any ideas why?

This is my terminal output:

When I look at my terminal I see the following:

Coerce None <type 'NoneType'>
Coerce EnterMedia <type 'unicode'>
Coerce EnterMedia <type 'str'>
Coerce WhalesMedia <type 'str'>

Body:
I've just been down the same rabbit hole. Not sure why, but coerce gets called with None when the form is initialised. After wasting a lot of time, I decided it's not worth coercing, and instead I just used:

field = SelectField("Label", choices=[(choice.name, choice.value) for choice in MyEnum])

and to get the value:

selected_value = MyEnum[field.data]


问:
Fixed header above scrollable table
I am trying to have a table header, in a seperate div stay in place while a div undernearth is able to scroll al arge list of records. Both divs are in a div named Layer 3. Hereis the css file I am using:

#Layer3
{
    position:absolute;
    width: 89%;
    height: 40%;
    left: 10%;
    top: 56%;
    background-color: #f1ffff;
}

#Layer3 h1 {
    font-size: medium;
    color: #000033;
    text-decoration: none;
    text-align: center;
}

.tableheader {
}

.tablecontent {
    overflow: auto;
}
```

<p>and part of the php code I am using to generate the html:</p>

```echo '
';

echo "
{$query} Auctions
" . "\n";
echo "
";
echo '
';

echo "

" . "\n";

echo "Seller ID	" . "\n";
echo "Start Date	" . "\n";
echo "Description	" . "\n";

echo "
\n";

// printing table rows

foreach ($rows as $row)
{
    $pk = $row['ARTICLE_NO'];
    echo '
' . "\n";

    // table contens generated in here

    echo '
' . "\n";
}
}

echo "
";
```

I am not sure what I have missed, but tableheader does not seem to be stationary, or even separate from tablecontent.

答:
You've forgotten to close the
 tag after your main foreach() loop.

Title: Fixed header above scrollable table

Body:
I am trying to have a table header, in a seperate div stay in place while a div undernearth is able to scroll al arge list of records. Both divs are in a div named Layer 3. Hereis the css file I am using:

#Layer3
{
    position:absolute;
    width: 89%;
    height: 40%;
    left: 10%;
    top: 56%;
    background-color: #f1ffff;
}

#Layer3 h1 {
    font-size: medium;
    color: #000033;
    text-decoration: none;
    text-align: center;
}

.tableheader {
}

.tablecontent {
    overflow: auto;
}

and part of the php code I am using to generate the html:

echo '
';

echo "
{$query} Auctions
" . "\n";
echo "
";
echo '
';

echo "

" . "\n";

echo "Seller ID	" . "\n";
echo "Start Date	" . "\n";
echo "Description	" . "\n";

echo "
\n";

// printing table rows

foreach ($rows as $row)
{
    $pk = $row['ARTICLE_NO'];
    echo '
' . "\n";

    // table contens generated in here

    echo '
' . "\n";
}
}

echo "
";

I am not sure what I have missed, but tableheader does not seem to be stationary, or even separate from tablecontent.

Body: You've forgotten to close the <table> tag after your main foreach() loop.

OwnerDisplayName: codeinthehole


问:
is there an easier way to set a view's origin and size on iphone
Shorter than

```<code>CGRect rect = self.webView.frame;
rect.origin = CGPointMake(0, 120);
self.webView.frame = rect;
</code>```

Or is this the shortest way (or efficient)

答: You can use CGRectMake. Four parameters.. x, y, width, height, all floats. Like this: self.webView.frame = CGRectMake(0, 0, 320, 480);

Body:
Shorter than

CGRect rect = self.webView.frame;
rect.origin = CGPointMake(0, 120);
self.webView.frame = rect;

Or is this the shortest way (or efficient)


问:
How to test if an input has only specific characters
Im trying to make a script that tests id there are characters in the input that are not A, T, C, G and if there are than the input is false.

I dont have any clue how to start. I would love if someone could help.
Thanks!

答:
Expressed using sets:

The list function takes a string and returns a list of its characters. The set function takes a list and returns a set (with duplicates discarded).

```<code>>>> def check_string(code):
...     return set(list('ACTG')).issuperset(set(list(code)))
...
>>> check_string('IT')
False
>>> check_string('ACTG')
True
>>> check_string('')
True
>>> check_string('ACT')
True
</code>```

Body:
Expressed using sets:

The list function takes a string and returns a list of its characters. The set function takes a list and returns a set (with duplicates discarded).

>>> def check_string(code):
...     return set(list('ACTG')).issuperset(set(list(code)))
...
>>> check_string('IT')
False
>>> check_string('ACTG')
True
>>> check_string('')
True
>>> check_string('ACT')
True


问:
unable to convert mp3 files to text format only support .wav files in java
I have created an application but it is only support .wav files to convert audio to text. It is not showing any answers when giving .mp3 files .. I am using sphinx for to convert audio files to text. My question is that why it is not converting to text from .MP3?</p>

答:
As it is specified in the CMU Sphinx documents, only the linear PCM WAV audio format is accept by its speech recognizer. Therefore, any MP3 audio file will be decoded to obtain the linear PCM format, of 16khz sampling rate, 16bit/frame, little-endian and one channel (mono).
This decoding is achieved by the Tarsos Transcoder 1.2. This library uses many Apache utilities, therefore beside the TarsosTranscoder.jar, mp3plugin.jar also has to be included in the project building path.</p>


问:
Unity - Raycast distance doesn't change
I'm trying to detect the ground ahead of a cube that doens't have boxcollider or rigid body. I can detect it ok but the distance never changes. I can use very big number or very small ones that it still detects the ground at the same distance.

The debug lines are working fine and nothing is detected before the ground. Even trying raycast without distance keeps the detection at the same distance.
I tried some other variations of the method Raycast with the same results.

Here is my script:

```<code>Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hitInfo;
Debug.DrawRay(pos, transform.forward * detectDistance, Color.green);
if (Physics.Raycast(ray,out hitInfo, detectDistance)) {
       Debug.Log(hitInfo.transform.name);
       Debug.DrawRay(pos, transform.forward * detectDistance, Color.red);
}
</code>```

答:
The problem was the other terrain chunks wasn't generating the collider mesh till you get really close to it.
I did find a way to generate it far away.</p>

Title: Unity - Raycast distance doesn't change

Body:
I'm trying to detect the ground ahead of a cube that doens't have boxcollider or rigid body. I can detect it ok but the distance never changes. I can use very big number or very small ones that it still detects the ground at the same distance.

The debug lines are working fine and nothing is detected before the ground. Even trying raycast without distance keeps the detection at the same distance.
I tried some other variations of the method Raycast with the same results.

Here is my script:

Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hitInfo;
Debug.DrawRay(pos, transform.forward * detectDistance, Color.green);
if (Physics.Raycast(ray,out hitInfo, detectDistance)) {
       Debug.Log(hitInfo.transform.name);
       Debug.DrawRay(pos, transform.forward * detectDistance, Color.red);
}


问:
Google OR Tools: Employee Scheduling with availability constraint
Following the nurse scheduling example from here, I'm trying to add more constraints to the problem. For instance: nurse A cannot work shifts 2 and 3 on Monday, nurse B can only work shifts 1 and 3 across all days.

How would one go about implementing a constraint like this?

If it's not possible in OR-tools, please give suggestions on how I can implement something like this.

答:
For your examples, all you need to do is add a constraint that prevents the shift from being assigned to that specific nurse:

```<code>   solver.Add(shifts[(2, 1)] != 3)  # Nurse 2 cannot be assigned shift 3 on day 1
</code>```

More generally:

```<code>   solver.Add(shifts[(j, i)] != n)  # Nurse j cannot be assigned shift n on day i
</code>```

Obviously you will want to do this in a loop to simplify it if possible.

Body:
For your examples, all you need to do is add a constraint that prevents the shift from being assigned to that specific nurse:

   solver.Add(shifts[(2, 1)] != 3)  # Nurse 2 cannot be assigned shift 3 on day 1

More generally:

   solver.Add(shifts[(j, i)] != n)  # Nurse j cannot be assigned shift n on day i

Obviously you will want to do this in a loop to simplify it if possible.


问:
How to select text in a textbox?
I have a userform with a textbox. I want to select the text within (highlight) after the keyDown event.

There are some restrictions to what the end user can enter. In case of wrong entry, a message would pop up, and the text in the textbox inviting the user to enter something should be selected.

I use the following code:

```<code>Me.txtbox_add_folder.SetFocus
Me.txtbox_add_folder.SelStart = 0
Me.txtbox_add_folder.SelLength = Len(Me.txtbox_add_folder.Text)
</code>```

The setFocus doesn't work. It seems that it's because setFocus triggers a series of other events see this discussion.

The solution proposed in a different discussion is to include a DoCmd.CancelEvent or Cancel = True, so that the focus doesn't go to another control, but these commands don't work on Excel.

答:
```<code> Application.enableevents = false
 Me.txtbox_add_folder.SetFocus
 Me.txtbox_add_folder.SelStart = 0
 Me.txtbox_add_folder.SelLength = Len(Me.txtbox_add_folder.Text)
 Application.enableevents = true
</code>```

Title: How to select text in a textbox?

Body:
I have a userform with a textbox. I want to select the text within (highlight) after the keyDown event.

There are some restrictions to what the end user can enter. In case of wrong entry, a message would pop up, and the text in the textbox inviting the user to enter something should be selected.

I use the following code:

Me.txtbox_add_folder.SetFocus
Me.txtbox_add_folder.SelStart = 0
Me.txtbox_add_folder.SelLength = Len(Me.txtbox_add_folder.Text)

The setFocus doesn't work. It seems that it's because setFocus triggers a series of other events see this discussion.

The solution proposed in a different discussion is to include a DoCmd.CancelEvent or Cancel = True, so that the focus doesn't go to another control, but these commands don't work on Excel.