问:
TypeScript Factory Subclass is not Assignable to Type Superclass
I want to use the Factory Pattern using TypeScript to convert raw data into a User.  I have two different types of Users: Employee and Customer.  Both extend the base class and compile without problems.  Below is an extremely simplified version of these three classes.

```<code>abstract class User {
  constructor(data: any) { }

  static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
    return new this(data);
  }
}

class Employee extends User {
  static '@type' = 'Employee';

  static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
    return new this(data);
  }
}

class Customer extends User {
  static '@type' = 'Customer';

  static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
    return new this(data);
  }
}
</code>```

Simple enough.  Now for the Factory.  I want to create a Factory that will take raw data returned from the server and convert that data into something the rest of the system can use (i.e. an instance of User).  What I want to do is something like

```<code>class UserFactory {
  /**
   * Vends a User constructed from the raw data from the server.
   *
   * @param userData (Object) - the User definition, as obtained from the server
   *
   * @return (User) the User initialized from `userData`
   */
  static vend<T extends User>(userData: any): T {
    switch (userData['@type']) {
      case Employee['@type']:
        return Employee.createFromServer(userData);

      case Customer['@type']:
        return Customer.createFromServer(userData);

      default:
        throw new Error('Unknown User type.');
    }
  }
}
</code>```

As you can probably guess (since I'm here and not relaxing over the weekend), that doesn't work.  I get the following error:

Type 'Employee' is not assignable to type 'T'.

Since T extends User and Employee extends User without adding or removing anything (in this simplified version), it seems like the above should work.  What's more annoying is it seems the above will work in other languages (e.g. Java (tested), C++), I'm just not sure why it won't work in this situation.

Somebody on GitHub suggested that the problem might be with overloading the constructor, but clearly that's not occurring here.

So, why isn't Employee assignable to type T?  (How) can I get the above to work?  Is there a better way to handle this in TypeScript?  A correct answer will answer at least the first 2 questions.

Addendum

createFromServer() is redefined in subclasses for a reason.  This is a minimally reproducible example.  The constructors don't actually take the raw data from the server.  Instead the createFromServer() converts the raw data into arguments the constructors can understand.

答:
I can't speak to the specific reason why TypeScript won't correctly infer the type, however, casting to any does allow the code to compile and for type inference to work correctly. eg.</p>

```<code>class UserFactory {
    /**
     * Vends a User constructed from the raw data from the server.
     *
     * @param userData (Object) - the User definition, as obtained from the server
     *
     * @return (User) the User initialized from `userData`
     */
    static vend<T extends User>(userData: any) : T {
      switch (userData['@type']) {
        case Employee['@type']:
          return <any>Employee.createFromServer(userData); // Cast

        case Customer['@type']:
          return <any>Customer.createFromServer(userData); // Cast

        default:
          throw new Error('Unknown User type.');
      }
    }
  }

// Tests
const employee = UserFactory.vend<Employee>("");
employee.customerId = 7; // Error
employee.employeeId = 7;

const customer = UserFactory.vend<Customer>("");
customer.customerId = 7;
customer.employeeId = 7; // Error

// Added id properties to Employee and Customer
  abstract class User {
    constructor(data: any) { }

    static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
      return new this(data);
    }
  }

  class Employee extends User {
    static '@type' = 'Employee';
    public employeeId : number;

    static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
      return new this(data);
    }
  }

  class Customer extends User {
    static '@type' = 'Customer';
    public customerId : number;
    static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
      return new this(data);
    }
  }
</code>```

Body:
I want to use the Factory Pattern using TypeScript to convert raw data into a User.  I have two different types of Users: Employee and Customer.  Both extend the base class and compile without problems.  Below is an extremely simplified version of these three classes.

abstract class User {
  constructor(data: any) { }

  static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
    return new this(data);
  }
}

class Employee extends User {
  static '@type' = 'Employee';

  static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
    return new this(data);
  }
}

class Customer extends User {
  static '@type' = 'Customer';

  static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
    return new this(data);
  }
}

Simple enough.  Now for the Factory.  I want to create a Factory that will take raw data returned from the server and convert that data into something the rest of the system can use (i.e. an instance of User).  What I want to do is something like

class UserFactory {
  /**
   * Vends a User constructed from the raw data from the server.
   *
   * @param userData (Object) - the User definition, as obtained from the server
   *
   * @return (User) the User initialized from `userData`
   */
  static vend<T extends User>(userData: any): T {
    switch (userData['@type']) {
      case Employee['@type']:
        return Employee.createFromServer(userData);

      case Customer['@type']:
        return Customer.createFromServer(userData);

      default:
        throw new Error('Unknown User type.');
    }
  }
}

As you can probably guess (since I'm here and not relaxing over the weekend), that doesn't work.  I get the following error:

Type 'Employee' is not assignable to type 'T'.

Since T extends User and Employee extends User without adding or removing anything (in this simplified version), it seems like the above should work.  What's more annoying is it seems the above will work in other languages (e.g. Java (tested), C++), I'm just not sure why it won't work in this situation.

Somebody on GitHub suggested that the problem might be with overloading the constructor, but clearly that's not occurring here.

So, why isn't Employee assignable to type T?  (How) can I get the above to work?  Is there a better way to handle this in TypeScript?  A correct answer will answer at least the first 2 questions.

Addendum

createFromServer() is redefined in subclasses for a reason.  This is a minimally reproducible example.  The constructors don't actually take the raw data from the server.  Instead the createFromServer() converts the raw data into arguments the constructors can understand.

Body:
I can't speak to the specific reason why TypeScript won't correctly infer the type, however, casting to any does allow the code to compile and for type inference to work correctly. eg.

class UserFactory {
    /**
     * Vends a User constructed from the raw data from the server.
     *
     * @param userData (Object) - the User definition, as obtained from the server
     *
     * @return (User) the User initialized from `userData`
     */
    static vend<T extends User>(userData: any) : T {
      switch (userData['@type']) {
        case Employee['@type']:
          return <any>Employee.createFromServer(userData); // Cast

        case Customer['@type']:
          return <any>Customer.createFromServer(userData); // Cast

        default:
          throw new Error('Unknown User type.');
      }
    }
  }

// Tests
const employee = UserFactory.vend<Employee>("");
employee.customerId = 7; // Error
employee.employeeId = 7;

const customer = UserFactory.vend<Customer>("");
customer.customerId = 7;
customer.employeeId = 7; // Error

// Added id properties to Employee and Customer
  abstract class User {
    constructor(data: any) { }

    static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
      return new this(data);
    }
  }

  class Employee extends User {
    static '@type' = 'Employee';
    public employeeId : number;

    static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
      return new this(data);
    }
  }

  class Customer extends User {
    static '@type' = 'Customer';
    public customerId : number;
    static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
      return new this(data);
    }
  }


来源: stackexchange

问:
mongodb - counting a non-null field using an index
I'm answering my own question in the hope that it may help someone else. I am using mongodb (3.4), running a count() on an indexed string field, in a collection of 10m documents. I am looking for non-empty strings. Here are some performance metrics, where slow == collection_scan and fast == index_scan:

```<code>+----------------+-----------+
|   Constraint   |Performance|
+----------------+-----------+
| $exists(false) |   slow    |
| $exists(true)  |   slow    |
| $ne: ''        |   slow    |
| $eq: ''        |   fast    |
| $eq: null      |   slow    |
+----------------+-----------+
</code>```

I think I mostly understand what is going on, namely:

1. $exists(false)

Non-existing fields will not enter the index, therefore mongodb must perform a collection scan in order to gather all documents for the count().

2. $exists(true)

This is the one that got me. I thought it would be fast, but I was wrong. I think this is because if a field exists, and it's value is set to undefined, $exists() returns true. I can only assume that fields set to undefined do not enter the index either, and therefore again, mongodb must perform a collection scan in order to gather all documents for the count().

3. $ne: ''

I guess it's the same as $exists(false)

4. $eq: ''

This is a genuine string value, so it must exist in the index, therefore fast.

4. $eq: null

