问:
How can tune MySQL for Wordpress sites?
I'm facing a problem that my MySQL database is slow, so I decided to check with mysqltuner.pl, I don't want to make any changes before I'm sure what I'm doing.

I'm running MySQL 5.7 on Ubuntu 18.04 LTS server.

This is a response from mysqltuner:

```<code>    -------- Performance Metrics -----------------------------------------------------------------------
    [--] Up for: 17h 51m 40s (400K q [6.226 qps], 15K conn, TX: 1G, RX: 63M)
    [--] Reads / Writes: 98% / 2%
    [--] Binary logging is disabled
    [--] Physical Memory     : 7.8G
    [--] Max MySQL memory    : 352.4M
    [--] Other process memory: 1.6G
    [--] Total buffers: 192.0M global + 1.1M per thread (151 max threads)
    [--] P_S Max memory usage: 72B
[OK] Maximum reached memory usage: 207.9M (2.61% of installed RAM)
[OK] Maximum possible memory usage: 352.4M (4.43% of installed RAM)
[OK] Overall possible memory usage with other process is compatible with memory available
[OK] Slow queries: 0% (0/400K)
[OK] Highest usage of available connections: 9% (15/151)
[OK] Aborted connections: 0.01%  (1/15256)
[!!] name resolution is active : a reverse name resolution is made for each new connection and can reduce performance
[!!] Query cache may be disabled by default due to mutex contention.
[!!] Query cache efficiency: 0.0% (0 cached / 338K selects)
[OK] Query cache prunes per day: 0
[OK] Sorts requiring temporary tables: 0% (0 temp sorts / 37K sorts)
[!!] Joins performed without indexes: 494
[!!] Temporary tables created on disk: 78% (15K on disk / 20K total)
[OK] Thread cache hit rate: 99% (30 created / 15K connections)
[OK] Table cache hit rate: 29% (1K open / 6K opened)
[OK] Open file limit used: 2% (136/5K)
[OK] Table locks acquired immediately: 100% (1K immediate / 1K locks)

-------- Performance schema ------------------------------------------------------------------------
[--] Memory used by P_S: 72B
[--] Sys schema is installed.

-------- ThreadPool Metrics ------------------------------------------------------------------------
[--] ThreadPool stat is disabled.

-------- MyISAM Metrics ----------------------------------------------------------------------------
[!!] Key buffer used: 18.2% (3M used / 16M cache)
[OK] Key buffer size / total MyISAM indexes: 16.0M/126.0K
[!!] Read Key buffer hit rate: 68.8% (16 cached / 5 reads)

-------- InnoDB Metrics ----------------------------------------------------------------------------
[--] InnoDB is enabled.
[--] InnoDB Thread Concurrency: 0
[OK] InnoDB File per table is activated
[OK] InnoDB buffer pool / data size: 128.0M/77.4M
[!!] Ratio InnoDB log file size / InnoDB Buffer pool size (75 %): 48.0M * 2/128.0M should be equal 25%
[OK] InnoDB buffer pool instances: 1
[--] Number of InnoDB Buffer Pool Chunk : 1 for 1 Buffer Pool Instance(s)
[OK] Innodb_buffer_pool_size aligned with Innodb_buffer_pool_chunk_size & Innodb_buffer_pool_instances
[OK] InnoDB Read buffer efficiency: 99.96% (12403660 hits/ 12408102 total)
[!!] InnoDB Write Log efficiency: 51.81% (14419 hits/ 27833 total)
[OK] InnoDB log waits: 0.00% (0 waits / 13414 writes)

-------- AriaDB Metrics ----------------------------------------------------------------------------
[--] AriaDB is disabled.

-------- TokuDB Metrics ----------------------------------------------------------------------------
[--] TokuDB is disabled.

-------- XtraDB Metrics ----------------------------------------------------------------------------
[--] XtraDB is disabled.

-------- RocksDB Metrics ---------------------------------------------------------------------------
[--] RocksDB is disabled.

-------- Spider Metrics ----------------------------------------------------------------------------
[--] Spider is disabled.

-------- Connect Metrics ---------------------------------------------------------------------------
[--] Connect is disabled.

-------- Galera Metrics ----------------------------------------------------------------------------
[--] Galera is disabled.

-------- Replication Metrics -----------------------------------------------------------------------
[--] Galera Synchronous replication: NO
[--] No replication slave(s) for this server.
[--] This is a standalone server.

-------- Recommendations ---------------------------------------------------------------------------
General recommendations:
    Control warning line(s) into /var/log/mysql/error.log file
    Control error line(s) into /var/log/mysql/error.log file
    MySQL started within last 24 hours - recommendations may be inaccurate
    Configure your accounts with ip or subnets only, then update your configuration with skip-name-resolve=1
    Adjust your join queries to always utilize indexes
    When making adjustments, make tmp_table_size/max_heap_table_size equal
    Reduce your SELECT DISTINCT queries which have no LIMIT clause
Variables to adjust:
    query_cache_size (=0)
    query_cache_type (=0)
    query_cache_limit (> 1M, or use smaller result sets)
    join_buffer_size (> 256.0K, or always use indexes with joins)
    tmp_table_size (> 16M)
    max_heap_table_size (> 16M)
    innodb_log_file_size * innodb_log_files_in_group should be equal to 1/4 of buffer pool size (=64M) if possible.
</code>```

All of my websites are running on latest version Wordpress, and most of the content is static - like business websites.

How can I improve performance of MySQL based on mysqltuner analyze?

答:
The "meta" tables are poorly implemented by WP.  Here is my fix for that:  http://mysql.rjweb.org/doc.php/index_cookbook_mysql#speeding_up_wp_postmeta

Also, if you provide Wilson's request, I will check the tuning.  77MB of data is rather small, so I don't expect much will need improving.

Title: How can tune MySQL for Wordpress sites?

Body:
I'm facing a problem that my MySQL database is slow, so I decided to check with mysqltuner.pl, I don't want to make any changes before I'm sure what I'm doing.

I'm running MySQL 5.7 on Ubuntu 18.04 LTS server.

This is a response from mysqltuner:

    -------- Performance Metrics -----------------------------------------------------------------------
    [--] Up for: 17h 51m 40s (400K q [6.226 qps], 15K conn, TX: 1G, RX: 63M)
    [--] Reads / Writes: 98% / 2%
    [--] Binary logging is disabled
    [--] Physical Memory     : 7.8G
    [--] Max MySQL memory    : 352.4M
    [--] Other process memory: 1.6G
    [--] Total buffers: 192.0M global + 1.1M per thread (151 max threads)
    [--] P_S Max memory usage: 72B
[OK] Maximum reached memory usage: 207.9M (2.61% of installed RAM)
[OK] Maximum possible memory usage: 352.4M (4.43% of installed RAM)
[OK] Overall possible memory usage with other process is compatible with memory available
[OK] Slow queries: 0% (0/400K)
[OK] Highest usage of available connections: 9% (15/151)
[OK] Aborted connections: 0.01%  (1/15256)
[!!] name resolution is active : a reverse name resolution is made for each new connection and can reduce performance
[!!] Query cache may be disabled by default due to mutex contention.
[!!] Query cache efficiency: 0.0% (0 cached / 338K selects)
[OK] Query cache prunes per day: 0
[OK] Sorts requiring temporary tables: 0% (0 temp sorts / 37K sorts)
[!!] Joins performed without indexes: 494
[!!] Temporary tables created on disk: 78% (15K on disk / 20K total)
[OK] Thread cache hit rate: 99% (30 created / 15K connections)
[OK] Table cache hit rate: 29% (1K open / 6K opened)
[OK] Open file limit used: 2% (136/5K)
[OK] Table locks acquired immediately: 100% (1K immediate / 1K locks)

-------- Performance schema ------------------------------------------------------------------------
[--] Memory used by P_S: 72B
[--] Sys schema is installed.

-------- ThreadPool Metrics ------------------------------------------------------------------------
[--] ThreadPool stat is disabled.

-------- MyISAM Metrics ----------------------------------------------------------------------------
[!!] Key buffer used: 18.2% (3M used / 16M cache)
[OK] Key buffer size / total MyISAM indexes: 16.0M/126.0K
[!!] Read Key buffer hit rate: 68.8% (16 cached / 5 reads)

-------- InnoDB Metrics ----------------------------------------------------------------------------
[--] InnoDB is enabled.
[--] InnoDB Thread Concurrency: 0
[OK] InnoDB File per table is activated
[OK] InnoDB buffer pool / data size: 128.0M/77.4M
[!!] Ratio InnoDB log file size / InnoDB Buffer pool size (75 %): 48.0M * 2/128.0M should be equal 25%
[OK] InnoDB buffer pool instances: 1
[--] Number of InnoDB Buffer Pool Chunk : 1 for 1 Buffer Pool Instance(s)
[OK] Innodb_buffer_pool_size aligned with Innodb_buffer_pool_chunk_size & Innodb_buffer_pool_instances
[OK] InnoDB Read buffer efficiency: 99.96% (12403660 hits/ 12408102 total)
[!!] InnoDB Write Log efficiency: 51.81% (14419 hits/ 27833 total)
[OK] InnoDB log waits: 0.00% (0 waits / 13414 writes)

-------- AriaDB Metrics ----------------------------------------------------------------------------
[--] AriaDB is disabled.

-------- TokuDB Metrics ----------------------------------------------------------------------------
[--] TokuDB is disabled.

-------- XtraDB Metrics ----------------------------------------------------------------------------
[--] XtraDB is disabled.

-------- RocksDB Metrics ---------------------------------------------------------------------------
[--] RocksDB is disabled.

-------- Spider Metrics ----------------------------------------------------------------------------
[--] Spider is disabled.

-------- Connect Metrics ---------------------------------------------------------------------------
[--] Connect is disabled.

-------- Galera Metrics ----------------------------------------------------------------------------
[--] Galera is disabled.

-------- Replication Metrics -----------------------------------------------------------------------
[--] Galera Synchronous replication: NO
[--] No replication slave(s) for this server.
[--] This is a standalone server.

-------- Recommendations ---------------------------------------------------------------------------
General recommendations:
    Control warning line(s) into /var/log/mysql/error.log file
    Control error line(s) into /var/log/mysql/error.log file
    MySQL started within last 24 hours - recommendations may be inaccurate
    Configure your accounts with ip or subnets only, then update your configuration with skip-name-resolve=1
    Adjust your join queries to always utilize indexes
    When making adjustments, make tmp_table_size/max_heap_table_size equal
    Reduce your SELECT DISTINCT queries which have no LIMIT clause
Variables to adjust:
    query_cache_size (=0)
    query_cache_type (=0)
    query_cache_limit (> 1M, or use smaller result sets)
    join_buffer_size (> 256.0K, or always use indexes with joins)
    tmp_table_size (> 16M)
    max_heap_table_size (> 16M)
    innodb_log_file_size * innodb_log_files_in_group should be equal to 1/4 of buffer pool size (=64M) if possible.

All of my websites are running on latest version Wordpress, and most of the content is static - like business websites.

How can I improve performance of MySQL based on mysqltuner analyze?


来源: stackexchange

问:
Can I coerce a lifetime parameter to a shorter lifetime (soundly) even in the presence of `&mut T`?
I'm trying to make a tree with parent pointers in Rust. A method on the node struct is giving me lifetime issues. Here's a minimal example, with lifetimes written explicitly so that I can understand them:

use core::mem::transmute;

pub struct LogNode<'n>(Option<&'n mut LogNode<'n>>);

