问:
Replacing items in nested list that contain same answer
I have a nested list that looks like this:

```<code>data = [
['student 1', '"answer 0"', '"answer 2"', '"answer 2"', '"answer 0"'],
['student 2', '"answer 4"', '"answer 2"', '"answer 4"', '"answer 0"']]
</code>```

I want the results to appear as:

```<code>data = [
['student 1', 'Blue', 'Up', 'Left', 'Football'],
['student 2', 'Red', 'Up', 'Right', 'Football']]
</code>```

Depending on the index in the list, it can have a different result, but in the data it can contain the same string.  What is an efficient way to accomplish this task?

答:
You can create a simple [index, answer, replacement] replacement map, like:

```<code>replacement_map = {
    1: {'"answer 0"': "Blue",  # replacements for index 1
        '"answer 1"': "Green",
        '"answer 2"': "Yellow",
        '"answer 3"': "Purple",
        '"answer 4"': "Red"},
    2: {'"answer 0"': "Right",  # replacements for index 2
        '"answer 1"': "Left",
        '"answer 2"': "Up",
        '"answer 4"': "Down"},
    3: {'"answer 0"': "Up",  # replacements for index 3
        '"answer 1"': "Down",
        '"answer 2"': "Left",
        '"answer 4"': "Right"},
    4: {'"answer 0"': "Football",  # replacements for index 4
        '"answer 1"': "Pocket billiard"}
}

data = [
    ['student 1', '"answer 0"', '"answer 2"', '"answer 2"', '"answer 0"'],
    ['student 2', '"answer 4"', '"answer 2"', '"answer 4"', '"answer 0"']
]

replaced_data = []  # we'll store our data here
for element in data:
    replaced_element = []
    for index, item in enumerate(element):
        if index in replacement_map:
            replaced_element.append(replacement_map[index].get(item, item))
        else:  # no replacement available for this index
            replaced_element.append(item)
    replaced_data.append(replaced_element)
# replaced_data contains:
# [['student 1', 'Blue', 'Up', 'Left', 'Football'],
#  ['student 2', 'Red', 'Up', 'Right', 'Football']]
</code>```

If you really want it as efficient as possible, you can do it through list comprehension:

```<code>replaced_data = [[replacement_map.get(index, {}).get(item, item) for index, item in enumerate(element)] for element in data]
</code>```

But that won't give you much of a speed up (in fact, in dependence on the replacement map it might end up slower) and is horrible to read.

Body:
I have a nested list that looks like this:

data = [
['student 1', '"answer 0"', '"answer 2"', '"answer 2"', '"answer 0"'],
['student 2', '"answer 4"', '"answer 2"', '"answer 4"', '"answer 0"']]

I want the results to appear as:

data = [
['student 1', 'Blue', 'Up', 'Left', 'Football'],
['student 2', 'Red', 'Up', 'Right', 'Football']]

Depending on the index in the list, it can have a different result, but in the data it can contain the same string.  What is an efficient way to accomplish this task?

Body:
You can create a simple [index, answer, replacement] replacement map, like:

replacement_map = {
    1: {'"answer 0"': "Blue",  # replacements for index 1
        '"answer 1"': "Green",
        '"answer 2"': "Yellow",
        '"answer 3"': "Purple",
        '"answer 4"': "Red"},
    2: {'"answer 0"': "Right",  # replacements for index 2
        '"answer 1"': "Left",
        '"answer 2"': "Up",
        '"answer 4"': "Down"},
    3: {'"answer 0"': "Up",  # replacements for index 3
        '"answer 1"': "Down",
        '"answer 2"': "Left",
        '"answer 4"': "Right"},
    4: {'"answer 0"': "Football",  # replacements for index 4
        '"answer 1"': "Pocket billiard"}
}

data = [
    ['student 1', '"answer 0"', '"answer 2"', '"answer 2"', '"answer 0"'],
    ['student 2', '"answer 4"', '"answer 2"', '"answer 4"', '"answer 0"']
]

replaced_data = []  # we'll store our data here
for element in data:
    replaced_element = []
    for index, item in enumerate(element):
        if index in replacement_map:
            replaced_element.append(replacement_map[index].get(item, item))
        else:  # no replacement available for this index
            replaced_element.append(item)
    replaced_data.append(replaced_element)
# replaced_data contains:
# [['student 1', 'Blue', 'Up', 'Left', 'Football'],
#  ['student 2', 'Red', 'Up', 'Right', 'Football']]

If you really want it as efficient as possible, you can do it through list comprehension:

replaced_data = [[replacement_map.get(index, {}).get(item, item) for index, item in enumerate(element)] for element in data]

But that won't give you much of a speed up (in fact, in dependence on the replacement map it might end up slower) and is horrible to read.


来源: stackexchange

问:
In R, why does %in% return FALSE although date time element is contained in the vector?
I have troubles to understand why R returns FALSE if I check whether a date-time element is contained in a vector with %in% although the date time element I check for is definitely contained in the vector. Put differently, I wonder how these outputs are possible:

```<code>> GOLD.5.event.times[1] == GOLD.5$`1.Date & Time`[24544]
[1] TRUE
> GOLD.5.event.times[1] %in% GOLD.5$`1.Date & Time`
[1] FALSE
</code>```

I would expect a TRUE return from the %in% operation as the respective date time value is contained in the vector.

A quick overview over the type of data I use:

```<code>> GOLD.5.event.times <- seq(ISOdatetime(2017, 4, 4, 0, 0, 0, tz = ""),
ISOdatetime(2017, 4, 5, 0, 0, 0, tz = ""), "5 min")
> GOLD.5.event.times[1:10]
[1] "2017-04-04 00:00:00 CEST" "2017-04-04 00:05:00 CEST" "2017-04-04
00:10:00 CEST" "2017-04-04 00:15:00 CEST" "2017-04-04 00:20:00 CEST"
[6] "2017-04-04 00:25:00 CEST" "2017-04-04 00:30:00 CEST" "2017-04-04
00:35:00 CEST" "2017-04-04 00:40:00 CEST" "2017-04-04 00:45:00 CEST"

> GOLD.5$`1.Date & Time`[24540:24550] # result of strptime() conversion
[1] "2017-04-03 22:55:00 CEST" "2017-04-03 23:00:00 CEST" "2017-04-03
23:45:00 CEST" "2017-04-03 23:55:00 CEST" "2017-04-04 00:00:00 CEST"
[6] "2017-04-04 00:05:00 CEST" "2017-04-04 00:10:00 CEST" "2017-04-04
00:15:00 CEST" "2017-04-04 00:20:00 CEST" "2017-04-04 00:25:00 CEST"
[11] "2017-04-04 00:30:00 CEST"
</code>```

And the dputs.

```<code>> dput(GOLD.5$`1.Date & Time`[24544])
structure(list(sec = 0, min = 0L, hour = 0L, mday = 4L, mon = 3L,
year = 117L, wday = 2L, yday = 93L, isdst = 1L, zone = "CEST",
gmtoff = NA_integer_), .Names = c("sec", "min", "hour", "mday",
"mon", "year", "wday", "yday", "isdst", "zone", "gmtoff"), class =
c("POSIXlt", "POSIXt"))
> dput(GOLD.5.event.times[1])
structure(1491256800, class = c("POSIXct", "POSIXt"), tzone = "")
</code>```

答:
Solved in comments.

Different classes of datetime elements caused the problem.
Check this for an overview of datetime conversion functions.

ContentLicense: CC BY-SA 3.0

Body:
I have troubles to understand why R returns FALSE if I check whether a date-time element is contained in a vector with %in% although the date time element I check for is definitely contained in the vector. Put differently, I wonder how these outputs are possible:

> GOLD.5.event.times[1] == GOLD.5$`1.Date & Time`[24544]
[1] TRUE
> GOLD.5.event.times[1] %in% GOLD.5$`1.Date & Time`
[1] FALSE

I would expect a TRUE return from the %in% operation as the respective date time value is contained in the vector.

A quick overview over the type of data I use:

> GOLD.5.event.times <- seq(ISOdatetime(2017, 4, 4, 0, 0, 0, tz = ""),
ISOdatetime(2017, 4, 5, 0, 0, 0, tz = ""), "5 min")
> GOLD.5.event.times[1:10]
[1] "2017-04-04 00:00:00 CEST" "2017-04-04 00:05:00 CEST" "2017-04-04
00:10:00 CEST" "2017-04-04 00:15:00 CEST" "2017-04-04 00:20:00 CEST"
[6] "2017-04-04 00:25:00 CEST" "2017-04-04 00:30:00 CEST" "2017-04-04
00:35:00 CEST" "2017-04-04 00:40:00 CEST" "2017-04-04 00:45:00 CEST"

