问:
SQL Server query help... super slow query
My query is taking too long to execute, do anyone know how to optimize the query below? P.S. The 'temp_db' has 1'024'912'779 rows.

Here is the query:

```<code>SELECT
    CASE
       WHEN user_agent LIKE '%Mobile%'
          THEN 'Mobile'
          ELSE 'Desktop'
    END AS DEVICE,
    CAST(DATEADD(hour, +8, timestamp_gmt) AS Date) AS HKDate,
    DATEPART(Hour, DATEADD(hour, +8, timestamp_gmt)) AS HKHour,
    pixel_name AS Pixel,
    COUNT(id) AS Fires,
    COUNT(DISTINCT id) AS Uu
FROM
    temp_db
WHERE
    CONVERT(date, timestamp_gmt) BETWEEN DATEADD(day, -3, GETDATE())
                                     AND CONVERT(date, GETDATE())
    AND advertiser_name LIKE '%TimCompany%'
GROUP BY
    CASE
       WHEN user_agent LIKE '%Mobile%'
          THEN 'Mobile'
          ELSE 'Desktop'
    END,
    CAST(DATEADD(hour, +8, timestamp_gmt) AS Date),
    DATEPART(Hour, DATEADD(hour, +8, timestamp_gmt)),
    pixel_name;
</code>```

答:
Try this : below script minimize the repetitive same function calls  </p>

```<code>SELECT DEVICE,
       HKDate,
       HKHour,
       Pixel
       COUNT(ID) Fires,
       COUNT(DISTINCT ID) Uu
FROM (
        SELECT
              CASE WHEN user_agent like '%Mobile%' THEN 'Mobile' ELSE 'Desktop' END AS DEVICE,
              CAST(DATEADD(hour,+8,timestamp_gmt) AS Date) AS HKDate,
              DATEPART(Hour,DATEADD(hour, +8, timestamp_gmt)) AS HKHour,
              pixel_name AS Pixel,
              ID
        FROM  temp_db
        WHERE  CONVERT(date,timestamp_gmt) BETWEEN DATEADD(day,-3,GETDATE()) AND CONVERT(date,GETDATE()) AND
       advertiser_name like '%TimCompany%'
)M
GROUP BY DEVICE,HKDATE,HKHOUR,pixel
</code>```

Body:
My query is taking too long to execute, do anyone know how to optimize the query below? P.S. The 'temp_db' has 1'024'912'779 rows.

Here is the query:

SELECT
    CASE
       WHEN user_agent LIKE '%Mobile%'
          THEN 'Mobile'
          ELSE 'Desktop'
    END AS DEVICE,
    CAST(DATEADD(hour, +8, timestamp_gmt) AS Date) AS HKDate,
    DATEPART(Hour, DATEADD(hour, +8, timestamp_gmt)) AS HKHour,
    pixel_name AS Pixel,
    COUNT(id) AS Fires,
    COUNT(DISTINCT id) AS Uu
FROM
    temp_db
WHERE
    CONVERT(date, timestamp_gmt) BETWEEN DATEADD(day, -3, GETDATE())
                                     AND CONVERT(date, GETDATE())
    AND advertiser_name LIKE '%TimCompany%'
GROUP BY
    CASE
       WHEN user_agent LIKE '%Mobile%'
          THEN 'Mobile'
          ELSE 'Desktop'
    END,
    CAST(DATEADD(hour, +8, timestamp_gmt) AS Date),
    DATEPART(Hour, DATEADD(hour, +8, timestamp_gmt)),
    pixel_name;

Body:
Try this : below script minimize the repetitive same function calls

SELECT DEVICE,
       HKDate,
       HKHour,
       Pixel
       COUNT(ID) Fires,
       COUNT(DISTINCT ID) Uu
FROM (
        SELECT
              CASE WHEN user_agent like '%Mobile%' THEN 'Mobile' ELSE 'Desktop' END AS DEVICE,
              CAST(DATEADD(hour,+8,timestamp_gmt) AS Date) AS HKDate,
              DATEPART(Hour,DATEADD(hour, +8, timestamp_gmt)) AS HKHour,
              pixel_name AS Pixel,
              ID
        FROM  temp_db
        WHERE  CONVERT(date,timestamp_gmt) BETWEEN DATEADD(day,-3,GETDATE()) AND CONVERT(date,GETDATE()) AND
       advertiser_name like '%TimCompany%'
)M
GROUP BY DEVICE,HKDATE,HKHOUR,pixel


来源: stackexchange

问:
How to reference an indexer member of a class in C# comments
In order to reference a member of a class in XML comments/documentation, you have to use the following tag:

```<code><see cref="member"/>
</code>```

It is better explained here.

How do you reference an indexer?

I mean, a member like this one:

```<code>internal object this[ int index ] {
    ...
}
</code>```

Thanks in advance.

答:
```<code><see cref="ReadOnlyCollection{T}.this[int]" />
</code>```

as proposed here.

OwnerDisplayName: Auron

ContentLicense: CC BY-SA 2.5

Body:
In order to reference a member of a class in XML comments/documentation, you have to use the following tag:

<see cref="member"/>

It is better explained here.

How do you reference an indexer?

I mean, a member like this one:

internal object this[ int index ] {
    ...
}

Thanks in advance.

Body:
<see cref="ReadOnlyCollection{T}.this[int]" />

as proposed here.

ContentLicense: CC BY-SA 3.0


问:
auto fill in react doesn't work
I like react, I was using angular 1 then switched to react, I like react but facing a pain issue using it - developing forms. In react I can't use auto fill, as the field has an onChange event. Auto fill using imacro won't work at all.

```<code><input onChange={this.handleChange} />
</code>```

Thus it make me hard to test if my form has lots of fields like checkbox, custom editor, dropdown etc.. I have to manually enter the value in every fields.

答:
In order to Autofill you should use a controlled input field

```<code> <input onChange={this.handleChange} value={this.state.inpVal} />
</code>```

Now you can initialise the state from the data that you fetch from anywhere that you have it stored to autofill the value

However if you are using redux, instead of state you would be using the props to set the value from the redux store

```<code> <input onChange={this.handleChange} value={this.props.inputForm.inpVal} />
</code>```

considering inputForm is the prop which refers to the state of you current form

Title: auto fill in react doesn't work

Body:
I like react, I was using angular 1 then switched to react, I like react but facing a pain issue using it - developing forms. In react I can't use auto fill, as the field has an onChange event. Auto fill using imacro won't work at all.

<input onChange={this.handleChange} />

Thus it make me hard to test if my form has lots of fields like checkbox, custom editor, dropdown etc.. I have to manually enter the value in every fields.

Body:
In order to Autofill you should use a controlled input field

 <input onChange={this.handleChange} value={this.state.inpVal} />

Now you can initialise the state from the data that you fetch from anywhere that you have it stored to autofill the value

However if you are using redux, instead of state you would be using the props to set the value from the redux store

 <input onChange={this.handleChange} value={this.props.inputForm.inpVal} />

considering inputForm is the prop which refers to the state of you current form


问:
Getting number of characters in a unicode string in python
How can I get the number of codepoints in a string which may contain unicode characters 3 byte long. https://unicode-table.com/

For example for "I❤U" I would like to get 3.

Doing len(str) returns the number of bytes, so for the above example I would get 5.

答:
Try to decode it in python2:

```<code>"I❤U".decode('utf-8')
</code>```

Output: u'I\u2764U'

then len("I❤U".decode('utf-8')), it will be 3

Body:
Try to decode it in python2:

"I❤U".decode('utf-8')

Output: u'I\u2764U'

then len("I❤U".decode('utf-8')), it will be 3


答:
This seems to do the trick. I've left it quite open since you haven't said whether you're doing this for all of your data or just a specific checklist.

The trick was to use a ROW_NUMBER() to obtain known names for the File columns:

```<code>declare @t1 table (ID int not null,ChecklistItemID int not null,Attachment int not null)
insert into @t1(ID,ChecklistItemID,Attachment) values
(327,912,611),
(328,912,612)

declare @t2 table (ID int not null, FileName varchar(9) not null)
insert into @t2(ID,FileName) values
(611,'2.jpg'),
(612,'3.jpg')

;With Ordered as (
    select
        t1.ChecklistItemID,
        FileName,
        'File' + CONVERT(varchar(5),ROW_NUMBER() OVER (PARTITION BY t1.ChecklistItemID
                                     ORDER BY t2.ID)) as FileTitle
    from
        @t1 t1
            inner join
        @t2 t2
            on
                t1.Attachment = t2.ID
)
select
    *
from
    Ordered
        pivot (MIN(FileName) for FileTitle in (File1,File2,File3)) u
</code>```

Result:

```<code>ChecklistItemID File1     File2     File3
--------------- --------- --------- ---------
912             2.jpg     3.jpg     NULL
</code>```

Title: I'm trying to implement Pivot SQL

Body:
this is my first time trying to do a pivot but even with all the information online, i'm still useless :(

I have this table.

+-----+-----------------+------------+
| ID  | ChecklistItemID | Attachment |
| 327 | 912             | 611        |
| 328 | 912             | 612        |
+-----+-----------------+------------+

and this table

+-----+----------+
| ID  | FileName |
| 611 | 2.jpg    |
| 612 | 3.jpg    |
+-----+----------+

I want my output to be like this

+-----------------+-------+-------+
| ChecklistItemID | File1 | File2 |
| 912             | 2.jpg | 3.jpg |
+-----------------+-------+-------+

Can anyone help please?

Body:
This seems to do the trick. I've left it quite open since you haven't said whether you're doing this for all of your data or just a specific checklist.

The trick was to use a ROW_NUMBER() to obtain known names for the File columns:

declare @t1 table (ID int not null,ChecklistItemID int not null,Attachment int not null)
insert into @t1(ID,ChecklistItemID,Attachment) values
(327,912,611),
(328,912,612)

declare @t2 table (ID int not null, FileName varchar(9) not null)
insert into @t2(ID,FileName) values
(611,'2.jpg'),
(612,'3.jpg')

;With Ordered as (
    select
        t1.ChecklistItemID,
        FileName,
        'File' + CONVERT(varchar(5),ROW_NUMBER() OVER (PARTITION BY t1.ChecklistItemID
                                     ORDER BY t2.ID)) as FileTitle
    from
        @t1 t1
            inner join
        @t2 t2
            on
                t1.Attachment = t2.ID
)
select
    *
from
    Ordered
        pivot (MIN(FileName) for FileTitle in (File1,File2,File3)) u

Result:

ChecklistItemID File1     File2     File3
--------------- --------- --------- ---------
912             2.jpg     3.jpg     NULL


问:
i am creating application where submitting from to aweber but i also need input fields to store on db
```<code><form method="post" class="af-form-wrapper" action="http://www.aweber.com/scripts/addlead.pl">
</code>```