impl<'n> LogNode<'n> {
    pub fn child<'a>(self: &'a mut LogNode<'n>) -> LogNode<'a> {
        LogNode(Some(self))
    }

    pub fn transmuted_child<'a>(self: &'a mut LogNode<'n>) -> LogNode<'a> {
        unsafe {
            LogNode(Some(
                transmute::<&'a mut LogNode<'n>, &'a mut LogNode<'a>>(self)
            ))
        }
    }
}
```

(Playground link)

Rust complains about child...

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter 'n due to conflicting requirements

...but it's fine with transmuted_child.

I think I understand why child won't compile: the self parameter's type is &'a mut LogNode<'n> but the child node contains an &'a mut LogNode<'a>, and Rust doesn't want to coerce LogNode<'n> to LogNode<'a>. If I change the mutable references to shared references, it compiles fine, so it sounds like the mutable references are a problem specifically because &mut T is invariant over T (whereas &T is covariant). I guess the mutable reference in LogNode bubbles up to make LogNode itself invariant over its lifetime parameter.

But I don't understand why that's true—intuitively it feels like it's perfectly sound to take LogNode<'n> and shorten its contents' lifetimes by turning it into a LogNode<'a>. Since no lifetime is made longer, no value can be accessed past its lifetime, and I can't think of any other unsound behavior that could happen.

transmuted_child avoids the lifetime issue because it sidesteps the borrow checker, but I don't know if the use of unsafe Rust is sound, and even if it is, I'd prefer to use safe Rust if possible. Can I?

I can think of three possible answers to this question:

child can be implemented entirely in safe Rust, and here's how.

child cannot be implemented entirely in safe Rust, but transmuted_child is sound.

child cannot be implemented entirely in safe Rust, and transmuted_child is unsound.

Edit 1: Fixed a claim that &mut T is invariant over the lifetime of the reference. (Wasn't reading the nomicon right.)

Edit 2: Fixed my first edit summary.

答:
To understand why the immutable version works and the mutable version is unsound (as written), we have to discuss subtyping and variance.

Rust mostly doesn't have subtyping. Values typically have a unique type. One place where Rust does have subtyping, however, is with lifetimes. If 'a: 'b (read 'a is longer than 'b), then, for example, &'a T is a subtype of &'b T, intuitively because longer lifetimes can be treated as if they were shorter.

Variance is how subtyping propagates. If A is a subtype of B, and we have a generic type Foo<T>, Foo might be a subtype of Foo, vice versa, or neither. In the first case, where the direction of subtyping stays the same, Foo<T> is said to be covariant with respect to T. In the second case, where the direction reverses, it's said to be contravariant, and in the third case, it's said to be invariant.

For this case, the relevant types are &'a T and &'a mut T. Both are covariant in 'a (so references with longer lifetimes can be coerced to references with shorter lifetimes). &'a T is covariant in T, but &'a mut T is invariant in T.

The reason for this is explained in the Nomicon (linked above), so I'll just show you the (somewhat simplified) example given there. Trentcl's code is a working example of what goes wrong if &'a mut T is covariant in T.

```<code>fn evil_feeder(pet: &mut Animal) {
    let spike: Dog = ...;

    // `pet` is an Animal, and Dog is a subtype of Animal,
    // so this should be fine, right..?
    *pet = spike;
}

fn main() {
    let mut mr_snuggles: Cat = ...;
    evil_feeder(&mut mr_snuggles);  // Replaces mr_snuggles with a Dog
    mr_snuggles.meow();             // OH NO, MEOWING DOG!
}
</code>```

So why does the immutable version of child work, but not the mutable version? In the immutable version, LogNode contains an immutable reference to a LogNode, so by covariance in both the lifetime and the type parameter, LogNode is covariant in its lifetime parameter. If 'a: 'b, then LogNode<'a> is a subtype of LogNode<'b>.

We have self: &'a LogNode<'n>, which implies 'n: 'a (otherwise this borrow would outlast the data in LogNode<'n>). Thus, since LogNode is covariant, LogNode<'n> is a subtype of LogNode<'a>. Furthermore, covariance in immutable references again allows &'a LogNode<'n> to be a subtype of &'a LogNode<'a>. Thus, self: &'a LogNode<'n> can be coerced to &'a LogNode<'a> as needed for the return type in child.

For the mutable version, LogNode<'n> isn't covariant in 'n. The variance here comes down to the variance of &'n mut LogNode<'n>. But since there's a lifetime in the "T" part of the mutable reference here, the invariance of mutable references (in T) implies that this must also be invariant.

This all combines to show that self: &'a mut LogNode<'n> can't be coerced to &'a mut LogNode<'a>. So the function doesn't compile.

One solution to this is to add the lifetime bound 'a: 'n, though as noted above, we already have 'n: 'a, so this forces the two lifetimes to be equal. That may or may not work with the rest of your code, so take it with a grain of salt.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make a tree with parent pointers in Rust. A method on the node struct is giving me lifetime issues. Here's a minimal example, with lifetimes written explicitly so that I can understand them:

use core::mem::transmute;

pub struct LogNode<'n>(Option<&'n mut LogNode<'n>>);

impl<'n> LogNode<'n> {
    pub fn child<'a>(self: &'a mut LogNode<'n>) -> LogNode<'a> {
        LogNode(Some(self))
    }

    pub fn transmuted_child<'a>(self: &'a mut LogNode<'n>) -> LogNode<'a> {
        unsafe {
            LogNode(Some(
                transmute::<&'a mut LogNode<'n>, &'a mut LogNode<'a>>(self)
            ))
        }
    }
}

(Playground link)

Rust complains about child...

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter 'n due to conflicting requirements

...but it's fine with transmuted_child.

I think I understand why child won't compile: the self parameter's type is &'a mut LogNode<'n> but the child node contains an &'a mut LogNode<'a>, and Rust doesn't want to coerce LogNode<'n> to LogNode<'a>. If I change the mutable references to shared references, it compiles fine, so it sounds like the mutable references are a problem specifically because &mut T is invariant over T (whereas &T is covariant). I guess the mutable reference in LogNode bubbles up to make LogNode itself invariant over its lifetime parameter.

But I don't understand why that's true—intuitively it feels like it's perfectly sound to take LogNode<'n> and shorten its contents' lifetimes by turning it into a LogNode<'a>. Since no lifetime is made longer, no value can be accessed past its lifetime, and I can't think of any other unsound behavior that could happen.

transmuted_child avoids the lifetime issue because it sidesteps the borrow checker, but I don't know if the use of unsafe Rust is sound, and even if it is, I'd prefer to use safe Rust if possible. Can I?

I can think of three possible answers to this question:

child can be implemented entirely in safe Rust, and here's how.

child cannot be implemented entirely in safe Rust, but transmuted_child is sound.

child cannot be implemented entirely in safe Rust, and transmuted_child is unsound.

Edit 1: Fixed a claim that &mut T is invariant over the lifetime of the reference. (Wasn't reading the nomicon right.)

Edit 2: Fixed my first edit summary.

Body:
To understand why the immutable version works and the mutable version is unsound (as written), we have to discuss subtyping and variance.

Rust mostly doesn't have subtyping. Values typically have a unique type. One place where Rust does have subtyping, however, is with lifetimes. If 'a: 'b (read 'a is longer than 'b), then, for example, &'a T is a subtype of &'b T, intuitively because longer lifetimes can be treated as if they were shorter.

Variance is how subtyping propagates. If A is a subtype of B, and we have a generic type Foo<T>, Foo<A> might be a subtype of Foo<B>, vice versa, or neither. In the first case, where the direction of subtyping stays the same, Foo<T> is said to be covariant with respect to T. In the second case, where the direction reverses, it's said to be contravariant, and in the third case, it's said to be invariant.

For this case, the relevant types are &'a T and &'a mut T. Both are covariant in 'a (so references with longer lifetimes can be coerced to references with shorter lifetimes). &'a T is covariant in T, but &'a mut T is invariant in T.

The reason for this is explained in the Nomicon (linked above), so I'll just show you the (somewhat simplified) example given there. Trentcl's code is a working example of what goes wrong if &'a mut T is covariant in T.

fn evil_feeder(pet: &mut Animal) {
    let spike: Dog = ...;

    // `pet` is an Animal, and Dog is a subtype of Animal,
    // so this should be fine, right..?
    *pet = spike;
}

fn main() {
    let mut mr_snuggles: Cat = ...;
    evil_feeder(&mut mr_snuggles);  // Replaces mr_snuggles with a Dog
    mr_snuggles.meow();             // OH NO, MEOWING DOG!
}

So why does the immutable version of child work, but not the mutable version? In the immutable version, LogNode contains an immutable reference to a LogNode, so by covariance in both the lifetime and the type parameter, LogNode is covariant in its lifetime parameter. If 'a: 'b, then LogNode<'a> is a subtype of LogNode<'b>.

We have self: &'a LogNode<'n>, which implies 'n: 'a (otherwise this borrow would outlast the data in LogNode<'n>). Thus, since LogNode is covariant, LogNode<'n> is a subtype of LogNode<'a>. Furthermore, covariance in immutable references again allows &'a LogNode<'n> to be a subtype of &'a LogNode<'a>. Thus, self: &'a LogNode<'n> can be coerced to &'a LogNode<'a> as needed for the return type in child.

For the mutable version, LogNode<'n> isn't covariant in 'n. The variance here comes down to the variance of &'n mut LogNode<'n>. But since there's a lifetime in the "T" part of the mutable reference here, the invariance of mutable references (in T) implies that this must also be invariant.

This all combines to show that self: &'a mut LogNode<'n> can't be coerced to &'a mut LogNode<'a>. So the function doesn't compile.

One solution to this is to add the lifetime bound 'a: 'n, though as noted above, we already have 'n: 'a, so this forces the two lifetimes to be equal. That may or may not work with the rest of your code, so take it with a grain of salt.


问:
How can you set the logger (log category / log name) in Camel's onException clause?
I have the following route:

```<code>            onException(Exception.class)
                .logExhausted(true)
                .logStackTrace(true)
                .logExhaustedMessageHistory(true)
                .process(new MyErrorProcessor());

            from(uri)
            .process(new MyProcessor());
</code>```

When an error occurs the logs are printed in the org.apache.camel.processor.DefaultErrorHandler log category. Is there a way to change this to a custom log category? .errorHandler() allows you to set a log category but .onException() doesn't seem to allow it.

Thanks.

答:
By default, the route ID is used as the logger category. Therefore, set the route ID to class name, and you can then configure logging in the usual way:

```<code>from(uri)
    .id(this.getClass().getName())
    .process(new MyProcessor());