> GOLD.5$`1.Date & Time`[24540:24550] # result of strptime() conversion
[1] "2017-04-03 22:55:00 CEST" "2017-04-03 23:00:00 CEST" "2017-04-03
23:45:00 CEST" "2017-04-03 23:55:00 CEST" "2017-04-04 00:00:00 CEST"
[6] "2017-04-04 00:05:00 CEST" "2017-04-04 00:10:00 CEST" "2017-04-04
00:15:00 CEST" "2017-04-04 00:20:00 CEST" "2017-04-04 00:25:00 CEST"
[11] "2017-04-04 00:30:00 CEST"

And the dputs.

> dput(GOLD.5$`1.Date & Time`[24544])
structure(list(sec = 0, min = 0L, hour = 0L, mday = 4L, mon = 3L,
year = 117L, wday = 2L, yday = 93L, isdst = 1L, zone = "CEST",
gmtoff = NA_integer_), .Names = c("sec", "min", "hour", "mday",
"mon", "year", "wday", "yday", "isdst", "zone", "gmtoff"), class =
c("POSIXlt", "POSIXt"))
> dput(GOLD.5.event.times[1])
structure(1491256800, class = c("POSIXct", "POSIXt"), tzone = "")


问:
O/R mapping tools ASP
Are there O/R mapping tools for ASP (not ASP.NET) and are these useful in ASP?

Lieven Cardoen

答: A quick scan a google search and i don't see anything that states classic ASP. Given the somewhat dated platform that ASP is, i doubt any major players would appear in that space.</p>

OwnerDisplayName: Lieven Cardoen

ContentLicense: CC BY-SA 2.5

Title: O/R mapping tools ASP

LastEditorDisplayName: recursive

OwnerDisplayName: Jason Miesionczek


问:
Javascript error, help please
I cant figure out why this is happening.

```<code>http://www.freemoviedb.com/watch/5749/28_weeks_later.html
</code>```

Click the thumb up / thumb down, it doesn't do anything but load.

In firebug, all it says is:

```<code>invalid 'in' operand a
http://static.freemoviedb.com/thumbsup/init.min.js.php
Line 1
</code>```

/

```<code>invalid 'in' operand a
error(Object { name="a"})init.min.js.php (line 1)
b()jquery.min.js (line 124)
abort(Object { name="q"})
</code>```

答:
The problem I see right away is that your Ajax request is going cross-domain and it seems to be generating a preceding error

XMLHttpRequest cannot load http://static.freemoviedb.com/thumbsup/init.php. Origin http://www.freemoviedb.com is not allowed by Access-Control-Allow-Origin.

www.xyz.com is different than static.xyz.com

This may be why the remaining code is failing

Title: Javascript error, help please

Body:
I cant figure out why this is happening.

http://www.freemoviedb.com/watch/5749/28_weeks_later.html

Click the thumb up / thumb down, it doesn't do anything but load.

In firebug, all it says is:

invalid 'in' operand a
http://static.freemoviedb.com/thumbsup/init.min.js.php
Line 1

/

invalid 'in' operand a
error(Object { name="a"})init.min.js.php (line 1)
b()jquery.min.js (line 124)
abort(Object { name="q"})


问:
Why doesn't SingletonSet implement SortedSet
In order so reduce memory consumption, I'm rewriting a class that has a SortedSet<Integer>. In 80% of cases, this collection contains only a single element . So I thought I could use a SingeltonSet in these cases and a normal TreeSet in other cases. Now I noticed that SingletonSet, as returned by Collections.singleton(), does not implement SortedSet. Is there any reason for this shortcoming? A single element can always be considered sorted I'd say. Do I have to write my own SingletonSet implementation?

答:
This is an interesting point, which seems to illustrate a small hole in the collections API.

The fact is that Collections.singleton() is specified to return a Set, not a SortedSet, and in fact the implementation doesn't support that interface. I don't think it would be helpful for Collections.singleton() to change its behavior and return an instance of a SortedSet. This would encourage implementations to perform instanceof checks and downcasting. (And similar for the corresponding Map methods and interfaces.)

It's a small consolation for this use case, but in Java SE 8 new methods Collections.emptyNavigableMap and emptyNavigableSet were introduced. This is helpful for use cases that want empty navigable collections, but if you really want a navigable with a single element or mapping, you're out of luck. There's an enhancement request JDK-6201174 that covers a similar area; I've updated and refocused it around providing APIs for a singleton navigable set and map.

But wait! As you pointed out, there is a bit of additional state that rides along with sorted/navigable collections, which is the comparator. (Or in the absence of a comparator, implicitly one that provides natural ordering.) Any new singleton APIs would have a provide for that as well. And this points out the fact that the empty* methods I mentioned above don't talk about the Comparator. That seems like another bug: JDK-8181754.

Unfortunately I don't have a really good workaround for you other than to buckle down and implement a one-element, possibly immutable SortedSet or NavigableSet. You could start off with Collections.UnmodifiableNavigableSet. This helps a little, but not much. In fact, the empty navigable set is one of these wrapped around an empty TreeSet! This is quite unhelpful, since you want to avoid TreeSet instances.

I'd probably start from AbstractSet and then add the minimal set of methods from SortedSet. There are rather fewer methods than in NavigableSet, so if you don't need all of its bells and whistles, it'd be a smaller task to stick to SortedSet.


问:
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?

答:
You can use Grub Customizer to set the default boot entry.
Install Grub Customizer by running this as root:

```<code>pacman -S grub-customizer
</code>```

And open it. Go to the tab "General settings" and set the default entry.

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?

Body:
You can use Grub Customizer to set the default boot entry.
Install Grub Customizer by running this as root:

pacman -S grub-customizer

And open it. Go to the tab "General settings" and set the default entry.


问:
Can't Edit/Update Certain Items In Database (Table)
I have database that I have multiple orders entered into. Everything seems to be working fine except for a few old entries which will not accept updates/changes to their Fields.

Note: The majority of the Fields are Strings with Possible Values entered via a DropDown Box.

So if I open Order A I can make adjustments just fine and those changes persist even after closing the page and coming back or refreshing.

But if I open Order B, I can make changes via the dropdowns and it looks like they have adjusted, however if I leave the page or refresh all the changes have reverted back.

One piece of info that may be helpful is that each of these orders has at least one Field that contains an entry that is no longer a Possible Value (the original entries were removed/changed per request of the client).

Maybe they are "locked" because of this? Is there a way to look at an error log for a Published app?

I can delete the "corrupt" entries and recreate them (since there are currently only a few), but I would prefer to find a better solution in case this happens again in the future.

Any help would be greatly appreciated.

答: Each deployment has its own log. Have you tried "App Settings > DEPLOYMENTS > (click on the desployment) > VIEW LOGS"?</p>


问:
localhost and "stream_socket_enable_crypto(): SSL operation failed with code 1"
I was sending emails using gmail and everything was working perfectly, but suddendly it stoped working. And it shows me this

```<code>ErrorException in StreamBuffer.php line 94:

stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed

in StreamBuffer.php line 94
at HandleExceptions->handleError('2', 'stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed', 'C:\xampp\htdocs\coparmex\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\StreamBuffer.php', '94', array())
at stream_socket_enable_crypto(resource, true, '9') in StreamBuffer.php line 94
at Swift_Transport_StreamBuffer->startTLS() in EsmtpTransport.php line 313
at Swift_Transport_EsmtpTransport->_doHeloCommand() in AbstractSmtpTransport.php line 118
at Swift_Transport_AbstractSmtpTransport->start() in Mailer.php line 79
at Swift_Mailer->send(object(Swift_Message), array()) in Mailer.php line 385
at Mailer->sendSwiftMessage(object(Swift_Message)) in Mailer.php line 171
</code>```

And this only happends in my localhost, in the web host works fine. I don't understand what is going on :c

These are my gmail settings

```<code>MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=gmail
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls
</code>```

答:
That's an error with your SSL certificate. You're trying to use a SSL connection (encrypted, secure connection) without a proper certificate.

That's because you're connecting from localhost, which isn't secure, and that is blocked by the connection. You could avoid that by changing your localhost connection to a SSL based one.

See this link for more details.

Body:
I was sending emails using gmail and everything was working perfectly, but suddendly it stoped working. And it shows me this

ErrorException in StreamBuffer.php line 94:

stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed

in StreamBuffer.php line 94
at HandleExceptions->handleError('2', 'stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed', 'C:\xampp\htdocs\coparmex\vendor\swiftmailer\swiftmailer\lib\classes\Swift\Transport\StreamBuffer.php', '94', array())
at stream_socket_enable_crypto(resource, true, '9') in StreamBuffer.php line 94
at Swift_Transport_StreamBuffer->startTLS() in EsmtpTransport.php line 313
at Swift_Transport_EsmtpTransport->_doHeloCommand() in AbstractSmtpTransport.php line 118
at Swift_Transport_AbstractSmtpTransport->start() in Mailer.php line 79
at Swift_Mailer->send(object(Swift_Message), array()) in Mailer.php line 385
at Mailer->sendSwiftMessage(object(Swift_Message)) in Mailer.php line 171