I am creating an application where submitting from to aweber but I also need input fields to store on db. But I also need that inputs to store inv database at my end how can I get them in PHP as we can't have two actions.

答:
We can do this with the help of CURL

```<code>    public function signup()
{
    $fields_string='';
    $ch = curl_init('http://www.aweber.com/scripts/addlead.pl');
    $fields = array(
        'name' => $this->input->post('name'),
        'email' => $this->input->post('email'),
        'meta_web_form_id' => '1122',
        'meta_split_id' => '',
        'listname' => 'abc',
        'meta_redirect_onlist' => '',
        'meta_adtracking' => 'My_Web_Form',
        'meta_message' => '1',
        'meta_required' => 'name,email',
        'meta_forward_vars' => '0',
    );
    foreach($fields as $key=>$value)
    {
        $fields_string .= $key.'='.$value.'&';
    }
    rtrim($fields_string,'&');
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch,CURLOPT_POST,count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $returned = curl_exec($ch);
    $this->register_user($fields);
}
</code>```

$this->register_user($fields); // This function will store values in my database as we are passing name and email to that function

Body:
<form method="post" class="af-form-wrapper" action="http://www.aweber.com/scripts/addlead.pl">

I am creating an application where submitting from to aweber but I also need input fields to store on db. But I also need that inputs to store inv database at my end how can I get them in PHP as we can't have two actions.

Body:
We can do this with the help of CURL

    public function signup()
{
    $fields_string='';
    $ch = curl_init('http://www.aweber.com/scripts/addlead.pl');
    $fields = array(
        'name' => $this->input->post('name'),
        'email' => $this->input->post('email'),
        'meta_web_form_id' => '1122',
        'meta_split_id' => '',
        'listname' => 'abc',
        'meta_redirect_onlist' => '',
        'meta_adtracking' => 'My_Web_Form',
        'meta_message' => '1',
        'meta_required' => 'name,email',
        'meta_forward_vars' => '0',
    );
    foreach($fields as $key=>$value)
    {
        $fields_string .= $key.'='.$value.'&';
    }
    rtrim($fields_string,'&');
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch,CURLOPT_POST,count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $returned = curl_exec($ch);
    $this->register_user($fields);
}

$this->register_user($fields); // This function will store values in my database as we are passing name and email to that function


问:
Change default kernel version in GRUB
This is the content of the grub.cfg file of my Arch Linux system.

```<code>#
# DO NOT EDIT THIS FILE
#
# It is automatically generated by grub-mkconfig using templates
# from /etc/grub.d and settings from /etc/default/grub
#

### BEGIN /etc/grub.d/00_header ###
insmod part_gpt
insmod part_msdos
if [ -s $prefix/grubenv ]; then
  load_env
fi
if [ "${next_entry}" ] ; then
   set default="${next_entry}"
   set next_entry=
   save_env next_entry
   set boot_once=true
else
   set default="0"
fi

if [ x"${feature_menuentry_id}" = xy ]; then
  menuentry_id_option="--id"
else
  menuentry_id_option=""
fi

export menuentry_id_option

if [ "${prev_saved_entry}" ]; then
  set saved_entry="${prev_saved_entry}"
  save_env saved_entry
  set prev_saved_entry=
  save_env prev_saved_entry
  set boot_once=true
fi

function savedefault {
  if [ -z "${boot_once}" ]; then
    saved_entry="${chosen}"
    save_env saved_entry
  fi
}

function load_video {
  if [ x$feature_all_video_module = xy ]; then
    insmod all_video
  else
    insmod efi_gop
    insmod efi_uga
    insmod ieee1275_fb
    insmod vbe
    insmod vga
    insmod video_bochs
    insmod video_cirrus
  fi
}

if [ x$feature_default_font_path = xy ] ; then
   font=unicode
else
insmod part_gpt
insmod ext2
set root='hd0,gpt3'
if [ x$feature_platform_search_hint = xy ]; then
  search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt3 --hint-efi=hd0,gpt3 --hint-baremetal=ahci0,gpt3  8fb68a6d-5088-47dc-8f9a-63e21ae275d4
else
  search --no-floppy --fs-uuid --set=root 8fb68a6d-5088-47dc-8f9a-63e21ae275d4
fi
    font="/usr/share/grub/unicode.pf2"
fi

if loadfont $font ; then
  set gfxmode=auto
  load_video
  insmod gfxterm
  set locale_dir=$prefix/locale
  set lang=pt_BR
  insmod gettext
fi
terminal_input console
terminal_output gfxterm
if [ x$feature_timeout_style = xy ] ; then
  set timeout_style=menu
  set timeout=5
# Fallback normal timeout code in case the timeout_style feature is
# unavailable.
else
  set timeout=5
fi
### END /etc/grub.d/00_header ###

### BEGIN /etc/grub.d/10_linux ###
menuentry 'Arch Linux' --class arch --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-8fb68a6d-5088-47dc-8f9a-63e21ae275d4' {
    load_video
    set gfxpayload=keep
    insmod gzio
    insmod part_gpt
    insmod ext2
    set root='hd0,gpt3'
    if [ x$feature_platform_search_hint = xy ]; then
      search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt3 --hint-efi=hd0,gpt3 --hint-baremetal=ahci0,gpt3  8fb68a6d-5088-47dc-8f9a-63e21ae275d4
    else
      search --no-floppy --fs-uuid --set=root 8fb68a6d-5088-47dc-8f9a-63e21ae275d4
    fi
    echo    'Carregando o Linux linux-lts...'
    linux    /boot/vmlinuz-linux-lts root=UUID=8fb68a6d-5088-47dc-8f9a-63e21ae275d4 rw  quiet
    echo    'Carregando o ramdisk inicial...'
    initrd  /boot/initramfs-linux-lts.img
}
submenu 'Opções avançadas para Arch Linux' $menuentry_id_option 'gnulinux-advanced-8fb68a6d-5088-47dc-8f9a-63e21ae275d4' {
    menuentry 'Arch Linux, com o Linux linux-lts' --class arch --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-linux-lts-advanced-8fb68a6d-5088-47dc-8f9a-63e21ae275d4' {
        load_video
        set gfxpayload=keep
        insmod gzio
        insmod part_gpt
        insmod ext2
        set root='hd0,gpt3'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt3 --hint-efi=hd0,gpt3 --hint-baremetal=ahci0,gpt3  8fb68a6d-5088-47dc-8f9a-63e21ae275d4
        else
          search --no-floppy --fs-uuid --set=root 8fb68a6d-5088-47dc-8f9a-63e21ae275d4
        fi
        echo    'Carregando o Linux linux-lts...'
        linux    /boot/vmlinuz-linux-lts root=UUID=8fb68a6d-5088-47dc-8f9a-63e21ae275d4 rw  quiet
        echo    'Carregando o ramdisk inicial...'
        initrd  /boot/initramfs-linux-lts.img
    }
    menuentry 'Arch Linux, with Linux linux-lts (fallback initramfs)' --class arch --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-linux-lts-fallback-8fb68a6d-5088-47dc-8f9a-63e21ae275d4' {
        load_video
        set gfxpayload=keep
        insmod gzio
        insmod part_gpt
        insmod ext2
        set root='hd0,gpt3'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt3 --hint-efi=hd0,gpt3 --hint-baremetal=ahci0,gpt3  8fb68a6d-5088-47dc-8f9a-63e21ae275d4
        else
          search --no-floppy --fs-uuid --set=root 8fb68a6d-5088-47dc-8f9a-63e21ae275d4
        fi
        echo    'Carregando o Linux linux-lts...'
        linux    /boot/vmlinuz-linux-lts root=UUID=8fb68a6d-5088-47dc-8f9a-63e21ae275d4 rw  quiet
        echo    'Carregando o ramdisk inicial...'
        initrd  /boot/initramfs-linux-lts-fallback.img
    }
    menuentry 'Arch Linux, com o Linux linux' --class arch --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-linux-advanced-8fb68a6d-5088-47dc-8f9a-63e21ae275d4' {
        load_video
        set gfxpayload=keep
        insmod gzio
        insmod part_gpt
        insmod ext2
        set root='hd0,gpt3'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt3 --hint-efi=hd0,gpt3 --hint-baremetal=ahci0,gpt3  8fb68a6d-5088-47dc-8f9a-63e21ae275d4
        else
          search --no-floppy --fs-uuid --set=root 8fb68a6d-5088-47dc-8f9a-63e21ae275d4
        fi
        echo    'Carregando o Linux linux...'
        linux    /boot/vmlinuz-linux root=UUID=8fb68a6d-5088-47dc-8f9a-63e21ae275d4 rw  quiet
        echo    'Carregando o ramdisk inicial...'
        initrd  /boot/initramfs-linux.img
    }
    menuentry 'Arch Linux, with Linux linux (fallback initramfs)' --class arch --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-linux-fallback-8fb68a6d-5088-47dc-8f9a-63e21ae275d4' {
        load_video
        set gfxpayload=keep
        insmod gzio
        insmod part_gpt
        insmod ext2
        set root='hd0,gpt3'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt3 --hint-efi=hd0,gpt3 --hint-baremetal=ahci0,gpt3  8fb68a6d-5088-47dc-8f9a-63e21ae275d4
        else
          search --no-floppy --fs-uuid --set=root 8fb68a6d-5088-47dc-8f9a-63e21ae275d4
        fi
        echo    'Carregando o Linux linux...'
        linux    /boot/vmlinuz-linux root=UUID=8fb68a6d-5088-47dc-8f9a-63e21ae275d4 rw  quiet
        echo    'Carregando o ramdisk inicial...'
        initrd  /boot/initramfs-linux-fallback.img
    }
}

### END /etc/grub.d/10_linux ###

### BEGIN /etc/grub.d/20_linux_xen ###
### END /etc/grub.d/20_linux_xen ###

### BEGIN /etc/grub.d/30_os-prober ###
### END /etc/grub.d/30_os-prober ###

### BEGIN /etc/grub.d/40_custom ###
# This file provides an easy way to add custom menu entries.  Simply type the
# menu entries you want to add after this comment.  Be careful not to change
# the 'exec tail' line above.
### END /etc/grub.d/40_custom ###

### BEGIN /etc/grub.d/41_custom ###
if [ -f  ${config_directory}/custom.cfg ]; then
  source ${config_directory}/custom.cfg
elif [ -z "${config_directory}" -a -f  $prefix/custom.cfg ]; then
  source $prefix/custom.cfg;
fi
### END /etc/grub.d/41_custom ###
</code>```

I want the non-LTS version to be the default version, so I don't need to go to Advanced Options and select the last version when I turn on my computer. How can I do it?

答:
Before any of this please make sure you can revert to your current state in case this attempt fails.

In your grub.cfg, the section starting with "menuentry 'Arch Linux'" is the one that points to default kernel. To make it point to your chosen kernel:

change the entry starting with "linux   /boot/vmlinuz-linux-lts..." to your custom kernel image (e.g. "linux   /boot/vmlinuz-linux root=UUID=8fb68a6d-5088-47dc-8f9a-63e21ae275d4 rw  quiet" in the same grub.cfg file)

change the entry "initrd  /boot/initramfs-linux-lts.img" to initramfs corresponding to your custom kernel.

I guess you already have your custom kernel and corresponding initramfs available. You can always generate initramfs by running # mkinitcpio -g /boot/mycustominitramfs -k /boot/mycustomkernelimage

ContentLicense: CC BY-SA 4.0

Title: Change default kernel version in GRUB

Body:
This is the content of the grub.cfg file of my Arch Linux system.

#
# DO NOT EDIT THIS FILE
#
# It is automatically generated by grub-mkconfig using templates
# from /etc/grub.d and settings from /etc/default/grub
#

### BEGIN /etc/grub.d/00_header ###
insmod part_gpt
insmod part_msdos
if [ -s $prefix/grubenv ]; then
  load_env
fi
if [ "${next_entry}" ] ; then
   set default="${next_entry}"
   set next_entry=
   save_env next_entry
   set boot_once=true
else
   set default="0"
fi

if [ x"${feature_menuentry_id}" = xy ]; then
  menuentry_id_option="--id"
else
  menuentry_id_option=""
fi

export menuentry_id_option

if [ "${prev_saved_entry}" ]; then
  set saved_entry="${prev_saved_entry}"
  save_env saved_entry
  set prev_saved_entry=
  save_env prev_saved_entry
  set boot_once=true
fi

function savedefault {
  if [ -z "${boot_once}" ]; then
    saved_entry="${chosen}"
    save_env saved_entry
  fi
}

function load_video {
  if [ x$feature_all_video_module = xy ]; then
    insmod all_video
  else
    insmod efi_gop
    insmod efi_uga
    insmod ieee1275_fb
    insmod vbe
    insmod vga
    insmod video_bochs
    insmod video_cirrus
  fi
}

if [ x$feature_default_font_path = xy ] ; then
   font=unicode
else
insmod part_gpt
insmod ext2
set root='hd0,gpt3'
if [ x$feature_platform_search_hint = xy ]; then
  search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt3 --hint-efi=hd0,gpt3 --hint-baremetal=ahci0,gpt3  8fb68a6d-5088-47dc-8f9a-63e21ae275d4
else
  search --no-floppy --fs-uuid --set=root 8fb68a6d-5088-47dc-8f9a-63e21ae275d4
fi
    font="/usr/share/grub/unicode.pf2"
fi

if loadfont $font ; then
  set gfxmode=auto
  load_video
  insmod gfxterm
  set locale_dir=$prefix/locale
  set lang=pt_BR
  insmod gettext
fi
terminal_input console
terminal_output gfxterm
if [ x$feature_timeout_style = xy ] ; then
  set timeout_style=menu
  set timeout=5
# Fallback normal timeout code in case the timeout_style feature is
# unavailable.
else
  set timeout=5
fi
### END /etc/grub.d/00_header ###

### BEGIN /etc/grub.d/10_linux ###
menuentry 'Arch Linux' --class arch --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-8fb68a6d-5088-47dc-8f9a-63e21ae275d4' {
    load_video
    set gfxpayload=keep
    insmod gzio
    insmod part_gpt
    insmod ext2
    set root='hd0,gpt3'
    if [ x$feature_platform_search_hint = xy ]; then
      search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt3 --hint-efi=hd0,gpt3 --hint-baremetal=ahci0,gpt3  8fb68a6d-5088-47dc-8f9a-63e21ae275d4
    else
      search --no-floppy --fs-uuid --set=root 8fb68a6d-5088-47dc-8f9a-63e21ae275d4
    fi
    echo    'Carregando o Linux linux-lts...'
    linux    /boot/vmlinuz-linux-lts root=UUID=8fb68a6d-5088-47dc-8f9a-63e21ae275d4 rw  quiet
    echo    'Carregando o ramdisk inicial...'
    initrd  /boot/initramfs-linux-lts.img
}
submenu 'Opções avançadas para Arch Linux' $menuentry_id_option 'gnulinux-advanced-8fb68a6d-5088-47dc-8f9a-63e21ae275d4' {
    menuentry 'Arch Linux, com o Linux linux-lts' --class arch --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-linux-lts-advanced-8fb68a6d-5088-47dc-8f9a-63e21ae275d4' {
        load_video
        set gfxpayload=keep
        insmod gzio
        insmod part_gpt
        insmod ext2
        set root='hd0,gpt3'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt3 --hint-efi=hd0,gpt3 --hint-baremetal=ahci0,gpt3  8fb68a6d-5088-47dc-8f9a-63e21ae275d4
        else
          search --no-floppy --fs-uuid --set=root 8fb68a6d-5088-47dc-8f9a-63e21ae275d4
        fi
        echo    'Carregando o Linux linux-lts...'
        linux    /boot/vmlinuz-linux-lts root=UUID=8fb68a6d-5088-47dc-8f9a-63e21ae275d4 rw  quiet
        echo    'Carregando o ramdisk inicial...'
        initrd  /boot/initramfs-linux-lts.img
    }
    menuentry 'Arch Linux, with Linux linux-lts (fallback initramfs)' --class arch --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-linux-lts-fallback-8fb68a6d-5088-47dc-8f9a-63e21ae275d4' {
        load_video
        set gfxpayload=keep
        insmod gzio
        insmod part_gpt
        insmod ext2
        set root='hd0,gpt3'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt3 --hint-efi=hd0,gpt3 --hint-baremetal=ahci0,gpt3  8fb68a6d-5088-47dc-8f9a-63e21ae275d4
        else
          search --no-floppy --fs-uuid --set=root 8fb68a6d-5088-47dc-8f9a-63e21ae275d4
        fi
        echo    'Carregando o Linux linux-lts...'
        linux    /boot/vmlinuz-linux-lts root=UUID=8fb68a6d-5088-47dc-8f9a-63e21ae275d4 rw  quiet
        echo    'Carregando o ramdisk inicial...'
        initrd  /boot/initramfs-linux-lts-fallback.img
    }
    menuentry 'Arch Linux, com o Linux linux' --class arch --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-linux-advanced-8fb68a6d-5088-47dc-8f9a-63e21ae275d4' {
        load_video
        set gfxpayload=keep
        insmod gzio
        insmod part_gpt
        insmod ext2
        set root='hd0,gpt3'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt3 --hint-efi=hd0,gpt3 --hint-baremetal=ahci0,gpt3  8fb68a6d-5088-47dc-8f9a-63e21ae275d4
        else
          search --no-floppy --fs-uuid --set=root 8fb68a6d-5088-47dc-8f9a-63e21ae275d4
        fi
        echo    'Carregando o Linux linux...'
        linux    /boot/vmlinuz-linux root=UUID=8fb68a6d-5088-47dc-8f9a-63e21ae275d4 rw  quiet
        echo    'Carregando o ramdisk inicial...'
        initrd  /boot/initramfs-linux.img
    }
    menuentry 'Arch Linux, with Linux linux (fallback initramfs)' --class arch --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-linux-fallback-8fb68a6d-5088-47dc-8f9a-63e21ae275d4' {
        load_video
        set gfxpayload=keep
        insmod gzio
        insmod part_gpt
        insmod ext2
        set root='hd0,gpt3'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt3 --hint-efi=hd0,gpt3 --hint-baremetal=ahci0,gpt3  8fb68a6d-5088-47dc-8f9a-63e21ae275d4
        else
          search --no-floppy --fs-uuid --set=root 8fb68a6d-5088-47dc-8f9a-63e21ae275d4
        fi
        echo    'Carregando o Linux linux...'
        linux    /boot/vmlinuz-linux root=UUID=8fb68a6d-5088-47dc-8f9a-63e21ae275d4 rw  quiet
        echo    'Carregando o ramdisk inicial...'
        initrd  /boot/initramfs-linux-fallback.img
    }
}

### END /etc/grub.d/10_linux ###

### BEGIN /etc/grub.d/20_linux_xen ###
### END /etc/grub.d/20_linux_xen ###

### BEGIN /etc/grub.d/30_os-prober ###
### END /etc/grub.d/30_os-prober ###

### BEGIN /etc/grub.d/40_custom ###
# This file provides an easy way to add custom menu entries.  Simply type the
# menu entries you want to add after this comment.  Be careful not to change
# the 'exec tail' line above.
### END /etc/grub.d/40_custom ###

### BEGIN /etc/grub.d/41_custom ###
if [ -f  ${config_directory}/custom.cfg ]; then
  source ${config_directory}/custom.cfg
elif [ -z "${config_directory}" -a -f  $prefix/custom.cfg ]; then
  source $prefix/custom.cfg;
fi
### END /etc/grub.d/41_custom ###

I want the non-LTS version to be the default version, so I don't need to go to Advanced Options and select the last version when I turn on my computer. How can I do it?


问:
JOIN table onto itself with parent id until no more rows
I have a table describing changes that has been made to an end_customers table. When someone changes and end_customer we create a new row in the end_customers table and add a row to end_customer_history table where end_customer_parent_id is the ID of the old end_customer, and end_customer_child_id is the ID of the new end_customer.

End Customer Table:

```<code>CREATE TABLE `end_customers` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `reference_person` varchar(255) DEFAULT NULL,
  `phone_number` varchar(255) NOT NULL,
  `email` varchar(255) DEFAULT NULL,
  `social_security_number` varchar(255) DEFAULT NULL,
  `comment` longtext,
  `token` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=101107 DEFAULT CHARSET=utf8;
</code>```

End Customer History Table:

```<code>CREATE TABLE `end_customer_history` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `end_customer_parent_id` bigint(20) NOT NULL,
  `end_customer_child_id` bigint(20) NOT NULL,
  `user_id` bigint(20) NOT NULL,
  `date` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `FK_end_customer_parent` (`end_customer_parent_id`),
  KEY `FK_end_customer_child` (`end_customer_child_id`),
  KEY `FK_user` (`user_id`),
  CONSTRAINT `end_customer_history_old_ibfk_1` FOREIGN KEY (`end_customer_parent_id`) REFERENCES `end_customers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `end_customer_history_old_ibfk_2` FOREIGN KEY (`end_customer_child_id`) REFERENCES `end_customers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `end_customer_history_old_ibfk_3` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=67 DEFAULT CHARSET=utf8;
</code>```

We are now refactoring the schema so that changes made to end_customers table directly edits the row instead of creating a new row, and puts a copy of the old data in a end_customer_history_new table that has the same schema as end_customers.

I need to migrate all old data to this new table.
So for each end_customer I have, I need to check if it has an entry in end_customer_history as a end_customer_child_id (it has been modified), and then check if that entrys parent is also present in end_customer_history as a child, and then check if that entrys parent is also present in end_customer_history as a child, and so forth until there are no more rows.