</code>```

(id may have been named routeId in Camel 2; the above works for Camel 3).

ContentLicense: CC BY-SA 3.0

Body:
I have the following route:

            onException(Exception.class)
                .logExhausted(true)
                .logStackTrace(true)
                .logExhaustedMessageHistory(true)
                .process(new MyErrorProcessor());

            from(uri)
            .process(new MyProcessor());

When an error occurs the logs are printed in the org.apache.camel.processor.DefaultErrorHandler log category. Is there a way to change this to a custom log category? .errorHandler() allows you to set a log category but .onException() doesn't seem to allow it.

Thanks.

Body:
By default, the route ID is used as the logger category. Therefore, set the route ID to class name, and you can then configure logging in the usual way:

from(uri)
    .id(this.getClass().getName())
    .process(new MyProcessor());

(id may have been named routeId in Camel 2; the above works for Camel 3).


问:
Azure Active Directory Admin Center Devices Manage button greyed out
In theory, I would like to manage our office devices from within the Azure Active Directory admin center at https://aad.portal.azure.com/#blade/Microsoft_AAD_Devices/DevicesMenuBlade/Devices/menuId/
However, when I select a device from the list the Manager button remains disabled. See screen shot:

I guess I'm missing something obvious but don't know what. Your help is much appreciated.

答:
If you are an Intune administrator, you can manage devices marked as
  Microsoft Intune. If the device is not enrolled with Microsoft Intune the "Manage" option will be greyed out.

Reference:

https://learn.microsoft.com/en-us/azure/active-directory/devices/device-management-azure-portal#manage-an-intune-device


问:
How to label every nth row of a pandas dataframe by an incremental value
I have a simple problem (hopefully!). and i am overly complicating it. Maybe there is a one liner out there; I have a dataframe that contains lets say 10 rows and I want to label rows in such a way it looks like col B. Every 4th row has an different label.

```<code>Row B
1   1
2   1
3   1
4   1
5   2
6   2
7   2
8   2
9   3
10  3
</code>```

I tried iterating by dataframe position and ended up complicating it.

```<code>num =4
id=1
    def label_id(x,num,id):
        if x > num:
          id=id+1
          label=id
          num=num*id
        else:
            label = id
            id=id
        return label
    id=1
    for i in range(len(df)):
        df.iat[i,1] = df.apply(label_id(df.iat[i,0],num,id),axis=1)
</code>```

i get an error TypeError: ("'int' object is not callable", 'occurred at index 0'). I am sure i am overthinking this. Any help?

答:
You can use np.repeat

```<code>import math
import numpy as np
import pandas as pd
df= pd.DataFrame({'Row': range(10)})
df['B'] = np.repeat(range(math.ceil(df.shape[0]/4)),4)[:df.shape[0]] + 1
</code>```

Body:
I have a simple problem (hopefully!). and i am overly complicating it. Maybe there is a one liner out there; I have a dataframe that contains lets say 10 rows and I want to label rows in such a way it looks like col B. Every 4th row has an different label.

Row B
1   1
2   1
3   1
4   1
5   2
6   2
7   2
8   2
9   3
10  3

I tried iterating by dataframe position and ended up complicating it.

num =4
id=1
    def label_id(x,num,id):
        if x > num:
          id=id+1
          label=id
          num=num*id
        else:
            label = id
            id=id
        return label
    id=1
    for i in range(len(df)):
        df.iat[i,1] = df.apply(label_id(df.iat[i,0],num,id),axis=1)

i get an error TypeError: ("'int' object is not callable", 'occurred at index 0'). I am sure i am overthinking this. Any help?

Body:
You can use np.repeat

import math
import numpy as np
import pandas as pd
df= pd.DataFrame({'Row': range(10)})
df['B'] = np.repeat(range(math.ceil(df.shape[0]/4)),4)[:df.shape[0]] + 1


问:
Reset functions after ajax
I have this javascript file: http://pastebin.com/m2keHsTM

A big part of it is a toggle switch that works by sliding your finger or mouse on it. As you see at the end of the document

```<code>var togglebox = "<div class='toggle_box'></div>";
    $('input[type=checkbox]').css('display','none');
    $('fieldset[data-input-type=checkbox]').append(togglebox);
    var mouseDown = false;
    var beginTouchDown = 0;
    create_elements();
    set_listeners();
</code>```

replaces the checkboxes on the page by div's that are "slideable" This works great, only when I load another page trough ajax, other new checkboxes do not get replaced.
Is there a way to reset those functions and make them check again after an ajax call?

Thanks a lot for your help :)

答:
You can:

Call set_listeners also after the load function call: http://api.jquery.com/load

Change set_listeners to bind to events with live instead of bind or mouse... event binders: http://api.jquery.com/live

Title: Reset functions after ajax

Body:
I have this javascript file: http://pastebin.com/m2keHsTM

A big part of it is a toggle switch that works by sliding your finger or mouse on it. As you see at the end of the document

var togglebox = "

";
    $('input[type=checkbox]').css('display','none');
    $('fieldset[data-input-type=checkbox]').append(togglebox);
    var mouseDown = false;
    var beginTouchDown = 0;
    create_elements();
    set_listeners();

replaces the checkboxes on the page by div's that are "slideable" This works great, only when I load another page trough ajax, other new checkboxes do not get replaced.
Is there a way to reset those functions and make them check again after an ajax call?

Thanks a lot for your help :)


问:
Should a separate event be allocated for an asynchronous delegate?
For asynchronous delegates in the code, I do the following everywhere:

```<code>public class SomeCaller
{
    public event Action SomeChanged;
    public event Func<Task> SomeChangedAsync;

    //If in Caller async method
    public async Task SomeMethodAsync()
    {
        SomeChanged?.Invoke();
        if (SomeChangedAsync != null)
            await SomeChangedAsync();
    }

    //if in Caller synchronous method
    public void SomeMethod()
    {
        SomeChanged?.Invoke();
        if (SomeChangedAsync != null)
            Task.Run(async () => await SomeChangedAsync());
    }
}
</code>```

Is there any point in such a solution (to separate the event for async) or is this an example of poor design?
If this is bad, then I would like to understand why and how best to call async delegates?

答:
is this an example of poor design?

This is probably a poor design. The synchronous version raises the delegates on a thread pool thread (instead of whatever thread caused the event), and it raises them as fire-and-forget, which means any exceptions will be silently swallowed and ignored. That's usually bad.

If this is bad, then I would like to understand why and how best to call async delegates?

You need to call asynchronous delegates asynchronously - from an asynchronous method. It's not always possible to safely call an asynchronous method (or delegate) synchronously, though there are some hacks that work in most situations.

Body:
For asynchronous delegates in the code, I do the following everywhere:

public class SomeCaller
{
    public event Action SomeChanged;
    public event Func<Task> SomeChangedAsync;

    //If in Caller async method
    public async Task SomeMethodAsync()
    {
        SomeChanged?.Invoke();
        if (SomeChangedAsync != null)
            await SomeChangedAsync();
    }

    //if in Caller synchronous method
    public void SomeMethod()
    {
        SomeChanged?.Invoke();
        if (SomeChangedAsync != null)
            Task.Run(async () => await SomeChangedAsync());
    }
}

Is there any point in such a solution (to separate the event for async) or is this an example of poor design?
If this is bad, then I would like to understand why and how best to call async delegates?


问:
Issues while validating the two JSON payloads in MUNIT 2.0
I have a service which is returning the below json payload:

```<code>{

  "location-details": {

    "fromPostalCode": "1508XB",

    "fromGeoCoordinates": "116532,496398",

    "toPostalCode": "1511MA",

    "toGeoCoordinates": "120427,493380"

  },

  "commute-distance": "5817.799",

  "commute-time": "370.0152"

}
</code>```

I have created a MUNIT test suite for the same where i am using the assert that utility to assert the payload. Snippet given below:

```<code><munit:validation >
<munit-tools:assert-that doc:name="Assert That Status Code is 200" doc:id="1c2e536b-513e-4b76-958b-2ea864a64805" expression="#[attributes.statusCode]" is="#[MunitTools::equalTo(200)]" message="The HTTP Status code is not correct!" />
<munit-tools:assert-that doc:name="Assert That - Payload is Expected" doc:id="f4b811fa-ff11-4746-93cc-f87576504808" expression="#[payload]" is="#[MunitTools::getResourceAsString('SuccessResponse.json')]" message="The response payload is not correct!"/>
</munit:validation>
</code>```

But this is throwing an below error and its not working:

```<code>...38 more

Caused by: org.mule.runtime.api.el.ExpressionExecutionException: Unable to convert '{
  "location-details": {
    "fromPostalCode": "1508XB",
    "fromGeoCoordinates": "116532,496398",
    "toPostalCode": "1511MA",
    "toGeoCoordinates": "120427,493380"
  },
  "commute-distance": "5817.799",
  "commute-time": "370.0152"

}' with class 'java.lang.String' to class 'Matcher', while writing Java at org.mule.munit.tools.util.GetResourceFunctions.getResourceAsString.

               at org.mule.weave.v2.el.WeaveExpressionLanguage.doEvaluate(WeaveExpressionLanguage.scala:139)
               at org.mule.weave.v2.el.WeaveExpressionLanguage.evaluate(WeaveExpressionLanguage.scala:236)
</code>```

答:
I had to use readUrl instead of MunitTools::getResourceAsString to compare two JSON objects in MUNIT 2.1

```<code><munit-tools:assert-that doc:name="Assert That - JSON compare" doc:id="2fab5bf0-a710-4619-a7a9-262a867e0ad9" expression="#[payload]" is="#[MunitTools::equalTo(readUrl('classpath://sample_data/test_payload.json', 'application/json'))]" message="payload is not correct" />
</code>```

Body:
I have a service which is returning the below json payload:

{

  "location-details": {

    "fromPostalCode": "1508XB",

    "fromGeoCoordinates": "116532,496398",

    "toPostalCode": "1511MA",

    "toGeoCoordinates": "120427,493380"

  },

  "commute-distance": "5817.799",

  "commute-time": "370.0152"

}

I have created a MUNIT test suite for the same where i am using the assert that utility to assert the payload. Snippet given below:

<munit:validation >
<munit-tools:assert-that doc:name="Assert That Status Code is 200" doc:id="1c2e536b-513e-4b76-958b-2ea864a64805" expression="#[attributes.statusCode]" is="#[MunitTools::equalTo(200)]" message="The HTTP Status code is not correct!" />
<munit-tools:assert-that doc:name="Assert That - Payload is Expected" doc:id="f4b811fa-ff11-4746-93cc-f87576504808" expression="#[payload]" is="#[MunitTools::getResourceAsString('SuccessResponse.json')]" message="The response payload is not correct!"/>
</munit:validation>

But this is throwing an below error and its not working:

...38 more

Caused by: org.mule.runtime.api.el.ExpressionExecutionException: Unable to convert '{
  "location-details": {
    "fromPostalCode": "1508XB",
    "fromGeoCoordinates": "116532,496398",
    "toPostalCode": "1511MA",
    "toGeoCoordinates": "120427,493380"
  },
  "commute-distance": "5817.799",
  "commute-time": "370.0152"

}' with class 'java.lang.String' to class 'Matcher', while writing Java at org.mule.munit.tools.util.GetResourceFunctions.getResourceAsString.

               at org.mule.weave.v2.el.WeaveExpressionLanguage.doEvaluate(WeaveExpressionLanguage.scala:139)
               at org.mule.weave.v2.el.WeaveExpressionLanguage.evaluate(WeaveExpressionLanguage.scala:236)

Body:
I had to use readUrl instead of MunitTools::getResourceAsString to compare two JSON objects in MUNIT 2.1

<munit-tools:assert-that doc:name="Assert That - JSON compare" doc:id="2fab5bf0-a710-4619-a7a9-262a867e0ad9" expression="#[payload]" is="#[MunitTools::equalTo(readUrl('classpath://sample_data/test_payload.json', 'application/json'))]" message="payload is not correct" />


问:
Permission denied to write a table with dbWriteTable in RPostgreSQL
I've been trying to solve a problem with the RPostgreSQL package for quite some time. My code:

```<code>path_ene <- "C:/Users/omen03/ENE"

nene <- "ene_2010_02_efm.csv"

drv <- dbDriver("PostgreSQL")

con = dbConnect(drv, user="postgres", password="mypassword",
            host="localhost", port=5432, dbname="ENE")

tn = "ene_2010_02_efm";

dbRemoveTable(con,tn);
dbWriteTable(conn = con, name = tn, value = paste0(path_ene,"/",nene),
                                    sep = ",", overwrite = FALSE))