And this only happends in my localhost, in the web host works fine. I don't understand what is going on :c

These are my gmail settings

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=gmail
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls


问:
How can I create a Keen IO query with "OR" filters?
I was wondering if the Filters in Keen IO queries can be done as "OR".

Basically, I have a "column" (event property) called "product_type".

I want to generate an API Query URL that has an extraction with a filter that is "if product_type equals x OR product_type equals y".

But right now, if I do a Filter like that, it's always "AND".

答:
Use the the "in" operator. This "in" operator will identify any events where the property equals any value in a list, like this:

```<code>var extraction = new Keen.Query("extraction", {
  event_collection: "purchases",
  timeframe: "this_14_days",
  filters: [
    {
      property_name: "product_type",
      operator: "in",
      property_value: ["x","y"]
    }
  ]
});
</code>```

Here's a handy list of all of the available filter operators.

Body:
Use the the "in" operator. This "in" operator will identify any events where the property equals any value in a list, like this:

var extraction = new Keen.Query("extraction", {
  event_collection: "purchases",
  timeframe: "this_14_days",
  filters: [
    {
      property_name: "product_type",
      operator: "in",
      property_value: ["x","y"]
    }
  ]
});

Here's a handy list of all of the available filter operators.


问:
Parallel.Foreach with modulo partitioning
When using Parallel.Foreach() for 100 items using 4 threads, it will divide the list into 4 blocks (0-24,25-49,50-74,75-99) of items, which means, that items 0, 25, 50 and 75 are processed in parallel.

Is it somehow possible to partition the items in a modulo way to handle those with lower indices first? Like:

```<code>Thread 1: 0, 5, 9,..
Thread 2: 1, 6, 10,...
Thread 3: 2, 7, 11,...
Thread 4: 3, 8, 12,...
</code>```

答:
This partitioning method is known as Round Robin, or Striping. The primary challenge of using this with Parallel.ForEach() is that ForEach() requires partitioners to support dynamic partitions, which would not be possible with this type of partitioning as the number of partitions must be fixed prior to execution of the loop.

One way to achieve this type of partitioning is to create a custom class derived from System.Collections.Concurrent.Partitioner<TSource> and use the ParallelQuery.ForAll() method, which does not have the dynamic partitioning support requirement. For most applications this should be equivalent to using ForEach().

Below is an example of a custom Partitioner and a basic implementation. The Partitioner will generate the same number of partitions as the degree of parallelism.

```<code>using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;

namespace RoundRobinPartitioning
{
    public class RoundRobinPartitioner<TSource> : Partitioner<TSource>
    {
        private readonly IList<TSource> _source;

        public RoundRobinPartitioner(IList<TSource> source)
        {
            _source = source;
        }

        public override bool SupportsDynamicPartitions { get { return false; } }

        public override IList<IEnumerator<TSource>> GetPartitions(int partitionCount)
        {
            var enumerators = new List<IEnumerator<TSource>>(partitionCount);

            for (int i = 0; i < partitionCount; i++)
            {
                enumerators.Add(GetEnumerator(i, partitionCount));
            }

            return enumerators;
        }

        private IEnumerator<TSource> GetEnumerator(
            int partition,
            int partitionCount)
        {
            int position = partition;
            TSource value;

            while (position < _source.Count)
            {
                value = _source[position];
                position += partitionCount;
                yield return value;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var values = Enumerable.Range(0, 100).ToList();

            var partitioner = new RoundRobinPartitioner<int>(values);

            partitioner.AsParallel()
                .WithDegreeOfParallelism(4)
                .ForAll(value =>
                {
                    // Perform work here
                });
        }
    }
}
</code>```

Body:
When using Parallel.Foreach() for 100 items using 4 threads, it will divide the list into 4 blocks (0-24,25-49,50-74,75-99) of items, which means, that items 0, 25, 50 and 75 are processed in parallel.

Is it somehow possible to partition the items in a modulo way to handle those with lower indices first? Like:

Thread 1: 0, 5, 9,..
Thread 2: 1, 6, 10,...
Thread 3: 2, 7, 11,...
Thread 4: 3, 8, 12,...

Body:
This partitioning method is known as Round Robin, or Striping. The primary challenge of using this with Parallel.ForEach() is that ForEach() requires partitioners to support dynamic partitions, which would not be possible with this type of partitioning as the number of partitions must be fixed prior to execution of the loop.

One way to achieve this type of partitioning is to create a custom class derived from System.Collections.Concurrent.Partitioner<TSource> and use the ParallelQuery.ForAll() method, which does not have the dynamic partitioning support requirement. For most applications this should be equivalent to using ForEach().

Below is an example of a custom Partitioner and a basic implementation. The Partitioner will generate the same number of partitions as the degree of parallelism.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;

namespace RoundRobinPartitioning
{
    public class RoundRobinPartitioner<TSource> : Partitioner<TSource>
    {
        private readonly IList<TSource> _source;

        public RoundRobinPartitioner(IList<TSource> source)
        {
            _source = source;
        }

        public override bool SupportsDynamicPartitions { get { return false; } }

        public override IList<IEnumerator<TSource>> GetPartitions(int partitionCount)
        {
            var enumerators = new List<IEnumerator<TSource>>(partitionCount);

            for (int i = 0; i < partitionCount; i++)
            {
                enumerators.Add(GetEnumerator(i, partitionCount));
            }

            return enumerators;
        }