How do I do this in one migration SQL script?

答:
In the solution I came up with, it doesn't use any stored functions to loop over rows, because I could never get it to work. It takes the latest version of an end customer, and then joins similar rows using a token that we know is always the same and unique.

```<code>-- Move data from old end customer history to the new schema
-- May remove some redundant history, this will be ok
-- If an end customer has been changed more than once, all changes will have the same date (latest change) and the same user responsible for change
-- This is also ok

-- Insert the latest version of changed end_customers into new history table
INSERT INTO end_customer_history (name, reference_person, phone_number, email, social_security_number, comment, end_customer_id, user_id, date)
SELECT
ec.name, ec.reference_person, ec.phone_number, ec.email, ec.social_security_number, ec.comment, ech.end_customer_child_id, ech.user_id, ech.date
FROM end_customer_history_old AS ech
JOIN end_customers AS ec ON ec.id = ech.end_customer_parent_id
WHERE ech.end_customer_child_id IN (SELECT end_customer_id FROM orders);

-- Remove all the old data
DROP TABLE end_customer_history_old;

-- Insert all versions of an end_customer based on the latest history, joined on token (always the same)
INSERT INTO end_customer_history (name, reference_person, phone_number, email, social_security_number, comment, end_customer_id, user_id, date)
SELECT
parent.name, parent.reference_person, parent.phone_number, parent.email, parent.social_security_number, parent.comment, ech.end_customer_id, ech.user_id, ech.date
FROM end_customer_history AS ech
JOIN end_customers AS ec ON ec.id = ech.end_customer_id
JOIN end_customers AS parent ON parent.token = ec.token AND parent.id <> ec.id;

-- This unfortunately creates duplicates of some rows, so it looks like changes have been made multiple times (with no new data)
-- Create a temporary table that copies over unique rows from end_customer_history
CREATE TABLE temp AS
SELECT * FROM end_customer_history
GROUP BY
name, reference_person, phone_number, email, social_security_number, comment, end_customer_id, user_id, date;

-- Clear the end_customer_history table all together
TRUNCATE TABLE end_customer_history;

-- Copy over filtered unique history rows
INSERT INTO end_customer_history (name, reference_person, phone_number, email, social_security_number, comment, end_customer_id, user_id, date)
SELECT
name, reference_person, phone_number, email, social_security_number, comment, end_customer_id, user_id, date
FROM temp;

-- Remove temporary table
DROP TABLE temp;
</code>```

Body:
I have a table describing changes that has been made to an end_customers table. When someone changes and end_customer we create a new row in the end_customers table and add a row to end_customer_history table where end_customer_parent_id is the ID of the old end_customer, and end_customer_child_id is the ID of the new end_customer.

End Customer Table:

CREATE TABLE `end_customers` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `reference_person` varchar(255) DEFAULT NULL,
  `phone_number` varchar(255) NOT NULL,
  `email` varchar(255) DEFAULT NULL,
  `social_security_number` varchar(255) DEFAULT NULL,
  `comment` longtext,
  `token` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=101107 DEFAULT CHARSET=utf8;

End Customer History Table:

CREATE TABLE `end_customer_history` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `end_customer_parent_id` bigint(20) NOT NULL,
  `end_customer_child_id` bigint(20) NOT NULL,
  `user_id` bigint(20) NOT NULL,
  `date` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `FK_end_customer_parent` (`end_customer_parent_id`),
  KEY `FK_end_customer_child` (`end_customer_child_id`),
  KEY `FK_user` (`user_id`),
  CONSTRAINT `end_customer_history_old_ibfk_1` FOREIGN KEY (`end_customer_parent_id`) REFERENCES `end_customers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `end_customer_history_old_ibfk_2` FOREIGN KEY (`end_customer_child_id`) REFERENCES `end_customers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `end_customer_history_old_ibfk_3` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=67 DEFAULT CHARSET=utf8;

We are now refactoring the schema so that changes made to end_customers table directly edits the row instead of creating a new row, and puts a copy of the old data in a end_customer_history_new table that has the same schema as end_customers.

I need to migrate all old data to this new table.
So for each end_customer I have, I need to check if it has an entry in end_customer_history as a end_customer_child_id (it has been modified), and then check if that entrys parent is also present in end_customer_history as a child, and then check if that entrys parent is also present in end_customer_history as a child, and so forth until there are no more rows.

How do I do this in one migration SQL script?

Body:
In the solution I came up with, it doesn't use any stored functions to loop over rows, because I could never get it to work. It takes the latest version of an end customer, and then joins similar rows using a token that we know is always the same and unique.

-- Move data from old end customer history to the new schema
-- May remove some redundant history, this will be ok
-- If an end customer has been changed more than once, all changes will have the same date (latest change) and the same user responsible for change
-- This is also ok

-- Insert the latest version of changed end_customers into new history table
INSERT INTO end_customer_history (name, reference_person, phone_number, email, social_security_number, comment, end_customer_id, user_id, date)
SELECT
ec.name, ec.reference_person, ec.phone_number, ec.email, ec.social_security_number, ec.comment, ech.end_customer_child_id, ech.user_id, ech.date
FROM end_customer_history_old AS ech
JOIN end_customers AS ec ON ec.id = ech.end_customer_parent_id
WHERE ech.end_customer_child_id IN (SELECT end_customer_id FROM orders);

-- Remove all the old data
DROP TABLE end_customer_history_old;

-- Insert all versions of an end_customer based on the latest history, joined on token (always the same)
INSERT INTO end_customer_history (name, reference_person, phone_number, email, social_security_number, comment, end_customer_id, user_id, date)
SELECT
parent.name, parent.reference_person, parent.phone_number, parent.email, parent.social_security_number, parent.comment, ech.end_customer_id, ech.user_id, ech.date
FROM end_customer_history AS ech
JOIN end_customers AS ec ON ec.id = ech.end_customer_id
JOIN end_customers AS parent ON parent.token = ec.token AND parent.id <> ec.id;

-- This unfortunately creates duplicates of some rows, so it looks like changes have been made multiple times (with no new data)
-- Create a temporary table that copies over unique rows from end_customer_history
CREATE TABLE temp AS
SELECT * FROM end_customer_history
GROUP BY
name, reference_person, phone_number, email, social_security_number, comment, end_customer_id, user_id, date;

-- Clear the end_customer_history table all together
TRUNCATE TABLE end_customer_history;

-- Copy over filtered unique history rows
INSERT INTO end_customer_history (name, reference_person, phone_number, email, social_security_number, comment, end_customer_id, user_id, date)
SELECT
name, reference_person, phone_number, email, social_security_number, comment, end_customer_id, user_id, date
FROM temp;

-- Remove temporary table
DROP TABLE temp;


问:
Rxjs: shorthand of create observable from value or observable
I'm using rxjs with typescript. I wrote following two simple functions. But I guess rxjs already has such functionality. Does rxjs?

```<code>export function isObservable(value: any): value is Observable<any> {
  return value instanceof Observable;
}

export function createObservable<T>(value: T | Observable<T>): Observable < T > {
  return isObservable(value) ? value : Observable.of(value);
}
</code>```

答:
I don't think RxJS 5 has exactly this functionality already because it's you who should be aware of what type of data you're working with.

However, you can make use of the fact that RxJS handles any Observables, Promises, Observable-like, array-like and so on ... objects the same way and write the following:

```<code>const val1 = Observable.of(42);
const val2 = [42];

Observable.from(val1).subscribe(console.log);
Observable.from(val2).subscribe(console.log);
</code>```

This will in both cases print just 42 even though once I used an Observable with a single value and then an array with a single value.

See live demo: https://jsbin.com/fubobon/3/edit?js,console

Body:
I'm using rxjs with typescript. I wrote following two simple functions. But I guess rxjs already has such functionality. Does rxjs?

export function isObservable(value: any): value is Observable<any> {
  return value instanceof Observable;
}

export function createObservable<T>(value: T | Observable<T>): Observable < T > {
  return isObservable(value) ? value : Observable.of(value);
}

Body:
I don't think RxJS 5 has exactly this functionality already because it's you who should be aware of what type of data you're working with.

However, you can make use of the fact that RxJS handles any Observables, Promises, Observable-like, array-like and so on ... objects the same way and write the following:

const val1 = Observable.of(42);
const val2 = [42];

Observable.from(val1).subscribe(console.log);
Observable.from(val2).subscribe(console.log);

This will in both cases print just 42 even though once I used an Observable with a single value and then an array with a single value.

See live demo: https://jsbin.com/fubobon/3/edit?js,console


问:
access textfield text from another viewController
I try to access a textfield content in my view profileView from my first view viewController but it doesn't work.
I read that I have to use override func prepare(for segue: UIStoryboardSegue, sender: Any?) {} so I did but it still not working and I don't understand why.

Here is my viewController code:

// This code is the code generated by xCode, only the loginField was added.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var loginField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
```

<p>and here is my <code>profileController</code> prepare func:</p>

<pre class="lang-swift prettyprint-override"><code>    var login: String!
    @IBOutlet weak var myLabel: UILabel!

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        print("prepare")
        if (segue.identifier == "mainMenu")
        {
            let svc = segue.source as! ViewController
            login = svc.loginField.text
            self.myLabel.text = login
            print(login)
        }
    }
</code>```

Actually, the thing i really read was "prepareForSegue" func but when I try to override it, xCode won't compile the code...

Thanks for your help.

答:
write your prepareforSegue method in your viewController

why?

Because you want to send ViewController textfield data to profileViewController.That is write your prepareForSegue in Source. Here,

```<code>Source = ViewController

Destination = ProfileView
</code>```

Note:

Use a variable in your destinationViewController(ProfileView Controller) and keep the textField data in this variable.

like this in prepareForSegue.

```<code> destinationVC.someVariable = self.SourceViewLabel.text // your sourceViewController
</code>```

and in viewDidLoad of your destinationViewController(ProfileView) write this.

```<code>self.profileLabel.text = somVariable
</code>```

In my first view i wrote this.

```<code>@IBAction func nexVCAction(_ sender: Any) {

    self.performSegue(withIdentifier: "secondvc", sender: self)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier  == "secondvc" {
        let vc = segue.destination as! secondVC
        vc.stringHolder = textField.text!
    }

}
</code>```

And this is the second view code.