</code>```

When executing the code described above, I throw the following error:

Error in postgresqlExecStatement (conn, statement, ...):
  RS-DBI driver: (could not Retrieve the result: ERROR:
  Could not open file Â«C: /Users/omen03/ENE/ene_2010_02_efm.csvÂ» for reading: Permission denied

HINT: COPY FROM tells the PostgreSQL server process to read a
  file. You may want to use a client-side facility such as psql \ copy.
  ) In addition: Warning message: In postgresqlImportFile (conn, name,
  value, ...):    could not load data into table

when I try without specifying the file path, it throws me another error

```<code>dbRemoveTable(con,tn);
dbWriteTable(conn = con, name = tn, value = nene),
                                    sep = ",", overwrite = FALSE))
</code>```

Error in postgresqlExecStatement (conn, statement, ...):    RS-DBI
  driver: (could not Retrieve the result: ERROR: could not open file Â
  «./ ene_2010_02_efmÂ» for reading: No such file or directory

HINT:
  COPY FROM tells the PostgreSQL server process to read a file. You may
  want to use a client-side facility such as psql \ copy. ) In addition:
  Warning message: In postgresqlImportFile (conn, name, value, ...):
  could not load data into table

Update:

Taking into account the error message, I decided to use sql directly to insert the csv values in each of the tables in the database. For that I used a couple of functions

```<code>createEmptyTable <- function(con,tn,df) {
  sql <- paste0("create table \"",tn,"\" (",paste0(collapse=',','"',names(df),'" ',sapply(df[0,],postgresqlDataType)),");");
  dbSendQuery(con,sql);
  invisible();
};
</code>```

Taken from: How to write a table in PostgreSQL from R?

and

```<code>#tn: Table name
#c_names: column names of each table (a list)
#source: The path to each csv files

insert_data = function(tn, source){
  sql = paste0('COPY ',tn,' FROM \'',paste0(path_ene,'\\',source),'\' DELIMITER \',\' CSV HEADER')
  dbSendQuery(con, sql);
}

insert_data(tn[1], paste0(path_ene, "/",nene[1]))
</code>```

Anyway, I still get a very similar error.

Error in postgresqlExecStatement (conn, statement, ...):    RS-DBI
  driver: (could not Retrieve the result: ERROR: Could not open file Â
  «C: /Users/omen03/ENE/ene_2010_02_efm.csvÂ» for reading: Permission
  denied HINT: COPY FROM tells the PostgreSQL server process to read a
  file. You may want to use a client-side facility such as psql \ copy.
  )

My session info:

R version 3.6.1 (2019-07-05) Platform: x86_64-w64-mingw32/x64 (64-bit)
  Running under: Windows 10 x64 (build 18362)

Matrix products: default

locale: [1] LC_COLLATE=Spanish_Chile.1252  LC_CTYPE=Spanish_Chile.1252
  LC_MONETARY=Spanish_Chile.1252 LC_NUMERIC=C                   [5]
  LC_TIME=Spanish_Chile.1252

attached base packages: [1] stats     graphics  grDevices utils

  datasets  methods   base

other attached packages:  [1] RPostgreSQL_0.6-2  DBI_1.0.0

  foreign_0.8-71     captioner_2.2.3    kableExtra_1.1.0   wordcloud_2.6
  tidytext_0.2.2     gridExtra_2.3       [9] gtable_0.3.0

  readstata13_0.9.2  RColorBrewer_1.1-2 ggrepel_0.8.1      pbapply_1.4-2
  srvyr_0.3.6        data.table_1.12.6  lubridate_1.7.4    [17]
  stringi_1.4.3      forcats_0.4.0      stringr_1.4.0      dplyr_0.8.3

  purrr_0.3.3        readr_1.3.1        tidyr_1.0.0        tibble_2.1.3
  [25] ggplot2_3.2.1      tidyverse_1.3.0

loaded via a namespace (and not attached):  [1] httr_1.4.1

  jsonlite_1.6      viridisLite_0.3.0 splines_3.6.1     modelr_0.1.5

  assertthat_0.2.1  cellranger_1.1.0  sessioninfo_1.1.1  [9]
  pillar_1.4.3      backports_1.1.5   lattice_0.20-38   glue_1.3.1

  digest_0.6.23     rvest_0.3.5       colorspace_1.4-1  htmltools_0.4.0
  [17] Matrix_1.2-17     survey_3.36       pkgconfig_2.0.3   broom_0.5.2
  haven_2.2.0       scales_1.1.0      webshot_0.5.2     generics_0.0.2

  [25] withr_2.1.2       lazyeval_0.2.2    cli_2.0.0

  survival_2.44-1.1 magrittr_1.5      crayon_1.3.4      readxl_1.3.1

  evaluate_0.14     [33] tokenizers_0.2.1  janeaustenr_0.1.5 fs_1.3.1

  fansi_0.4.0       nlme_3.1-140      SnowballC_0.6.0   xml2_1.2.2

  tools_3.6.1       [41] hms_0.5.2         mitools_2.4

  lifecycle_0.1.0   munsell_0.5.0     reprex_0.3.0      compiler_3.6.1

  rlang_0.4.2       grid_3.6.1        [49] rstudioapi_0.10

  rmarkdown_1.18    R6_2.4.1          knitr_1.26        zeallot_0.1.0

  parallel_3.6.1    Rcpp_1.0.3        vctrs_0.2.1       [57]
  dbplyr_1.4.2      tidyselect_0.2.5  xfun_0.11

答:
Finally, I found the answer by looking for the problem of directly importing data into postgresql. It was enough to change the configuration of the folder containing the .csv files.

I reproduce this answer that was the one I finally used.

Right click the folder containing the data file(s) that permission    was denied to and then click Properties.

In the Folder's Properties    window, select the Security tab.

Click the Edit button. In the    "Permissions for the folder" window that opened, click the Add...    button.

Type Everyone into the "Enter the object names to select"    text area box.

Click OK and the window will close.

Body:
I've been trying to solve a problem with the RPostgreSQL package for quite some time. My code:

path_ene <- "C:/Users/omen03/ENE"

nene <- "ene_2010_02_efm.csv"

drv <- dbDriver("PostgreSQL")

con = dbConnect(drv, user="postgres", password="mypassword",
            host="localhost", port=5432, dbname="ENE")

tn = "ene_2010_02_efm";

dbRemoveTable(con,tn);
dbWriteTable(conn = con, name = tn, value = paste0(path_ene,"/",nene),
                                    sep = ",", overwrite = FALSE))

When executing the code described above, I throw the following error:

Error in postgresqlExecStatement (conn, statement, ...):
  RS-DBI driver: (could not Retrieve the result: ERROR:
  Could not open file Â«C: /Users/omen03/ENE/ene_2010_02_efm.csvÂ» for reading: Permission denied

HINT: COPY FROM tells the PostgreSQL server process to read a
  file. You may want to use a client-side facility such as psql \ copy.
  ) In addition: Warning message: In postgresqlImportFile (conn, name,
  value, ...):    could not load data into table

when I try without specifying the file path, it throws me another error

dbRemoveTable(con,tn);
dbWriteTable(conn = con, name = tn, value = nene),
                                    sep = ",", overwrite = FALSE))

Error in postgresqlExecStatement (conn, statement, ...):    RS-DBI
  driver: (could not Retrieve the result: ERROR: could not open file Â
  «./ ene_2010_02_efmÂ» for reading: No such file or directory

HINT:
  COPY FROM tells the PostgreSQL server process to read a file. You may
  want to use a client-side facility such as psql \ copy. ) In addition:
  Warning message: In postgresqlImportFile (conn, name, value, ...):
  could not load data into table

Update:

Taking into account the error message, I decided to use sql directly to insert the csv values in each of the tables in the database. For that I used a couple of functions

createEmptyTable <- function(con,tn,df) {
  sql <- paste0("create table \"",tn,"\" (",paste0(collapse=',','"',names(df),'" ',sapply(df[0,],postgresqlDataType)),");");
  dbSendQuery(con,sql);
  invisible();
};

Taken from: How to write a table in PostgreSQL from R?

and

#tn: Table name
#c_names: column names of each table (a list)
#source: The path to each csv files

insert_data = function(tn, source){
  sql = paste0('COPY ',tn,' FROM \'',paste0(path_ene,'\\',source),'\' DELIMITER \',\' CSV HEADER')
  dbSendQuery(con, sql);
}

insert_data(tn[1], paste0(path_ene, "/",nene[1]))

Anyway, I still get a very similar error.

Error in postgresqlExecStatement (conn, statement, ...):    RS-DBI
  driver: (could not Retrieve the result: ERROR: Could not open file Â
  «C: /Users/omen03/ENE/ene_2010_02_efm.csvÂ» for reading: Permission
  denied HINT: COPY FROM tells the PostgreSQL server process to read a
  file. You may want to use a client-side facility such as psql \ copy.
  )

My session info:

R version 3.6.1 (2019-07-05) Platform: x86_64-w64-mingw32/x64 (64-bit)
  Running under: Windows 10 x64 (build 18362)

Matrix products: default

locale: [1] LC_COLLATE=Spanish_Chile.1252  LC_CTYPE=Spanish_Chile.1252
  LC_MONETARY=Spanish_Chile.1252 LC_NUMERIC=C                   [5]
  LC_TIME=Spanish_Chile.1252

attached base packages: [1] stats     graphics  grDevices utils

  datasets  methods   base

other attached packages:  [1] RPostgreSQL_0.6-2  DBI_1.0.0

  foreign_0.8-71     captioner_2.2.3    kableExtra_1.1.0   wordcloud_2.6
  tidytext_0.2.2     gridExtra_2.3       [9] gtable_0.3.0

  readstata13_0.9.2  RColorBrewer_1.1-2 ggrepel_0.8.1      pbapply_1.4-2
  srvyr_0.3.6        data.table_1.12.6  lubridate_1.7.4    [17]
  stringi_1.4.3      forcats_0.4.0      stringr_1.4.0      dplyr_0.8.3

  purrr_0.3.3        readr_1.3.1        tidyr_1.0.0        tibble_2.1.3
  [25] ggplot2_3.2.1      tidyverse_1.3.0

loaded via a namespace (and not attached):  [1] httr_1.4.1

  jsonlite_1.6      viridisLite_0.3.0 splines_3.6.1     modelr_0.1.5

  assertthat_0.2.1  cellranger_1.1.0  sessioninfo_1.1.1  [9]
  pillar_1.4.3      backports_1.1.5   lattice_0.20-38   glue_1.3.1

  digest_0.6.23     rvest_0.3.5       colorspace_1.4-1  htmltools_0.4.0
  [17] Matrix_1.2-17     survey_3.36       pkgconfig_2.0.3   broom_0.5.2
  haven_2.2.0       scales_1.1.0      webshot_0.5.2     generics_0.0.2

  [25] withr_2.1.2       lazyeval_0.2.2    cli_2.0.0

  survival_2.44-1.1 magrittr_1.5      crayon_1.3.4      readxl_1.3.1

  evaluate_0.14     [33] tokenizers_0.2.1  janeaustenr_0.1.5 fs_1.3.1

  fansi_0.4.0       nlme_3.1-140      SnowballC_0.6.0   xml2_1.2.2

  tools_3.6.1       [41] hms_0.5.2         mitools_2.4

  lifecycle_0.1.0   munsell_0.5.0     reprex_0.3.0      compiler_3.6.1

  rlang_0.4.2       grid_3.6.1        [49] rstudioapi_0.10

  rmarkdown_1.18    R6_2.4.1          knitr_1.26        zeallot_0.1.0

  parallel_3.6.1    Rcpp_1.0.3        vctrs_0.2.1       [57]
  dbplyr_1.4.2      tidyselect_0.2.5  xfun_0.11


问:
Is there a way to create a module that can read the directory that it is used in? (TypeScript/JavaScript)
What I'm trying do is make a handler that will read a folder that it is in. However, this handler is a module that will be imported into multiple folders.

For example, if given the current directory:

```<code>->Main
   ->folder a
      ->languages
   a.js
   ->folder b
      ->languages
   b.js
   ->folder c
      ->languages
   c.js