        private IEnumerator<TSource> GetEnumerator(
            int partition,
            int partitionCount)
        {
            int position = partition;
            TSource value;

            while (position < _source.Count)
            {
                value = _source[position];
                position += partitionCount;
                yield return value;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var values = Enumerable.Range(0, 100).ToList();

            var partitioner = new RoundRobinPartitioner<int>(values);

            partitioner.AsParallel()
                .WithDegreeOfParallelism(4)
                .ForAll(value =>
                {
                    // Perform work here
                });
        }
    }
}


问:
Angular CLI (AOT) gives error: ERROR in Cannot determine the module for class
I have recently migrated my project to use Angular CLI to package my project. It works fine using "ng build" but when I try to use "ng build --prod" (which in turn uses Angular AOT and other additional steps) I get these errors:

```<code>ERROR in Cannot determine the module for class CustomDialog in F:/depot/depot/code/main/web/CedarsReport/src/a
pp/dialogs/customDialog.ts! Add CustomDialog to the NgModule to fix it.
Cannot determine the module for class ConfirmDialog in F:/depot/depot/code/main/web/CedarsReport/src/app/dialo
gs/confirmDialog.ts! Add ConfirmDialog to the NgModule to fix it.
Cannot determine the module for class EditUserDialog in F:/depot/depot/code/main/web/CedarsReport/src/app/dial
ogs/editUserDialog.ts! Add EditUserDialog to the NgModule to fix it.
Cannot determine the module for class LoginDialog in F:/depot/depot/code/main/web/CedarsReport/src/app/dialogs
/loginDialog.ts! Add LoginDialog to the NgModule to fix it.
Cannot determine the module for class EditAllControlsDlg in F:/depot/depot/code/main/web/CedarsReport/src/app/
dialogs/editAllControlsDlg.ts! Add EditAllControlsDlg to the NgModule to fix it.
Cannot determine the module for class EmptyTemplateDlg in F:/depot/depot/code/main/web/CedarsReport/src/app/di
alogs/emptyDialogTemplate.ts! Add EmptyTemplateDlg to the NgModule to fix it.
Cannot determine the module for class PopupSkeleton in F:/depot/depot/code/main/web/CedarsReport/src/app/direc
tives/popupSkeleton.ts! Add PopupSkeleton to the NgModule to fix it.
</code>```

However, most of these files ARE referenced in a module called CRDialogs.module.ts:

```<code>import { NgModule }      from '@angular/core';
import { CommonModule } from '@angular/common'; // ngFor, ngIf, ngStyle, and so on

import { Ng2Bs3ModalModule, ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';

    // Some dialogs use directives we've created
import { CRDirectives } from '../directives/CRDirectives.module';

    // What we want to declare and export. Also, anything in 'imports' below is made available to all of these components
import { ChangePasswordDialog } from "./changePasswordDialog"
import { ConfirmDialog } from "./ConfirmDialog"
import { CreateShortcutDialog } from "./CreateShortcutDialog"
import { CustomDialog } from "./CustomDialog"
import { EditControlDlg } from "./EditControlDlg"
import { EditSectionDlg } from "./EditSectionDialog"
import { EditSitesDialog } from "./EditSitesDialog"
import { StandardFieldDialog } from "./editStandardFieldDialog"
import { EditUserDialog } from "./EditUserDialog"
import { ErrorsDialog } from "./ErrorsDialog"
import { GenericListDlg } from "./GenericListDialog"
import { LoginDialog } from "./LoginDialog"
import { ReferringPhysDialog } from "./ReferringPhysDialog"
import { SignReportDlg } from "./SignReportDlg"

@NgModule(
{
    imports: [CommonModule, CRDirectives, Ng2Bs3ModalModule],       // Other modules to import

    declarations: [
        ChangePasswordDialog, ConfirmDialog, CreateShortcutDialog, CustomDialog, EditControlDlg, EditSectionDlg, EditSitesDialog,
        EditUserDialog, StandardFieldDialog, ErrorsDialog, GenericListDlg, LoginDialog, ReferringPhysDialog, SignReportDlg
    ],

    exports: [
        ChangePasswordDialog, ConfirmDialog, CreateShortcutDialog, CustomDialog, EditControlDlg, EditSectionDlg, EditSitesDialog,
        EditUserDialog, StandardFieldDialog, ErrorsDialog, GenericListDlg, LoginDialog, ReferringPhysDialog, SignReportDlg
    ]
})

export class CRDialogs {}
</code>```

And this module in turn is referenced in my app.module.ts:

```<code>import { CRGlobals } from "./globals"

[...]

@NgModule({
    declarations: [
        CSReportMain,
        AppTestTemp
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        CRDirectives,
        **CRDialogs,**
        CRPages,

       [...]
    ],
    providers: [
        CRGlobals
    ],
    bootstrap: [CSReportMain]
})
</code>```

Here it main.ts:

```<code>import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule);
</code>```

So why am I getting this error?

答:
in the app.module.ts have you try to do the actual imports instead of just referencing them back to CRDialogs.module.ts
I also noticed that in main.ts you are only importing the app.module.ts, you could probably try to import the CRDialogs.module.ts there first before you do any importing inside the app.module.ts.

I'm new to Angular and I just fixed a similar issue, my problem was that I didn't do the correct importing in the app.model.ts I hope this helps

Body:
I have recently migrated my project to use Angular CLI to package my project. It works fine using "ng build" but when I try to use "ng build --prod" (which in turn uses Angular AOT and other additional steps) I get these errors:

ERROR in Cannot determine the module for class CustomDialog in F:/depot/depot/code/main/web/CedarsReport/src/a
pp/dialogs/customDialog.ts! Add CustomDialog to the NgModule to fix it.
Cannot determine the module for class ConfirmDialog in F:/depot/depot/code/main/web/CedarsReport/src/app/dialo
gs/confirmDialog.ts! Add ConfirmDialog to the NgModule to fix it.
Cannot determine the module for class EditUserDialog in F:/depot/depot/code/main/web/CedarsReport/src/app/dial
ogs/editUserDialog.ts! Add EditUserDialog to the NgModule to fix it.
Cannot determine the module for class LoginDialog in F:/depot/depot/code/main/web/CedarsReport/src/app/dialogs
/loginDialog.ts! Add LoginDialog to the NgModule to fix it.
Cannot determine the module for class EditAllControlsDlg in F:/depot/depot/code/main/web/CedarsReport/src/app/
dialogs/editAllControlsDlg.ts! Add EditAllControlsDlg to the NgModule to fix it.
Cannot determine the module for class EmptyTemplateDlg in F:/depot/depot/code/main/web/CedarsReport/src/app/di
alogs/emptyDialogTemplate.ts! Add EmptyTemplateDlg to the NgModule to fix it.
Cannot determine the module for class PopupSkeleton in F:/depot/depot/code/main/web/CedarsReport/src/app/direc
tives/popupSkeleton.ts! Add PopupSkeleton to the NgModule to fix it.

However, most of these files ARE referenced in a module called CRDialogs.module.ts:

import { NgModule }      from '@angular/core';
import { CommonModule } from '@angular/common'; // ngFor, ngIf, ngStyle, and so on

import { Ng2Bs3ModalModule, ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';

    // Some dialogs use directives we've created
import { CRDirectives } from '../directives/CRDirectives.module';

    // What we want to declare and export. Also, anything in 'imports' below is made available to all of these components
import { ChangePasswordDialog } from "./changePasswordDialog"
import { ConfirmDialog } from "./ConfirmDialog"
import { CreateShortcutDialog } from "./CreateShortcutDialog"
import { CustomDialog } from "./CustomDialog"
import { EditControlDlg } from "./EditControlDlg"
import { EditSectionDlg } from "./EditSectionDialog"
import { EditSitesDialog } from "./EditSitesDialog"
import { StandardFieldDialog } from "./editStandardFieldDialog"
import { EditUserDialog } from "./EditUserDialog"
import { ErrorsDialog } from "./ErrorsDialog"
import { GenericListDlg } from "./GenericListDialog"
import { LoginDialog } from "./LoginDialog"
import { ReferringPhysDialog } from "./ReferringPhysDialog"
import { SignReportDlg } from "./SignReportDlg"

@NgModule(
{
    imports: [CommonModule, CRDirectives, Ng2Bs3ModalModule],       // Other modules to import

    declarations: [
        ChangePasswordDialog, ConfirmDialog, CreateShortcutDialog, CustomDialog, EditControlDlg, EditSectionDlg, EditSitesDialog,
        EditUserDialog, StandardFieldDialog, ErrorsDialog, GenericListDlg, LoginDialog, ReferringPhysDialog, SignReportDlg
    ],

    exports: [
        ChangePasswordDialog, ConfirmDialog, CreateShortcutDialog, CustomDialog, EditControlDlg, EditSectionDlg, EditSitesDialog,
        EditUserDialog, StandardFieldDialog, ErrorsDialog, GenericListDlg, LoginDialog, ReferringPhysDialog, SignReportDlg
    ]
})

export class CRDialogs {}

And this module in turn is referenced in my app.module.ts:

import { CRGlobals } from "./globals"

[...]

@NgModule({
    declarations: [
        CSReportMain,
        AppTestTemp
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        CRDirectives,
        **CRDialogs,**
        CRPages,

       [...]
    ],
    providers: [
        CRGlobals
    ],
    bootstrap: [CSReportMain]
})

Here it main.ts:

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule);

So why am I getting this error?


问:
Best way to download and install Eclipse if you want to do C++ and Java and GUI design
I'm interested in using Eclipse. The Eclipse Downloads page has versions for Java Developers for Java EE Developers for C/C++ developers, and so on. I want to use Eclipse for Java, C/C++, GUI design, and more. There doesn't seem to be a single download that has it all. Am I missing something? Or is there an easy way to download and install all of the components.

And then it's a big pain every time they upgrade, as I have to do it all over again, and it seems that I have to do it again for every machine. Can I simply move the Eclipse folder form one machine to another?

答:
Every package available in the Downloads page is simply a package that bundles Eclipse with a set of plugins that intend to achieve the wanted goal.

Just choose a package (or begin from scratch with Eclipse Classic), and use the integrated update manager to install the plugins that you want.

And yes, moving your installation of Eclipse from one machine to another works.

EDIT: Here is a screenshot of what the update menu looks like. (Help/Install new Software…)
http://img375.imageshack.us/img375/8932/eclipsedownloadmenu.png


问:
Saving an Object that contains a list gives "referential integrity constraint violation"
I'm attempting to understand how to edit a One-to-Many relationship using MVC and Entity Framework and I am running into a few issues, I am attempting to edit the One (Person) and the Many (Color) on the same View (I will move onto Many-to-Many once this is complete).

I've reviewed many other posts and don't see a direct solution to what I think I am experiencing.

BaseObject Class:

```<code>public class BaseObject
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    [Column(Order = 1)]
    public Guid Oid { get; set; }
}
</code>```

Person Class:

```<code>public class Person : BaseObject
{
    public string Name { get; set; }
    public virtual List<Color> Colors { get; set; }
}
</code>```

Color Class:

```<code>public class Color : BaseObject
{
    public string Name { get; set; }

    [DisplayName("Person")]
    public Guid? PersonID { get; set; }

    [ForeignKey("PersonID")]
    public virtual Person Person { get; set; }

}
</code>```

After this I create my Scafolding (and Views), from there I have modified the Person/Edit.cshtml to use a Model Binder method  starting with @for (var i = 0; i < Model.Colors.Count(); i++):

```<code>@model x.Models.One_to_Many.Person
@using x.Models.One_to_Many

@{
    ViewBag.Title = "Edit Person and associated Colors";
}

<h2>Edit</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Person showing associated Colors</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Oid)

        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Colors, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">

                @for(var i = 0; i < Model.Colors.Count(); i++)
                {
                    @Html.HiddenFor(model => Model.Colors[i].Oid)
                    @Html.EditorFor(modelItem => Model.Colors[i].Name, new { htmlAttributes = new { @class = "form-control" } })
                }

                </div>
            </div>

            <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
</code>```

From there, I have the Person Controller (PeopleController) basically untouched (I've added Colors to the Bind > Include as a test):

```<code>    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Oid,Name,Colors")] Person person)
    {
        if (ModelState.IsValid)
        {
            db.Entry(person).State = EntityState.Modified; //<-- Error
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(person);
    }
</code>```

When I run the app, open an existing Person I see the Person Name and a list of the colors (Blue and Green).  Modifying or not, when I click "Save", db.Entry(person).State = EntityState.Modified; returns the following error:

System.InvalidOperationException: 'A referential integrity constraint violation occurred: The property value(s) of 'Person.Oid' on one end of a relationship do not match the property value(s) of 'Color.PersonID' on the other end.'

Inspecting at the Person object, it does have 2 Colors (got past that using the Model Binder), going into the Colors collection I see the Name of the color has changed, the Person object is populated, but the PersonID is not.

```<code>person.Colors[0].Name       "Blue updated"                  string
person.Colors[0].PersonID   null                            System.Guid?
+person.Colors[0].Person    {x.Models.One_to_Many.Person}   x.Models.One_to_Many.Person
</code>```

I believe that the PersonID is my issue, it needs to be populated with the current Person.

Do I need to Bind or Include in the Edit GET?

```<code>public ActionResult Edit(Guid? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Person person = db.One.Find(id);
    if (person == null)
    {
        return HttpNotFound();
    }
    return View(person);
}
</code>```

I'm not sure what the best approach is to having this set or setting it on Save.

Edit

This is based on @gert-arnold advice to go to a ViewModel, my plan was to move to that after I figure out the One-to-Many and future Many-to-Many.

Saving the Model wasn't working out too well, if you see below, I would be able to adapt the code to the PeopleController, but putting it into a ViewModel and Controller definitely made sense.

I have now created a PersonViewModel:

```<code>public class PersonView
{
    public string Name { get; set; }
    public virtual List<Color> Colors { get; set; }
}
</code>```

And an associated Controller; PersonViewController:

```<code>public class PersonViewController : Controller
{
    private ApplicationDBContext db = new ApplicationDBContext();
    private Person person;
    private Color color;

    public ActionResult Edit(Guid id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        person = db.People.Find(id);
        if (person == null)
        {
            return HttpNotFound();
        }

        //Setup ViewModel
        PersonView personView = new PersonView();
        personView.Name = person.Name;
        personView.Colors = person.Colors;

        return View(personView);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Guid? id, PersonView personViewModel)
    {
        if (ModelState.IsValid)
        {
            //Person
            person = db.People.Find(id);
            person.Name = personViewModel.Name;
            db.Entry(person).State = EntityState.Modified;
            db.SaveChanges();

            //Colors
            foreach (Color item in personViewModel.Colors)
            {
                color = db.Colors.Find(item.Oid);
                color.Name = item.Name;
                //color.PersonID = id; //Is this neccessary?
                db.Entry(color).State = EntityState.Modified;
                db.SaveChanges();
            }

            return View(personViewModel); //return RedirectToAction("Index");
        }
        return View(personViewModel);
    }
}
</code>```

Finally, the Edit.cshtml is very similar (if not the same) as above.  I believe that I am getting the results that I am looking for and I can expand to allow new Colors to be added inline with Ajax, etc.

I know that I need to check for and catch errors, but I feel this will suffice as a proof of concept.  In short, does anyone have any advice on this code and approach, I am looking to improve it now and apply to my actual project.

答:
Starting to use view models is a sensible choice. When doing that, there are multiple ways to "paint the state" back to the EF entities. Looking at Person, one of them is:

```<code>person = db.People.Find(id);
person.Name = personViewModel.Name;
db.SaveChanges();
</code>```

By the Find statement, EF starts tracking the person entity. EF notices the name modification and will update just that. Setting the state to Modified isn't necessary, less optimal even, because it will cause EF to update all person's properties.

Another way to paint the state is:

```<code>person = new Person { Oid = personViewModel.Oid, Name = personViewModel.Name };
db.Persons.Attach(person);
db.Entry(person).Property(p => p.Name).IsModified = true;
db.SaveChanges();
</code>```

This removes a database roundtrip, which may improve performance, but it takes more code, especially when nested objects are involved. Another major drawback is that person, a so-called stub entity, is now likely to fail validation because required properties may be null. This can be skirted around by disabling validation on save (db.Configuration.ValidateOnSaveEnabled = false), but then you need some other mechanism validation than the one EF provides.

More on how to choose between these alternatives here.

Body:
I'm attempting to understand how to edit a One-to-Many relationship using MVC and Entity Framework and I am running into a few issues, I am attempting to edit the One (Person) and the Many (Color) on the same View (I will move onto Many-to-Many once this is complete).

I've reviewed many other posts and don't see a direct solution to what I think I am experiencing.

BaseObject Class:

public class BaseObject
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    [Column(Order = 1)]
    public Guid Oid { get; set; }
}

Person Class:

public class Person : BaseObject
{
    public string Name { get; set; }
    public virtual List<Color> Colors { get; set; }
}

Color Class:

public class Color : BaseObject
{
    public string Name { get; set; }