```<code>import UIKit

class secondVC: UIViewController {

    @IBOutlet weak var textlabel: UILabel!
    var stringHolder:String = ""
    override func viewDidLoad() {
        super.viewDidLoad()

        textlabel.text = stringHolder

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

I made git project for this.

Check only FirstVC.swift and secondVC.swift

And this is the output.

Body:
I try to access a textfield content in my view profileView from my first view viewController but it doesn't work.
I read that I have to use override func prepare(for segue: UIStoryboardSegue, sender: Any?) {} so I did but it still not working and I don't understand why.

Here is my viewController code:

// This code is the code generated by xCode, only the loginField was added.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var loginField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

and here is my profileController prepare func:

    var login: String!
    @IBOutlet weak var myLabel: UILabel!

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        print("prepare")
        if (segue.identifier == "mainMenu")
        {
            let svc = segue.source as! ViewController
            login = svc.loginField.text
            self.myLabel.text = login
            print(login)
        }
    }

Actually, the thing i really read was "prepareForSegue" func but when I try to override it, xCode won't compile the code...

Thanks for your help.

Body:
write your prepareforSegue method in your viewController

why?

Because you want to send ViewController textfield data to profileViewController.That is write your prepareForSegue in Source. Here,

Source = ViewController

Destination = ProfileView

Note:

Use a variable in your destinationViewController(ProfileView Controller) and keep the textField data in this variable.

like this in prepareForSegue.

 destinationVC.someVariable = self.SourceViewLabel.text // your sourceViewController

and in viewDidLoad of your destinationViewController(ProfileView) write this.

self.profileLabel.text = somVariable

In my first view i wrote this.

@IBAction func nexVCAction(_ sender: Any) {

    self.performSegue(withIdentifier: "secondvc", sender: self)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier  == "secondvc" {
        let vc = segue.destination as! secondVC
        vc.stringHolder = textField.text!
    }

}

And this is the second view code.

import UIKit

class secondVC: UIViewController {

    @IBOutlet weak var textlabel: UILabel!
    var stringHolder:String = ""
    override func viewDidLoad() {
        super.viewDidLoad()

        textlabel.text = stringHolder

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

I made git project for this.

Check only FirstVC.swift and secondVC.swift

And this is the output.


问:
I'm trying to echo an image in a PHP variable in CodeIgniter
Hello I'm trying to echo an image on a view page in CodeIgniter but nothing is displayed on the page.

Here I'm making the variable:

```<code><?php $image = "<img src='../../images/stoel.jpg' alt='img' />";  ?>
</code>```

And here I'm trying to echo the image:

```<code><img src="<?php echo $image;?>">
</code>```

答:
I think this is what you mean. Since you are echoing inside the src attribute, you do not need to store the whole <image>, just the path will do.

```<code><?php
    $image = "../../images/stoel.jpg";
?>

<img src="<?php echo $image;?>">
</code>```

Body:
Hello I'm trying to echo an image on a view page in CodeIgniter but nothing is displayed on the page.

Here I'm making the variable:

<?php $image = "";  ?>

And here I'm trying to echo the image:

<img src="<?php echo $image;?>">

Body:
I think this is what you mean. Since you are echoing inside the src attribute, you do not need to store the whole <image>, just the path will do.

<?php
    $image = "../../images/stoel.jpg";
?>

<img src="<?php echo $image;?>">


问:
WebDeploy - Connection String TFS2017
In my WebConfig I have the following connection String.

```<code><connectionStrings>

   <add name="Name" connectionString="Url=hSomeURL; Domain=SomeDomain; Username=UserName; Password=YYYYY;"

</connectionStrings>
</code>```

In my pub.pubxml file I am trying to transform this String with the Env variables from my Release definition for Username,password and Domain. Could I call this connection string from a parameters.xml file? I tried adding this to my Web.Release.Config file but it did not work xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/> .

答:
Make sure you are using a right format such as the name matches the auto generated connection string name  in the parameters.xml. A sample:

```<code><parameters>
  <parameter name="Username" value="xxx">
    <parameterEntry type="XMLFile" scope="web.config$" match="//configuration/connectionStrings/site/@xxx"/>
  </parameter>
</code>```

For more details, you could take a look at this blog: How to build a connection string from other parameters within MSDeploy packages to avoid repeating yourself in Release Management variables

Title: WebDeploy - Connection String TFS2017

Body:
In my WebConfig I have the following connection String.

<connectionStrings>

   <add name="Name" connectionString="Url=hSomeURL; Domain=SomeDomain; Username=UserName; Password=YYYYY;"

</connectionStrings>

In my pub.pubxml file I am trying to transform this String with the Env variables from my Release definition for Username,password and Domain. Could I call this connection string from a parameters.xml file? I tried adding this to my Web.Release.Config file but it did not work xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/> .

Body:
Make sure you are using a right format such as the name matches the auto generated connection string name  in the parameters.xml. A sample:

<parameters>
  <parameter name="Username" value="xxx">
    <parameterEntry type="XMLFile" scope="web.config$" match="//configuration/connectionStrings/site/@xxx"/>
  </parameter>

For more details, you could take a look at this blog: How to build a connection string from other parameters within MSDeploy packages to avoid repeating yourself in Release Management variables


问:
If statement variable returning empty
this is a test code i wrote to get a value set for $rectype to insert into a table. problem I'm having is $rectype is returning 0 or empty. the files do exist since I perform a similar is_file check to start the process that leads up to this section of the coding</p>

```<code>$dirchk1 = "/temp/files/" . $data[0] . ".doc"; // exist
$dirchk2 = "/temp/files/" . $data[1] . ".doc"; // exist

$file_1 = (is_file($dirchk1));
$file_2 = (is_file($dirchk2));

if ($file_1) {
$rectype == ($file_2 ? '3' : '1');
}

echo $rectype . "\n";
</code>```

答:
You have a typo:

```<code>$rectype = ($file_2 ? '3' : '1');
</code>```

Also read something about operator precedence to avoid using so many useless parentheses.

Title: If statement variable returning empty

Body:
this is a test code i wrote to get a value set for $rectype to insert into a table. problem I'm having is $rectype is returning 0 or empty. the files do exist since I perform a similar is_file check to start the process that leads up to this section of the coding

$dirchk1 = "/temp/files/" . $data[0] . ".doc"; // exist
$dirchk2 = "/temp/files/" . $data[1] . ".doc"; // exist

$file_1 = (is_file($dirchk1));
$file_2 = (is_file($dirchk2));

if ($file_1) {
$rectype == ($file_2 ? '3' : '1');
}

echo $rectype . "\n";

Body:
You have a typo:

$rectype = ($file_2 ? '3' : '1');

Also read something about operator precedence to avoid using so many useless parentheses.


问:
TextIO. Read multiple files from GCS using pattern {}
I tried using the following

```<code>TextIO.Read.from("gs://xyz.abc/xxx_{2017-06-06,2017-06-06}.csv")
</code>```

That pattern didn't work, as I get

```<code>java.lang.IllegalStateException: Unable to find any files matching StaticValueProvider{value=gs://xyz.abc/xxx_{2017-06-06,2017-06-06}.csv}
</code>```

Even though those 2 files do exist. And I tried with a local file using a similar expression

```<code>TextIO.Read.from("somefolder/xxx_{2017-06-06,2017-06-06}.csv")
</code>```

And that did work just fine.

I would've thought there would be support for all kinds of globs for files in GCS, but nope. Why is that? is there away to accomplish what I'm looking for?

答:
This may be another option, in addition to Scott's suggestion and your comment on his answer:

You can define a list with the paths you want to read and then iterate over it, creating a number of PCollections in the usual way:

```<code>PCollection<String> events1 = p.apply(TextIO.Read.from(path1));
PCollection<String> events2 = p.apply(TextIO.Read.from(path2));
</code>```

Then create a PCollectionList:

```<code>PCollectionList<String> eventsList = PCollectionList.of(events1).and(events2);
</code>```

And then flatten this list into your PCollection for your main input:

PCollection<String> events = eventsList.apply(Flatten.pCollections());

Body:
I tried using the following

TextIO.Read.from("gs://xyz.abc/xxx_{2017-06-06,2017-06-06}.csv")

That pattern didn't work, as I get

java.lang.IllegalStateException: Unable to find any files matching StaticValueProvider{value=gs://xyz.abc/xxx_{2017-06-06,2017-06-06}.csv}

Even though those 2 files do exist. And I tried with a local file using a similar expression

TextIO.Read.from("somefolder/xxx_{2017-06-06,2017-06-06}.csv")

And that did work just fine.

I would've thought there would be support for all kinds of globs for files in GCS, but nope. Why is that? is there away to accomplish what I'm looking for?

Body:
This may be another option, in addition to Scott's suggestion and your comment on his answer:

You can define a list with the paths you want to read and then iterate over it, creating a number of PCollections in the usual way:

PCollection<String> events1 = p.apply(TextIO.Read.from(path1));
PCollection<String> events2 = p.apply(TextIO.Read.from(path2));

Then create a PCollectionList:

PCollectionList<String> eventsList = PCollectionList.of(events1).and(events2);

And then flatten this list into your PCollection for your main input:

PCollection<String> events = eventsList.apply(Flatten.pCollections());


问:
How to load chat history on top of recycler view android
Hi I am developing a chat application like whatsapp. I have to load the chat history from the api when user scrolls down like in whatsapp. I get the data and set it to the adapter. But the history is loading at the bottom of recycler view. I need to add it on top for every scroll. This is my code. Please help me. Thanks in advance.</p>

```<code>                              if (Status.equals("1")) {
                                historyList = resp.getHistory();
                                Log.i("history size",String.valueOf(resp.getHistory().size()));
                                String historysize = String.valueOf(resp.getHistory().size());
                                Message message = new Message();
                                for (int i = 0; i < resp.getHistory().size(); i++) {
                                    String fromusertoken = String.valueOf(resp.getHistory().get(i).getFromUserToken());
                                    String txtmsg = resp.getHistory().get(i).getMessage();
                                    String username = String.valueOf(resp.getHistory().get(i).getFromUserName());

                                    if (fromusertoken.equals(user_token)) {
                                        Message messages = new Message();
                                        messages.setUser_token(fromusertoken);
                                        messages.setUsername(username);
                                        messages.setIsMine(true);
                                        messages.setMessage(txtmsg);
                                        messageAdapter.add(messages);

                                    }
                                    else {
                                        Message messages = new Message();
                                        messages.setUser_token(fromusertoken);
                                        messages.setUsername(username);
                                        messages.setIsMine(false);
                                        messages.setMessage(txtmsg);
                                        messageAdapter.add(messages);
                                    }
                                }

                                messageAdapter.notifyDataSetChanged();
                                onItemsLoadComplete();

                                Toast.makeText(Single_chat.this, msg, Toast.LENGTH_SHORT).show();
                            }

                        } else {
                            Toast.makeText(Single_chat.this, msg, Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    Toast.makeText(Single_chat.this, "No Response", Toast.LENGTH_SHORT).show();
                }

            }