This is the other one that got me. This document helped a lot (https://jira.mongodb.org/browse/SERVER-18653). In short, with the 2.6 release (https://docs.mongodb.com/manual/release-notes/2.6-compatibility/#null-comparison-queries):

null equality queries (i.e. field: null ) now match fields with values undefined

This query is slow. I can only assume that undefined fields are not indexed, and since null matches both, again, mongodb must perform a collection scan in order to gather all documents for the count().

So, what do?

答:
Solution

What I ended up doing, was using the regex /^.+$/ to find non-empty strings. This uses the index and is super-fast. Equally important, I now try to avoid using $exists() and $ne:.

Thanks

ContentLicense: CC BY-SA 3.0

Body:
I'm answering my own question in the hope that it may help someone else. I am using mongodb (3.4), running a count() on an indexed string field, in a collection of 10m documents. I am looking for non-empty strings. Here are some performance metrics, where slow == collection_scan and fast == index_scan:

+----------------+-----------+
|   Constraint   |Performance|
+----------------+-----------+
| $exists(false) |   slow    |
| $exists(true)  |   slow    |
| $ne: ''        |   slow    |
| $eq: ''        |   fast    |
| $eq: null      |   slow    |
+----------------+-----------+

I think I mostly understand what is going on, namely:

1. $exists(false)

Non-existing fields will not enter the index, therefore mongodb must perform a collection scan in order to gather all documents for the count().

2. $exists(true)

This is the one that got me. I thought it would be fast, but I was wrong. I think this is because if a field exists, and it's value is set to undefined, $exists() returns true. I can only assume that fields set to undefined do not enter the index either, and therefore again, mongodb must perform a collection scan in order to gather all documents for the count().

3. $ne: ''

I guess it's the same as $exists(false)

4. $eq: ''

This is a genuine string value, so it must exist in the index, therefore fast.

4. $eq: null

This is the other one that got me. This document helped a lot (https://jira.mongodb.org/browse/SERVER-18653). In short, with the 2.6 release (https://docs.mongodb.com/manual/release-notes/2.6-compatibility/#null-comparison-queries):

null equality queries (i.e. field: null ) now match fields with values undefined

This query is slow. I can only assume that undefined fields are not indexed, and since null matches both, again, mongodb must perform a collection scan in order to gather all documents for the count().

So, what do?


问:
Lock tables and/or transaction for stock table?
How can I maintain data integrity for a stock table with InnoDB? Does this require the use of both a table lock and a transaction? I have tried to find some good examples, but even well known opensource ecommerce software doesn't implement table locks/transactions. Would below code work? Do I really need to lock the whole table, or is there a way to only lock the rows of the sold products? Or does anyone have a good example?

```<code>CREATE TABLE `stock` (
    `product_id` VARCHAR(50) NOT NULL COLLATE 'utf8mb4_unicode_ci',
    `quantity` INT(10) UNSIGNED NOT NULL DEFAULT '0',
    PRIMARY KEY (`product_id`)
)
COLLATE='utf8mb4_unicode_ci'
ENGINE=InnoDB;
</code>```

.

```<code>LOCK TABLES stock WRITE;
START TRANSACTION;
SET autocommit = 0;
UPDATE stock SET quantity = quantity - 4 WHERE product_id = 'PRODUCT_1' AND quantity >= 4;
UPDATE stock SET quantity = quantity - 2 WHERE product_id = 'PRODUCT_2' AND quantity >= 2;
UPDATE stock SET quantity = quantity - 5 WHERE product_id = 'PRODUCT_3' AND quantity >= 5;
COMMIT or ROLLBACK;
</code>```

COMMIT if all UPDATE queries have 1 affected row, otherwise ROLLBACK

答:
"1 affected row" is not what is tested.  Failure, deadlock, timeout, etc are tested.  If you want to fail if it is not exactly 1 row each, then you need to fetch rows_affected, test it for "1", then ROLLBACK or not.

Also, the

```<code>COMMIT or ROLLBACK
</code>```

needs to be "if ... then ROLLBACK else COMMIT".  This is best done in your application language.

Body:
How can I maintain data integrity for a stock table with InnoDB? Does this require the use of both a table lock and a transaction? I have tried to find some good examples, but even well known opensource ecommerce software doesn't implement table locks/transactions. Would below code work? Do I really need to lock the whole table, or is there a way to only lock the rows of the sold products? Or does anyone have a good example?

CREATE TABLE `stock` (
    `product_id` VARCHAR(50) NOT NULL COLLATE 'utf8mb4_unicode_ci',
    `quantity` INT(10) UNSIGNED NOT NULL DEFAULT '0',
    PRIMARY KEY (`product_id`)
)
COLLATE='utf8mb4_unicode_ci'
ENGINE=InnoDB;

.

LOCK TABLES stock WRITE;
START TRANSACTION;
SET autocommit = 0;
UPDATE stock SET quantity = quantity - 4 WHERE product_id = 'PRODUCT_1' AND quantity >= 4;
UPDATE stock SET quantity = quantity - 2 WHERE product_id = 'PRODUCT_2' AND quantity >= 2;
UPDATE stock SET quantity = quantity - 5 WHERE product_id = 'PRODUCT_3' AND quantity >= 5;
COMMIT or ROLLBACK;

COMMIT if all UPDATE queries have 1 affected row, otherwise ROLLBACK

Body:
"1 affected row" is not what is tested.  Failure, deadlock, timeout, etc are tested.  If you want to fail if it is not exactly 1 row each, then you need to fetch rows_affected, test it for "1", then ROLLBACK or not.

Also, the

COMMIT or ROLLBACK

needs to be "if ... then ROLLBACK else COMMIT".  This is best done in your application language.


问:
how to prevent object from casting shadow in scenekit?
In scenekit you can remove an object from receiving light by setting its   categoryBitMask different than the the lights categoryBitMask

say the light has categoryBitMask=0001 and the node has categoryBitMask=0010, then the object will not be illuminated by the light.

But the object still throws a shadow on other objects from that light. How can I prevent an object from casting a shadow at all?

答: you are looking for the castsShadow property on SCNNode


问:
How do I detect a failed subprocess in a bash read statement?
In bash we can set an environment variable from a sequence of commands using read and a pipe to a subprocess. But I'm having trouble detecting errors in my processing in one edge case - a part of the subprocess pipeline producing some output before erroring.

A simplified example which takes an input file, looks for a line starting with "foo" and sets var to the first word on that line is:

```<code>set -e
set -o pipefail
set -o nounset

die() {
  echo $1 > /dev/stderr
  exit 1
}

read -r var rest < <( \
    cat data.txt \
    | grep foo \
    || die "PIPELINE" \
) || die "OUTER"

echo "var=$var"
</code>```

Running this with data.txt like

```<code>blah
zap foo awesome
bang foo
</code>```

will output

```<code>var=zap
</code>```

Running this on a data.txt file that doesn't contain foo outputs (to stderr)

```<code>DEAD: PIPELINE
DEAD: OUTER
</code>```

This is all as expected.

We can introduce another no-op stage like cat at the end of the process

```<code>...
read -r var rest < <( \
    cat data.txt \
    | grep foo \
    | cat \
    || die "PIPELINE" \
) || die "OUTER"
...
</code>```

and everything continues to work.

But if the additional stage is paste -s -d' ' and the input does not contain "foo" the output is

```<code>var=
DEAD: PIPELINE
</code>```

Which seems to show that the pipeline errors, but read succeeds with an empty line. (It looks like paste -s -d' '  outputs a line of output even when its input is empty.)

Is there a simple way to detect this failure of the pipeline, and cause the main script to error out?

I guess I could check that the variable is not empty - but this is a simplified version - I'm actually using sed and paste to join multiple lines to set multiple variables, like

```<code>read -r v1 v2 v3 rest < <( \
   cat data.txt \
   | grep "^foo=" \
   | sed -e 's/foo=//' \
   | paste -s -d' ' \
   || die "PIPELINE"
) || die "OUTER"
</code>```

答:
In the end I went with two different solutions depending on the context.

The first was to pipe the results to a temporary file. This will process the entire file before performing the read, and thus any failures in the pipe will cause the script to fail.

cat data.txt \
    | grep "^foo=" \
    | sed -e 's/foo=//' \
    | paste -s -d' ' \
    > $TMP/result.txt
    || die "PIPELINE"

read -r var rest < $TMP/result.txt || die "OUTER"
```

<p>The second was to just test that the variables were set. While this meant
there was a bunch of duplication that I wanted to avoid, it seemed the most bullet-proof solution.</p>

<pre class="lang-bash prettyprint-override"><code>read -r var rest < <( cat data.txt \
    | grep "^foo=" \
    | sed -e 's/foo=//' \
    | paste -s -d' ' \
    || die "PIPELINE"
    ) || die "OUTER"

 [ ! -z "$var" ] || die "VARIABLE NOT SET"
</code>```

Body:
In bash we can set an environment variable from a sequence of commands using read and a pipe to a subprocess. But I'm having trouble detecting errors in my processing in one edge case - a part of the subprocess pipeline producing some output before erroring.

A simplified example which takes an input file, looks for a line starting with "foo" and sets var to the first word on that line is:

set -e
set -o pipefail
set -o nounset

die() {
  echo $1 > /dev/stderr
  exit 1
}

read -r var rest < <( \
    cat data.txt \
    | grep foo \
    || die "PIPELINE" \
) || die "OUTER"

echo "var=$var"

Running this with data.txt like

blah
zap foo awesome
bang foo

will output

var=zap

Running this on a data.txt file that doesn't contain foo outputs (to stderr)

DEAD: PIPELINE
DEAD: OUTER

This is all as expected.

We can introduce another no-op stage like cat at the end of the process

...
read -r var rest < <( \
    cat data.txt \
    | grep foo \
    | cat \
    || die "PIPELINE" \
) || die "OUTER"
...

and everything continues to work.

But if the additional stage is paste -s -d' ' and the input does not contain "foo" the output is

var=
DEAD: PIPELINE

Which seems to show that the pipeline errors, but read succeeds with an empty line. (It looks like paste -s -d' '  outputs a line of output even when its input is empty.)

Is there a simple way to detect this failure of the pipeline, and cause the main script to error out?

I guess I could check that the variable is not empty - but this is a simplified version - I'm actually using sed and paste to join multiple lines to set multiple variables, like

read -r v1 v2 v3 rest < <( \
   cat data.txt \
   | grep "^foo=" \
   | sed -e 's/foo=//' \
   | paste -s -d' ' \
   || die "PIPELINE"
) || die "OUTER"

Body:
In the end I went with two different solutions depending on the context.

The first was to pipe the results to a temporary file. This will process the entire file before performing the read, and thus any failures in the pipe will cause the script to fail.

cat data.txt \
    | grep "^foo=" \
    | sed -e 's/foo=//' \
    | paste -s -d' ' \
    > $TMP/result.txt
    || die "PIPELINE"

read -r var rest < $TMP/result.txt || die "OUTER"

The second was to just test that the variables were set. While this meant
there was a bunch of duplication that I wanted to avoid, it seemed the most bullet-proof solution.

read -r var rest < <( cat data.txt \
    | grep "^foo=" \
    | sed -e 's/foo=//' \
    | paste -s -d' ' \
    || die "PIPELINE"
    ) || die "OUTER"

 [ ! -z "$var" ] || die "VARIABLE NOT SET"


问:
Format phone number string from google form to spreadsheets into an email draft using google script
For the most part of this code I have down. The only issue I am having is formatting a phone number that has been inputted to the Google Form. On the Spreadsheet the values come in looking like 1234567890, just a string of numbers. I am using body.replaceText("%PHONE1%", row[2]); to replace %PHONE1% in the template document. Issue is it numbers come in the same as the spreadsheet 1234567890 and I want the phone number to look like (123) 456-7890.
It may possibly something like

Utilities.formatString('%11.6f', 123.456);

Please help, im a super newb at any type of scripting any help would be appreciated. Thank you

答:
Here's a simple example:</p>

```<code>function formatPhoneNumber()
{
  var s='1234567890';
  if(s)
  {
    var mA=s.match(/(\d{3})(\d{3})(\d{4})/);
    var s=Utilities.formatString('(%s) %s-%s', mA[1],mA[2],mA[3]);
    var ui=HtmlService.createHtmlOutput(s);
    SpreadsheetApp.getUi().showModelessDialog(ui, 'Phone Number')
  }
}
</code>```

Body:
Here's a simple example:

function formatPhoneNumber()
{
  var s='1234567890';
  if(s)
  {
    var mA=s.match(/(\d{3})(\d{3})(\d{4})/);
    var s=Utilities.formatString('(%s) %s-%s', mA[1],mA[2],mA[3]);
    var ui=HtmlService.createHtmlOutput(s);
    SpreadsheetApp.getUi().showModelessDialog(ui, 'Phone Number')
  }
}


问:
Selecting one row based on the values in a group
Novice SQL coder here. My data looks like this:

```<code>Case          Allegation          Result
1             1                   Supported
1             2                   Not Supported
2             1                   Not Supported
3             1                   Not Supported
3             2                   Supported
3             3                   Not Supported
4             1                   Not Supported
4             2                   Supported
</code>```

For my purposes, a case is considered "supported" if any allegations within it are supported. What I need to do is to return one row per unique Case which reads "Supported" if that condition is met, and otherwise reads "Not Supported":

```<code>Case          Result
1             Supported
2             Not Supported
3             Supported
4             Supported
</code>```

In the past I'd have "over-selected" what I needed and done the display work through Reporting Services expressions, but this time I'm delivering a query. I'd imagine I need a subselect with groups for this but haven't the first idea of how to do it.

答:
GROUP by the CASE field
Max of the Result field (where S is higher than N)

```<code>declare @mytable table ([case] smallint, allegation smallint,result varchar(20))

insert into @mytable
values (1            , 1                 ,'Supported'),
(1           ,  2                   ,'Not Supported'),
(2          ,   1                   ,'Not Supported'),
(3        ,     1                   ,'Not Supported'),
(3       ,      2                   ,'Supported'),
(3      ,       3                   ,'Not Supported'),
(4     ,        1                   ,'Not Supported'),
(4     ,        2                   ,'Supported')

select [case], max(result) [Result]
 from @mytable
group by [case]
</code>```

Result

```<code>1   Supported
2   Not Supported
3   Supported
4   Supported
</code>```

Body:
Novice SQL coder here. My data looks like this:

Case          Allegation          Result
1             1                   Supported
1             2                   Not Supported
2             1                   Not Supported
3             1                   Not Supported
3             2                   Supported
3             3                   Not Supported
4             1                   Not Supported
4             2                   Supported

For my purposes, a case is considered "supported" if any allegations within it are supported. What I need to do is to return one row per unique Case which reads "Supported" if that condition is met, and otherwise reads "Not Supported":

Case          Result
1             Supported
2             Not Supported
3             Supported
4             Supported

In the past I'd have "over-selected" what I needed and done the display work through Reporting Services expressions, but this time I'm delivering a query. I'd imagine I need a subselect with groups for this but haven't the first idea of how to do it.

Body:
GROUP by the CASE field
Max of the Result field (where S is higher than N)

declare @mytable table ([case] smallint, allegation smallint,result varchar(20))

insert into @mytable
values (1            , 1                 ,'Supported'),
(1           ,  2                   ,'Not Supported'),
(2          ,   1                   ,'Not Supported'),
(3        ,     1                   ,'Not Supported'),
(3       ,      2                   ,'Supported'),
(3      ,       3                   ,'Not Supported'),
(4     ,        1                   ,'Not Supported'),
(4     ,        2                   ,'Supported')

select [case], max(result) [Result]
 from @mytable
group by [case]

Result

1   Supported
2   Not Supported
3   Supported
4   Supported


问:
Call Cygwin from Java app
I need to call Cygwin from Java code ( example : to call make command in Cygwin from Java app which run on linux and windows  ).Does anybody have experience with this problem ?</p>

答:
Use ProcessBuilder from Java:

http://download.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html

You will need to make sure your path/environment is set up properly, but that depends on your machine and set up.

Also, note that many cygwin "capabilities" (e.g., less, awk, sed, etc) are simply binaries (executables) that you can call directly -- no need for the bash shell to facilitate access to those.  Look at the actual files in wherever your bin folder is (usually c:/cygwin/bin) and try calling those directly from ProcessBuilder.  If you need to actually leverage the shell (e.g., pipes, variables, globbing, etc) then that's a different story -- you would then integrate with the bash.exe file itself (check the man page for usage info).

ContentLicense: CC BY-SA 2.5

Title: Call Cygwin from Java app


问:
LDAP: Join Like Query or Custom `memberOf` like Attribute
I am having two LDAP Subtrees:

users

mailinglists

a user has (besides many other attributes) an attribute emailForwardTo which contains email addresses to that mailinglists should be forwarded for this user and forwardList, containing a list of mailinglist ou attributes that should be forwarded.

Those fields need to be set in the user (as 1st the user config should be all in one place and 2nd the user can edit only their own entry). But for my postfix alias lookup, I need to have a list of those alias addresses in the alias objects attribute forwardTo.

I remember that for groups, there is the memberOf virtual attribute that acts acts similarly. Is it possible to do the same for my case? (edit: as stated in the comments, I now know this kind of attribute is called overlay)

Or would it be possible to do joins in ldap queries?

Edit 2: As Joins are probably impossible in LDAP, is it possible to write an own overlay, that works like memberOf but on other attributes?

答:
I remember that for groups, there is the memberOf virtual attribute that acts acts similarly. Is it possible to do the same for my case?

No.

Or would it be possible to do joins in ldap queries?

No. You would have to write it, by which I mean the 'join', manually.

ContentLicense: CC BY-SA 4.0


问:
Implementing a dynamic Time Zone selector Angular 2/4/5
I need to build a TimeZone selector in my Angular 4/5 Application. When a user changes the timezone, I expect all displayed time values on the page to update immediately.

I was planning to use:

momentjs with timezone support using angular2-moment and angular-moment-timezone.

To format the date use amLocal pipe, followed by other pipes.

When user selects a different time zone, I am planning to call moment.tz.setDefault(_timezone)

With the above values from this point on gets formatted as new time zone, while currently displayed time values do not change. Angular change detection mechanism does not update displayed time values, as the input values have not changed.

I do not want to create an 'impure' pipe because of performance overheads (considering timezone change is not a frequent activity).

As fallback I can create a pipe (or use an existing one) that takes the current time zone as parameter. It actually works but I will need to pass around the current time zone value to each component and template.

I have not been able to find a way for Angular change detection to believe there is a change even when there was no change of values.

Any suggestions will be welcome.

答:
Pipes are not components (obvious), they do not have their own change detection mechanics except pure flag. So there two ways to achieve desired result:

Use smart impure pipe which will track previous value and previous formatted result. Angular's AsyncPipe (which is impure actually, if there was another way to do that then I believe it would be made pure) is implemented this way:

```<code>if (value !== this.value || this.timeZoneChanged)
{
    this.value = value;
    this.formattedValue = ... render value ...;
}
return this.formattedValue;
</code>```

You can browse AsyncPipe source code on github.

Use custom component to render dates i.e. custom ControlValueAccessor.

Body:
Pipes are not components (obvious), they do not have their own change detection mechanics except pure flag. So there two ways to achieve desired result:

Use smart impure pipe which will track previous value and previous formatted result. Angular's AsyncPipe (which is impure actually, if there was another way to do that then I believe it would be made pure) is implemented this way:

if (value !== this.value || this.timeZoneChanged)
{
    this.value = value;
    this.formattedValue = ... render value ...;
}
return this.formattedValue;

You can browse AsyncPipe source code on github.

Use custom component to render dates i.e. custom ControlValueAccessor.


问:
JBossEAP / Wildfly error renaming temporary file
for the past several days I've been experiencing this error, while publishing to either JBoss EAP 6.3 or Wildfly 8.2 from Eclipse.

```<code>Error renaming D:\Servers\wildfly-8.2.0.Final\standalone\tmp\tmp9064011157118650757.jar
to D:\Servers\wildfly-8.2.0.Final\standalone\deployments\BusinessService.war\WEB-INF\lib\spring-web-4.2.3.RELEASE.jar.

This may be caused by incorrect file permissions, or your server's temporary deploy
directory may be on a different filesystem than the final destination. You may adjust
these settings in the server editor.
</code>```

The problem occurs when I "Add and Remove..." projects from the server, then try to publish them, so the server can start.

I've experienced this issue on two different machines (home (Wildfly) and work (JBoss EAP)).

I'm using:

Windows 7 / 10

Eclipse Mars / Luna

JBoss Tools plugin 4.3 / 4.2

JDK 1.8.0.66 / 1.8.0.65

Maven

Building with maven from Eclipse and from the command line makes no difference. The server is configured to deploy projects as compressed archives. On both machines my user has administrator rights and has full rights on the server directory.

So far I've tried:

recreating the server multiple times with different configurations

using a newly created workspace

reinstalling JBoss Tools

reinstalling Eclipse

using different JDK versions

I'm really at a loss here and I don't know how to proceed in resolving this issue. Please help.

答:
I have moved the wildfly home to reduce the overall path length, and also removed any non-alphanumeric characters from the folder name (like "-"  and "." ) . This worked for me, everything else (removing tmp, deployment, rebooting wildfly, rebooting eclipse, rebooting computer) failed.
I also suspect that the issue was stemming from running Wildfly from a ConEmu and/or git bash shell. Running from a plain CMD shell seems more robust.</p>

Body:
for the past several days I've been experiencing this error, while publishing to either JBoss EAP 6.3 or Wildfly 8.2 from Eclipse.

Error renaming D:\Servers\wildfly-8.2.0.Final\standalone\tmp\tmp9064011157118650757.jar
to D:\Servers\wildfly-8.2.0.Final\standalone\deployments\BusinessService.war\WEB-INF\lib\spring-web-4.2.3.RELEASE.jar.

This may be caused by incorrect file permissions, or your server's temporary deploy
directory may be on a different filesystem than the final destination. You may adjust
these settings in the server editor.

The problem occurs when I "Add and Remove..." projects from the server, then try to publish them, so the server can start.

I've experienced this issue on two different machines (home (Wildfly) and work (JBoss EAP)).

I'm using:

Windows 7 / 10

Eclipse Mars / Luna

JBoss Tools plugin 4.3 / 4.2

JDK 1.8.0.66 / 1.8.0.65

Maven

Building with maven from Eclipse and from the command line makes no difference. The server is configured to deploy projects as compressed archives. On both machines my user has administrator rights and has full rights on the server directory.

So far I've tried:

recreating the server multiple times with different configurations

using a newly created workspace

reinstalling JBoss Tools

reinstalling Eclipse

using different JDK versions

I'm really at a loss here and I don't know how to proceed in resolving this issue. Please help.


问:
VBA Macro, Replace and Formula
I am trying to replace certain cells with a vlookup function.

```<code>Columns("R").Select
Columns("R").Replace What:="N/A", _
                        Replacement:="=VLOOKUP(RC[-15], [test.xls]test_data'!$C:$R , 16, FALSE)", _
                        LookAt:=xlPart, _
                        SearchOrder:=xlByRows, _
                        MatchCase:=False, _
                        SearchFormat:=False, _
                        ReplaceFormat:=False
</code>```

The current code above does not replace the N/A with the vlookup. It just leaves the cell unchanged.

If I removed the "=" in brackets, so it looks like this:

Replacement:="VLOOKUP(RC[-15], [test.xls]test_data'!$C:$R , 16, FALSE)"

This does replace my cells, but wont be in a formula format.

Can anyone help?

Thanks,

答:
You have several problems with your formula which is preventing Excel from actually accepting it.  You are trying to use

=VLOOKUP(RC[-15], [test.xls]test_data'!$C:$R , 16, FALSE)
```

<p>but that</p>

<ul>
<li>has a syntax error, due to the missing quotation mark, i.e. <code>[test.xls]test_data'</code> should be <code>'[test.xls]test_data'</code>, and</li>
<li>is mixing R1C1 notation (<code>RC[-15]</code>) and A1 notation (<code>$C:$R</code>)</li>
</ul>

<p>The formula you intended to use was probably</p>

<pre class="lang-none prettyprint-override"><code>=VLOOKUP(RC[-15], '[test.xls]test_data'!C3:C18 , 16, FALSE)
</code>```

So you probably meant your code to say

```<code>Columns("R").Select
Columns("R").Replace What:="N/A", _
                     Replacement:="=VLOOKUP(RC[-15], '[test.xls]test_data'!C3:C18, 16, FALSE)", _
                     LookAt:=xlPart, _
                     SearchOrder:=xlByRows, _
                     MatchCase:=False, _
                     SearchFormat:=False, _
                     ReplaceFormat:=False
</code>```

Now, if your Excel settings are set so that you use R1C1 notation as the default, the correction to your formula is probably all that you will have to change.

But, if you use A1 notation as the default, that formula won't be interpreted correctly due to C3:C18 being ambiguous as to the notation being used.

So you will possibly need to temporarily set Excel to use R1C1 notation:

```<code>Application.ReferenceStyle = xlR1C1
Columns("R").Select
Columns("R").Replace What:="N/A", _
                     Replacement:="=VLOOKUP(RC[-15], '[test.xls]test_data'!C3:C18, 16, FALSE)", _
                     LookAt:=xlPart, _
                     SearchOrder:=xlByRows, _
                     MatchCase:=False, _
                     SearchFormat:=False, _
                     ReplaceFormat:=False
Application.ReferenceStyle = xlA1
</code>```

Title: VBA Macro, Replace and Formula

Body:
I am trying to replace certain cells with a vlookup function.

Columns("R").Select
Columns("R").Replace What:="N/A", _
                        Replacement:="=VLOOKUP(RC[-15], [test.xls]test_data'!$C:$R , 16, FALSE)", _
                        LookAt:=xlPart, _
                        SearchOrder:=xlByRows, _
                        MatchCase:=False, _
                        SearchFormat:=False, _
                        ReplaceFormat:=False

The current code above does not replace the N/A with the vlookup. It just leaves the cell unchanged.

If I removed the "=" in brackets, so it looks like this:

Replacement:="VLOOKUP(RC[-15], [test.xls]test_data'!$C:$R , 16, FALSE)"

This does replace my cells, but wont be in a formula format.

Can anyone help?

Thanks,

Body:
You have several problems with your formula which is preventing Excel from actually accepting it.  You are trying to use

=VLOOKUP(RC[-15], [test.xls]test_data'!$C:$R , 16, FALSE)

but that

has a syntax error, due to the missing quotation mark, i.e. [test.xls]test_data' should be '[test.xls]test_data', and

is mixing R1C1 notation (RC[-15]) and A1 notation ($C:$R)

The formula you intended to use was probably

=VLOOKUP(RC[-15], '[test.xls]test_data'!C3:C18 , 16, FALSE)

So you probably meant your code to say

Columns("R").Select
Columns("R").Replace What:="N/A", _
                     Replacement:="=VLOOKUP(RC[-15], '[test.xls]test_data'!C3:C18, 16, FALSE)", _
                     LookAt:=xlPart, _
                     SearchOrder:=xlByRows, _
                     MatchCase:=False, _
                     SearchFormat:=False, _
                     ReplaceFormat:=False

Now, if your Excel settings are set so that you use R1C1 notation as the default, the correction to your formula is probably all that you will have to change.

But, if you use A1 notation as the default, that formula won't be interpreted correctly due to C3:C18 being ambiguous as to the notation being used.

So you will possibly need to temporarily set Excel to use R1C1 notation:

Application.ReferenceStyle = xlR1C1
Columns("R").Select
Columns("R").Replace What:="N/A", _
                     Replacement:="=VLOOKUP(RC[-15], '[test.xls]test_data'!C3:C18, 16, FALSE)", _
                     LookAt:=xlPart, _
                     SearchOrder:=xlByRows, _
                     MatchCase:=False, _
                     SearchFormat:=False, _
                     ReplaceFormat:=False
Application.ReferenceStyle = xlA1


问:
Improve perceived WPF app startup time
I have a WPF database viewer application: It's a simple main window containing a user control with a data grid showing the data extracted from an SQLite database.

The problem is that this application takes 6 seconds to start until it is usable.

I tried building the user control (and doing all the data loading) in the constructor of the main window:

The splash screen will be shown 5s this way, then followed by 1s of empty main window until the application is ready to be used.

Users said that it takes too long until something (visually) happens.

I then moved the user control creation (and data loading) into the Loaded event handler of the main window:
The splash screen will be shown 3s, followed by 3s of empty main window until the application is ready.

Users said that it is "better", but don't like the fact that a half finished main window is shown in disabled state for so long.

Is there some general advice to be found about perceived application load time or are there any other recommendations about how this situation can be improved?

I believe ideally the main window would be shown as fast as possible, along with some hour glass or spinner until the data is loaded. But then I cannot just move the user control creation into a background worker as this would be done on the wrong thread.

Does anybody have any suggestions to this problem?

Edit:

Note that right now I've just assigned a LINQ-to-EF query as the grid data source.

One possible improvement may be to load this data into a data table in background and assign it only once loaded...

Edit2:
I'm using .net 4 with System.Data.SQLite and EF4 to load the data. There are more or less 4000 rows and 30 columns.

答:
There are many reasons for this.

1) Deployment machine might have fairly low configuration.

2) In-Proper or problem with data binding.

Possible solutions would be:

1) Lazy load the data

2) Optimize the performance. http://msdn.microsoft.com/en-us/library/aa970683.aspx