    [DisplayName("Person")]
    public Guid? PersonID { get; set; }

    [ForeignKey("PersonID")]
    public virtual Person Person { get; set; }

}

After this I create my Scafolding (and Views), from there I have modified the Person/Edit.cshtml to use a Model Binder method  starting with @for (var i = 0; i < Model.Colors.Count(); i++):

@model x.Models.One_to_Many.Person
@using x.Models.One_to_Many

@{
    ViewBag.Title = "Edit Person and associated Colors";
}

Edit

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Person showing associated Colors

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Oid)

            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Colors, htmlAttributes: new { @class = "control-label col-md-2" })

                @for(var i = 0; i < Model.Colors.Count(); i++)
                {
                    @Html.HiddenFor(model => Model.Colors[i].Oid)
                    @Html.EditorFor(modelItem => Model.Colors[i].Name, new { htmlAttributes = new { @class = "form-control" } })
                }

                <input type="submit" value="Save" class="btn btn-default" />

}

    @Html.ActionLink("Back to List", "Index")

From there, I have the Person Controller (PeopleController) basically untouched (I've added Colors to the Bind > Include as a test):

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Oid,Name,Colors")] Person person)
    {
        if (ModelState.IsValid)
        {
            db.Entry(person).State = EntityState.Modified; //<-- Error
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(person);
    }

When I run the app, open an existing Person I see the Person Name and a list of the colors (Blue and Green).  Modifying or not, when I click "Save", db.Entry(person).State = EntityState.Modified; returns the following error:

System.InvalidOperationException: 'A referential integrity constraint violation occurred: The property value(s) of 'Person.Oid' on one end of a relationship do not match the property value(s) of 'Color.PersonID' on the other end.'

Inspecting at the Person object, it does have 2 Colors (got past that using the Model Binder), going into the Colors collection I see the Name of the color has changed, the Person object is populated, but the PersonID is not.

person.Colors[0].Name       "Blue updated"                  string
person.Colors[0].PersonID   null                            System.Guid?
+person.Colors[0].Person    {x.Models.One_to_Many.Person}   x.Models.One_to_Many.Person

I believe that the PersonID is my issue, it needs to be populated with the current Person.

Do I need to Bind or Include in the Edit GET?

public ActionResult Edit(Guid? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Person person = db.One.Find(id);
    if (person == null)
    {
        return HttpNotFound();
    }
    return View(person);
}

I'm not sure what the best approach is to having this set or setting it on Save.

Edit

This is based on @gert-arnold advice to go to a ViewModel, my plan was to move to that after I figure out the One-to-Many and future Many-to-Many.

Saving the Model wasn't working out too well, if you see below, I would be able to adapt the code to the PeopleController, but putting it into a ViewModel and Controller definitely made sense.

I have now created a PersonViewModel:

public class PersonView
{
    public string Name { get; set; }
    public virtual List<Color> Colors { get; set; }
}

And an associated Controller; PersonViewController:

public class PersonViewController : Controller
{
    private ApplicationDBContext db = new ApplicationDBContext();
    private Person person;
    private Color color;

    public ActionResult Edit(Guid id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        person = db.People.Find(id);
        if (person == null)
        {
            return HttpNotFound();
        }

        //Setup ViewModel
        PersonView personView = new PersonView();
        personView.Name = person.Name;
        personView.Colors = person.Colors;

        return View(personView);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Guid? id, PersonView personViewModel)
    {
        if (ModelState.IsValid)
        {
            //Person
            person = db.People.Find(id);
            person.Name = personViewModel.Name;
            db.Entry(person).State = EntityState.Modified;
            db.SaveChanges();

            //Colors
            foreach (Color item in personViewModel.Colors)
            {
                color = db.Colors.Find(item.Oid);
                color.Name = item.Name;
                //color.PersonID = id; //Is this neccessary?
                db.Entry(color).State = EntityState.Modified;
                db.SaveChanges();
            }

            return View(personViewModel); //return RedirectToAction("Index");
        }
        return View(personViewModel);
    }
}

Finally, the Edit.cshtml is very similar (if not the same) as above.  I believe that I am getting the results that I am looking for and I can expand to allow new Colors to be added inline with Ajax, etc.

I know that I need to check for and catch errors, but I feel this will suffice as a proof of concept.  In short, does anyone have any advice on this code and approach, I am looking to improve it now and apply to my actual project.

Body:
Starting to use view models is a sensible choice. When doing that, there are multiple ways to "paint the state" back to the EF entities. Looking at Person, one of them is:

person = db.People.Find(id);
person.Name = personViewModel.Name;
db.SaveChanges();

By the Find statement, EF starts tracking the person entity. EF notices the name modification and will update just that. Setting the state to Modified isn't necessary, less optimal even, because it will cause EF to update all person's properties.

Another way to paint the state is:

person = new Person { Oid = personViewModel.Oid, Name = personViewModel.Name };
db.Persons.Attach(person);
db.Entry(person).Property(p => p.Name).IsModified = true;
db.SaveChanges();

This removes a database roundtrip, which may improve performance, but it takes more code, especially when nested objects are involved. Another major drawback is that person, a so-called stub entity, is now likely to fail validation because required properties may be null. This can be skirted around by disabling validation on save (db.Configuration.ValidateOnSaveEnabled = false), but then you need some other mechanism validation than the one EF provides.

More on how to choose between these alternatives here.


问:
Join two queries in MySQL to map result of one query with another
I have a query like below in MYSQL. This query gives me list of table names without certain special charcters in the column names.

```<code>select distinct A.table_name from (select TABLE_NAME from information_schema.columns where TABLE_SCHEMA = 'testing' order by TABLE_NAME) A LEFT JOIN
(select table_name from information_schema.columns where (COLUMN_NAME like '% %' or COLUMN_NAME like '%{%' or COLUMN_NAME like '%(%' or COLUMN_NAME like '%;%'
or COLUMN_NAME like '%.%') and TABLE_SCHEMA = 'testing' order by TABLE_NAME) B ON (A.TABLE_NAME=B.TABLE_NAME) where B.table_name IS NULL
</code>```

Result of the above query:

```<code>100_test
101_test
102_backup
103_backup
</code>```

I have another query like below:

```<code>select src_table,dst_table from test.mapping
</code>```

Here test is database and mapping is the table name.

Result:

```<code>100_test    100_testing
101_test    101_testing
102_backup  102_backup_old
103_backup  103_backup_old
105_old_test    105_archived
</code>```

Now I want to create a query that gives me src_table and dst_table from test.mapping for each table of the result of the 1st query.

I want to join both queries as a single query which gives me result like below

```<code>100_test    100_testing
101_test    101_testing
102_backup  102_backup_old
103_backup  103_backup_old
</code>```

How can I achieve that?

答:
```<code>select src_table,dst_table from test.mapping
where src_table in
(
select distinct A.table_name from (select TABLE_NAME from information_schema.columns where TABLE_SCHEMA = 'testing' order by TABLE_NAME) A LEFT JOIN
(select table_name from information_schema.columns where (COLUMN_NAME like '% %' or COLUMN_NAME like '%{%' or COLUMN_NAME like '%(%' or COLUMN_NAME like '%;%'
or COLUMN_NAME like '%.%') and TABLE_SCHEMA = 'testing' order by TABLE_NAME) B ON (A.TABLE_NAME=B.TABLE_NAME) where B.table_name IS NULL
)
</code>```

Body:
I have a query like below in MYSQL. This query gives me list of table names without certain special charcters in the column names.

select distinct A.table_name from (select TABLE_NAME from information_schema.columns where TABLE_SCHEMA = 'testing' order by TABLE_NAME) A LEFT JOIN
(select table_name from information_schema.columns where (COLUMN_NAME like '% %' or COLUMN_NAME like '%{%' or COLUMN_NAME like '%(%' or COLUMN_NAME like '%;%'
or COLUMN_NAME like '%.%') and TABLE_SCHEMA = 'testing' order by TABLE_NAME) B ON (A.TABLE_NAME=B.TABLE_NAME) where B.table_name IS NULL

Result of the above query:

100_test
101_test
102_backup
103_backup

I have another query like below:

select src_table,dst_table from test.mapping

Here test is database and mapping is the table name.

Result:

100_test    100_testing
101_test    101_testing
102_backup  102_backup_old
103_backup  103_backup_old
105_old_test    105_archived

Now I want to create a query that gives me src_table and dst_table from test.mapping for each table of the result of the 1st query.

I want to join both queries as a single query which gives me result like below

100_test    100_testing
101_test    101_testing
102_backup  102_backup_old
103_backup  103_backup_old

How can I achieve that?


问:
the cost of rewrite __setattr__ () was too high
I want to save the time and mark the object as modified, so I wrote a class and override its __setattr__ function.

```<code>import time

class CacheObject(object):
    __slots__ = ('modified', 'lastAccess')
    def __init__(self):
        object.__setattr__(self,'modified',False)
        object.__setattr__(self,'lastAccess',time.time())

    def setModified(self):
        object.__setattr__(self,'modified',True)
        object.__setattr__(self,'lastAccess',time.time())

    def resetTime(self):
        object.__setattr__(self,'lastAccess',time.time())

    def __setattr__(self,name,value):
        if (not hasattr(self,name)) or object.__getattribute__(self,name)!=value:
            object.__setattr__(self,name,value)
            self.setModified()

class example(CacheObject):
    __slots__ = ('abc',)
    def __init__(self,i):
        self.abc = i
        super(example,self).__init__()

t = time.time()
f = example(0)
for i in range(100000):
    f.abc = i

print(time.time()-t)
</code>```

I measured the process time, and it took 2 seconds. When I commented out overridden function, the process time was 0.1 second, I know the overridden function would be slower but almost 20 times the gap is too much. I think I must get something wrong.

take the suggestion from cfi

1.elimate the if condition

```<code>    def __setattr__(self,name,value):
#        if (not hasattr(self,name)) or object.__getattribute__(self,name)!=value:
            object.__setattr__(self,name,value)
            self.setModified()
</code>```

the running time down to 1.9, a little improve but mark the object modified if it's not changed would cost more in other process, so not an option.

2.change self.func to classname.func(self)

```<code>def __setattr__(self,name,value):
    if (not hasattr(self,name)) or object.__getattribute__(self,name)!=value:
        object.__setattr__(self,name,value)
        CacheObject.setModified(self)
</code>```

running time is 2.0 .so nothing really changed

3)extract setmodified function

```<code>def __setattr__(self,name,value):
    if (not hasattr(self,name)) or object.__getattribute__(self,name)!=value:
        object.__setattr__(self,name,value)
        object.__setattr__(self,'modified',True)
        object.__setattr__(self,'lastAccess',time.time())
</code>```

running time down to 1.2!!That's great ,it do save almost 50% time,though the cost is  still  high.

答:
Old question but worth an update.

I ran into the same problem with pydantic using python 3.6.

object.__setattr__(self, name, value) just is slower than setting an attribute on a class normally. No apparent way round that.

If performance is important the only option is to keep calls to object.__setattr__(self, name, value) to an absolute minimum in classes where you need to override _setattr_.

Body:
I want to save the time and mark the object as modified, so I wrote a class and override its __setattr__ function.

import time

class CacheObject(object):
    __slots__ = ('modified', 'lastAccess')
    def __init__(self):
        object.__setattr__(self,'modified',False)
        object.__setattr__(self,'lastAccess',time.time())

    def setModified(self):
        object.__setattr__(self,'modified',True)
        object.__setattr__(self,'lastAccess',time.time())

    def resetTime(self):
        object.__setattr__(self,'lastAccess',time.time())

    def __setattr__(self,name,value):
        if (not hasattr(self,name)) or object.__getattribute__(self,name)!=value:
            object.__setattr__(self,name,value)
            self.setModified()

class example(CacheObject):
    __slots__ = ('abc',)
    def __init__(self,i):
        self.abc = i
        super(example,self).__init__()

t = time.time()
f = example(0)
for i in range(100000):
    f.abc = i

print(time.time()-t)

I measured the process time, and it took 2 seconds. When I commented out overridden function, the process time was 0.1 second, I know the overridden function would be slower but almost 20 times the gap is too much. I think I must get something wrong.

take the suggestion from cfi

1.elimate the if condition

    def __setattr__(self,name,value):
#        if (not hasattr(self,name)) or object.__getattribute__(self,name)!=value:
            object.__setattr__(self,name,value)
            self.setModified()

the running time down to 1.9, a little improve but mark the object modified if it's not changed would cost more in other process, so not an option.

2.change self.func to classname.func(self)

def __setattr__(self,name,value):
    if (not hasattr(self,name)) or object.__getattribute__(self,name)!=value:
        object.__setattr__(self,name,value)
        CacheObject.setModified(self)

running time is 2.0 .so nothing really changed

3)extract setmodified function