</code>```

答:
I changed the list in adapter as messagelist.add(0,message). It worked.

```<code>public void add(Message message) {
    messageList.add(0,message);
    notifyItemInserted(messageList.size() - 1);
}
</code>```

Body:
Hi I am developing a chat application like whatsapp. I have to load the chat history from the api when user scrolls down like in whatsapp. I get the data and set it to the adapter. But the history is loading at the bottom of recycler view. I need to add it on top for every scroll. This is my code. Please help me. Thanks in advance.

                              if (Status.equals("1")) {
                                historyList = resp.getHistory();
                                Log.i("history size",String.valueOf(resp.getHistory().size()));
                                String historysize = String.valueOf(resp.getHistory().size());
                                Message message = new Message();
                                for (int i = 0; i < resp.getHistory().size(); i++) {
                                    String fromusertoken = String.valueOf(resp.getHistory().get(i).getFromUserToken());
                                    String txtmsg = resp.getHistory().get(i).getMessage();
                                    String username = String.valueOf(resp.getHistory().get(i).getFromUserName());

                                    if (fromusertoken.equals(user_token)) {
                                        Message messages = new Message();
                                        messages.setUser_token(fromusertoken);
                                        messages.setUsername(username);
                                        messages.setIsMine(true);
                                        messages.setMessage(txtmsg);
                                        messageAdapter.add(messages);

                                    }
                                    else {
                                        Message messages = new Message();
                                        messages.setUser_token(fromusertoken);
                                        messages.setUsername(username);
                                        messages.setIsMine(false);
                                        messages.setMessage(txtmsg);
                                        messageAdapter.add(messages);
                                    }
                                }

                                messageAdapter.notifyDataSetChanged();
                                onItemsLoadComplete();

                                Toast.makeText(Single_chat.this, msg, Toast.LENGTH_SHORT).show();
                            }

                        } else {
                            Toast.makeText(Single_chat.this, msg, Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    Toast.makeText(Single_chat.this, "No Response", Toast.LENGTH_SHORT).show();
                }

            }

Body:
I changed the list in adapter as messagelist.add(0,message). It worked.

public void add(Message message) {
    messageList.add(0,message);
    notifyItemInserted(messageList.size() - 1);
}


问:
SQL - One very long table with several foreign keys VS several short tables
What would be better, performance wise?

One table with several foreign keys and a lot of rows

OR

Several tables with one foreign keys with less data per table.

Example:

I want to create one a table that will contains notes for the user to right, and each note will be related to another table.
On one option it will be

Notes(ID, Text, CustomerID, AccountID, UserID, AnotherID)
which will contain null values for each unrelated foreign key so:

```<code>ID  Text           CustomerID  AccountID  UserID   AnotherID
1   "Call James"   1           null       null     null
2   "Call Havale"  null        2          null     null
3   "Call Shimi"   null        null       4556     null
</code>```

An other option will be to open separate tables that will be typed foreign key for each:

```<code>AccountNotes(ID, Text, AccountID)

CustomerNotes(ID, Text, CustomerID)

UserNotes(ID, Text, UserID), etc...
</code>```

The last option will be to treat it like a many to many relation, although it isn't (the Notes_to_Accounts(NoteID,AccountID) table, for example..).

All the answers i found here were about one table with several columnsthen a lot of small tables with less columns, which is not the problem i'm trying to solve.

答:
A offer third option, but  it can be too complicated for simple entity(one text field):</p>

```<code>Notes(Id, Text)
AccountNotes(AccountId, NoteId)
CustomerNotes(CustomerId, NoteId)
</code>```

Body:
What would be better, performance wise?

One table with several foreign keys and a lot of rows

OR

Several tables with one foreign keys with less data per table.

Example:

I want to create one a table that will contains notes for the user to right, and each note will be related to another table.
On one option it will be

Notes(ID, Text, CustomerID, AccountID, UserID, AnotherID)
which will contain null values for each unrelated foreign key so:

ID  Text           CustomerID  AccountID  UserID   AnotherID
1   "Call James"   1           null       null     null
2   "Call Havale"  null        2          null     null
3   "Call Shimi"   null        null       4556     null

An other option will be to open separate tables that will be typed foreign key for each:

AccountNotes(ID, Text, AccountID)

CustomerNotes(ID, Text, CustomerID)

UserNotes(ID, Text, UserID), etc...

The last option will be to treat it like a many to many relation, although it isn't (the Notes_to_Accounts(NoteID,AccountID) table, for example..).

All the answers i found here were about one table with several columnsthen a lot of small tables with less columns, which is not the problem i'm trying to solve.

Body:
A offer third option, but  it can be too complicated for simple entity(one text field):

Notes(Id, Text)
AccountNotes(AccountId, NoteId)
CustomerNotes(CustomerId, NoteId)


问:
Providing initial data django unit test
I'm working on a Django application which have a lot of unit tests.

Some of those test functionalities on unmanaged models (Manage = False). In order to test them, there are in setUpClass the execution of some sql files.

Now, after upgrading at Django 1.11.2, some warnings are raised during the execution of sql files.

The warning is the following:

```<code>Warning: Unknown table '<table name>' return self.cursor.execute(query, args)
</code>```

I searched the reason of this warning and seems it is linked to the sql file that check if the table exists before create or drop it.

I would remove this warnings, and to do this, I thought of drop the table in tearDownClass, in order to remove the IF EXISTS statements in sql files.

I think that this approach makes unit tests slower and I don't know if it is a best practice.

Furthermore, I found in Django documentation that is possible use fixtures to providing initial data. Since documentation is not very clear (from my point of view) on how use fixtures in unit tests, I'm asking this question to understand how is the best practice/approach to solve this problem.

Thanks in advance

答:
I did not understand your concern fully. However if the problem is loading initial data (fixtures) for testing, that can be done with following procedures:

```<code>class Test1(TestCase):
    fixtures = [
       "fixtures.json",
    ]

    def setUp(self):
        ...

    // test cases
</code>```

More information on https://docs.djangoproject.com/en/1.11/topics/testing/tools/#fixture-loading

Title: Providing initial data django unit test

Body:
I'm working on a Django application which have a lot of unit tests.

Some of those test functionalities on unmanaged models (Manage = False). In order to test them, there are in setUpClass the execution of some sql files.

Now, after upgrading at Django 1.11.2, some warnings are raised during the execution of sql files.

The warning is the following:

Warning: Unknown table '
' return self.cursor.execute(query, args)

I searched the reason of this warning and seems it is linked to the sql file that check if the table exists before create or drop it.

I would remove this warnings, and to do this, I thought of drop the table in tearDownClass, in order to remove the IF EXISTS statements in sql files.

I think that this approach makes unit tests slower and I don't know if it is a best practice.

Furthermore, I found in Django documentation that is possible use fixtures to providing initial data. Since documentation is not very clear (from my point of view) on how use fixtures in unit tests, I'm asking this question to understand how is the best practice/approach to solve this problem.

Thanks in advance

Body:
I did not understand your concern fully. However if the problem is loading initial data (fixtures) for testing, that can be done with following procedures:

class Test1(TestCase):
    fixtures = [
       "fixtures.json",
    ]

    def setUp(self):
        ...

    // test cases

More information on https://docs.djangoproject.com/en/1.11/topics/testing/tools/#fixture-loading


答:
You are inserting full Image tag into src attribute.

```<code><?php $image = "<img src='../../images/stoel.jpg' alt='img' />";  ?>

and

<?php echo $image; ?>
</code>```

or

```<code><?php $image = "../../images/stoel.jpg"; ?>

and

<img src="<?php echo $image;?>">
</code>```

Title: I'm trying to echo an image in a PHP variable in CodeIgniter

Body:
You are inserting full Image tag into src attribute.

<?php $image = "<img src='../../images/stoel.jpg' alt='img' />";  ?>

and

<?php echo $image; ?>

or

<?php $image = "../../images/stoel.jpg"; ?>

and

<img src="<?php echo $image;?>">


问:
Why we extends WCMUsePojo class while working with AEM?
Why we extends WCMUsepojo abstract class in our program while working with AEM?

What is the advantage of using this class?

答:
Because in AEM’s component development mechanism, you likely need a way to provide back-end logic to components.

That's because Sightly (when used as a rendering script language instead of the JSP pages) is on purpose a limited template language that allows to do only small basic operations, and the heavy lifting logic should be done inside a Java class or a server-side JS (that you refer using the data-sly-use element inside the Sightly script).

This provide better decoupling of the business logic and so your code will be more easily maintainable and also easier to debug.

In order to abstract component Java class with page context or binding objects, previously Adobe’s WCMUse was used, or a custom implementation of Use class. If your working with AEM 6.1 or 6.2 WCMUsePojo class is used (or even Sling Models). With the release of AEM 6.3 and AEM Core WCM Components, we see that using Sling Models have been advocated by Adobe as the best practice.


答:
```<code><?php $image = "<img src='../../images/stoel.jpg' alt='img' />";  ?>
</code>```

you try like this

```<code><?php echo $image; ?>
</code>```

Body:
<?php $image = "<img src='../../images/stoel.jpg' alt='img' />";  ?>

you try like this

<?php echo $image; ?>


问:
SOAP Client with access to a WSDL-file
I am working in ASP.NET in C# in webservices of sabre, I am trying to call wwebservice airlowfaresearch and it's fine but I will do work to get the bargain finder max alternate date, I used this: webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirLowFareSearchLLS1.13.1RQ.wsdl
and changed the action for :BargainFinderMax_ADRQ and this is my request:

```<code><?xml version="1.0" encoding="UTF-8"?>
<OTA_AirLowFareSearchRQ AltLangID="en-us" PrimaryLangID="en-us" SequenceNmbr="1" Version="3.1.0" Target="Test" TimeStamp="0001-01-01T12:00:00" EchoToken="String" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <POS>
        <Source PseudoCityCode="X0JA"/>
    </POS>
    <OriginDestinationInformation RPH="1">
        <DepartureDateTime>2017-06-07</DepartureDateTime>
        <OriginLocation LocationCode="LIM"/>
        <DestinationLocation LocationCode="AQP"/>
        <TPA_Extensions>
            <SegmentType Code="O"/>
            <WithoutAvail/>
        </TPA_Extensions>
    </OriginDestinationInformation>
    <OriginDestinationInformation RPH="2">
        <DepartureDateTime>2017-06-10</DepartureDateTime>
        <OriginLocation LocationCode="AQP"/>
        <DestinationLocation LocationCode="LIM"/>
        <TPA_Extensions>
            <SegmentType Code="O"/>
            <WithoutAvail/>
        </TPA_Extensions>
    </OriginDestinationInformation>
    <TravelPreferences MaxStopsQuantity="2">
        <CabinPref RPH="1" Code="Y"/>
        <CabinPref RPH="2" Code="Y"/>
        <TPA_Extensions>
            <ExcludeVendorPref Code="2I"/>
            <ExcludeVendorPref Code="UA"/>
            <ExcludeVendorPref Code="IB"/>
            <NumTrips Number="19"/>
        </TPA_Extensions>
    </TravelPreferences>
    <TravelerInformation>
        <PassengerTypeQuantity Code="ADT" Quantity="1"/>
        <TPA_Extensions/>
    </TravelerInformation>
    <PriceRequestInformation CurrencyCode="USD">
        <TPA_Extensions>
            <FareCalc>
                <FareBasis WithFareCalc="true"/>
            </FareCalc>
            <Priority>
                <Price Priority="1"/>
                <DirectFlights Priority="2"/>
                <Time Priority="3"/>
                <Vendor Priority="4"/>
            </Priority>
        </TPA_Extensions>
    </PriceRequestInformation>
    <TPA_Extensions>
        <IntelliSellTransaction>
            <RequestType Name="AD3"/>
        </IntelliSellTransaction>
    </TPA_Extensions>