I had saw applications render 5M records less than a second in wpf.

PS:One more least possible reasons may be 30 columns, due to column order access.

Title: Improve perceived WPF app startup time


问:
Node Positioning on iPhone X
I am having a problem with some code not displaying properly on iPhone X, I've tested on all other devices and it works the way it should but won't work display properly on the iPhone X

```<code>    coinRect.path = UIBezierPath(roundedRect: CGRect(x: -60, y: -20, width: 120, height: 40), cornerRadius: 5).cgPath
    coinRect.position = CGPoint(x: frame.maxX - 70, y: size.height / 2 - ((ceil?.size.height)! + 40))
</code>```

I have included some screenshots to show the problem I'm having...

iPhone X rectangle is off screen:

iPhone 7 displays as expected:

答:
You are probably running afoul of the scene not having the proper scaleMode assigned.  What scaleMode are you using, and how are you assigning the positioning of your screen elements relative to the scene and device size?

Another possibility is that the SKView is larger than the window; have you ensured that it has the proper constraints to peg the SKView to the size of the window?

Title: Node Positioning on iPhone X

Body:
I am having a problem with some code not displaying properly on iPhone X, I've tested on all other devices and it works the way it should but won't work display properly on the iPhone X

    coinRect.path = UIBezierPath(roundedRect: CGRect(x: -60, y: -20, width: 120, height: 40), cornerRadius: 5).cgPath
    coinRect.position = CGPoint(x: frame.maxX - 70, y: size.height / 2 - ((ceil?.size.height)! + 40))