def __setattr__(self,name,value):
    if (not hasattr(self,name)) or object.__getattribute__(self,name)!=value:
        object.__setattr__(self,name,value)
        object.__setattr__(self,'modified',True)
        object.__setattr__(self,'lastAccess',time.time())

running time down to 1.2!!That's great ,it do save almost 50% time,though the cost is  still  high.


问:
howto efficiently have a WritableBitmap which matches a WPF control pixels 1:1?
I'm using WritableBitmap to draw fast 2d graphics in WPF.

The problem is, my WritableBitmap does not match the pixel size of the Image control 1:1. When I try to make a new WritableBitmap based on size-change events of the Image control, the performance is terrible.

How can I render a WPF control's pixels 1:1 with a WritableBitmap?

You can see both WPF and Windows.Forms versions of my code on github.

The application is a tiny mini-app called SoundLevelMonitor, which monitors audio levels of applications and paints a continuously moving graph with a legend. Below is a screenshot of the Windows.Forms version. The WPF version is basically the same, except the Image is a fixed size and stretched to fit the window.

Before I started using WritableBitmap, I tried using UIElement, but the drawing performance was horrible. One problem is that triggering repaint requires InvalidateVisual() which causes a slow re-layout. The other problem is that drawing text with DrawingContext is extremely slow.