</OTA_AirLowFareSearchRQ>
</code>```

but could not find, in the response, the object oAirLowFareSearchRS

```<code>oAirLowFareSearchRS = oAirLowFareSearchRQService.OTA_AirLowFareSearchRQ(oAirLowFareSearchRQ)
</code>```

I get this error:

Object reference not set to an instance of an object.

and the xml response only this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<OTA_AirLowFareSearchRS xsi:nil="true" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
</code>```

What is the cause of this problem?

答:
Here is sample working BFM_AD request for you:

```<code><soapenv:Body>
    <OTA_AirLowFareSearchRQ AvailableFlightsOnly="true" ResponseType="OTA" ResponseVersion="3.0.0" Version="3.0.0" xmlns="http://www.opentravel.org/OTA/2003/05">
        <POS>
            <Source PseudoCityCode="***">
                <RequestorID ID="1" Type="1">
                    <CompanyName Code="TN"/>
                </RequestorID>
            </Source>
        </POS>
        <OriginDestinationInformation RPH="1">
            <DepartureDateTime>2017-06-15T00:00:00</DepartureDateTime>
            <DepartureWindow>00002359</DepartureWindow>
            <OriginLocation LocationCode="LIM" LocationType="A"/>
            <DestinationLocation LocationCode="AQP" LocationType="A"/>
            <TPA_Extensions>
                <SegmentType Code="O"/>
            </TPA_Extensions>
        </OriginDestinationInformation>
        <OriginDestinationInformation RPH="2">
            <DepartureDateTime>2017-06-18T00:00:00</DepartureDateTime>
            <DepartureWindow>00002359</DepartureWindow>
            <OriginLocation LocationCode="AQP" LocationType="A"/>
            <DestinationLocation LocationCode="LIM" LocationType="A"/>
            <TPA_Extensions>
                <SegmentType Code="O"/>
            </TPA_Extensions>
        </OriginDestinationInformation>
        <TravelPreferences ETicketDesired="true" ValidInterlineTicket="true">
            <TPA_Extensions>
                <TripType Value="Return"/>
                <FlightStopsAsConnections Ind="true"/>
                <ExcludeCallDirectCarriers Enabled="true"/>
            </TPA_Extensions>
            <Baggage Description="true" RequestType="A"/>
        </TravelPreferences>
        <TravelerInfoSummary>
            <SeatsRequested>1</SeatsRequested>
            <AirTravelerAvail>
                <PassengerTypeQuantity Code="ADT" Quantity="1"/>
            </AirTravelerAvail>
            <PriceRequestInformation CurrencyCode="TRY" NegotiatedFaresOnly="false">
                <TPA_Extensions>
                    <BrandedFareIndicators MultipleBrandedFares="true"/>
                </TPA_Extensions>
            </PriceRequestInformation>
        </TravelerInfoSummary>
        <TPA_Extensions>
            <IntelliSellTransaction>
                <RequestType Name="AD3"/>
            </IntelliSellTransaction>
        </TPA_Extensions>
    </OTA_AirLowFareSearchRQ>
</soapenv:Body>
</code>```

I advice you to start from working request, after getting successful response, you should specialize that request for your need.

Title: SOAP Client with access to a WSDL-file

Body:
I am working in ASP.NET in C# in webservices of sabre, I am trying to call wwebservice airlowfaresearch and it's fine but I will do work to get the bargain finder max alternate date, I used this: webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirLowFareSearchLLS1.13.1RQ.wsdl
and changed the action for :BargainFinderMax_ADRQ and this is my request:

<?xml version="1.0" encoding="UTF-8"?>
<OTA_AirLowFareSearchRQ AltLangID="en-us" PrimaryLangID="en-us" SequenceNmbr="1" Version="3.1.0" Target="Test" TimeStamp="0001-01-01T12:00:00" EchoToken="String" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <POS>
        <Source PseudoCityCode="X0JA"/>
    </POS>
    <OriginDestinationInformation RPH="1">
        <DepartureDateTime>2017-06-07</DepartureDateTime>
        <OriginLocation LocationCode="LIM"/>
        <DestinationLocation LocationCode="AQP"/>
        <TPA_Extensions>
            <SegmentType Code="O"/>
            <WithoutAvail/>
        </TPA_Extensions>
    </OriginDestinationInformation>
    <OriginDestinationInformation RPH="2">
        <DepartureDateTime>2017-06-10</DepartureDateTime>
        <OriginLocation LocationCode="AQP"/>
        <DestinationLocation LocationCode="LIM"/>
        <TPA_Extensions>
            <SegmentType Code="O"/>
            <WithoutAvail/>
        </TPA_Extensions>
    </OriginDestinationInformation>
    <TravelPreferences MaxStopsQuantity="2">
        <CabinPref RPH="1" Code="Y"/>
        <CabinPref RPH="2" Code="Y"/>
        <TPA_Extensions>
            <ExcludeVendorPref Code="2I"/>
            <ExcludeVendorPref Code="UA"/>
            <ExcludeVendorPref Code="IB"/>
            <NumTrips Number="19"/>
        </TPA_Extensions>
    </TravelPreferences>
    <TravelerInformation>
        <PassengerTypeQuantity Code="ADT" Quantity="1"/>
        <TPA_Extensions/>
    </TravelerInformation>
    <PriceRequestInformation CurrencyCode="USD">
        <TPA_Extensions>
            <FareCalc>
                <FareBasis WithFareCalc="true"/>
            </FareCalc>
            <Priority>
                <Price Priority="1"/>
                <DirectFlights Priority="2"/>
                <Time Priority="3"/>
                <Vendor Priority="4"/>
            </Priority>
        </TPA_Extensions>
    </PriceRequestInformation>
    <TPA_Extensions>
        <IntelliSellTransaction>
            <RequestType Name="AD3"/>
        </IntelliSellTransaction>
    </TPA_Extensions>
</OTA_AirLowFareSearchRQ>

but could not find, in the response, the object oAirLowFareSearchRS

oAirLowFareSearchRS = oAirLowFareSearchRQService.OTA_AirLowFareSearchRQ(oAirLowFareSearchRQ)

I get this error:

Object reference not set to an instance of an object.

and the xml response only this:

<?xml version="1.0" encoding="UTF-8"?>
<OTA_AirLowFareSearchRS xsi:nil="true" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>

What is the cause of this problem?

Body:
Here is sample working BFM_AD request for you:

<soapenv:Body>
    <OTA_AirLowFareSearchRQ AvailableFlightsOnly="true" ResponseType="OTA" ResponseVersion="3.0.0" Version="3.0.0" xmlns="http://www.opentravel.org/OTA/2003/05">
        <POS>
            <Source PseudoCityCode="***">
                <RequestorID ID="1" Type="1">
                    <CompanyName Code="TN"/>
                </RequestorID>
            </Source>
        </POS>
        <OriginDestinationInformation RPH="1">
            <DepartureDateTime>2017-06-15T00:00:00</DepartureDateTime>
            <DepartureWindow>00002359</DepartureWindow>
            <OriginLocation LocationCode="LIM" LocationType="A"/>
            <DestinationLocation LocationCode="AQP" LocationType="A"/>
            <TPA_Extensions>
                <SegmentType Code="O"/>
            </TPA_Extensions>
        </OriginDestinationInformation>
        <OriginDestinationInformation RPH="2">
            <DepartureDateTime>2017-06-18T00:00:00</DepartureDateTime>
            <DepartureWindow>00002359</DepartureWindow>
            <OriginLocation LocationCode="AQP" LocationType="A"/>
            <DestinationLocation LocationCode="LIM" LocationType="A"/>
            <TPA_Extensions>
                <SegmentType Code="O"/>
            </TPA_Extensions>
        </OriginDestinationInformation>
        <TravelPreferences ETicketDesired="true" ValidInterlineTicket="true">
            <TPA_Extensions>
                <TripType Value="Return"/>
                <FlightStopsAsConnections Ind="true"/>
                <ExcludeCallDirectCarriers Enabled="true"/>
            </TPA_Extensions>
            <Baggage Description="true" RequestType="A"/>
        </TravelPreferences>
        <TravelerInfoSummary>
            <SeatsRequested>1</SeatsRequested>
            <AirTravelerAvail>
                <PassengerTypeQuantity Code="ADT" Quantity="1"/>
            </AirTravelerAvail>
            <PriceRequestInformation CurrencyCode="TRY" NegotiatedFaresOnly="false">
                <TPA_Extensions>
                    <BrandedFareIndicators MultipleBrandedFares="true"/>
                </TPA_Extensions>
            </PriceRequestInformation>
        </TravelerInfoSummary>
        <TPA_Extensions>
            <IntelliSellTransaction>
                <RequestType Name="AD3"/>
            </IntelliSellTransaction>
        </TPA_Extensions>
    </OTA_AirLowFareSearchRQ>
</soapenv:Body>

I advice you to start from working request, after getting successful response, you should specialize that request for your need.


问:
Post ajax request send a options request instead of a post
I'm sending a post ajax request:

```<code>var responsehttpreq = {}
function createAndSendXmlHttpReq(){
    requestBody = {
        hostname: "prova",
        pathname: "prova",
        query: "prova",
        method: "prova"
    }
    console.log("Siamo nella funzione createAndSendXmlHttpReq")
    var req = new XMLHttpRequest()
    req.onreadystatechange = handler
    req.open("POST","http://localhost:8080",true)
    req.setRequestHeader("Content-type","application/json")
    req.send(JSON.stringify(requestBody))
}

function handler(){
    if(this.readyState == 4 && this.status == 200){
        console.log('----Risposta http------')
        console.log('Status Code:'+this.status)
        console.log('Dati:'+this.response)
        responsehttpreq = JSON.parse(this.response)
    }
}
</code>```

The createAndSendXmlHttpReq() is called from a button in a html page, when I press the button I don't recive any response, but I can see from the developer console that an option request has been send, for the CORS option.
I have implemented a node js server that in case of an options request send a properly response:

```<code>if(req.method == "OPTIONS"){
        res.setHeader("Access-Control-Allow-Origin","*")
        res.setHeader("Access-Control-Allow-Methods","POST")
        res.setHeader("Access-Control-Request-Headers","content-type")
        res.end()
    }
</code>```

The browser receive a 200 ok response from the server for the options request, but after that my ajax post request don'arrive to the server.
What is the problem?