I have included some screenshots to show the problem I'm having...

iPhone X rectangle is off screen:

iPhone 7 displays as expected:


问:
Is it possible to only show the DescriptionField in a custom PXSelector?
I'm working on a form mod for the Employee Time Activities screen (EP307000). I'm building an additional grid to show all data for a given month. To do that, I need to have a field that allows the user to select a Month/Year combo. I've built the custom PXSelector and gotten all of the data to populate it, but the issue that I'm having is whenever the focus is shifted to that field, the description field is hidden, and only the natural key is shown. For example, if a user selects June 2017, the value stored in the field should be "20170630", but the value shown to the user should be "June-2017".

The "From Week" and "Until Week" PXSelector fields have the functionality I want, but I can't seem to replicate it. This is how "Until Week" is declared:

```<code>#region TillWeek
public abstract class tillWeek : IBqlField
{
}
[PXDBInt]
[PXWeekSelector2(DescriptionField = typeof(EPWeekRaw.shortDescription))]
[PXUIField(DisplayName = "Until Week", Visibility = PXUIVisibility.Visible)]
public virtual int? TillWeek { set; get; }
#endregion
</code>```

The pictures below show the difference between the fields. The "From Week" field looks different because I removed the "DescriptionField = typeof(EPWeekRaw.shortDescription)" from the PXWeekSelector2.

Here's my code for the custom selector:

```<code>public class MonthYearSelectorAttribute : PXCustomSelectorAttribute
{

    public MonthYearSelectorAttribute()
        : base(typeof(DateInfoExt.dateInt), new Type[]{ typeof (DateInfoExt.monthName), typeof (DateInfoExt.year)})
    {
        DescriptionField = typeof(DateInfoExt.description);
    }

    public override void FieldVerifying(PXCache sender, PXFieldVerifyingEventArgs e)
    {
    }

    protected virtual IEnumerable GetRecords()
    {
        DateTime currentDate = DateTime.Now;
        PX.SM.DateInfo dateInfo = PXSelect<PX.SM.DateInfo, Where<PX.SM.DateInfo.month, Equal<Required<PX.SM.DateInfo.month>>, And<PX.SM.DateInfo.year, Equal<Required<PX.SM.DateInfo.year>>>>>.Select(this._Graph, currentDate.Month, currentDate.Year);
        int? currentDateInt = dateInfo.DateInt;
        int? pastDateInt = dateInfo.DateInt - 50000;

        foreach(PX.SM.DateInfo result in PXSelectGroupBy<PX.SM.DateInfo, Where<PX.SM.DateInfo.dateInt, LessEqual<Required<PX.SM.DateInfo.year>>, And<PX.SM.DateInfo.dateInt, GreaterEqual<Required<PX.SM.DateInfo.dateInt>>>>, Aggregate<GroupBy<PX.SM.DateInfo.month, GroupBy<PX.SM.DateInfo.year>>>, OrderBy<Asc<PX.SM.DateInfo.year, Asc<PX.SM.DateInfo.month>>>>.Select(this._Graph, currentDateInt, pastDateInt))
        {
            DateInfoExt ext = new DateInfoExt();
            ext.Year = result.Year;
            ext.MonthName = result.MonthName;
            ext.DateInt = result.DateInt;
            ext.Description = result.MonthName + "-" + result.Year.ToString();
            yield return ext;
        }
    }
}
public class DateInfoExt : IBqlTable
{
    public DateInfoExt()
    {
    }
    [PXString]
    [PXUIField(DisplayName = "Description")]
    public virtual string Description { get; set; }
    public abstract class description : IBqlField
    {
    }
    [PXDBString]
    [PXUIField(DisplayName = "MonthYear", IsReadOnly = true)]
    public virtual string MonthYear { get; set; }
    public abstract class monthYear : IBqlField
    {
    }
    [PXDBString]
    [PXUIField(DisplayName = "Month Name", IsReadOnly = true)]
    public virtual string MonthName { get; set; }
    public abstract class monthName : IBqlField
    {
    }
    [PXDBInt]
    [PXUIField(DisplayName = "Year", IsReadOnly = true)]
    public virtual int? Year { get; set; }
    public abstract class year : IBqlField
    {
    }
    [PXDBInt(IsKey = true)]
    [PXUIField(DisplayName = "Date (Integer)", IsReadOnly = true, Visible = false)]
    public virtual int? DateInt { get; set; }
    public abstract class dateInt : IBqlField
    {
    }
}
public class PMTimeActivityFilterExt : PXCacheExtension<PX.Objects.EP.EmployeeActivitiesEntry.PMTimeActivityFilter>
{

    public abstract class month : IBqlField
    {
    }
    [PXDBInt]
    [MonthYearSelector]
    [PXUIField(DisplayName = "Month", Visibility = PXUIVisibility.Visible)]
    public virtual int Month
    {
        get; set;
    }
}
</code>```