So I found this suggestion to write to WriteableBitmap using GDI, and it actually works really well, and is SUPER fast.  (the WPF version feels more responsive than the windows forms version!)

However, the WriteableBitmap is a fixed-sized backingstore which WPF is scaling  up to fit in the Image control. I want the WriteableBitmap to be a 1:1 pixel backing store for the control, even when the control is resized.

I tried to use both OnRender and LayoutUpdated to trigger creating a new size-matched WriteableBitmap, but both of them were incredibly slow. Probably because setting Image.Source is triggering a relayout.

Any ideas?

答:
My biggest discovery is that I don't need to use a bitmap to get the results I want. I can create a DrawingGroup as a backingstore, draw this to the drawing context during OnRender, and then still update it later whenever I want.

```<code>DrawingGroup backingStore = new DrawingGroup();

protected override void OnRender(DrawingContext drawingContext) {
    base.OnRender(drawingContext);

    Render(); // put content into our backingStore
    drawingContext.DrawDrawing(backingStore);
}

// I can call this anytime, and it'll update my visual drawing
// without ever triggering layout or OnRender()
private void Render() {
    var drawingContext = backingStore.Open();
    Render(drawingContext);
    drawingContext.Close();
}
</code>```

I also learned that StreamGeometry with Freeze() is notably faster than other drawing methods, as it optimizes for no animation.

Related to my bitmap attempts -- the correct way to be notified when the Image Control size changes is to listen to SizeChanged, which fires only when the control changes size. In this event handler, I had to make a new WriteableBitmap of size Image.RenderSize and assign it to the Image.Source.

Also, in the Image Control instantiation, I had to set it to Stretch="Fill" to cause it to fill it's containing box completely, instead of maintaining the image's aspect ratio.

LayoutUpdated is fired every time the control content updates, which is what was causing my original performance problem.

I also found that I can use RenderTargetBitmap instead of WriteableBitmap, and then I can issue WPF drawing commands to it, instead of using a GDI Graphics context.

..and I can catch the CompositionTarget.Rendering event to cause it to be redrawn every frame.

Body:
My biggest discovery is that I don't need to use a bitmap to get the results I want. I can create a DrawingGroup as a backingstore, draw this to the drawing context during OnRender, and then still update it later whenever I want.

DrawingGroup backingStore = new DrawingGroup();

protected override void OnRender(DrawingContext drawingContext) {
    base.OnRender(drawingContext);

    Render(); // put content into our backingStore
    drawingContext.DrawDrawing(backingStore);
}

// I can call this anytime, and it'll update my visual drawing
// without ever triggering layout or OnRender()
private void Render() {
    var drawingContext = backingStore.Open();
    Render(drawingContext);
    drawingContext.Close();
}

I also learned that StreamGeometry with Freeze() is notably faster than other drawing methods, as it optimizes for no animation.

Related to my bitmap attempts -- the correct way to be notified when the Image Control size changes is to listen to SizeChanged, which fires only when the control changes size. In this event handler, I had to make a new WriteableBitmap of size Image.RenderSize and assign it to the Image.Source.

Also, in the Image Control instantiation, I had to set it to Stretch="Fill" to cause it to fill it's containing box completely, instead of maintaining the image's aspect ratio.

LayoutUpdated is fired every time the control content updates, which is what was causing my original performance problem.

I also found that I can use RenderTargetBitmap instead of WriteableBitmap, and then I can issue WPF drawing commands to it, instead of using a GDI Graphics context.

..and I can catch the CompositionTarget.Rendering event to cause it to be redrawn every frame.


问:
Reflexion in java

Heading

Just a little question i can't figure

```<code>    Person per = new Person();
    Class cla = per.getClass();

    for(Method m : cla.getDeclaredMethods())
         System.out.println(m);
</code>```

for example i have in my class Person method lined like this: setName,setSecondName,getName,getSecondName and when i list the Object m my output is getName and below setName so to the last method. Can someone explain me why the method is not lists as they lined up in my Class Person?Thanks

Here is my problem in full:

```<code>    Person per = new Person();
    Class cla = per.getClass();

    for(Method m : cla.getDeclaredMethods())
    {
         System.out.println(m.getName());
        if(m.getParameterCount() > 0){
             Parameter [] pa = m.getParameters();
             if(pa.length == 1){
                 if(m.getName().equals("setName") )
                     m.invoke(per , "John");
                 else if(m.getName().endsWith("setSecondName"))
                     m.invoke(per, "Cameron");
             }

        }
         else
             System.out.println(m.invoke(per));
    }
</code>```

Acutal output:

getName

null

setName

setSecondName

getSecondName

Cameron

答:
Look at JavaDoc:

public Method[] getDeclaredMethods()
                              throws SecurityException

Returns an array containing Method objects reflecting all the declared
  methods of the class or interface represented by this Class object,
  including public, protected, default (package) access, and private
  methods, but excluding inherited methods.

If this Class object represents a type that has multiple declared
  methods with the same name and parameter types, but different return
  types, then the returned array has a Method object for each such
  method.

If this Class object represents a type that has a class initialization
  method , then the returned array does not have a corresponding
  Method object.

If this Class object represents a class or interface with no declared
  methods, then the returned array has length 0.

If this Class object represents an array type, a primitive type, or
  void, then the returned array has length 0.

The elements in the returned array are not sorted and are not in any
   particular order.

Title: Reflexion in java

Body:
Heading

Just a little question i can't figure

    Person per = new Person();
    Class cla = per.getClass();

    for(Method m : cla.getDeclaredMethods())
         System.out.println(m);

for example i have in my class Person method lined like this: setName,setSecondName,getName,getSecondName and when i list the Object m my output is getName and below setName so to the last method. Can someone explain me why the method is not lists as they lined up in my Class Person?Thanks

Here is my problem in full:

    Person per = new Person();
    Class cla = per.getClass();

    for(Method m : cla.getDeclaredMethods())
    {
         System.out.println(m.getName());
        if(m.getParameterCount() > 0){
             Parameter [] pa = m.getParameters();
             if(pa.length == 1){
                 if(m.getName().equals("setName") )
                     m.invoke(per , "John");
                 else if(m.getName().endsWith("setSecondName"))
                     m.invoke(per, "Cameron");
             }

        }
         else
             System.out.println(m.invoke(per));
    }

Acutal output:

getName

null

setName

setSecondName

getSecondName

Cameron


问:
simulate current date during tests
I am writing tests and I wonder if there is a way to change the current date during my test?

The point is that I am testing the statistic functionality of the application, which is connected to a tracking model that creates an instance every time an action is called (only some actions are tracked, via a "before_filter only" call)

So I need to call this actions in different controller at different points in time to test my analytics component is making the right calculations, but I did not find any way to implement change_current_time in the following sample code:

```<code>test "login count" do
  change_current_time(2.day.ago)
  get "users/login/testuser/testpassword"
  assert login_count(2.day.ago) == 1
  change_current_time(1.day.ago)
  get "users/login/testuser/testpassword"
  get "users/login/testuser1/testpassword1"
  assert login_count(1.day.ago) == 2
end
</code>```

答:
One way to go about this kind of testing is to Mock the method/class you want to test.