d.js
</code>```

d.js - handler used in a.js, b.js and c.js

```<code>var Translate = ((lang) => {
  // this line below is what I want to know how to do.
  import { lang } from "./languages/"+lang;

  // do stuff with lang
}

export { Translate }
</code>```

With the d.js handler, it should be able to be used in a.js/b.js/c.js. However I want to know how to read the directory (in this case the language folder) it is being imported in rather than from the handler.  I'm doing this to handle multiple languages for an app, and I figure this way its a lot easier to manage.

答:
If you are executing the code in NodeJS environment, you can use this to get the current directory name:

```<code>import path from "path";
const dirName = path.basename(path.dirname(filename));
</code>```

The dirName variable will contain the folder name as a string.
Then you can dynamically import using ES6 template literal.

```<code>import { lang } from `./languages/${dirname}`
</code>```

Body:
What I'm trying do is make a handler that will read a folder that it is in. However, this handler is a module that will be imported into multiple folders.

For example, if given the current directory:

->Main
   ->folder a
      ->languages
   a.js
   ->folder b
      ->languages
   b.js
   ->folder c
      ->languages
   c.js
d.js

d.js - handler used in a.js, b.js and c.js

var Translate = ((lang) => {
  // this line below is what I want to know how to do.
  import { lang } from "./languages/"+lang;

  // do stuff with lang
}

export { Translate }

With the d.js handler, it should be able to be used in a.js/b.js/c.js. However I want to know how to read the directory (in this case the language folder) it is being imported in rather than from the handler.  I'm doing this to handle multiple languages for an app, and I figure this way its a lot easier to manage.

Body:
If you are executing the code in NodeJS environment, you can use this to get the current directory name:

import path from "path";
const dirName = path.basename(path.dirname(filename));

The dirName variable will contain the folder name as a string.
Then you can dynamically import using ES6 template literal.

import { lang } from `./languages/${dirname}`


答:
you have to use repeat function

```<code>import math
df['B'] = (np.repeat(range(math.ceil(df.shape[0]/4)),4))[:df.shape[0]] + 1
</code>```

Title: How to label every nth row of a pandas dataframe by an incremental value

Body:
you have to use repeat function

import math
df['B'] = (np.repeat(range(math.ceil(df.shape[0]/4)),4))[:df.shape[0]] + 1


问:
Trigger Update after Insert with If Condition
```<code>DELIMITER $$
CREATE TRIGGER cobaEditPegawai1 AFTER INSERT ON detail_pemangku_jabatan
FOR EACH ROW
IF detail_pemangku_jabatan.nip_pemangku = "0" THEN
BEGIN
    UPDATE ekinerja_tempsimpeg.lap_bagan SET  ID_Peg = "" WHERE KUnKer = NEW.kode_jabatan;
ELSE
    UPDATE ekinerja_tempsimpeg.lap_bagan SET  ID_Peg = NEW.id_pegawai WHERE KUnKer = NEW.kode_jabatan;
END IF ;
END$$
DELIMITER ;
</code>```

on my app, its not work.

message : "SQLSTATE[42S02]: Base table or view not found: 1109 Unknown table 'detail_pemangku_jabatan' in field list

答:
I think you intend:</p>

```<code>IF new.nip_pemangku = 0 THEN
</code>```

Body:
DELIMITER $$
CREATE TRIGGER cobaEditPegawai1 AFTER INSERT ON detail_pemangku_jabatan
FOR EACH ROW
IF detail_pemangku_jabatan.nip_pemangku = "0" THEN
BEGIN
    UPDATE ekinerja_tempsimpeg.lap_bagan SET  ID_Peg = "" WHERE KUnKer = NEW.kode_jabatan;
ELSE
    UPDATE ekinerja_tempsimpeg.lap_bagan SET  ID_Peg = NEW.id_pegawai WHERE KUnKer = NEW.kode_jabatan;
END IF ;
END$$
DELIMITER ;

on my app, its not work.

message : "SQLSTATE[42S02]: Base table or view not found: 1109 Unknown table 'detail_pemangku_jabatan' in field list

Body:
I think you intend:

IF new.nip_pemangku = 0 THEN


问:
How to create a simple html live reload with gulp and browser-sync
I'm new to using Gulp (especially Gulp 4) and to start of I just want to have a very basic live reload on any changes in my index.html file (in the root folder). So far I have this:

```<code>var gulp = require("gulp"),
browserSync = require("browser-sync").create();

// Static server
gulp.task('browser-sync', function() {
    browserSync.init({
        server: {
            baseDir: "./"
        }
    });
});

gulp.task('default', ['html'], function() {
    // watch for HTML changes
    gulp.watch('*.html', function() {
       // run styles upon changes
       gulp.run('html');
    });
 });
</code>```

How do I connect the browser-sync task with the gulp watch? I have tried using the official documentation but the examples there seem to be more complex than what I am trying to achieve.

答:
Change to:

```<code>gulp.task('default', gulp.series('html', function() {
  // watch for HTML changes
  gulp.watch('*.html', gulp.series('html'))
}));
</code>```

and see a how to migrate from gulp v3 to v4 guide since most of the code you are going to find is v3.

Body:
I'm new to using Gulp (especially Gulp 4) and to start of I just want to have a very basic live reload on any changes in my index.html file (in the root folder). So far I have this:

var gulp = require("gulp"),
browserSync = require("browser-sync").create();

// Static server
gulp.task('browser-sync', function() {
    browserSync.init({
        server: {
            baseDir: "./"
        }
    });
});

gulp.task('default', ['html'], function() {
    // watch for HTML changes
    gulp.watch('*.html', function() {
       // run styles upon changes
       gulp.run('html');
    });
 });

How do I connect the browser-sync task with the gulp watch? I have tried using the official documentation but the examples there seem to be more complex than what I am trying to achieve.

Body:
Change to:

gulp.task('default', gulp.series('html', function() {
  // watch for HTML changes
  gulp.watch('*.html', gulp.series('html'))
}));

and see a how to migrate from gulp v3 to v4 guide since most of the code you are going to find is v3.


问:
Filter object properties by key in ES6
Let's say I have an object:

```<code>{
  item1: { key: 'sdfd', value:'sdfd' },
  item2: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
}
</code>```

I want to create another object by filtering the object above so I have something like.

```<code> {
    item1: { key: 'sdfd', value:'sdfd' },
    item3: { key: 'sdfd', value:'sdfd' }
 }
</code>```

I am looking for a clean way to accomplish this using Es6, so spread operators are available to me.

答:
I'm surprised how nobody has suggested this yet. It's super clean and very explicit about which keys you want to keep.

```<code>const unfilteredObj = {a: ..., b:..., c:..., x:..., y:...}

const filterObject = ({a,b,c}) => ({a,b,c})
const filteredObject = filterObject(unfilteredObject)
</code>```

Or if you want a dirty one liner:

```<code>const unfilteredObj = {a: ..., b:..., c:..., x:..., y:...}

const filteredObject = (({a,b,c})=>({a,b,c}))(unfilteredObject);
</code>```

Title: Filter object properties by key in ES6

Body:
Let's say I have an object:

{
  item1: { key: 'sdfd', value:'sdfd' },
  item2: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
}

I want to create another object by filtering the object above so I have something like.

 {
    item1: { key: 'sdfd', value:'sdfd' },
    item3: { key: 'sdfd', value:'sdfd' }
 }

I am looking for a clean way to accomplish this using Es6, so spread operators are available to me.

Body:
I'm surprised how nobody has suggested this yet. It's super clean and very explicit about which keys you want to keep.

const unfilteredObj = {a: ..., b:..., c:..., x:..., y:...}

const filterObject = ({a,b,c}) => ({a,b,c})
const filteredObject = filterObject(unfilteredObject)

Or if you want a dirty one liner:

const unfilteredObj = {a: ..., b:..., c:..., x:..., y:...}

const filteredObject = (({a,b,c})=>({a,b,c}))(unfilteredObject);


问:
Logic Apps liquid template ask
I am a complete newcomer to Liquid, started playing with it a few hours ago.

i am trying to parse a JSON and extract certain key value pairs out of it, yet i am not successful at all. the JSON is outputed from Azure Form Recognizer, and i am trying to do a Liquid json 2 json in Logic Apps.

the JSON looks like this

```<code>{
  "status": "success",
  "pages": [
    {
      "number": 1,
      "keyValuePairs": [
        {
          "key": [
            {
              "text": "Page No:",
              "boundingBox": [
                507.4
               ]
            }
          ],
          "value": [
            {
              "text": "1",
              "boundingBox": [
                586.8
              ],
              "confidence": 1.0
            }
          ]
        },
....
...
</code>```

what i am looking for is to loop through the keyValuePairs array, and then pull the "text" element from the "key" array, and the "text"+"confidence" element from the "value"array.

Could you please help me in understanding the approach here? I tried something like this, but the array comes back empty

```<code>{
"results":[
{% for kvp in content.keyValuePairs  %}

{% for mykey in kvp.key  %}

"thiskey":"{{mykey.text}}
{%- endfor -%}
{% for myval in kvp.value  %}

"thisvalue":{{myval.text}}
"thisconfidence":{{myval.confidence}}
{%- endfor -%}
{%- endfor -%}
]
}
</code>```

And second question: what's the best approach for debugging Liquid, so i can see where i am getting it wrong and adjust?

Thank you!

答:
According to the sample of json data and the liquid template you provided, I know there are more than one object under the property keyValuePairs in your json data. So I think using "Parse JSON" action is not a good solution for it, we'd better use liquid template as you mentioned in your question. But I'm confused about that if there are more than one object under the property pages in your json data ?

Now I assume the json data just has one object under the property pages and provide the solution of liquid template for your reference (If the json data has more than one object under the property pages, please provide some more details of your requirements and I will modify my solution).

I assume your json data like below:

```<code>{
    "status": "success",
    "pages": [
        {
            "number": 1,
            "keyValuePairs": [
                {
                    "key": [
                        {
                            "text": "Page No:",
                            "boundingBox": [
                                507.4
                            ]
                        }
                    ],
                    "value": [
                        {
                            "text": "1",
                            "boundingBox": [
                                586.8
                            ],
                            "confidence": 1.0
                        }
                    ]
                },
                {
                    "key": [
                        {
                            "text": "Page No:",
                            "boundingBox": [
                                507.4
                            ]
                        }
                    ],
                    "value": [
                        {
                            "text": "2",
                            "boundingBox": [
                                586.8
                            ],
                            "confidence": 2.0
                        }
                    ]
                }
            ]
        }
    ]
}
</code>```

1. We need to get the object under the property pages and put it in the "content" of "Transform JSON to JSON" action. We can parse the whole json data(with "Parse JSON" action) first and do something like below:

2. Upload the liquid template to integration account, please refer to my liquid template:

```<code>{
    "results":[
        {% for kvp in content.keyValuePairs  %}
            {%- if forloop.Last == true -%}
                {
                    {% for mykey in kvp.key  %}
                        "thiskey": "{{mykey.text}}",
                    {%- endfor -%}
                    {% for myval in kvp.value  %}
                        "thisvalue": "{{myval.text}}",
                        "thisconfidence": "{{myval.confidence}}"
                    {%- endfor -%}
                }
            {%- else -%}
                {
                    {% for mykey in kvp.key  %}
                        "thiskey": "{{mykey.text}}",
                    {%- endfor -%}
                    {% for myval in kvp.value  %}
                        "thisvalue": "{{myval.text}}",
                        "thisconfidence": "{{myval.confidence}}"
                    {%- endfor -%}
                },
            {%- endif -%}
        {%- endfor -%}
    ]
}
</code>```

3. After running this logic, we can get the result as:

```<code>{
  "results": [
    {
      "thiskey": "Page No:",
      "thisvalue": "1",
      "thisconfidence": "1"
    },
    {
      "thiskey": "Page No:",
      "thisvalue": "2",
      "thisconfidence": "2"
    }
  ]
}
</code>```

Something you need to be aware of:

Since we put the object under the property pages to the content of "Transform JSON to JSON" action, so the content in the liquid template represents it.

In liquid template, we need to be careful about the comma character, so I use {%- if forloop.Last == true -%} to judge if it is the last object in the loop, and then judge if we need to add the comma character.

For your second question about what's the best approach for debugging Liquid ?, unfortunately I think we can just complete the liquid template and upload to the integration account, then we can see the result. I don't know if there is a way for us to debug it easily.

Hope it helps~

Title: Logic Apps liquid template ask

Body:
I am a complete newcomer to Liquid, started playing with it a few hours ago.

i am trying to parse a JSON and extract certain key value pairs out of it, yet i am not successful at all. the JSON is outputed from Azure Form Recognizer, and i am trying to do a Liquid json 2 json in Logic Apps.

the JSON looks like this

{
  "status": "success",
  "pages": [
    {
      "number": 1,
      "keyValuePairs": [
        {
          "key": [
            {
              "text": "Page No:",
              "boundingBox": [
                507.4
               ]
            }
          ],
          "value": [
            {
              "text": "1",
              "boundingBox": [
                586.8
              ],
              "confidence": 1.0
            }
          ]
        },
....
...

what i am looking for is to loop through the keyValuePairs array, and then pull the "text" element from the "key" array, and the "text"+"confidence" element from the "value"array.

Could you please help me in understanding the approach here? I tried something like this, but the array comes back empty

{
"results":[
{% for kvp in content.keyValuePairs  %}

{% for mykey in kvp.key  %}

"thiskey":"{{mykey.text}}
{%- endfor -%}
{% for myval in kvp.value  %}

"thisvalue":{{myval.text}}
"thisconfidence":{{myval.confidence}}
{%- endfor -%}
{%- endfor -%}
]
}

And second question: what's the best approach for debugging Liquid, so i can see where i am getting it wrong and adjust?

Thank you!

Body:
According to the sample of json data and the liquid template you provided, I know there are more than one object under the property keyValuePairs in your json data. So I think using "Parse JSON" action is not a good solution for it, we'd better use liquid template as you mentioned in your question. But I'm confused about that if there are more than one object under the property pages in your json data ?

Now I assume the json data just has one object under the property pages and provide the solution of liquid template for your reference (If the json data has more than one object under the property pages, please provide some more details of your requirements and I will modify my solution).

I assume your json data like below:

{
    "status": "success",
    "pages": [
        {
            "number": 1,
            "keyValuePairs": [
                {
                    "key": [
                        {
                            "text": "Page No:",
                            "boundingBox": [
                                507.4
                            ]
                        }
                    ],
                    "value": [
                        {
                            "text": "1",
                            "boundingBox": [
                                586.8
                            ],
                            "confidence": 1.0
                        }
                    ]
                },
                {
                    "key": [
                        {
                            "text": "Page No:",
                            "boundingBox": [
                                507.4
                            ]
                        }
                    ],
                    "value": [
                        {
                            "text": "2",
                            "boundingBox": [
                                586.8
                            ],
                            "confidence": 2.0
                        }
                    ]
                }
            ]
        }
    ]
}

1. We need to get the object under the property pages and put it in the "content" of "Transform JSON to JSON" action. We can parse the whole json data(with "Parse JSON" action) first and do something like below:

2. Upload the liquid template to integration account, please refer to my liquid template:

{
    "results":[
        {% for kvp in content.keyValuePairs  %}
            {%- if forloop.Last == true -%}
                {
                    {% for mykey in kvp.key  %}
                        "thiskey": "{{mykey.text}}",
                    {%- endfor -%}
                    {% for myval in kvp.value  %}
                        "thisvalue": "{{myval.text}}",
                        "thisconfidence": "{{myval.confidence}}"
                    {%- endfor -%}
                }
            {%- else -%}
                {
                    {% for mykey in kvp.key  %}
                        "thiskey": "{{mykey.text}}",
                    {%- endfor -%}
                    {% for myval in kvp.value  %}
                        "thisvalue": "{{myval.text}}",
                        "thisconfidence": "{{myval.confidence}}"
                    {%- endfor -%}
                },
            {%- endif -%}
        {%- endfor -%}
    ]
}

3. After running this logic, we can get the result as:

{
  "results": [
    {
      "thiskey": "Page No:",
      "thisvalue": "1",
      "thisconfidence": "1"
    },
    {
      "thiskey": "Page No:",
      "thisvalue": "2",
      "thisconfidence": "2"
    }
  ]
}

Something you need to be aware of:

Since we put the object under the property pages to the content of "Transform JSON to JSON" action, so the content in the liquid template represents it.

In liquid template, we need to be careful about the comma character, so I use {%- if forloop.Last == true -%} to judge if it is the last object in the loop, and then judge if we need to add the comma character.

For your second question about what's the best approach for debugging Liquid ?, unfortunately I think we can just complete the liquid template and upload to the integration account, then we can see the result. I don't know if there is a way for us to debug it easily.

Hope it helps~


问:
How do you render tooltip on disabled HTML Button
I have a HTML button. I have tried to render a tooltip on it based on the "title" attribute of the button and it doesn't render. Mainly because it's disabled.

I then tried wrapping the button in a span and setting the "title" attribute of the span.

Hovering over the button that is wrapped in the span still has no effect. The tooltip will render on any other part of the span that is not part of the button tag. Like if I put some text in the span as well as the button, hovering over the text produces the tooltip, but if you hover over the button it will not render.

So: how can I display a tooltip for a disabled button?

答: This is a bug in firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=274626</p>


问:
On page navigation with anchor tag on dropdown menu
I'm currently building a top navigation bar that shows dropdown on hover on some of the nav-items.
It currently looks like this

$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
  });

    const $dropdown = $(".dropdown");
    const $dropdownToggle = $(".dropdown-toggle");
    const $dropdownMenu = $(".dropdown-menu");
    const showClass = "show";

    $(window).on("load resize", function() {
      if (this.matchMedia("(min-width: 768px)").matches) {
        $dropdown.hover(
          function() {
            const $this = $(this);
            $this.addClass(showClass);
            $this.find($dropdownToggle).attr("aria-expanded", "true");
            $this.find($dropdownMenu).addClass(showClass);
          },
          function() {
            const $this = $(this);
            $this.removeClass(showClass);
            $this.find($dropdownToggle).attr("aria-expanded", "false");
            $this.find($dropdownMenu).removeClass(showClass);
          }
        );
      } else {
        $dropdown.off("mouseenter mouseleave");
      }
    });

  ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.navbar{
  background-color: black;
  padding-left: 5vw;
  padding-right: 4vw;
}

.navbar .nav-item{
  text-align: center;
  padding-top: 40px;
  padding-bottom: 40px;
}

.navbar .nav-item .nav-link{
  color: white;
  font-size: 18px;
  font-family: 'Roboto';
  font-weight: bold;
}

.navbar .nav-item .nav-link:hover{
  color: red;
  text-decoration: none;
}

.navbar .nav-item a:hover{
  color: #4c4c4c;
}

.navbar .nav-item:not(:last-child) {
  margin-right: 5px;
}

.dropdown-toggle::after {
   transition: transform 0.15s linear;
   content: none;
}

.show.dropdown .dropdown-toggle::after {
  transform: translateY(3px);
}

.dropdown-menu {
  margin-top: 5px;
  border-top: 5px solid red;
  border-radius: 0;
  padding: 0;
}

.navbar .nav-item a{
  font-size: 18px;
  color: #080808;
  padding-top: 12px;
  padding-bottom: 12px;
  padding-right: 40px;
  font-weight: 400;
  font-family: 'Roboto';
  background-color: none;
  border-bottom: 1px solid rgba(193,193,193,0.59);
}

.navbar .nav-item .nav-link{
  border-bottom: none;
}</code>```

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

      </button>

                        About Us

                        Who we are
                        What we do

                    Events

                    Contact Us

```

So what I want to do is having both dropdown on hover working as well as using the dropdown same button(nav-item) to work as a button that navigates the user to specified section.

In the above code, it would be "About Us" that will show its following dropdown on hover. And when "About Us" is clicked, it would navigate the user to specified section ("#information").

I can only get one or the other working. If i get dropdown on hover, navigation doesn't work, if i get navigation work, then dropdown doesn't appear on hover.

Any help would be much appreciated

Thank you.

答:
You have no hover on mobile devices, so the click cannot open the submenu and navigate to the desired section. It wouldn't be ideal, so Bootstrap works like this.

One solution would be to remove data-toggle="dropdown" from the  tag, however the dropdown would not work in mobile devices, since it needs click event.

If you want to maintain the submenu for mobile working, it's better to not have anchor navigation on mobile. So, keep the data-toggle="dropdown" and add this code:

```<code>$("#navbarDropdown1").click(function() {
  if ($(window).width() > 991) {
    var href = $(this).attr('href');
    $('body, html').animate({ // an animation if you prefer, slim jQuery doesn't include animate
      scrollTop: $(href).offset().top
    }, 600);
  }
});
</code>```

Now when clicking on "About Us", it will navigate to the section, but not if the screen width is less than the Bootstrap breakpoint reserved for mobile devices (991px).

Body:
I'm currently building a top navigation bar that shows dropdown on hover on some of the nav-items.
It currently looks like this

$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
  });

    const $dropdown = $(".dropdown");
    const $dropdownToggle = $(".dropdown-toggle");
    const $dropdownMenu = $(".dropdown-menu");
    const showClass = "show";

    $(window).on("load resize", function() {
      if (this.matchMedia("(min-width: 768px)").matches) {
        $dropdown.hover(
          function() {
            const $this = $(this);
            $this.addClass(showClass);
            $this.find($dropdownToggle).attr("aria-expanded", "true");
            $this.find($dropdownMenu).addClass(showClass);
          },
          function() {
            const $this = $(this);
            $this.removeClass(showClass);
            $this.find($dropdownToggle).attr("aria-expanded", "false");
            $this.find($dropdownMenu).removeClass(showClass);
          }
        );
      } else {
        $dropdown.off("mouseenter mouseleave");
      }
    });

.navbar{
  background-color: black;
  padding-left: 5vw;
  padding-right: 4vw;
}

.navbar .nav-item{
  text-align: center;
  padding-top: 40px;
  padding-bottom: 40px;
}

.navbar .nav-item .nav-link{
  color: white;
  font-size: 18px;
  font-family: 'Roboto';
  font-weight: bold;
}

.navbar .nav-item .nav-link:hover{
  color: red;
  text-decoration: none;
}

.navbar .nav-item a:hover{
  color: #4c4c4c;
}

.navbar .nav-item:not(:last-child) {
  margin-right: 5px;
}

.dropdown-toggle::after {
   transition: transform 0.15s linear;
   content: none;
}

.show.dropdown .dropdown-toggle::after {
  transform: translateY(3px);
}

.dropdown-menu {
  margin-top: 5px;
  border-top: 5px solid red;
  border-radius: 0;
  padding: 0;
}

.navbar .nav-item a{
  font-size: 18px;
  color: #080808;
  padding-top: 12px;
  padding-bottom: 12px;
  padding-right: 40px;
  font-weight: 400;
  font-family: 'Roboto';
  background-color: none;
  border-bottom: 1px solid rgba(193,193,193,0.59);
}

.navbar .nav-item .nav-link{
  border-bottom: none;
}

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

      </button>

                        About Us

                        Who we are
                        What we do

                    Events

                    Contact Us

So what I want to do is having both dropdown on hover working as well as using the dropdown same button(nav-item) to work as a button that navigates the user to specified section.

In the above code, it would be "About Us" that will show its following dropdown on hover. And when "About Us" is clicked, it would navigate the user to specified section ("#information").

I can only get one or the other working. If i get dropdown on hover, navigation doesn't work, if i get navigation work, then dropdown doesn't appear on hover.

Any help would be much appreciated

Thank you.

Body:
You have no hover on mobile devices, so the click cannot open the submenu and navigate to the desired section. It wouldn't be ideal, so Bootstrap works like this.

One solution would be to remove data-toggle="dropdown" from the <a> tag, however the dropdown would not work in mobile devices, since it needs click event.

If you want to maintain the submenu for mobile working, it's better to not have anchor navigation on mobile. So, keep the data-toggle="dropdown" and add this code:

$("#navbarDropdown1").click(function() {
  if ($(window).width() > 991) {
    var href = $(this).attr('href');
    $('body, html').animate({ // an animation if you prefer, slim jQuery doesn't include animate
      scrollTop: $(href).offset().top
    }, 600);
  }
});

Now when clicking on "About Us", it will navigate to the section, but not if the screen width is less than the Bootstrap breakpoint reserved for mobile devices (991px).


问:
Update records in table from CTE results
I want to update the records in my table using CTE.
And I've been trying with the insert function using CTE and it's working.
This is my query with the insert function:

```<code>; WITH CTE AS
(
    SELECT *, RN = ROW_NUMBER() OVER (PARTITION BY NIP, NAME, DEPARTMENT ORDER BY DATEATTEND)
    FROM DAILYDATA
)
INSERT INTO DAILYDATAWH (NIP, NAME, DEPARTMENT, STATUSIN, STATUSOUT)
SELECT  NIP, NAME, DEPARTMENT, STATUSIN = MIN(DATEATTEND), STATUSOUT = MAX(DATEATTEND)
FROM    CTE
GROUP BY NIP, NAME, DEPARTMENT, (RN - 1) / 2
</code>```

How to change that with the update function?

i want to change to update function because when i use insert function,the previous data that already exists in DAILYDATA appear again

This is table DAILYDATA

This is table DAILYDATAWH

答:
You just use the CTE as if it were a table.  Your question is rather vague on what you want updated with the CTE, but the syntax is something like:</p>

```<code>WITH TOUPDATE AS (
      SELECT DD.*,
             RN = ROW_NUMBER() OVER (PARTITION BY NIP, NAME, DEPARTMENT ORDER BY DATEATTEND)
      FROM DAILYDATA dd
     )
UPDATE TOUPDATE
    SET something = run;
</code>```

Body:
I want to update the records in my table using CTE.
And I've been trying with the insert function using CTE and it's working.
This is my query with the insert function:

; WITH CTE AS
(
    SELECT *, RN = ROW_NUMBER() OVER (PARTITION BY NIP, NAME, DEPARTMENT ORDER BY DATEATTEND)
    FROM DAILYDATA
)
INSERT INTO DAILYDATAWH (NIP, NAME, DEPARTMENT, STATUSIN, STATUSOUT)
SELECT  NIP, NAME, DEPARTMENT, STATUSIN = MIN(DATEATTEND), STATUSOUT = MAX(DATEATTEND)
FROM    CTE
GROUP BY NIP, NAME, DEPARTMENT, (RN - 1) / 2

How to change that with the update function?

i want to change to update function because when i use insert function,the previous data that already exists in DAILYDATA appear again

This is table DAILYDATA

This is table DAILYDATAWH

Body:
You just use the CTE as if it were a table.  Your question is rather vague on what you want updated with the CTE, but the syntax is something like:

WITH TOUPDATE AS (
      SELECT DD.*,
             RN = ROW_NUMBER() OVER (PARTITION BY NIP, NAME, DEPARTMENT ORDER BY DATEATTEND)
      FROM DAILYDATA dd
     )
UPDATE TOUPDATE
    SET something = run;


问:
How can I delete all windows user profiles EXCEPT for the ones I specify?
I am trying to remove all user profiles except for certain profiles I specify (administrator, Public, default, DOMAIN\administrator, etc)

I am able to do this successfully and exclude a single user profile, however I am having issues with the correct syntax to exclude multiple user profiles.  Here is the code I have found to successfully list all profiles except administrator:

Get-CimInstance -ComputerName computer1,computer2 -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -ne 'administrator' }

which I got from here:

https://adamtheautomator.com/powershell-delete-user-profile/

I changed the -eq to a -ne to exclude the administrator profile, but I also want to exclude several other ones.

I think I need something like:

Get-CimInstance -ComputerName computer1,computer2 -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -ne 'administrator','Public','default','DOMAIN\administrator' }

however that does not seem to be working and it's only excluding the first name on the list (administrator).

What would be the correct syntax for this command?

Thanks!

答:
Optional: Create an array with the list you want to keep like this:

```<code>$AccountsToKeep = @('administrator','Public','default','DOMAIN\administrator')
</code>```

Then use this:

```<code>Get-CimInstance -ComputerName computer1,computer2 -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -notin $AccountsToKeep }
</code>```

Hope this helps.

If you like this answer, please don't forget to accept it!

Body:
Optional: Create an array with the list you want to keep like this:

$AccountsToKeep = @('administrator','Public','default','DOMAIN\administrator')

Then use this:

Get-CimInstance -ComputerName computer1,computer2 -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -notin $AccountsToKeep }

Hope this helps.

If you like this answer, please don't forget to accept it!


问:
I cannot use SHL (shift left) with int64 variables
```<code> Result:= b8;
 Result:= Result+ (b7  SHL  8);
 Result:= Result+ (b6  SHL 16);
 Result:= Result+ (b5  SHL 24);
 Result:= Result+ (b4  SHL 32);
 Result:= Result+ (b3  SHL 40);      <------ here
 Result:= Result+ (b2  SHL 48);
 Result:= Result+ (MSB SHL 56);
</code>```

(Result is int64 and b1-b8 is byte).

But the compiler complains about "constant exp violates subrange bounds".
Then I have found this warning "The compiler will reject hardcoded shift right values that exceed 32, unless the data type is Int64. The same is not true for Shl" on a web site. Delphi Help says nothing about it. Why is there a limit? Can I stop it? Maybe a compiler directive or something? I can use a multiplication to get over it, but it will be slower. There is a faster way to do it?

Edit:
I am thinking also in creating two cardinals because I can use SHL on cardinals, then to merge the cardinals together. This will require only one multiplication. Any other ideas?

Edit2:
The code is part of an algorithm that converts a number form base 255 to base 256 (and the other way around). I do this 50000 million times; so speed is important.

答:
Here is another solution that uses shifts but I believe is "cleaner" (though not as clean as David's suggestion):

```<code>result := MSB;
result := (result shl 8) or b2;  { could use "shl sizeof(b2)" instead of 8 }
result := (result shl 8) or b3;
etc
result := (result shl 8) or b8;
</code>```

this solution avoids all the "magic" shifting values and it is probably easier to understand.  Also, if MSB..b8 (or b1..b8) were an array of bytes, the above code could easily be converted into a single line loop.

To answer your question as to why the compiler does not accept the value 40 and above, the reason is most likely due to this quote from Volume 2B of the Intel Instruction Set Reference for the SHLD instruction:

In non-64-bit modes and default 64-bit
  mode; only bits 0 through 4 of the
  count are used. This masks the count
  to a value between 0 and 31. If a
  count is greater than the operand
  size, the result is undefined.

The equivalent condition on the SHL instruction is not quite as stringent:

The 8086 does not mask the shift
  count. However, all other IA-32
  processors (starting with the Intel
  286 processor) do mask the shift count
  to 5 bits, resulting in a maximum
  count of 31. This masking is done in
  all operating modes (including the
  virtual-8086 mode) to reduce the
  maximum execution time of the
  instructions.

In either case, a value greater than 31 is either useless (when using SHL) or undefined (when using SHLD).  The compiler obviously knows this and, it is preventing you from writing code that is potentially erroneous (in 64 bit mode.)

if you, indeed are doing this operation 50 BILLION times, then you may want to consider doing it in inline assembly, which would be quite simple:

```<code>asm
    xor eax, eax
    or  eax, MSB   { or b1 depending on how you named the MSB }
    shl eax, 8
    or  eax, b2
    shl eax, 8
    or  eax, b3
    shl eax, 8
    or  eax, b4
    mov High32bit, eax
end;
</code>```

and repeat the above operation for the low 32 bit dword and b5 thru b8.  I didn't suggest using SHLD because I don't believe Delphi supports the 64 bit registers nor 64bit instructions (I could be wrong, I've never tried it.)

Note: I've heard rumors that the 64bit version of Delphi will not support inline assembly.  This may or may not be the case but, I would stay away from inline assembly unless it is truly absolutely necessary.

Hope that helps,

John.

PS: there is another reason why David Heffernan's solution is the best one. In the solution I presented, every instruction depends on the previous instruction (that is, eax must be shifted by 8 before the next "or" instruction can be executed).  David's solution sets individual bytes, as such, each assignment is independent of the previous assignment, this will allow the processor to potentially carry out multiple assignments in parallel.  In this era of multi-core processors this has the potential of being quite a bit faster than the assembly code I gave as an example.

Body:
 Result:= b8;
 Result:= Result+ (b7  SHL  8);
 Result:= Result+ (b6  SHL 16);
 Result:= Result+ (b5  SHL 24);
 Result:= Result+ (b4  SHL 32);
 Result:= Result+ (b3  SHL 40);      <------ here
 Result:= Result+ (b2  SHL 48);
 Result:= Result+ (MSB SHL 56);

(Result is int64 and b1-b8 is byte).

But the compiler complains about "constant exp violates subrange bounds".
Then I have found this warning "The compiler will reject hardcoded shift right values that exceed 32, unless the data type is Int64. The same is not true for Shl" on a web site. Delphi Help says nothing about it. Why is there a limit? Can I stop it? Maybe a compiler directive or something? I can use a multiplication to get over it, but it will be slower. There is a faster way to do it?

Edit:
I am thinking also in creating two cardinals because I can use SHL on cardinals, then to merge the cardinals together. This will require only one multiplication. Any other ideas?

Edit2:
The code is part of an algorithm that converts a number form base 255 to base 256 (and the other way around). I do this 50000 million times; so speed is important.

Body:
Here is another solution that uses shifts but I believe is "cleaner" (though not as clean as David's suggestion):

result := MSB;
result := (result shl 8) or b2;  { could use "shl sizeof(b2)" instead of 8 }
result := (result shl 8) or b3;
etc
result := (result shl 8) or b8;

this solution avoids all the "magic" shifting values and it is probably easier to understand.  Also, if MSB..b8 (or b1..b8) were an array of bytes, the above code could easily be converted into a single line loop.

To answer your question as to why the compiler does not accept the value 40 and above, the reason is most likely due to this quote from Volume 2B of the Intel Instruction Set Reference for the SHLD instruction:

In non-64-bit modes and default 64-bit
  mode; only bits 0 through 4 of the
  count are used. This masks the count
  to a value between 0 and 31. If a
  count is greater than the operand
  size, the result is undefined.

The equivalent condition on the SHL instruction is not quite as stringent:

The 8086 does not mask the shift
  count. However, all other IA-32
  processors (starting with the Intel
  286 processor) do mask the shift count
  to 5 bits, resulting in a maximum
  count of 31. This masking is done in
  all operating modes (including the
  virtual-8086 mode) to reduce the
  maximum execution time of the
  instructions.

In either case, a value greater than 31 is either useless (when using SHL) or undefined (when using SHLD).  The compiler obviously knows this and, it is preventing you from writing code that is potentially erroneous (in 64 bit mode.)

if you, indeed are doing this operation 50 BILLION times, then you may want to consider doing it in inline assembly, which would be quite simple:

asm
    xor eax, eax
    or  eax, MSB   { or b1 depending on how you named the MSB }
    shl eax, 8
    or  eax, b2
    shl eax, 8
    or  eax, b3
    shl eax, 8
    or  eax, b4
    mov High32bit, eax
end;

and repeat the above operation for the low 32 bit dword and b5 thru b8.  I didn't suggest using SHLD because I don't believe Delphi supports the 64 bit registers nor 64bit instructions (I could be wrong, I've never tried it.)

Note: I've heard rumors that the 64bit version of Delphi will not support inline assembly.  This may or may not be the case but, I would stay away from inline assembly unless it is truly absolutely necessary.

Hope that helps,

John.

PS: there is another reason why David Heffernan's solution is the best one. In the solution I presented, every instruction depends on the previous instruction (that is, eax must be shifted by 8 before the next "or" instruction can be executed).  David's solution sets individual bytes, as such, each assignment is independent of the previous assignment, this will allow the processor to potentially carry out multiple assignments in parallel.  In this era of multi-core processors this has the potential of being quite a bit faster than the assembly code I gave as an example.


问:
Correct word-count of a LaTeX document
I'm currently searching for an application or a script that does a correct word count for a LaTeX document.

Up till now, I have only encountered scripts that only work on a single file but what I want is a script that can safely ignore LaTeX keywords and also traverse linked files...ie follow \include and \input links to produce a correct word-count for the whole document.

With vim, I currently use ggVGg CTRL+G but obviously that shows the count for the current file and does not ignore LaTeX keywords.

Does anyone know of any script (or application) that can do this job?

答:
If the use of a vim plugin suits you, the vimtex plugin has integrated the texcount tool quite nicely.

Here is an excerpt from their documentation:

```<code>:VimtexCountLetters       Shows the number of letters/characters or words in
:VimtexCountWords         the current project or in the selected region. The
                          count is created with `texcount` through a call on
                          the main project file similar to: >

                            texcount -nosub -sum [-letter] -merge -q -1 FILE
<
                          Note: Default arguments may be controlled with
                                |g:vimtex_texcount_custom_arg|.

                          Note: One may access the information through the
                                function `vimtex#misc#wordcount(opts)`, where
                                `opts` is a dictionary with the following
                                keys (defaults indicated): >

                                'range' : [1, line('$')]
                                'count_letters' : 0/1
                                'detailed' : 0
<
                                If `detailed` is 0, then it only returns the
                                total count. This makes it possible to use for
                                e.g. statusline functions. If the `opts` dict
                                is not passed, then the defaults are assumed.

                                             *VimtexCountLetters!*
                                             *VimtexCountWords!*
:VimtexCountLetters!      Similar to |VimtexCountLetters|/|VimtexCountWords|, but
:VimtexCountWords!        show separate reports for included files.  I.e.
                          presents the result of: >

                            texcount -nosub -sum [-letter] -inc FILE
<
                                             *VimtexImapsList*
                                             *<plug>(vimtex-imaps-list)*

</code>```

The nice part about this is how extensible it is. On top of counting the number of words in your current file, you can make a visual selection (say two or three paragraphs) and then only apply the command to your selection.

Title: Correct word-count of a LaTeX document

Body:
If the use of a vim plugin suits you, the vimtex plugin has integrated the texcount tool quite nicely.

Here is an excerpt from their documentation:

:VimtexCountLetters       Shows the number of letters/characters or words in
:VimtexCountWords         the current project or in the selected region. The
                          count is created with `texcount` through a call on
                          the main project file similar to: >

                            texcount -nosub -sum [-letter] -merge -q -1 FILE
<
                          Note: Default arguments may be controlled with
                                |g:vimtex_texcount_custom_arg|.

                          Note: One may access the information through the
                                function `vimtex#misc#wordcount(opts)`, where
                                `opts` is a dictionary with the following
                                keys (defaults indicated): >

                                'range' : [1, line('$')]
                                'count_letters' : 0/1
                                'detailed' : 0
<
                                If `detailed` is 0, then it only returns the
                                total count. This makes it possible to use for
                                e.g. statusline functions. If the `opts` dict
                                is not passed, then the defaults are assumed.

                                             *VimtexCountLetters!*
                                             *VimtexCountWords!*
:VimtexCountLetters!      Similar to |VimtexCountLetters|/|VimtexCountWords|, but
:VimtexCountWords!        show separate reports for included files.  I.e.
                          presents the result of: >

                            texcount -nosub -sum [-letter] -inc FILE
<
                                             *VimtexImapsList*
                                             *<plug>(vimtex-imaps-list)*

The nice part about this is how extensible it is. On top of counting the number of words in your current file, you can make a visual selection (say two or three paragraphs) and then only apply the command to your selection.


问:
Rails + Postgres drop error: database is being accessed by other users
I have a rails application running over Postgres.

I have two servers: one for testing and the other for production.

Very often I need to clone the production DB on the test server.

The command I'm runnig via Vlad is:

```<code>rake RAILS_ENV='test_server' db:drop db:create
</code>```

The problem I'm having is that I receive the following error:

```<code>ActiveRecord::StatementInvalid: PGError: ERROR: database <database_name> is being accessed by other users DROP DATABASE IF EXISTS <database_name>
</code>```

This happens if someone has accessed the application via web recently (postgres keeps a "session" opened)

Is there any way that I can terminate the sessions on the postgres DB?

Thank you.

Edit

I can delete the database using phppgadmin's interface but not with the rake task.

How can I replicate phppgadmin's drop with a rake task?

答:
Solution

Bash script

```<code>ENV=development

# restart postgresql
brew services restart postgresql

# get name of the db from rails app
RAILS_CONSOLE_COMMAND="bundle exec rails c -e $ENV"
DB_NAME=$(echo 'ActiveRecord::Base.connection_config[:database]' | $RAILS_CONSOLE_COMMAND | tail -2 | tr -d '\"')

# delete all connections to $DB_NAME
for pid in $(ps -ef | grep $DB_NAME | awk {'print$2'})
do
   kill -9 $pid
done

# drop db
DISABLE_DATABASE_ENVIRONMENT_CHECK=1 RAILS_ENV=$ENV bundle exec rails db:drop:_unsafe
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a rails application running over Postgres.

I have two servers: one for testing and the other for production.

Very often I need to clone the production DB on the test server.

The command I'm runnig via Vlad is:

rake RAILS_ENV='test_server' db:drop db:create

The problem I'm having is that I receive the following error:

ActiveRecord::StatementInvalid: PGError: ERROR: database <database_name> is being accessed by other users DROP DATABASE IF EXISTS <database_name>

This happens if someone has accessed the application via web recently (postgres keeps a "session" opened)

Is there any way that I can terminate the sessions on the postgres DB?

Thank you.

Edit

I can delete the database using phppgadmin's interface but not with the rake task.

How can I replicate phppgadmin's drop with a rake task?

Body:
Solution

Bash script

ENV=development

# restart postgresql
brew services restart postgresql

# get name of the db from rails app
RAILS_CONSOLE_COMMAND="bundle exec rails c -e $ENV"
DB_NAME=$(echo 'ActiveRecord::Base.connection_config[:database]' | $RAILS_CONSOLE_COMMAND | tail -2 | tr -d '\"')

# delete all connections to $DB_NAME
for pid in $(ps -ef | grep $DB_NAME | awk {'print$2'})
do
   kill -9 $pid
done

# drop db
DISABLE_DATABASE_ENVIRONMENT_CHECK=1 RAILS_ENV=$ENV bundle exec rails db:drop:_unsafe


问:
How to calcluate sum of column python pandas
I am simply trying to get the sum of a column ('Value') in a dataframe in python. I believe I am creating the dataframe, but I am not sure. I am getting a result back, however, it's not the result I imagine when it comes to .sum().

```<code>import csv
import pandas as pd

with open('new_taste.csv', 'r') as csv_trades:
    csv_reader = csv.DictReader(csv_trades)

    df = pd.DataFrame(data=csv_reader)
    total = df['Value'].sum()
    df.loc['Value'] = pd.Series(df['Value'].sum(), index=['Value'])
    print(df['Value'])

</code>```

is giving me

```<code>0                                                      133
1                                                      180
2                                                     -117
3                                                     -159
4                                                        1
                               ...
316                                                     14
317                                                     14
318                                                     19
319                                                     18
Value    133180-117-15911-84-3-10-23434245-23-3085-5241...
Name: Value, Length: 321, dtype: object
</code>```

I noticed it's bringing back every number, not the sum of the numbers. I would like to bring back the sum.

答:
I think this is my answer. I have to go through and check the math cause I believe I have to further tweak what I'm adding up. I was returning a string.</p>

```<code>import csv
import pandas as pd

with open('new_taste.csv', 'r') as csv_trades:
    csv_reader = csv.DictReader(csv_trades)

    df = pd.DataFrame(data=csv_reader)
    total = df['Value'].sum()
    df.loc['Value'] = pd.Series(df['Value'].astype(float).sum(), index=['Value'])
    print(df['Value'])

print(total)

</code>```

Body:
I am simply trying to get the sum of a column ('Value') in a dataframe in python. I believe I am creating the dataframe, but I am not sure. I am getting a result back, however, it's not the result I imagine when it comes to .sum().

import csv
import pandas as pd

with open('new_taste.csv', 'r') as csv_trades:
    csv_reader = csv.DictReader(csv_trades)

    df = pd.DataFrame(data=csv_reader)
    total = df['Value'].sum()
    df.loc['Value'] = pd.Series(df['Value'].sum(), index=['Value'])
    print(df['Value'])

is giving me

0                                                      133
1                                                      180
2                                                     -117
3                                                     -159
4                                                        1
                               ...
316                                                     14
317                                                     14
318                                                     19
319                                                     18
Value    133180-117-15911-84-3-10-23434245-23-3085-5241...
Name: Value, Length: 321, dtype: object

I noticed it's bringing back every number, not the sum of the numbers. I would like to bring back the sum.

Body:
I think this is my answer. I have to go through and check the math cause I believe I have to further tweak what I'm adding up. I was returning a string.

import csv
import pandas as pd

with open('new_taste.csv', 'r') as csv_trades:
    csv_reader = csv.DictReader(csv_trades)

    df = pd.DataFrame(data=csv_reader)
    total = df['Value'].sum()
    df.loc['Value'] = pd.Series(df['Value'].astype(float).sum(), index=['Value'])
    print(df['Value'])

print(total)