Thanks in advance

答:
Attempt #1: Can this be the DisplayMode property set to Text missing on your PXSelector control in Aspx?

```<code><px:PXSelector runat="server" DataField="Month" ID="edMonth" ... DisplayMode="Text"/>
</code>```

Attempt #2: Below is the only achievable result supported by the framework - the Year-Month combination followed by the MonthName Year description within parentheses.:

It won't be possible to show value from one field inside the Month selector and order records within the drop-down grid by some other field - such behavior is simply not supported by the framework.

To get the result above, you should set Visible to false for the PXUIFieldAttribute used on DateInfoExt Description field:

```<code>public class DateInfoExt : IBqlTable
{
    ...
    public abstract class description : IBqlField { }
    [PXString()]
    [PXUIField(DisplayName = "Description", Visible = false)]
    public virtual string Description { get; set; }
    ...

}
</code>```

and slightly change how Description field of the DateInfoExt DAC gets populated with values within the delagate:

```<code>foreach (PX.SM.DateInfo result in PXSelectGroupBy<PX.SM.DateInfo,
    Where<PX.SM.DateInfo.dateInt, LessEqual<Required<PX.SM.DateInfo.year>>,
        And<PX.SM.DateInfo.dateInt, GreaterEqual<Required<PX.SM.DateInfo.dateInt>>>>,
    Aggregate<GroupBy<PX.SM.DateInfo.month, GroupBy<PX.SM.DateInfo.year>>>,
    OrderBy<Asc<PX.SM.DateInfo.year, Asc<PX.SM.DateInfo.month>>>>.Select(this._Graph, currentDateInt, pastDateInt))
{
    DateInfoExt ext = new DateInfoExt();
    ext.DateInt = result.DateInt;
    ext.Year = result.Year;
    ext.MonthName = result.MonthName;
    ext.Description = string.Format("{0}-{1} ({2} {0})", result.Year, result.Month, result.MonthName);
    yield return ext;
}
</code>```

This is how I declared Month selector in Aspx:

```<code><px:PXSelector runat="server" DataField="Month" ID="edMonth" CommitChanges="True" TextMode="Search" ValueField="DateInt" DisplayMode="Text"/>
</code>```

Body:
I'm working on a form mod for the Employee Time Activities screen (EP307000). I'm building an additional grid to show all data for a given month. To do that, I need to have a field that allows the user to select a Month/Year combo. I've built the custom PXSelector and gotten all of the data to populate it, but the issue that I'm having is whenever the focus is shifted to that field, the description field is hidden, and only the natural key is shown. For example, if a user selects June 2017, the value stored in the field should be "20170630", but the value shown to the user should be "June-2017".

The "From Week" and "Until Week" PXSelector fields have the functionality I want, but I can't seem to replicate it. This is how "Until Week" is declared:

#region TillWeek
public abstract class tillWeek : IBqlField
{
}
[PXDBInt]
[PXWeekSelector2(DescriptionField = typeof(EPWeekRaw.shortDescription))]
[PXUIField(DisplayName = "Until Week", Visibility = PXUIVisibility.Visible)]
public virtual int? TillWeek { set; get; }
#endregion

The pictures below show the difference between the fields. The "From Week" field looks different because I removed the "DescriptionField = typeof(EPWeekRaw.shortDescription)" from the PXWeekSelector2.

Here's my code for the custom selector:

public class MonthYearSelectorAttribute : PXCustomSelectorAttribute
{

    public MonthYearSelectorAttribute()
        : base(typeof(DateInfoExt.dateInt), new Type[]{ typeof (DateInfoExt.monthName), typeof (DateInfoExt.year)})
    {
        DescriptionField = typeof(DateInfoExt.description);
    }

    public override void FieldVerifying(PXCache sender, PXFieldVerifyingEventArgs e)
    {
    }

    protected virtual IEnumerable GetRecords()
    {
        DateTime currentDate = DateTime.Now;
        PX.SM.DateInfo dateInfo = PXSelect<PX.SM.DateInfo, Where<PX.SM.DateInfo.month, Equal<Required<PX.SM.DateInfo.month>>, And<PX.SM.DateInfo.year, Equal<Required<PX.SM.DateInfo.year>>>>>.Select(this._Graph, currentDate.Month, currentDate.Year);
        int? currentDateInt = dateInfo.DateInt;
        int? pastDateInt = dateInfo.DateInt - 50000;

        foreach(PX.SM.DateInfo result in PXSelectGroupBy<PX.SM.DateInfo, Where<PX.SM.DateInfo.dateInt, LessEqual<Required<PX.SM.DateInfo.year>>, And<PX.SM.DateInfo.dateInt, GreaterEqual<Required<PX.SM.DateInfo.dateInt>>>>, Aggregate<GroupBy<PX.SM.DateInfo.month, GroupBy<PX.SM.DateInfo.year>>>, OrderBy<Asc<PX.SM.DateInfo.year, Asc<PX.SM.DateInfo.month>>>>.Select(this._Graph, currentDateInt, pastDateInt))
        {
            DateInfoExt ext = new DateInfoExt();
            ext.Year = result.Year;
            ext.MonthName = result.MonthName;
            ext.DateInt = result.DateInt;
            ext.Description = result.MonthName + "-" + result.Year.ToString();
            yield return ext;
        }
    }
}
public class DateInfoExt : IBqlTable
{
    public DateInfoExt()
    {
    }
    [PXString]
    [PXUIField(DisplayName = "Description")]
    public virtual string Description { get; set; }
    public abstract class description : IBqlField
    {
    }
    [PXDBString]
    [PXUIField(DisplayName = "MonthYear", IsReadOnly = true)]
    public virtual string MonthYear { get; set; }
    public abstract class monthYear : IBqlField
    {
    }
    [PXDBString]
    [PXUIField(DisplayName = "Month Name", IsReadOnly = true)]
    public virtual string MonthName { get; set; }
    public abstract class monthName : IBqlField
    {
    }
    [PXDBInt]
    [PXUIField(DisplayName = "Year", IsReadOnly = true)]
    public virtual int? Year { get; set; }
    public abstract class year : IBqlField
    {
    }
    [PXDBInt(IsKey = true)]
    [PXUIField(DisplayName = "Date (Integer)", IsReadOnly = true, Visible = false)]
    public virtual int? DateInt { get; set; }
    public abstract class dateInt : IBqlField
    {
    }
}
public class PMTimeActivityFilterExt : PXCacheExtension<PX.Objects.EP.EmployeeActivitiesEntry.PMTimeActivityFilter>
{

    public abstract class month : IBqlField
    {
    }
    [PXDBInt]
    [MonthYearSelector]
    [PXUIField(DisplayName = "Month", Visibility = PXUIVisibility.Visible)]
    public virtual int Month
    {
        get; set;
    }
}

Thanks in advance

Body:
Attempt #1: Can this be the DisplayMode property set to Text missing on your PXSelector control in Aspx?

<px:PXSelector runat="server" DataField="Month" ID="edMonth" ... DisplayMode="Text"/>

Attempt #2: Below is the only achievable result supported by the framework - the Year-Month combination followed by the MonthName Year description within parentheses.:

It won't be possible to show value from one field inside the Month selector and order records within the drop-down grid by some other field - such behavior is simply not supported by the framework.

To get the result above, you should set Visible to false for the PXUIFieldAttribute used on DateInfoExt Description field:

public class DateInfoExt : IBqlTable
{
    ...
    public abstract class description : IBqlField { }
    [PXString()]
    [PXUIField(DisplayName = "Description", Visible = false)]
    public virtual string Description { get; set; }
    ...

}

and slightly change how Description field of the DateInfoExt DAC gets populated with values within the delagate:

foreach (PX.SM.DateInfo result in PXSelectGroupBy<PX.SM.DateInfo,
    Where<PX.SM.DateInfo.dateInt, LessEqual<Required<PX.SM.DateInfo.year>>,
        And<PX.SM.DateInfo.dateInt, GreaterEqual<Required<PX.SM.DateInfo.dateInt>>>>,
    Aggregate<GroupBy<PX.SM.DateInfo.month, GroupBy<PX.SM.DateInfo.year>>>,
    OrderBy<Asc<PX.SM.DateInfo.year, Asc<PX.SM.DateInfo.month>>>>.Select(this._Graph, currentDateInt, pastDateInt))
{
    DateInfoExt ext = new DateInfoExt();
    ext.DateInt = result.DateInt;
    ext.Year = result.Year;
    ext.MonthName = result.MonthName;
    ext.Description = string.Format("{0}-{1} ({2} {0})", result.Year, result.Month, result.MonthName);
    yield return ext;
}

This is how I declared Month selector in Aspx:

<px:PXSelector runat="server" DataField="Month" ID="edMonth" CommitChanges="True" TextMode="Search" ValueField="DateInt" DisplayMode="Text"/>


问:
No Such Module 'FBSDKLoginKit' Xcode 9
Using CocoaPods, I have imported the below frameworks:

```<code>platform :ios, '11.0'
use frameworks!

target '{APP NAME}' do
    pod 'Firebase'
    pod 'Firebase/Auth'
    pod 'Firebase/Core'
    pod 'Firebase/Database'
    pod 'Firebase/AdMob'
    pod 'Firebase/Messaging'
    pod 'Batch'
    pod 'FBSDKLoginKit'
    pod 'FBSDKCoreKit'
    pod 'Google-Mobile-Ads-SDK'
end
</code>```

When I build my project, it runs happily on my iPhone with no errors.

When I try to create an Archive of the project, it shows one of the below and refuses to build the project to Archive.

```<code>No such module 'FBSDKCoreKit'
No such module 'FBSDKLoginKit'
</code>```

I have no idea what I'm doing wrong as nothing has changed. I haven't archived in a few months and it's suddenly stopped working.

I've removed and re-installed the Pods but nothing seems to fix the issue.
Even if I remove one of the import statements the other FBSKD seems to fail.

答:
Please add

```<code>pod 'FBSDKCoreKit'
</code>```

also.

Title: No Such Module 'FBSDKLoginKit' Xcode 9

Body:
Using CocoaPods, I have imported the below frameworks:

platform :ios, '11.0'
use frameworks!

target '{APP NAME}' do
    pod 'Firebase'
    pod 'Firebase/Auth'
    pod 'Firebase/Core'
    pod 'Firebase/Database'
    pod 'Firebase/AdMob'
    pod 'Firebase/Messaging'
    pod 'Batch'
    pod 'FBSDKLoginKit'
    pod 'FBSDKCoreKit'
    pod 'Google-Mobile-Ads-SDK'
end

When I build my project, it runs happily on my iPhone with no errors.

When I try to create an Archive of the project, it shows one of the below and refuses to build the project to Archive.

No such module 'FBSDKCoreKit'
No such module 'FBSDKLoginKit'

I have no idea what I'm doing wrong as nothing has changed. I haven't archived in a few months and it's suddenly stopped working.

I've removed and re-installed the Pods but nothing seems to fix the issue.
Even if I remove one of the import statements the other FBSKD seems to fail.

Body:
Please add

pod 'FBSDKCoreKit'

also.


问:
How to get sqlalchemy query for a delete statement?
I'm new to sqlalchemy and have been trying to figure this out for days!

I have some python code which is executing the following line:

mdb_session.query(PendingConfig).filter(PendingConfig.id == config.id).delete()

It's deleting all rows in a table called PendingConfig which have an id equals to a given config.id.

I want to log the underlying SQL query sqlalchemy that generates, but don't know how to do that since delete() returns an integer equal to the number of rows deleted.

I tried setting up a logger but that had it's own issues, as I explained in this post.

Need help on this!

答:
If you really want to get the SQL that was actually run by the MySQL server, then you can enable the MySQL query log or slow query log, and read it from the database server.

See https://dev.mysql.com/doc/refman/5.7/en/slow-query-log.html

The MySQL Server doesn't know anything about Python, it just knows that a client sent it a query to execute.

If it's a parameterized query, it will contain ? placeholders in the SQL text, but SQLAlchemy doesn't do placeholders as far as I know. It always interpolates parameter values into the SQL query before sending it to MySQL.


问:
Memory leak with Android camera2 API
I am facing some weird memory leak using camera2 api. Tested with https://github.com/googlesamples/android-Camera2Basic adding empty activity to launch the camera activity and close it then launch again, I get following trace:

11-12 12:52:19.506 16069-16078/com.example.android.camera2basic E/StrictMode: A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
                                                                                java.lang.Throwable: Explicit termination method 'release' not called
                                                                                at dalvik.system.CloseGuard.open(CloseGuard.java:180)
                                                                                at android.view.Surface.setNativeObjectLocked(Surface.java:511)
                                                                                at android.view.Surface.(Surface.java:179)
                                                                                at com.example.android.camera2basic.Camera2BasicFragment.createCameraPreviewSession(Camera2BasicFragment.java:684)
                                                                                at com.example.android.camera2basic.Camera2BasicFragment.access$400(Camera2BasicFragment.java:74)
                                                                                at com.example.android.camera2basic.Camera2BasicFragment$2.onOpened(Camera2BasicFragment.java:194)
                                                                                at android.hardware.camera2.impl.CameraDeviceImpl$1.run(CameraDeviceImpl.java:134)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.os.HandlerThread.run(HandlerThread.java:61)
  11-12 12:52:19.506 16069-16078/com.example.android.camera2basic W/System.err: StrictMode VmPolicy violation with POLICY_DEATH; shutting down.

I use

```<code>StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
    .detectAll()
    .penaltyLog()
    .penaltyDeath()
    .build());
</code>```

Running on LG Nexus 5X, OS 7.1.2

Any ideas if this is something to worry about?

Thanks.

答:
This is more or less a spurious error, due to the framework handling of Surfaces in some cases.

It is not an issue you can do anything about, but in practice it should not cause you any real memory leaks.

Title: Memory leak with Android camera2 API

Body:
I am facing some weird memory leak using camera2 api. Tested with https://github.com/googlesamples/android-Camera2Basic adding empty activity to launch the camera activity and close it then launch again, I get following trace:

11-12 12:52:19.506 16069-16078/com.example.android.camera2basic E/StrictMode: A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
                                                                                java.lang.Throwable: Explicit termination method 'release' not called
                                                                                at dalvik.system.CloseGuard.open(CloseGuard.java:180)
                                                                                at android.view.Surface.setNativeObjectLocked(Surface.java:511)
                                                                                at android.view.Surface.(Surface.java:179)
                                                                                at com.example.android.camera2basic.Camera2BasicFragment.createCameraPreviewSession(Camera2BasicFragment.java:684)
                                                                                at com.example.android.camera2basic.Camera2BasicFragment.access$400(Camera2BasicFragment.java:74)
                                                                                at com.example.android.camera2basic.Camera2BasicFragment$2.onOpened(Camera2BasicFragment.java:194)
                                                                                at android.hardware.camera2.impl.CameraDeviceImpl$1.run(CameraDeviceImpl.java:134)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.os.HandlerThread.run(HandlerThread.java:61)
  11-12 12:52:19.506 16069-16078/com.example.android.camera2basic W/System.err: StrictMode VmPolicy violation with POLICY_DEATH; shutting down.

I use

StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
    .detectAll()
    .penaltyLog()
    .penaltyDeath()
    .build());

Running on LG Nexus 5X, OS 7.1.2

Any ideas if this is something to worry about?

Thanks.


问:
Angular 2 Router - change just named outlet
I have a primary router outlet and a named outlet.  The primary outlet contains a child router outlet.  When I try to change just the named outlet, it fails - I get routed to the default primary route and nothing happens in the named outlet.

AppRouter (primary/AppModule):

```<code>{ path: 'dashboard', component: DashboardComponent },
{ path: 'person/:id', component: PersonProfileComponent }
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
{ path: '**', redirectTo: 'dashboard', pathMatch: 'full' }
</code>```

Child Router (separate module) :

```<code>{
        path: 'person/:id',
        component: PersonProfileComponent,
        children: [
            { path: 'people', component: PersonPeopleComponent },
            {
                path:'person-edit',
                component: PersonEditPanelComponent,
                outlet:'taskPane'
            },
}
</code>```