http://en.wikipedia.org/wiki/Mock_object

The idea is you can create an identical function, except for passing in a date instead of relying on current date, and test that instead.  The difficulty comes from making sure the two functions really are otherwise equivalent and keeping any changes to them in sync.

There are existing frameworks and such out there for mocking, but I'm not really familiar enough with them to recommend one to you.

Title: simulate current date during tests

Body:
I am writing tests and I wonder if there is a way to change the current date during my test?

The point is that I am testing the statistic functionality of the application, which is connected to a tracking model that creates an instance every time an action is called (only some actions are tracked, via a "before_filter only" call)

So I need to call this actions in different controller at different points in time to test my analytics component is making the right calculations, but I did not find any way to implement change_current_time in the following sample code:

test "login count" do
  change_current_time(2.day.ago)
  get "users/login/testuser/testpassword"
  assert login_count(2.day.ago) == 1
  change_current_time(1.day.ago)
  get "users/login/testuser/testpassword"
  get "users/login/testuser1/testpassword1"
  assert login_count(1.day.ago) == 2
end


问:
Can I print labels on a Zebra GX430t printer without sending raw text
I created an application in C# that creates label formats and sends them to the Zebra printer in the ZPL II format. In order to make the printer behave correctly, I needed to send the printer raw text using pinvoke calls to the winspool.Drv dll. It worked fine until we tried it on one of our customers that remotes in to one of our servers using RDP. It turns out that the printer redirect through RDP uses EasyPrint and EasyPrint jams up the RawPrinterHelper calls and prevents anything from printing. My network person claims we cannot turn this off without breaking all the other redirected printers on the server.

I noticed that the default driver for the printer seems to behave as a 'normal' printer. I am trying to find a way to print labels to this printer using this default driver (ZDesigner GX430t). I can't seem to find any documentation on doing this. I am about to try using standard C# commands to draw to the printer the way I would any other printer but want to make sure I am not missing anything. Has anyone else done anything like this?

答:
Okay, thanks to the folks at ScanTexas I think I found a solution.
The printer driver has a setting to allow 'Pass Through' characters. You can include these in your PrintDocument, just prefix your labels with the start chars '${' and append the end characters at the end '}$'. Here are the instructions:
pass thru instructions

Here is my test code (winform form):

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;

namespace ZebraPrint
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Button1_Click(object sender, System.EventArgs e)
        {
            using (PrintDocument doc = new PrintDocument())
            {
                doc.PrintPage += new PrintPageEventHandler(document_PrintPage);

                using (PrintDialog pd = new PrintDialog())
                {
                    pd.PrinterSettings = new PrinterSettings();
                    pd.Document = doc;
                    if (pd.ShowDialog(this) == DialogResult.OK)
                    {
                        pd.Document.Print();
                    }
                }
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void document_PrintPage(object sender, PrintPageEventArgs e)
        {
            Font printFont = new Font("Consolas", 6);
            SizeF size = e.Graphics.MeasureString("WWWWWW", printFont);
            float printTextHeight = size.Height;
            float top = 0;

            e.Graphics.DrawString(@"${^XA", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^MD0", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^MMT", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^MNY", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^LL600", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^LH95,75", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^FO0,0^AA,54^FD  Palmdale Oil Company, Inc.^FS", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^FO0,100^AC,36^FDCustomer: AVERITT EXPRESS^FS", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^FO0,136^AC,36^FD Vehicle: 66030^FS", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^FO0,172^AC,36^FD    Desc: REEFER^FS", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^FO0,208^AC,36^FD     TAG: ^FS", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^FO0,275", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^BY5", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^BC,150,N,N,N,N^FD4770013-66030", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^FS", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^FO0,430^AC,36^FD4770013-66030^FS", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^XZ}$", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
        }
    }
}
</code>```

Body:
Okay, thanks to the folks at ScanTexas I think I found a solution.
The printer driver has a setting to allow 'Pass Through' characters. You can include these in your PrintDocument, just prefix your labels with the start chars '${' and append the end characters at the end '}$'. Here are the instructions:
pass thru instructions

Here is my test code (winform form):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;

namespace ZebraPrint
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Button1_Click(object sender, System.EventArgs e)
        {
            using (PrintDocument doc = new PrintDocument())
            {
                doc.PrintPage += new PrintPageEventHandler(document_PrintPage);

                using (PrintDialog pd = new PrintDialog())
                {
                    pd.PrinterSettings = new PrinterSettings();
                    pd.Document = doc;
                    if (pd.ShowDialog(this) == DialogResult.OK)
                    {
                        pd.Document.Print();
                    }
                }
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void document_PrintPage(object sender, PrintPageEventArgs e)
        {
            Font printFont = new Font("Consolas", 6);
            SizeF size = e.Graphics.MeasureString("WWWWWW", printFont);
            float printTextHeight = size.Height;
            float top = 0;

            e.Graphics.DrawString(@"${^XA", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^MD0", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^MMT", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^MNY", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^LL600", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^LH95,75", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^FO0,0^AA,54^FD  Palmdale Oil Company, Inc.^FS", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^FO0,100^AC,36^FDCustomer: AVERITT EXPRESS^FS", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^FO0,136^AC,36^FD Vehicle: 66030^FS", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^FO0,172^AC,36^FD    Desc: REEFER^FS", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^FO0,208^AC,36^FD     TAG: ^FS", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^FO0,275", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^BY5", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^BC,150,N,N,N,N^FD4770013-66030", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^FS", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^FO0,430^AC,36^FD4770013-66030^FS", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
            e.Graphics.DrawString(@"^XZ}$", printFont, System.Drawing.Brushes.Black, 10, top += printTextHeight);
        }
    }
}


问:
Variable changable
Hello guys I have a query that need a variable to be executed but that variable is returned by a select on a form

```<code>$obtermaxcampo = "SELECT P$pagina as maxcampo FROM slider_settings where ID = $ID";
</code>```

if I define $pagina = 1 it only query me the P1 and I have 12 P's.
My question is if theres any way to start the variable in 1 but after submit delete that definition and give him a $pagina = $_POST['selectedPagina'];

here is the selected form

```<code><form action="" method="POST" name="carregarinfo">
    <label>Pagina</label>
    <select name ="selectedPagina" id="selected" >
        <?php for ($k = 1; $k <= $result['max']; $k++){?>
        <option value ="<?php echo $k;?>" <?php if($_POST['selectedPagina'] == $k){echo "selected='$k'"; }?>><?php echo $k;?></option>
        <?php
            }
        ?>
    </select>
    <label>Campo</label>
    <select name ="selectedCampo" id="selected" >
        <?php for ($z = 1; $z <= $resultmaxcampo['maxcampo']; $z++){?>
        <option value ="<?php echo $z;?>"><?php echo $z;?></option>
        <?php
            }
        ?>
    </select>
    <input type="submit" name="carregar" id="carregar" value="Carregar">
</form>
</code>```

答:
```<code>if(isset($_POST['carregar'])){
    $sql = "SELECT tituloP$pagina as titulopag, Butao, Titulo, Texto FROM slider_settings, slider_config where slider_settings.ID = $ID and slider_config.P_NUM = $pagina and slider_config.Campo = $campo and slider_config.ID = $ID";
    $sqlconnect = $connect->query($sql);
    $sqlresult = $sqlconnect->fetch_assoc();
    $pagina = $_POST['selectedPagina'];
    $obtermaxcampo = "SELECT P$pagina as maxcampo FROM slider_settings where ID = $ID";
    $connectionmaxcampo = $connect->query($obtermaxcampo);
    $resultmaxcampo = $connectionmaxcampo ->fetch_assoc();

}
</code>```

Title: Variable changable

Body:
Hello guys I have a query that need a variable to be executed but that variable is returned by a select on a form

$obtermaxcampo = "SELECT P$pagina as maxcampo FROM slider_settings where ID = $ID";

if I define $pagina = 1 it only query me the P1 and I have 12 P's.
My question is if theres any way to start the variable in 1 but after submit delete that definition and give him a $pagina = $_POST['selectedPagina'];

here is the selected form

<form action="" method="POST" name="carregarinfo">
    Pagina
    <select name ="selectedPagina" id="selected" >
        <?php for ($k = 1; $k <= $result['max']; $k++){?>
        <option value ="<?php echo $k;?>" <?php if($_POST['selectedPagina'] == $k){echo "selected='$k'"; }?>><?php echo $k;?></option>
        <?php
            }
        ?>
    </select>
    Campo
    <select name ="selectedCampo" id="selected" >
        <?php for ($z = 1; $z <= $resultmaxcampo['maxcampo']; $z++){?>
        <option value ="<?php echo $z;?>"><?php echo $z;?></option>
        <?php
            }
        ?>
    </select>
    <input type="submit" name="carregar" id="carregar" value="Carregar">
</form>