答:
```<code>res.setHeader("Access-Control-Allow-Origin","*")
</code>```

An Access-Control-Allow-Origin header in response to a preflight OPTIONS request can't use a wildcard.

The Console of your browser should tell you this.

You need to look at the Origin request header, determine if it is acceptable to you, then use it as the value of the Access-Control-Allow-Origin header.

Body:
I'm sending a post ajax request:

var responsehttpreq = {}
function createAndSendXmlHttpReq(){
    requestBody = {
        hostname: "prova",
        pathname: "prova",
        query: "prova",
        method: "prova"
    }
    console.log("Siamo nella funzione createAndSendXmlHttpReq")
    var req = new XMLHttpRequest()
    req.onreadystatechange = handler
    req.open("POST","http://localhost:8080",true)
    req.setRequestHeader("Content-type","application/json")
    req.send(JSON.stringify(requestBody))
}

function handler(){
    if(this.readyState == 4 && this.status == 200){
        console.log('----Risposta http------')
        console.log('Status Code:'+this.status)
        console.log('Dati:'+this.response)
        responsehttpreq = JSON.parse(this.response)
    }
}

The createAndSendXmlHttpReq() is called from a button in a html page, when I press the button I don't recive any response, but I can see from the developer console that an option request has been send, for the CORS option.
I have implemented a node js server that in case of an options request send a properly response:

if(req.method == "OPTIONS"){
        res.setHeader("Access-Control-Allow-Origin","*")
        res.setHeader("Access-Control-Allow-Methods","POST")
        res.setHeader("Access-Control-Request-Headers","content-type")
        res.end()
    }

The browser receive a 200 ok response from the server for the options request, but after that my ajax post request don'arrive to the server.
What is the problem?

Body:
res.setHeader("Access-Control-Allow-Origin","*")

An Access-Control-Allow-Origin header in response to a preflight OPTIONS request can't use a wildcard.

The Console of your browser should tell you this.

You need to look at the Origin request header, determine if it is acceptable to you, then use it as the value of the Access-Control-Allow-Origin header.


答:
You need to do an assignment

```<code>$rectype = ($file_2 ? '3' : '1');
</code>```

instead of a comparison

```<code>$rectype == ($file_2 ? '3' : '1');
</code>```

Title: If statement variable returning empty

Body:
You need to do an assignment

$rectype = ($file_2 ? '3' : '1');

instead of a comparison

$rectype == ($file_2 ? '3' : '1');


问:
How to re-render Wicket component after the Event reception
I have a Wicket component which is listening for some event (IEvent). If such event arrives, I want to re-render the component with a changed model. There are no active controls on the page, like AjaxLink, which can trigger the re-rendering.

Is there a way to refresh such kind of component?

I was thinking to somehow trigger an AJAX request from the onEvent method and add an AjaxBehavior to the mentioned component. But I don't know, how to trigger the AJAX request.

public class PersonPanel extends Panel implements Observer {

    private WebMarkupContainer wrapper;

    public PersonPanel(String id) {
        super(id);

        setDefaultModel(new CompoundPropertyModel<PersonInfo>(getModel()));

        wrapper = new WebMarkupContainer("wrapper");
        wrapper.setOutputMarkupId(true);
        add(wrapper);

        wrapper.add(new Label("personID"));
        // some more content
    }

    private IModel<PersonInfo> getModel() {
        return new LoadableDetachableModel<PersonInfo>() {
            @Override
            protected PersonInfo load() {
                // model loading logic
            }
        };
    }

    @Override
    public void onEvent(IEvent<?> event) {
        logger.debug("\n   Person Panel received an Event: " + event.getPayload());

        // Re-rendering of "wrapper" should be triggered from here.
    }

    @Override
    public void update(Observable observable, Object o) {
        send(this, Broadcast.EXACT, "Observable cache has changed.");
    }
}
```

答:
At the send side you can pass the AjaxRequestTarget with the payload of the event.

```<code>send(getPage(), Broadcast.DEPTH, new MyPayload(target));
</code>```

and then on the receive side:

```<code>MyPayload payload = (MyPayload) event.getPayload();
payload.getTarget().add(this);
</code>```

Body:
At the send side you can pass the AjaxRequestTarget with the payload of the event.

send(getPage(), Broadcast.DEPTH, new MyPayload(target));

and then on the receive side:

MyPayload payload = (MyPayload) event.getPayload();
payload.getTarget().add(this);


问:
Why doesn't empty() work on input in search bar?
When clicking theinviteButton, the input search bar should clear out, but it doesn't work with my current code.

Am I targeting the element incorrectly?

 $("#inviteButton").click(function(){
  var userName = $("#searchUser").val();
  if (userName.trim() != "") {
    if (userName == myUserName) {
    $("#connectToBox").append("You can't invite yourself");
    $("#searchUser").empty(); // Doesn't work
   } else {
    socket.emit("checkUserConnect", userName, function(data){
     if (data.result === undefined) {
      console.log("No name");
      $("#connectToBox").append("User does not exist");
      $("#searchUser").empty(); // Doesn't work
     } else {
      console.log("name exists");
      $("#searchUser").empty(); // Doesn't work
      $("#connectToBox").append("Invite send");
      UserID = data.result.id;
      socket.emit("connectToUser", myUserName, UserID, currentConversation);
     }
     });
   }
  }
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="connectToBox">
    <label for="search-2">Type in username</label>
    <input type="search" name="search-2" id="searchUser" value="">
    Connect
   </div></code>```

答:
```<code>$('#searchUser').val('');
</code>```

This will work fine according to your application.

The empty() method removes all child nodes and content from the selected elements. Src: W3Schools

According to your requirement you need to reset the value of an input field, for that we have val() function. You can assign an empty string and it will work fine.
Using empty() won't work here.

Check these examples -

empty() working correctly -

function emptyOperation(){
    $("div").empty();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="text" id="input-field" value="Random string">
</div>
<button onclick="emptyOperation()">Check</button></code>```

empty() as per your code [won't work] -

function emptyOperation(){
    $("#input-field").empty();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="text" id="input-field" value="Random string">
</div>
<button onclick="emptyOperation()">Check</button></code>```

Solution to your problem -

function emptyOperation(){
    $("#input-field").val('');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="text" id="input-field" value="Random string">
</div>
<button onclick="emptyOperation()">Check</button></code>```

Body:
When clicking theinviteButton, the input search bar should clear out, but it doesn't work with my current code.

Am I targeting the element incorrectly?

 $("#inviteButton").click(function(){
  var userName = $("#searchUser").val();
  if (userName.trim() != "") {
    if (userName == myUserName) {
    $("#connectToBox").append("You can't invite yourself");
    $("#searchUser").empty(); // Doesn't work
   } else {
    socket.emit("checkUserConnect", userName, function(data){
     if (data.result === undefined) {
      console.log("No name");
      $("#connectToBox").append("User does not exist");
      $("#searchUser").empty(); // Doesn't work
     } else {
      console.log("name exists");
      $("#searchUser").empty(); // Doesn't work
      $("#connectToBox").append("Invite send");
      UserID = data.result.id;
      socket.emit("connectToUser", myUserName, UserID, currentConversation);
     }
     });
   }
  }
 });

    Type in username
    <input type="search" name="search-2" id="searchUser" value="">
    Connect

Body:
$('#searchUser').val('');

This will work fine according to your application.

The empty() method removes all child nodes and content from the selected elements. Src: W3Schools

According to your requirement you need to reset the value of an input field, for that we have val() function. You can assign an empty string and it will work fine.
Using empty() won't work here.

Check these examples -

empty() working correctly -

function emptyOperation(){
    $("div").empty();
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="text" id="input-field" value="Random string">
</div>
<button onclick="emptyOperation()">Check</button>

empty() as per your code [won't work] -

function emptyOperation(){
    $("#input-field").empty();
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="text" id="input-field" value="Random string">
</div>
<button onclick="emptyOperation()">Check</button>

Solution to your problem -

function emptyOperation(){
    $("#input-field").val('');
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="text" id="input-field" value="Random string">
</div>
<button onclick="emptyOperation()">Check</button>


问:
Sorting a multidimensional array in javascript?
I am new to programming and I have just worked out a multidimensional array problem by using pure javascript but I think I made it too complicated and just wondering can anyone tell me how do you think about my method and do you have a better way to do it.
the problem is to console.log all the numbers in the arrays and the array is [[[1,2],[3,4]],[[5,6]]]. My code is as below, please post your suggestions,thanks</p>

```<code>     var nestedArr = [[[1,2],[3,4]],[[5,6]]];
     var nestedArrOne = nestedArr[0];
     var nestedArrTwo = nestedArr[1];
     var newArr = nestedArrOne.concat(nestedArrTwo);
      function showAll(){
        for(var i=0; i<newArr.length; i++){
        for(var j=0; j<newArr[i].length; j++){
        console.log(newArr[i][j]);
                }
            }
       }

       showAll();
</code>```

答:
The recursive function could be used to flatten the array.

let isArray = val => val.constructor === Array

let log = val => console.log(val)

let flatten = val =>
  val
    .reduce((acc, cur) =>
      isArray(cur) ? [...acc, ...flatten(cur)] : [...acc, cur],
      [])

// Running examples
let arrA = [[[1,2],[3,4]],[[5,6]]]
flatten(arrA).forEach(log)

log('-------------------')

let arrB = [[[1,2],[3,4]],[[5,6]],[7],[[[[9]]]]]
flatten(arrB).forEach(log)```

Body:
I am new to programming and I have just worked out a multidimensional array problem by using pure javascript but I think I made it too complicated and just wondering can anyone tell me how do you think about my method and do you have a better way to do it.
the problem is to console.log all the numbers in the arrays and the array is [[[1,2],[3,4]],[[5,6]]]. My code is as below, please post your suggestions,thanks

     var nestedArr = [[[1,2],[3,4]],[[5,6]]];
     var nestedArrOne = nestedArr[0];
     var nestedArrTwo = nestedArr[1];
     var newArr = nestedArrOne.concat(nestedArrTwo);
      function showAll(){
        for(var i=0; i<newArr.length; i++){
        for(var j=0; j<newArr[i].length; j++){
        console.log(newArr[i][j]);
                }
            }
       }

       showAll();


答: You are using == instead of =.

Title: If statement variable returning empty

Body:
this is a test code i wrote to get a value set for $rectype to insert into a table. problem I'm having is $rectype is returning 0 or empty. the files do exist since I perform a similar is_file check to start the process that leads up to this section of the coding

$dirchk1 = "/temp/files/" . $data[0] . ".doc"; // exist
$dirchk2 = "/temp/files/" . $data[1] . ".doc"; // exist

$file_1 = (is_file($dirchk1));
$file_2 = (is_file($dirchk2));

if ($file_1) {
$rectype == ($file_2 ? '3' : '1');
}

echo $rectype . "\n";

Body: You are using == instead of =.