From the PersonPeopleComponent (url of #/person/8/people - which matches person/:id in the primary outlet and people in the child outlet), I have the following RouterLink:

```<code><a [routerLink]="[{outlets:{taskPane : ['person-edit']} }]">Click Me!</a>
</code>```

where taskPane is the named outlet.

What I would expect to happen is that the PersonEditPanelComponent would show in the taskPane named outlet, and the PersonProfileComponent and the PersonPeopleComponent would remain unchanged in the primary and child outlets.  Instead, what I see is the Dashboard route (my fallback route) gets loaded into the primary outlet and the taskPane outlet is empty.  No error is recorded in the console.

The href on my link ends up as something like #/person/8/(people//taskPane:person-edit) which doesn't work  (I've tried many different permutations on the router link so that is an example of just one invalid URL).  The URL needs to be #/person/8/people(taskPane:person-edit) which does work (I tested it manually) but I can't figure out how to set the RouterLink to generate that URL.

I think that the routes are configured correctly because the URL works when I hardcode it, which means then that the problem is in the RouterLink.

Any clues as to what I'm doing wrong?

Thanks.

答:
Path for the primary outlet has to be set in [routerLink] directive. It's pretty easy to do with Router injected into the component:

```<code>@Component({
  template: `<a [routerLink]="[router.url, {outlets: {taskPane: ['person-edit']} }]">Click Me!</a>`
})
export class YourComponent {
  constructor(public router: Router) {}
}
</code>```

If it still does not work, then I'd try to pass parameter for named outlet as a string in:

```<code>{outlets: {taskPane: 'person-edit'}}
</code>```

Body:
I have a primary router outlet and a named outlet.  The primary outlet contains a child router outlet.  When I try to change just the named outlet, it fails - I get routed to the default primary route and nothing happens in the named outlet.

AppRouter (primary/AppModule):

{ path: 'dashboard', component: DashboardComponent },
{ path: 'person/:id', component: PersonProfileComponent }
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
{ path: '**', redirectTo: 'dashboard', pathMatch: 'full' }

Child Router (separate module) :

{
        path: 'person/:id',
        component: PersonProfileComponent,
        children: [
            { path: 'people', component: PersonPeopleComponent },
            {
                path:'person-edit',
                component: PersonEditPanelComponent,
                outlet:'taskPane'
            },
}

From the PersonPeopleComponent (url of #/person/8/people - which matches person/:id in the primary outlet and people in the child outlet), I have the following RouterLink:

Click Me!

where taskPane is the named outlet.

What I would expect to happen is that the PersonEditPanelComponent would show in the taskPane named outlet, and the PersonProfileComponent and the PersonPeopleComponent would remain unchanged in the primary and child outlets.  Instead, what I see is the Dashboard route (my fallback route) gets loaded into the primary outlet and the taskPane outlet is empty.  No error is recorded in the console.

The href on my link ends up as something like #/person/8/(people//taskPane:person-edit) which doesn't work  (I've tried many different permutations on the router link so that is an example of just one invalid URL).  The URL needs to be #/person/8/people(taskPane:person-edit) which does work (I tested it manually) but I can't figure out how to set the RouterLink to generate that URL.

I think that the routes are configured correctly because the URL works when I hardcode it, which means then that the problem is in the RouterLink.

Any clues as to what I'm doing wrong?

Thanks.

Body:
Path for the primary outlet has to be set in [routerLink] directive. It's pretty easy to do with Router injected into the component:

@Component({
  template: `<a [routerLink]="[router.url, {outlets: {taskPane: ['person-edit']} }]">Click Me!</a>`
})
export class YourComponent {
  constructor(public router: Router) {}
}

If it still does not work, then I'd try to pass parameter for named outlet as a string in:

{outlets: {taskPane: 'person-edit'}}


问:
Rollback under condition in MariaDB
I have a transaction which reduces the variable with amount of money in loop, if the variable with money is below 0, the money amount should return to the value before transaction. How can I appropriately use rollback in MariaDB in this case?

---edit

I have something like that, and it doesn't work, check out the lines in if(budget<0) because if the money is below 0 and some, but not all of them, iterations were made and saved to the temp table, the table shows them

```<code>BEGIN
    DECLARE temppesel text;
    DECLARE tempsalary int;
    DECLARE budget int DEFAULT cash;
    DECLARE done bool DEFAULT false;
    DECLARE occ CURSOR FOR (SELECT pesel, pensja FROM pracownicy where zawod=occupation);
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = true;

    START TRANSACTION;
        DROP TABLE IF EXISTS temp;
        CREATE TABLE temp ( Result text );
        OPEN occ;
            occ : LOOP
                FETCH occ INTO temppesel, tempsalary;
                SET budget = budget - tempsalary;

                IF(done) THEN
                    LEAVE occ;
                END IF;

                IF(budget<0) THEN
                    ROLLBACK;
                    LEAVE occ;
                END IF;

                INSERT INTO temp VALUES (concat('********',substr(temppesel,9,3), ', wyplacono'));
            END LOOP;
        CLOSE occ;

        SELECT * FROM temp;
        DROP TABLE temp;
    COMMIT;
END
</code>```

答:
```<code>BEGIN;
do some SQL
Loop:
    do some SQL
    if something is wrong, ROLLBACK and exit the loop and transaction
    do some SQL
if something, go back to Loop
do some SQL
COMMIT;
</code>```

That is, let ROLLBACK undo everything since the BEGIN.

More

Now that the SP is visible...

What engine is temp?  If it MyISAM, then it is not rolled back.  SHOW VARIABLES LIKE 'default_storage_engine';.

Please don't use occ for 2 different things, it confuses the reader.

Do you want the output to be part of the rows of pracownicy when the budget is blown?  Or do you want no rows?

If you have multiple connections doing the same thing, there is a serious problem -- temp is visible to all connections, and they could step on each other.  Change to CREATE TEMPORARY TABLE temp ...

However, with the pre-test (below), you can completely avoid the use of temp.  First test for its need, then (if needed) simply do a single SELECT for all the rows.

If you want nothing, then a simple test something like this would pre-test whether it will overflow, therey obviating the need for testing in the loop:

..

```<code>IF ( SELECT  SUM(pensja)
    FROM  pracownicy
    where  zawod=occupation ) > budget )
</code>```

Title: Rollback under condition in MariaDB

Body:
I have a transaction which reduces the variable with amount of money in loop, if the variable with money is below 0, the money amount should return to the value before transaction. How can I appropriately use rollback in MariaDB in this case?

---edit

I have something like that, and it doesn't work, check out the lines in if(budget<0) because if the money is below 0 and some, but not all of them, iterations were made and saved to the temp table, the table shows them

BEGIN
    DECLARE temppesel text;
    DECLARE tempsalary int;
    DECLARE budget int DEFAULT cash;
    DECLARE done bool DEFAULT false;
    DECLARE occ CURSOR FOR (SELECT pesel, pensja FROM pracownicy where zawod=occupation);
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = true;

    START TRANSACTION;
        DROP TABLE IF EXISTS temp;
        CREATE TABLE temp ( Result text );
        OPEN occ;
            occ : LOOP
                FETCH occ INTO temppesel, tempsalary;
                SET budget = budget - tempsalary;

                IF(done) THEN
                    LEAVE occ;
                END IF;

                IF(budget<0) THEN
                    ROLLBACK;
                    LEAVE occ;
                END IF;

                INSERT INTO temp VALUES (concat('********',substr(temppesel,9,3), ', wyplacono'));
            END LOOP;
        CLOSE occ;

        SELECT * FROM temp;
        DROP TABLE temp;
    COMMIT;
END

Body:
BEGIN;
do some SQL
Loop:
    do some SQL
    if something is wrong, ROLLBACK and exit the loop and transaction
    do some SQL
if something, go back to Loop
do some SQL
COMMIT;

That is, let ROLLBACK undo everything since the BEGIN.

More

Now that the SP is visible...

What engine is temp?  If it MyISAM, then it is not rolled back.  SHOW VARIABLES LIKE 'default_storage_engine';.

Please don't use occ for 2 different things, it confuses the reader.

Do you want the output to be part of the rows of pracownicy when the budget is blown?  Or do you want no rows?

If you have multiple connections doing the same thing, there is a serious problem -- temp is visible to all connections, and they could step on each other.  Change to CREATE TEMPORARY TABLE temp ...

However, with the pre-test (below), you can completely avoid the use of temp.  First test for its need, then (if needed) simply do a single SELECT for all the rows.

If you want nothing, then a simple test something like this would pre-test whether it will overflow, therey obviating the need for testing in the loop:

..

IF ( SELECT  SUM(pensja)
    FROM  pracownicy
    where  zawod=occupation ) > budget )


问:
Cannot import localization in Xcode Couldn't Communicate with a helper application
I am using macOS High Sierra (beta) and xCode 9 (beta) and trying to work with localization. Anytime I try to import a localized .xliff I get an error that states: Couldn't communicate with a helper application. Try your operation again. If that fails, quit and relaunch the application and try again.

I have done everything I can think of. Any thoughts?

答:
Localization using Apple's provided tools tends to go wrong much more often than it goes right. As far as my applications are concerned, I don't use these tools at all. That goes for any project where I'm using anything more complicated than the default localization function with default parameters:

```<code>NSLocalizedString("this is a key but also a string I guess")
</code>```

Trying to do anything even slightly more cohesive:

```<code>NSLocalizedString("this_is_a_key", value: "This is a string", comment: "This tells the translator useful stuff")
</code>```

ends up breaking the genstrings program and creating a whole other mess. I've taken to manually updating string resource files and using a third party or in-house script to generate other files (any .strings files for example). It may add a bit of arguably unnecessary human touch to the string generation process, though I don't find this to be problematic since it increases visibility of how strings work between the resource and application code.

Body:
Localization using Apple's provided tools tends to go wrong much more often than it goes right. As far as my applications are concerned, I don't use these tools at all. That goes for any project where I'm using anything more complicated than the default localization function with default parameters:

NSLocalizedString("this is a key but also a string I guess")

Trying to do anything even slightly more cohesive:

NSLocalizedString("this_is_a_key", value: "This is a string", comment: "This tells the translator useful stuff")

ends up breaking the genstrings program and creating a whole other mess. I've taken to manually updating string resource files and using a third party or in-house script to generate other files (any .strings files for example). It may add a bit of arguably unnecessary human touch to the string generation process, though I don't find this to be problematic since it increases visibility of how strings work between the resource and application code.


问:
Email intent ignoring line-breaks in preset text (Android)
In various Android applications, I use the following code to show an application chooser for email and, after the user has decided for one of the apps, insert a predefined text into the email form:

```<code>final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { "info@example.org" });
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Sample subject");
String contentStr = "";
for (Object o : mArrayList) { // mArrayList: ArrayList<Object>
    content = contentStr+o.toString()+"\n";
}
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, backupStr);
startActivity(Intent.createChooser(emailIntent, "Choose application"));
</code>```

In the for-loop, the objects' string output is concatenated with the temporary string "contentStr". After every object, there should be a line break ("\n").

So when I test this code on my phone, it works fine and every single object has its own line.

But users report that their email application (Android standard as well) puts everything in one line and ignores the line breaks.

So am I doing anything wrong? Or can I just ignore this bug report as its not an issue which the developer can solve?

答:
You need replace \n to
 even you put EXTRA_TEXT. There is my code:

```<code>final Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, "xxx@xxx.com");
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(Intent.EXTRA_TEXT, "This\nis\na\ntest!".replace("\n", "<br/>"););
</code>```

Body:
In various Android applications, I use the following code to show an application chooser for email and, after the user has decided for one of the apps, insert a predefined text into the email form:

final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { "info@example.org" });
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Sample subject");
String contentStr = "";
for (Object o : mArrayList) { // mArrayList: ArrayList<Object>
    content = contentStr+o.toString()+"\n";
}
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, backupStr);
startActivity(Intent.createChooser(emailIntent, "Choose application"));

In the for-loop, the objects' string output is concatenated with the temporary string "contentStr". After every object, there should be a line break ("\n").

So when I test this code on my phone, it works fine and every single object has its own line.

But users report that their email application (Android standard as well) puts everything in one line and ignores the line breaks.

So am I doing anything wrong? Or can I just ignore this bug report as its not an issue which the developer can solve?

Body:
You need replace \n to <br/> even you put EXTRA_TEXT. There is my code:

final Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, "xxx@xxx.com");
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(Intent.EXTRA_TEXT, "This\nis\na\ntest!".replace("\n", "<br/>"););


问:
subset and change multiple columns with different "functions"
How is it possible to change multiple columns on subset by some conditions in a pandas dataframe?

For example given the input data:

```<code>import pandas as pd
dat = pd.DataFrame({"y": ("441912", "abc", "121", "4455")})
dat['leny'] = dat['y'].str.len()
dat['yfoo'] = None

dat

        y leny yfoo
1: 441912    6   NA
2:    abc    3   NA
3:    121    3   NA
4:   4455    4   NA
</code>```

Then subset the rows for which y starts with 44 and has a length of 4 or 5, then for those rows strip the 44 from the beginning in y, substract 2 from leny and set yfoo to False, resulting to the following output:

```<code>        y leny  yfoo
1: 441912    6    NA
2:    abc    3    NA
3:    121    3    NA
4:     55    2 FALSE
</code>```

My attempt at doing this:

```<code># pandas struggle follows
dat[dat.leny.isin((4, 5)) & dat.y.str.match('^44', na=False)]
</code>```

What do I do next?

答:
Create a mask:

```<code>m = dat.leny.isin((4, 5)) & dat.y.str.startswith('44')
</code>```

Now, use loc and perform your operations.

```<code>dat.loc[m, 'y'] = dat.loc[m, 'y'].str[2:]
dat.loc[m, 'leny'] -= 2
dat.loc[m, 'yfoo'] = False

dat

        y  leny   yfoo
0  441912     6   None
1     abc     3   None
2     121     3   None
3      55     2  False
</code>```

Body:
How is it possible to change multiple columns on subset by some conditions in a pandas dataframe?

For example given the input data:

import pandas as pd
dat = pd.DataFrame({"y": ("441912", "abc", "121", "4455")})
dat['leny'] = dat['y'].str.len()
dat['yfoo'] = None

dat

        y leny yfoo
1: 441912    6   NA
2:    abc    3   NA
3:    121    3   NA
4:   4455    4   NA

Then subset the rows for which y starts with 44 and has a length of 4 or 5, then for those rows strip the 44 from the beginning in y, substract 2 from leny and set yfoo to False, resulting to the following output:

        y leny  yfoo
1: 441912    6    NA
2:    abc    3    NA
3:    121    3    NA
4:     55    2 FALSE

My attempt at doing this:

# pandas struggle follows
dat[dat.leny.isin((4, 5)) & dat.y.str.match('^44', na=False)]

What do I do next?

Body:
Create a mask:

m = dat.leny.isin((4, 5)) & dat.y.str.startswith('44')

Now, use loc and perform your operations.

dat.loc[m, 'y'] = dat.loc[m, 'y'].str[2:]
dat.loc[m, 'leny'] -= 2
dat.loc[m, 'yfoo'] = False

dat

        y  leny   yfoo
0  441912     6   None
1     abc     3   None
2     121     3   None
3      55     2  False


问:
Store read/write data in assembly similar to filesystem
I am creating a custom operating system and is there any way to store data (almost like a filesystem) in assembly so that if the computer shuts off and turns back on the data will still be there?</p>

答:
You can write device drivers for SATA hard drives, USB mass storage, floppy disks, NVMe flash, or whatever else in asm.  You might also be able to use BIOS functions to access them (especially if you're on x86).  But then you have to manage writes in chunks of 512B or 4096B, because those kinds of storage are block-based.

A more literal interpretation of the question has an interesting answer: can a store instruction like mov [mem], eax put data into persistent storage where a load instruction can get it later (after a power cycle)?

Yes, if your hardware has some memory-mapped non-volatile RAM.  (Physically memory-mapped NVRAM like an NVDIMM, not like mmap() to logically map a file into the virtual memory address space of a process).  See this answer on Superuser about Intel Optane DC Persistent Memory

x86 for example has recently gotten more instructions to support NVRAM, like clwb to write-back a cache line (all the way to memory) without necessarily evicting it.  Early implementations of clwb may just run it like clflushopt, though: @Ana reports that Skylake-X does evict.

Also, clflushopt is a more efficient way to force more cache lines to memory.  Use a memory barrier like sfence after a weakly-ordered flush like clflushopt to make sure data is in non-volatile RAM before further writes appear.

For a while Intel was going to require pcommit as part of making sure data had hit non-volatile storage, but decided against it.  With that in mind, see Why Intel added the CLWB and PCOMMIT instructions for more details about using persistent RAM.

IDK what the situation is on architectures other than x86, but presumably NV RAM is / will be usable with ARM and other CPUs, too.


问:
How to "update" a column using pig latin
Imagine I have the following table available to me:

```<code>A: { x: int, y: int, z: int, ...99 other columns... }
</code>```

I now want to transform this, such that z is set to NULL where x > y, with the resulting dataset to be stored as B.

and I want to do it without having to explicitly mention all the other columns, as this becomes a maintenance nightmare.

Is there a simple solution?

答:
I was able to drop some of the column bloat by nesting them in single-row bags and flattening afterwards.

Still, it feels like a bit of a hack. So I'm also investigating cascading to see if it's a better fit for my scenario.

Body:
Imagine I have the following table available to me:

A: { x: int, y: int, z: int, ...99 other columns... }

I now want to transform this, such that z is set to NULL where x > y, with the resulting dataset to be stored as B.

and I want to do it without having to explicitly mention all the other columns, as this becomes a maintenance nightmare.

Is there a simple solution?


问:
How to list all resources without know the package name or filesystem path for jar files in Java 9
in Java 7 & 8 I use to be able to do

```<code>URLClassLoader urlLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
for (URL u : urlLoader.getURLs()) {
    System.out.println("*************** url=" + url);
}
</code>```

But in Java 9 the above gives an error

```<code>java.lang.ClassCastException: java.base/jdk.internal.loader.ClassLoaders$AppClassLoader cannot be cast to java.base/java.net.URLClass
Loader
</code>```

So how do I list all resources without knowing the package prefix or the filesystem path of the jar files?

答:
Because of the move to modular architecture, the old approach for looking up class paths is no longer supported:

The application class loader is no longer an instance of
  URLClassLoader but, rather, of an internal class. It is the default
  loader for classes in modules that are neither Java SE nor JDK
  modules.

https://docs.oracle.com/javase/9/migrate/toc.htm

You can try to parse the classpath property directly or try to do something with modules using ModuleFinder and friends.

Body:
in Java 7 & 8 I use to be able to do

URLClassLoader urlLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
for (URL u : urlLoader.getURLs()) {
    System.out.println("*************** url=" + url);
}

But in Java 9 the above gives an error

java.lang.ClassCastException: java.base/jdk.internal.loader.ClassLoaders$AppClassLoader cannot be cast to java.base/java.net.URLClass
Loader

So how do I list all resources without knowing the package prefix or the filesystem path of the jar files?


问:
List attachments as menu items in ribbon group
I am developing a Office.js addin for Outlook. My goal is to display a menu button in the ribbon group whereas the menu items should be the attachments of the mail item currently active.

I am aware of this restriction:
https://officespdev.uservoice.com/forums/224641-general/suggestions/13225365-support-dynamic-content-in-add-in-commands-ribbon

I was still wondering if there is a work-around since the list of attachments is already available at the addin's initialization. So I am not trying to dynamically modify the list during the addin's execution, I just need to provide the list of menu items at it's startup (in the manifest).

Any help is much appreciated.

答:
Thank you for your feedback. Learning about the new requirements add-in developers have, helps us continue to enable great scenarios on our platform. Currently the feature you requested is not part of the product. However we track Outlook add-in feature requests on our user-voice page. Please add your request there. Features on user-voice are also considered when we go through our planning process.

Link to user voice: https://officespdev.uservoice.com/forums/224641-general/category/131778-outlook-add-ins.

Thanks again for your feedback,
Outlook Engineering Team


问:
how to remove duplicate and filter array object like below mentioned
let array1 = [{id: 562, name: "Eva Bridal"},{id: 582, name: "Finger Touch"},]

let array2 = [{id: 575, name: "Saloon Grand"} , {id: 562, name: "Eva Bridal"}]

Final Output :

```<code>let newarray = [{id: 582, name: "Finger Touch"},{id: 575, name: "Saloon Grand"} ]
</code>```

答:
Add all items from array1, and those items from array2 that are not found in array1 to a resulting array.

This uses spread syntax in an array literal, and .filter() with .find() to exclude the duplicates.

let array1 = [{id: 562, name: "Eva Bridal"},{id: 582, name: "Finger Touch"},];

let array2 = [{id: 575, name: "Saloon Grand"} , {id: 562, name: "Eva Bridal"}];

var result = [
  ...array1.filter(o => !array2.find(o2 => o.id == o2.id)),
  ...array2.filter(o => !array1.find(o2 => o.id == o2.id))
];

console.log(result);```

Body:
let array1 = [{id: 562, name: "Eva Bridal"},{id: 582, name: "Finger Touch"},]

let array2 = [{id: 575, name: "Saloon Grand"} , {id: 562, name: "Eva Bridal"}]

Final Output :

let newarray = [{id: 582, name: "Finger Touch"},{id: 575, name: "Saloon Grand"} ]


问:
Ruby no longer loading BigDecimal by default
After months without issue, I've begun to get an error saying that BigDecimal isn't loaded (specifically uninitialized constant BigDecimal). The simple solution would of course be to just add the require statement as needed, but I'm working on this project with several others and this issue is only affecting me. It's happening on both of my computers (MacOS + Arch), and I'm generally curious as to why this would suddenly start.

I had a suspicion that it could be something to do with switching from system Ruby to RVM-managed Ruby, but switching back to system Ruby didn't remedy the issue. I've done some searching on this and haven't come up with anything.

答: You have to use require bigdecimel to use it, Probably some of the dependency gems for your app were requiring it before so that you didn't had to require them manually</p>


答:
The Java9 Release Note states this:

The application class loader is no longer an instance of
  java.net.URLClassLoader (an implementation detail that was never
  specified in previous releases). Code that assumes that
  ClassLoader.getSytemClassLoader() returns a URLClassLoader object will
  need to be updated. Note that Java SE and the JDK do not provide an
  API for applications or libraries to dynamically augment the class
  path at run-time.

To add to this from the mailing list there are few resource-lookup methods which include ways such as :

A class in a named module can read its own resources via the Class::getResourceAsStream method, which returns an InputStream. It can get a URL to one of its own resources via the Class::getResource method.  These methods will not locate resources in other named modules.

The ClassLoader::getResource* methods do not locate resources in any
named modules.

All existing resource-lookup methods in Class and ClassLoader work as they do today for resources on the classpath.

The new Module::getResourceAsStream method can be
used to read the resources of any named module, without restriction.

These choices provides a balance between both resource encapsulation and readable artifact requirements on Jigsaw.

Title: How to list all resources without know the package name or filesystem path for jar files in Java 9


问:
Unable to install JDK - malformed configuration file
I have thouroughly scoured the internet for anyone who has encountered the same error as me but to no success. I also checked this website for any previous threads asking a similar question and found nothing helpful.

I want to install a Java Development Kit (JDK) which I need to do in order to program a mod for Minecraft. I've downloaded: 'jdk-8u5-windows-x64' from the official Oracle website as I was instructed to by a person's tutorial. The guy said that installing the JDK is "pretty straight-forward" and that all you have to do is "download the executable and run it, and it will install everything for you".

Here's the problem/error. When I open the exe. for the JDK installer I get the following error:
https://i.stack.imgur.com/Exqxj.png

And when I go to the directory I see this:
https://i.stack.imgur.com/2sSB0.png

Notes that may be of interest:

I have previously installed and uninstalled versions of Java in the past.

I'm using this JDK for the program 'Eclipse' which I have recently re-installed.

I have no idea what I'm doing.

答:
Deleting the file allows it to be regenerated but the error is telling you the actual issue.

If you look at line 1 in your java.settings.cfg, you will see that it doesn't match the Oracle flags. How this happens I don't know but I noticed it installing Java 9 JDK on a new machine.

On an installation of java 8, I had the settings line 1 as "AUTOUPDATE=0"
But if you check the config guidelines.
You will see the actual pair should have 'AUTO_UPDATE not AUTOUPDATE'.

You can delete the file but you are deleting your configuration and hoping it rebuilds correctly.