问:
How to can http services from https server
I have apache server(Frontend code) running on 80 port with https secure(SSL is configured). Backend server is nodejs and it is configured on 3000 port. When I tried to call services from https to http i.e. Apache(port 80 ssl configured) to Nodejs (port 3000 non-ssl) it is giving showing failed with status as "net::ERR_SSL_PROTOCOL_ERROR". </p>

答:
This may have something to do with Same Origin policy.
Please see that answer: HTTP Ajax Request via HTTPS Page.</p>


来源: stackexchange

问:
iPhone - Using a static Library?
I created a static library project which generates an "a" file.
I included this "a" file to another project as a static library.

The only way I could use the classes in this static library was to copy all header filed over as well as the "a" file.

Is it possible to avoid copying the header files, and still be able to use and import classes from this static library?

答:
The best option I could find is here:

http://www.cocoanetics.com/2010/05/making-your-own-iphone-frameworks-in-xcode/

...basically, you can jump through a few hoops to package your static library as a Framework.  The Framework will create an internal copy of your header files, so you get access to them automatically when you include it in your project.

ContentLicense: CC BY-SA 3.0

Title: iPhone - Using a static Library?


问:
Overcoming the 50 MiB limitation on PWA cache for iOS
We are building a progressive web app for iOS devices and we know about the 50 MiB cache limitation imposed by the Safari web browser. How can we handle this limitation when we know that our app's service worker might have to cache data more than 50 MiB if we include all the static resources, videos and pictures etc. Our first preference is to keep the app running offline even after the cache is full and if that is not possible than at least prevent the app from breaking if the user is working offline.

It would be good if you give a generic answer which we can implement in other PWAs also.

答:
As of at least iOS 13 both IndexedDB and cacheStorage should have a unified quota of 1GB.
See the following WebKit change: https://bugs.webkit.org/show_bug.cgi?id=198133#c15</p>

ContentLicense: CC BY-SA 4.0


问:
C# AES Decryption - mac check in GCM failed
Trying to do AES decrypt the data using BounceCastle, getting  mac check in GCM failed error at line:  output = cipher.DoFinal(cipherData);

https://github.com/psraju1/CSharpApplePayDecrypter for full code

Error:

```<code>mac check in GCM failed
BouncyCastle.Crypto
   at Org.BouncyCastle.Crypto.Modes.GcmBlockCipher.DoFinal(Byte[] output, Int32 outOff)
   at Org.BouncyCastle.Crypto.BufferedAeadBlockCipher.DoFinal(Byte[] output, Int32 outOff)
   at Org.BouncyCastle.Crypto.BufferedAeadBlockCipher.DoFinal(Byte[] input, Int32 inOff, Int32 inLen)
   at Org.BouncyCastle.Crypto.BufferedCipherBase.DoFinal(Byte[] input)
   at ApplePayDecrypter.ApplePay.DoDecrypt(Byte[] cipherData, Byte[] encryptionKeyBytes) in ApplePayDecrypter.cs:line 107
</code>```

Code:

```<code>protected byte[] RestoreSymmertricKey(byte[] sharedSecretBytes)
{
    byte[] merchantIdentifier = GetHashSha256Bytes("");//applePayRequest.MerchantIdentifier);

    ConcatenationKdfGenerator generator = new ConcatenationKdfGenerator(new Sha256Digest());
    byte[] COUNTER = { 0x00, 0x00, 0x00, 0x01 };
    byte[] algorithmIdBytes = Encoding.UTF8.GetBytes((char)0x0d + "id-aes256-GCM");
    byte[] partyUInfoBytes = Encoding.UTF8.GetBytes("Apple");
    byte[] partyVInfoBytes = merchantIdentifier;
    byte[] otherInfoBytes = Combine(Combine(algorithmIdBytes, partyUInfoBytes), COUNTER);//, partyVInfoBytes);

    generator.Init(new KdfParameters(sharedSecretBytes, otherInfoBytes));
    byte[] encryptionKeyBytes = new byte[16];
    generator.GenerateBytes(encryptionKeyBytes, 0, encryptionKeyBytes.Length);
    return encryptionKeyBytes;
}

private byte[] DoDecrypt(byte[] cipherData, byte[] encryptionKeyBytes)
{
    byte[] output;
    try
    {
        KeyParameter keyparam = ParameterUtilities.CreateKeyParameter("AES", encryptionKeyBytes);
        ParametersWithIV parameters = new ParametersWithIV(keyparam, symmetricIv);
        IBufferedCipher cipher = GetCipher();
        cipher.Init(false, parameters);
        try
        {
            output = cipher.DoFinal(cipherData);
        }
        catch (Exception ex)
        {
            throw new ApplicationException("Invalid Data");
        }
    }
    catch (Exception ex)
    {
        throw new ApplicationException("There was an error occured when decrypting message.");
    }

    return output;
}

public IBufferedCipher GetCipher()
{
    return CipherUtilities.GetCipher("AES/GCM/NoPadding");
}

private static byte[] GetHashSha256Bytes(string text)
{
    byte[] bytes = Encoding.UTF8.GetBytes(text);
    SHA256Managed hashstring = new SHA256Managed();
    byte[] hash = hashstring.ComputeHash(bytes);
    return hash;
}

protected static byte[] Combine(byte[] first, byte[] second)
{
    byte[] ret = new byte[first.Length + second.Length];
    Buffer.BlockCopy(first, 0, ret, 0, first.Length);
    Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
    return ret;
}
</code>```

Actually, I'm trying to decrypt this for ApplePay, and converting sample Java code to C#. Let me know, if you want to take a look at JAVA code

Here is the full code in JAVA & C#. Please check it.

https://github.com/psraju1/CSharpApplePayDecrypter

答:
I had the same problem, so I forked the repo above, made the necessary changes, cleaned it up and pushed it to GitHub.

https://github.com/fscopel/CSharpApplePayDecrypter

Happy Coding!

Body:
Trying to do AES decrypt the data using BounceCastle, getting  mac check in GCM failed error at line:  output = cipher.DoFinal(cipherData);

https://github.com/psraju1/CSharpApplePayDecrypter for full code

Error:

mac check in GCM failed
BouncyCastle.Crypto
   at Org.BouncyCastle.Crypto.Modes.GcmBlockCipher.DoFinal(Byte[] output, Int32 outOff)
   at Org.BouncyCastle.Crypto.BufferedAeadBlockCipher.DoFinal(Byte[] output, Int32 outOff)
   at Org.BouncyCastle.Crypto.BufferedAeadBlockCipher.DoFinal(Byte[] input, Int32 inOff, Int32 inLen)
   at Org.BouncyCastle.Crypto.BufferedCipherBase.DoFinal(Byte[] input)
   at ApplePayDecrypter.ApplePay.DoDecrypt(Byte[] cipherData, Byte[] encryptionKeyBytes) in ApplePayDecrypter.cs:line 107

Code:

protected byte[] RestoreSymmertricKey(byte[] sharedSecretBytes)
{
    byte[] merchantIdentifier = GetHashSha256Bytes("");//applePayRequest.MerchantIdentifier);

    ConcatenationKdfGenerator generator = new ConcatenationKdfGenerator(new Sha256Digest());
    byte[] COUNTER = { 0x00, 0x00, 0x00, 0x01 };
    byte[] algorithmIdBytes = Encoding.UTF8.GetBytes((char)0x0d + "id-aes256-GCM");
    byte[] partyUInfoBytes = Encoding.UTF8.GetBytes("Apple");
    byte[] partyVInfoBytes = merchantIdentifier;
    byte[] otherInfoBytes = Combine(Combine(algorithmIdBytes, partyUInfoBytes), COUNTER);//, partyVInfoBytes);

    generator.Init(new KdfParameters(sharedSecretBytes, otherInfoBytes));
    byte[] encryptionKeyBytes = new byte[16];
    generator.GenerateBytes(encryptionKeyBytes, 0, encryptionKeyBytes.Length);
    return encryptionKeyBytes;
}

private byte[] DoDecrypt(byte[] cipherData, byte[] encryptionKeyBytes)
{
    byte[] output;
    try
    {
        KeyParameter keyparam = ParameterUtilities.CreateKeyParameter("AES", encryptionKeyBytes);
        ParametersWithIV parameters = new ParametersWithIV(keyparam, symmetricIv);
        IBufferedCipher cipher = GetCipher();
        cipher.Init(false, parameters);
        try
        {
            output = cipher.DoFinal(cipherData);
        }
        catch (Exception ex)
        {
            throw new ApplicationException("Invalid Data");
        }
    }
    catch (Exception ex)
    {
        throw new ApplicationException("There was an error occured when decrypting message.");
    }

    return output;
}

public IBufferedCipher GetCipher()
{
    return CipherUtilities.GetCipher("AES/GCM/NoPadding");
}

private static byte[] GetHashSha256Bytes(string text)
{
    byte[] bytes = Encoding.UTF8.GetBytes(text);
    SHA256Managed hashstring = new SHA256Managed();
    byte[] hash = hashstring.ComputeHash(bytes);
    return hash;
}

protected static byte[] Combine(byte[] first, byte[] second)
{
    byte[] ret = new byte[first.Length + second.Length];
    Buffer.BlockCopy(first, 0, ret, 0, first.Length);
    Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
    return ret;
}

Actually, I'm trying to decrypt this for ApplePay, and converting sample Java code to C#. Let me know, if you want to take a look at JAVA code

Here is the full code in JAVA & C#. Please check it.

https://github.com/psraju1/CSharpApplePayDecrypter


问:
How to sum two rows by a simple condition in a data frame
I'd like to sum rows 2 by 2, in order to study the lag of certain variable.

Suppose that I have the following the data base:

```<code>> SE eggs
  4  2.0
  6  4.0
  7 10.0
  8  0.5
  5  1.0
  1  3.0
  2  6.0
  3  9.0
</code>```

So, I expected to obtain the following, where eggsare the sum of the indexes "SE"'s:

```<code>> df
    SE2    eggs
  "4+5"    3
  "6+7"    14
  "8+1"    3.5
  "2+3"    15
</code>```

Where

```<code>df = data.frame(SE=c(4,6,7,8,5,1,2,3),eggs = c(2,4,10,0.5,1,3,6,9))
</code>```

Obs.: Don't mater the order of the data frame, but I need to start from certain number (in this case, number 4), and then take the next number, in this case, number 5, and keep this logic. After SE 6+7, SE 8+1, SE 2+3...

Any hint on how can I do that?

答:
Another option, just a slight variation on my comment where we re-arrange the rows according to the specified logic and then aggregate every two rows:

```<code>aggregate(
  eggs ~ ceiling(seq_along(SE)/2),
  FUN = sum,
  data = df[with(df, order(factor(SE, levels = c(seq(SE[1], max(SE)), SE[!SE %in% seq(SE[1], max(SE))])))),]
  )[, -1]

[1]  3.0 14.0  3.5 15.0
</code>```

Or, if you'd like to keep the SE in the specified format:

```<code>df <- aggregate(
  . ~ ceiling(seq_along(SE)/2),
  FUN = paste, collapse = '+',
  data = df[with(df, order(factor(SE, levels = c(seq(SE[1], max(SE)), SE[!SE %in% seq(SE[1], max(SE))])))),]
  )[, -1]

df$eggs <- sapply(df$eggs, function(x) eval(parse(text = x)))
</code>```

Output:

```<code>df

   SE eggs
1 4+5  3.0
2 6+7 14.0
3 8+1  3.5
4 2+3 15.0
</code>```

Body:
I'd like to sum rows 2 by 2, in order to study the lag of certain variable.

Suppose that I have the following the data base:

> SE eggs
  4  2.0
  6  4.0
  7 10.0
  8  0.5
  5  1.0
  1  3.0
  2  6.0
  3  9.0

So, I expected to obtain the following, where eggsare the sum of the indexes "SE"'s:

> df
    SE2    eggs
  "4+5"    3
  "6+7"    14
  "8+1"    3.5
  "2+3"    15

Where

df = data.frame(SE=c(4,6,7,8,5,1,2,3),eggs = c(2,4,10,0.5,1,3,6,9))

Obs.: Don't mater the order of the data frame, but I need to start from certain number (in this case, number 4), and then take the next number, in this case, number 5, and keep this logic. After SE 6+7, SE 8+1, SE 2+3...

Any hint on how can I do that?

Body:
Another option, just a slight variation on my comment where we re-arrange the rows according to the specified logic and then aggregate every two rows:

aggregate(
  eggs ~ ceiling(seq_along(SE)/2),
  FUN = sum,
  data = df[with(df, order(factor(SE, levels = c(seq(SE[1], max(SE)), SE[!SE %in% seq(SE[1], max(SE))])))),]
  )[, -1]

[1]  3.0 14.0  3.5 15.0

Or, if you'd like to keep the SE in the specified format:

df <- aggregate(
  . ~ ceiling(seq_along(SE)/2),
  FUN = paste, collapse = '+',
  data = df[with(df, order(factor(SE, levels = c(seq(SE[1], max(SE)), SE[!SE %in% seq(SE[1], max(SE))])))),]
  )[, -1]

df$eggs <- sapply(df$eggs, function(x) eval(parse(text = x)))

Output:

df

   SE eggs
1 4+5  3.0
2 6+7 14.0
3 8+1  3.5
4 2+3 15.0


问:
Get all not NULL column names from a SQL Server table
I have a table with following columns: F1, F2, ...F10
Some of these columns contain only NULLS, let's say they are F2 and F7.
How can I get a string with the names of these columns, I would like to get 'F2,F7' as a return value.
This is a temporary table and column names and the number of columns is unknown. I need some very generic function to extract the column names containing NULLs

NOTE:
I know it is fairy easy in Oracle using some system objects (i.e. all_tab_columns, etc), not sure if possible in SQL Server as well.

Thank you.

答:
```<code>SELECT t.name, c.name, c.is_nullable
FROM sys.tables t
JOIN sys.columns c on t.object_id = c.object_id
WHERE t.name = 'YourTableNameHere'
  AND c.is_nullable = 0
</code>```

If you are on MS SQL Server and trying to avoid INFORMATION_SCHEMA.

Body:
SELECT t.name, c.name, c.is_nullable
FROM sys.tables t
JOIN sys.columns c on t.object_id = c.object_id
WHERE t.name = 'YourTableNameHere'
  AND c.is_nullable = 0

If you are on MS SQL Server and trying to avoid INFORMATION_SCHEMA.


问:
Unique Constraint Violation on Hibernate @ManyToMany Relationship
I have 3 entities in my database, let's call them A, B, and C.

A and B share a many-to-many relationship with one another. A has a SortedSet of Bs, but B does not reference A (no collection or w/e configured). So we have the following.

```<code>// Inside class A
@ManyToMany
@JoinTable(name = "a_b",
           joinColumns = {@JoinColumn(name = "a_id")},
           inverseJoinColumns = {@JoinColumn(name = "b_id")})
@LazyCollection(LazyCollectionOption.FALSE)
@SortNatural
private SortedSet<B> bSet = new TreeSet<B>();
</code>```

B and C have a one-to-many relationship with one another (1 B to many Cs). C has a B in it's entity, but B does not have a reference to it's many C entities. So we have the following

```<code>// Inside class C
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "b_id", nullable = false, updatable = true)
protected B b;
</code>```

We have a sync process that runs a nightly job to update the A entities and their associations to B entities (which doesn't change very often). We end up having something similar to the following (really, it's a lot more complicated with DAOs, services, etc).

```<code>// Get the A value to be updated
A aToUpdate = entityManager.find(A.class, idForA);

// Out of scope of the question, but we need to figure out B via a string field on C
C cValue = myDao.getByProperty("fieldName", fieldValue);

// Determine the B values to set on aToUpdate
B bToSetOnA = cValue.getB();
TreeSet<B> bSet = new TreeSet<>();
bSet.add(bToSetOnA);

// Update aToUpdate
aToUpdate.setBSet(bSet);
aToUpdate = entityManager.merge(aToUpdate);
entityManager.flush();
</code>```

When this happens, the following error occurs.

```<code>ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (Sync Thread)
Duplicate entry 'myAId-almostMyBId' for key 'uk_a_b'
</code>```

One interesting thing is that the almostMyBId is 1 character short of the actual B ID. But only the full ID appears in the a_b table.

When I look through the code base, there is a uk_a_b constraint on an index on the a_b table. This is from liquibase.

```<code><createIndex indexName="uk_a_b" tableName="a_b" unique="true">
    <column name="a_id"/>
    <column name="b_id"/>
</createIndex>
</code>```

If I remove the aToUpdate.setBSet(bSet); line, the error disappears.

I added logging and confirmed that the IDs of the new bSet are the same as the old ones on aToUpdate.

Somehow, Hibernate seems to be trying to re-add the association, even though we're doing a merge and the associations haven't really changed.

I've tried changing a few CascadeType and FetchType things here and there, but the error doesn't seem to go away. Anyone have an idea of what's going on?

答:
This is very specific to my situation, but figured I'd post the answer anyways in case anyone read my question and has been working on it.

Another developer on my team was tasked with speeding up a report based on the a and a_b tables. To avoid needing to do a JOIN and a WHERE clause, the developer copied the data over from a_b into a new table (using the WHERE clause) and added triggers so that whenever things were updated, it would insert into the new table. This new table had a constraint named the same as the a_b table (namely, uk_a_b). The duplicate case was not properly handled, so an error was being thrown. Due to the name similarities, it seemed to be the a_b table causing the issue when it was really the new table. Fun times.

Body:
I have 3 entities in my database, let's call them A, B, and C.

A and B share a many-to-many relationship with one another. A has a SortedSet of Bs, but B does not reference A (no collection or w/e configured). So we have the following.

// Inside class A
@ManyToMany
@JoinTable(name = "a_b",
           joinColumns = {@JoinColumn(name = "a_id")},
           inverseJoinColumns = {@JoinColumn(name = "b_id")})
@LazyCollection(LazyCollectionOption.FALSE)
@SortNatural
private SortedSet bSet = new TreeSet();

B and C have a one-to-many relationship with one another (1 B to many Cs). C has a B in it's entity, but B does not have a reference to it's many C entities. So we have the following

// Inside class C
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "b_id", nullable = false, updatable = true)
protected B b;

We have a sync process that runs a nightly job to update the A entities and their associations to B entities (which doesn't change very often). We end up having something similar to the following (really, it's a lot more complicated with DAOs, services, etc).

// Get the A value to be updated
A aToUpdate = entityManager.find(A.class, idForA);

// Out of scope of the question, but we need to figure out B via a string field on C
C cValue = myDao.getByProperty("fieldName", fieldValue);

// Determine the B values to set on aToUpdate
B bToSetOnA = cValue.getB();
TreeSet bSet = new TreeSet<>();
bSet.add(bToSetOnA);

// Update aToUpdate
aToUpdate.setBSet(bSet);
aToUpdate = entityManager.merge(aToUpdate);
entityManager.flush();

When this happens, the following error occurs.

ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (Sync Thread)
Duplicate entry 'myAId-almostMyBId' for key 'uk_a_b'

One interesting thing is that the almostMyBId is 1 character short of the actual B ID. But only the full ID appears in the a_b table.

When I look through the code base, there is a uk_a_b constraint on an index on the a_b table. This is from liquibase.

<createIndex indexName="uk_a_b" tableName="a_b" unique="true">
    <column name="a_id"/>
    <column name="b_id"/>
</createIndex>

If I remove the aToUpdate.setBSet(bSet); line, the error disappears.

I added logging and confirmed that the IDs of the new bSet are the same as the old ones on aToUpdate.

Somehow, Hibernate seems to be trying to re-add the association, even though we're doing a merge and the associations haven't really changed.

I've tried changing a few CascadeType and FetchType things here and there, but the error doesn't seem to go away. Anyone have an idea of what's going on?


问:
How to set CORS headers to a client
I'm using this client

var client = new forcetk.Client();

To make requests. I'm trying to pass another URL but the

has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

error shows up. Can i set up any headers to the client? Is there a way to make my client's request inside an XMLHttpRequest call? Any help would be much appreciated. Thanks in advance.

Here is my oversimplified code

```<code>> forcetk.Client.prototype.createBlob = function (objtype, fields,
> filename, payloadField, payload, callback, error, retry) {
> 'use strict';
>         let res = this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/',
>                          fields, filename, payloadField, payload, callback, error, retry);
>         res.header("Access-Control-Allow-Origin", "*");
>         return res;
>     };
</code>```

答:
CORS headers should be sent FROM the backend side. See more info here.
your domain from which the request comes should be in a white list (in response heasers)</p>

Title: How to set CORS headers to a client

Body:
I'm using this client

var client = new forcetk.Client();

To make requests. I'm trying to pass another URL but the

has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

error shows up. Can i set up any headers to the client? Is there a way to make my client's request inside an XMLHttpRequest call? Any help would be much appreciated. Thanks in advance.

Here is my oversimplified code

> forcetk.Client.prototype.createBlob = function (objtype, fields,
> filename, payloadField, payload, callback, error, retry) {
> 'use strict';
>         let res = this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/',
>                          fields, filename, payloadField, payload, callback, error, retry);
>         res.header("Access-Control-Allow-Origin", "*");
>         return res;
>     };


问:
Query Where & Group by
```<code>WITH AGE_2020 AS
(
    SELECT
        2020 - YEAR(DATE_DE_NAISSANCE) AS AGE,
        DATE_DE_NAISSANCE, DEPARTEMENT_CODE
    FROM
        ELUS
    INNER JOIN
        VILLES ON ELUS.CODE_INSEE = VILLES.CODE_INSEE
)
SELECT
    AVG(AGE) AGE_MOYEN,
    DEPARTEMENT_CODE
FROM
    AGE_2020
WHERE
    AVG(AGE) > 54
GROUP BY
    DEPARTEMENT_CODE
ORDER BY
    AGE_MOYEN;
</code>```

I need to group by department where age > 54
but that means a error form group by, that work without the clause where
how I can solve this ?

答:
You need to use having, when using a aggregation in you filtering, go with having instead of group by</p>

```<code>WITH AGE_2020 AS
(
    SELECT
        2020 - YEAR(DATE_DE_NAISSANCE) AS AGE,
        DATE_DE_NAISSANCE, DEPARTEMENT_CODE
    FROM
        ELUS
    INNER JOIN
        VILLES ON ELUS.CODE_INSEE = VILLES.CODE_INSEE
)
SELECT
    AVG(AGE) AGE_MOYEN,
    DEPARTEMENT_CODE
FROM
    AGE_2020

GROUP BY
    DEPARTEMENT_CODE
HAVING
    AVG(AGE) > 54
ORDER BY
    AGE_MOYEN;
</code>```

Title: Query Where & Group by

Body:
WITH AGE_2020 AS
(
    SELECT
        2020 - YEAR(DATE_DE_NAISSANCE) AS AGE,
        DATE_DE_NAISSANCE, DEPARTEMENT_CODE
    FROM
        ELUS
    INNER JOIN
        VILLES ON ELUS.CODE_INSEE = VILLES.CODE_INSEE
)
SELECT
    AVG(AGE) AGE_MOYEN,
    DEPARTEMENT_CODE
FROM
    AGE_2020
WHERE
    AVG(AGE) > 54
GROUP BY
    DEPARTEMENT_CODE
ORDER BY
    AGE_MOYEN;

I need to group by department where age > 54
but that means a error form group by, that work without the clause where
how I can solve this ?

Body:
You need to use having, when using a aggregation in you filtering, go with having instead of group by

WITH AGE_2020 AS
(
    SELECT
        2020 - YEAR(DATE_DE_NAISSANCE) AS AGE,
        DATE_DE_NAISSANCE, DEPARTEMENT_CODE
    FROM
        ELUS
    INNER JOIN
        VILLES ON ELUS.CODE_INSEE = VILLES.CODE_INSEE
)
SELECT
    AVG(AGE) AGE_MOYEN,
    DEPARTEMENT_CODE
FROM
    AGE_2020

GROUP BY
    DEPARTEMENT_CODE
HAVING
    AVG(AGE) > 54
ORDER BY
    AGE_MOYEN;


问:
Catch array combine warning and print own error message?
I read some csv file and map the contents to the field names using array_combine:

```<code>$csv = array();
$a = array('some fields');
$b = array_combine($a, $csv);
</code>```

However if the field names in $a are different from what I specified in my csv file the method will fails with a warning

array_combine()
  [function.array-combine]: Both
  parameters should have an equal number
  of elements

I tried using try and catch but this does not work. As a note, I am working with zend framework.

Any ideas how to catch the warning?

答:
```<code>$b = @array_combine($a, $csv);
if (!$b) {
    // error!
}
</code>```

You should not (ab)use the @ operator, but in this case it does most literally what you want.

Body:
I read some csv file and map the contents to the field names using array_combine:

$csv = array();
$a = array('some fields');
$b = array_combine($a, $csv);

However if the field names in $a are different from what I specified in my csv file the method will fails with a warning

array_combine()
  [function.array-combine]: Both
  parameters should have an equal number
  of elements

I tried using try and catch but this does not work. As a note, I am working with zend framework.

Any ideas how to catch the warning?

Body:
$b = @array_combine($a, $csv);
if (!$b) {
    // error!
}

You should not (ab)use the @ operator, but in this case it does most literally what you want.


问:
React Hooks / Unnecessary component rendering
I have a problem with unnecessary rendering
basically i have a hook for a theme switch, but every time i type something in my text area i end up rendering my theme unnecessarily:

basically almost all of my components will use my theme so i think maybe this is something problematic

my code:

```<code>export default function App() {
  const theme = useTheme();
  const [text, setText] = useState('');
  const handleClick = () => {
    setText('');
  };
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <div className="App">
        <Header />
        <button
          css={css`
            background: red;
            width: 100px;
            height: 50px;
            border-radius: 10px;
          `}
          onClick={() =>
            theme.setTheme(
              theme.type === 'dark' ? { type: 'light' } : { type: 'dark' },
            )
          }
        >
          a
        </button>
        <textarea
          onKeyPress={e => {
            if (e.key === 'Enter') {
              e.preventDefault();
            }
            if (e.key === 'Enter') {
              handleClick();
            }
          }}
          value={text}
          onChange={e => setText(e.target.value)}
          placeholder="Digite aqui sua mensagem"
        />
      </div>
    </ThemeProvider>
</code>```

my hook:

```<code>export default function useTheme(defaultTheme = lightTheme) {
  const [theme, _setTheme] = useState(getInitialTheme);

  function getInitialTheme() {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme === 'dark' || savedTheme === 'light') {
      return JSON.parse(savedTheme) === 'dark' ? darkTheme : defaultTheme;
    } else {
      return defaultTheme;
    }
  }

  useEffect(() => {
    localStorage.setItem('theme', JSON.stringify(theme.type));
  }, [theme]);

  return {
    ...theme,
    setTheme: ({ setTheme, ...theme }) => {
      if (theme.type === 'dark') {
        return _setTheme(darkTheme);
      } else {
        return _setTheme(lightTheme);
      }
    },
  };
}
</code>```

and my component that uses the theme:

```<code>const Top = props => {
  console.log(props.theme);
  return (
    <HeaderTop>
      <div></div>
    </HeaderTop>
  );
};

const Header = () => {
  const Theme = useTheme();
  return (
    <Container theme={Theme}>
      <Content theme={Theme} flexdirection={'column'}>
        <Top theme={Theme} />
      </Content>
    </Container>
  );
};
</code>```

答:
I've updated the codesandbox for you here.

There were a few issues with your code:

Passing a theme to ThemeProvider

In your useTheme hook you were spreading the theme object and returning it:

```<code>// useTheme.js
return {
  ...theme,
  setTheme: ({ setTheme, ...theme }) => {
    if (theme.type === "dark") {
      return _setTheme(darkTheme);
    } else {
      return _setTheme(lightTheme);
    }
  }
}

// App.js
const theme = useTheme();
<ThemeProvider theme={theme}>
</code>```

ThemeProvider expects a simple object, so you should just pass the theme straight out of your useTheme hook without spreading it, and pass that to the provider:

```<code>// useTheme.js
return {
  theme, // don't spread
  setTheme: ({ setTheme, ...theme }) => {
    if (theme.type === "dark") {
      return _setTheme(darkTheme);
    } else {
      return _setTheme(lightTheme);
    }
  }
}

// App.js
const { theme } = useTheme();
<ThemeProvider theme={theme}>
</code>```

I also renamed your useTheme hook to useAppTheme because it will get confused with Emotion's useTheme hook which you use in every other component.

Setting state in your App component

The App component is the top level of your app, so if it re-renders, the whole app re-renders. You want to avoid this, because the whole point of using React is to NOT have to re-render the whole app every time something changes.

I removed any state from your App component, and it now looks like this:

```<code>/** @jsx jsx */
import { useEffect } from "react";
import { jsx } from "@emotion/core";
import { ThemeProvider } from "emotion-theming";
import GlobalStyle from "./globalStyle";
import Page from "./page";
import useAppTheme from "./useAppTheme";

export default function App() {
  const { theme } = useAppTheme();

  useEffect(() => {
    console.log("rendering app");
  });

  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <Page />
    </ThemeProvider>
  );
}
</code>```

I've left the useEffect in there to log when the App renders - which you will see only happens once on initialization.

I moved all your logic to the new component Page, which is the component that will re-render when state changes:

```<code>/** @jsx jsx */
import { useState, useEffect } from "react";
import { jsx, css } from "@emotion/core";
import Header from "./header";
import { useTheme } from "emotion-theming";

export default function Page() {
  const theme = useTheme();
  const [text, setText] = useState("");
  const handleClick = () => {
    setText("");
  };

  useEffect(() => {
    console.log("rendering page");
  });

  return (
    <div className="App">
      <Header />
      <textarea
        onKeyPress={e => {
          if (e.key === "Enter") {
            e.preventDefault();
          }
          if (e.key === "Enter") {
            handleClick();
          }
        }}
        value={text}
        onChange={e => setText(e.target.value)}
        placeholder="Digite aqui sua mensagem"
      />
    </div>
  );
}
</code>```

You will see that the Page component re-renders every time text changes. This is correct behavior. Usually, you should store local state as far down the component tree as possible, so only the smallest components re-render.

Theme hook re-rendering

You useTheme hook was being called over and over again because you called useTheme in a component that re-renders (App). This is expected.

Now that all state has been removed from App your useTheme (now renamed to useAppTheme is only called once when the App component renders.

You shouldn't call useAppTheme in any child components. You get the theme from the ThemeProvider by calling Emotion's useTheme hook.

If you want to change the current theme, then the component that changes the theme can call your useAppTheme hook, but understand that every time that component re-renders, you useAppTheme hook will be called.

I've moved your button that sets the theme to your Header component:

```<code>import React from "react";
import { useTheme } from "emotion-theming";
import { css } from "@emotion/core";
import useAppTheme from "./useAppTheme";

const NavBar = props => {
  return <div>ae</div>;
};

const Header = () => {
  const Theme = useTheme();
  const { theme, setTheme } = useAppTheme();
  return (
    <div>
      <NavBar />
      <button
        css={css`
          background: red;
          width: 100px;
          height: 50px;
          border-radius: 10px;
        `}
        onClick={() => {
          console.log("setting theme from", theme.type);
          setTheme(
            theme.type === "dark" ? { type: "light" } : { type: "dark" }
          );
        }}
      >
        a
      </button>
    </div>
  );
};

export default Header;
</code>```

Body:
I have a problem with unnecessary rendering
basically i have a hook for a theme switch, but every time i type something in my text area i end up rendering my theme unnecessarily:

basically almost all of my components will use my theme so i think maybe this is something problematic

my code:

export default function App() {
  const theme = useTheme();
  const [text, setText] = useState('');
  const handleClick = () => {
    setText('');
  };
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />

        <button
          css={css`
            background: red;
            width: 100px;
            height: 50px;
            border-radius: 10px;
          `}
          onClick={() =>
            theme.setTheme(
              theme.type === 'dark' ? { type: 'light' } : { type: 'dark' },
            )
          }
        >
          a
        </button>
        <textarea
          onKeyPress={e => {
            if (e.key === 'Enter') {
              e.preventDefault();
            }
            if (e.key === 'Enter') {
              handleClick();
            }
          }}
          value={text}
          onChange={e => setText(e.target.value)}
          placeholder="Digite aqui sua mensagem"
        />

    </ThemeProvider>

my hook:

export default function useTheme(defaultTheme = lightTheme) {
  const [theme, _setTheme] = useState(getInitialTheme);

  function getInitialTheme() {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme === 'dark' || savedTheme === 'light') {
      return JSON.parse(savedTheme) === 'dark' ? darkTheme : defaultTheme;
    } else {
      return defaultTheme;
    }
  }

  useEffect(() => {
    localStorage.setItem('theme', JSON.stringify(theme.type));
  }, [theme]);

  return {
    ...theme,
    setTheme: ({ setTheme, ...theme }) => {
      if (theme.type === 'dark') {
        return _setTheme(darkTheme);
      } else {
        return _setTheme(lightTheme);
      }
    },
  };
}

and my component that uses the theme:

const Top = props => {
  console.log(props.theme);
  return (
    <HeaderTop>

    </HeaderTop>
  );
};

const Header = () => {
  const Theme = useTheme();
  return (
    <Container theme={Theme}>
      <Content theme={Theme} flexdirection={'column'}>
        <Top theme={Theme} />
      </Content>
    </Container>
  );
};

Body:
I've updated the codesandbox for you here.

There were a few issues with your code:

Passing a theme to ThemeProvider

In your useTheme hook you were spreading the theme object and returning it:

// useTheme.js
return {
  ...theme,
  setTheme: ({ setTheme, ...theme }) => {
    if (theme.type === "dark") {
      return _setTheme(darkTheme);
    } else {
      return _setTheme(lightTheme);
    }
  }
}

// App.js
const theme = useTheme();
<ThemeProvider theme={theme}>

ThemeProvider expects a simple object, so you should just pass the theme straight out of your useTheme hook without spreading it, and pass that to the provider:

// useTheme.js
return {
  theme, // don't spread
  setTheme: ({ setTheme, ...theme }) => {
    if (theme.type === "dark") {
      return _setTheme(darkTheme);
    } else {
      return _setTheme(lightTheme);
    }
  }
}

// App.js
const { theme } = useTheme();
<ThemeProvider theme={theme}>

I also renamed your useTheme hook to useAppTheme because it will get confused with Emotion's useTheme hook which you use in every other component.

Setting state in your App component

The App component is the top level of your app, so if it re-renders, the whole app re-renders. You want to avoid this, because the whole point of using React is to NOT have to re-render the whole app every time something changes.

I removed any state from your App component, and it now looks like this:

/** @jsx jsx */
import { useEffect } from "react";
import { jsx } from "@emotion/core";
import { ThemeProvider } from "emotion-theming";
import GlobalStyle from "./globalStyle";
import Page from "./page";
import useAppTheme from "./useAppTheme";

export default function App() {
  const { theme } = useAppTheme();

  useEffect(() => {
    console.log("rendering app");
  });

  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <Page />
    </ThemeProvider>
  );
}

I've left the useEffect in there to log when the App renders - which you will see only happens once on initialization.

I moved all your logic to the new component Page, which is the component that will re-render when state changes:

/** @jsx jsx */
import { useState, useEffect } from "react";
import { jsx, css } from "@emotion/core";
import Header from "./header";
import { useTheme } from "emotion-theming";

export default function Page() {
  const theme = useTheme();
  const [text, setText] = useState("");
  const handleClick = () => {
    setText("");
  };

  useEffect(() => {
    console.log("rendering page");
  });

  return (
    <div className="App">
      <Header />
      <textarea
        onKeyPress={e => {
          if (e.key === "Enter") {
            e.preventDefault();
          }
          if (e.key === "Enter") {
            handleClick();
          }
        }}
        value={text}
        onChange={e => setText(e.target.value)}
        placeholder="Digite aqui sua mensagem"
      />
    </div>
  );
}

You will see that the Page component re-renders every time text changes. This is correct behavior. Usually, you should store local state as far down the component tree as possible, so only the smallest components re-render.

Theme hook re-rendering

You useTheme hook was being called over and over again because you called useTheme in a component that re-renders (App). This is expected.

Now that all state has been removed from App your useTheme (now renamed to useAppTheme is only called once when the App component renders.

You shouldn't call useAppTheme in any child components. You get the theme from the ThemeProvider by calling Emotion's useTheme hook.

If you want to change the current theme, then the component that changes the theme can call your useAppTheme hook, but understand that every time that component re-renders, you useAppTheme hook will be called.

I've moved your button that sets the theme to your Header component:

import React from "react";
import { useTheme } from "emotion-theming";
import { css } from "@emotion/core";
import useAppTheme from "./useAppTheme";

const NavBar = props => {
  return <div>ae</div>;
};

const Header = () => {
  const Theme = useTheme();
  const { theme, setTheme } = useAppTheme();
  return (
    <div>
      <NavBar />
      <button
        css={css`
          background: red;
          width: 100px;
          height: 50px;
          border-radius: 10px;
        `}
        onClick={() => {
          console.log("setting theme from", theme.type);
          setTheme(
            theme.type === "dark" ? { type: "light" } : { type: "dark" }
          );
        }}
      >
        a
      </button>
    </div>
  );
};

export default Header;


问:
Replace active flag to the next item after filtering in Javascript
I have a response from an api that I need to filter. After filtering I need to set the active item. After the filtering there is case that no active item is set to true because the initial active has been filtered. I want to enable the next possible active element.

```<code>// This object array is always sorted with the same length.
const data = [
  { id: 241, name: "item 1",count: 0, active: false},
  { id: 221, name: "item 2",count: 4, active: true},
  { id: 343, name: "item 3",count: 0, active: false},
  { id: 129, name: "item 3",count: 0, active: false}
]

const dataActive = data.find( el=> el.active === true);
const filtered = data.filter(el => el.count < 3);

</code>```

How can I change the active flag of item 3 in the filtered array of objects to true?

So the output of filtered to be:

```<code>  { id: 241, name: "item 1",count: 0, active: false},
  { id: 343, name: "item 3",count: 0, active: true},
  { id: 129, name: "item 3",count: 0, active: false}
</code>```

答:
This seems to work but there may be better ways to do it.</p>

```<code>const data = [
  { id: 241, name: "item 1",count: 0, active: false},
  { id: 221, name: "item 2",count: 4, active: true},
  { id: 343, name: "item 3",count: 0, active: false},
  { id: 129, name: "item 3",count: 0, active: false}
]

const dataActive = data.find( el=> el.active === true);
let isFound = false;
//you have to consider the edge cases if you take this process in consideration
const newMappedData = data.map(el => {
    if(el.active && !isFound){
      isFound = true;
      data[data.indexOf(el) + 1].active = true;
      //any kind of identifier that says the data is to be filtered out
      return false;
  }
  return el;
});

const filtered = newMappedData.filter(el => el != false)
console.log(filtered)
</code>```

Body:
I have a response from an api that I need to filter. After filtering I need to set the active item. After the filtering there is case that no active item is set to true because the initial active has been filtered. I want to enable the next possible active element.

// This object array is always sorted with the same length.
const data = [
  { id: 241, name: "item 1",count: 0, active: false},
  { id: 221, name: "item 2",count: 4, active: true},
  { id: 343, name: "item 3",count: 0, active: false},
  { id: 129, name: "item 3",count: 0, active: false}
]

const dataActive = data.find( el=> el.active === true);
const filtered = data.filter(el => el.count < 3);

How can I change the active flag of item 3 in the filtered array of objects to true?

So the output of filtered to be:

  { id: 241, name: "item 1",count: 0, active: false},
  { id: 343, name: "item 3",count: 0, active: true},
  { id: 129, name: "item 3",count: 0, active: false}

Body:
This seems to work but there may be better ways to do it.

const data = [
  { id: 241, name: "item 1",count: 0, active: false},
  { id: 221, name: "item 2",count: 4, active: true},
  { id: 343, name: "item 3",count: 0, active: false},
  { id: 129, name: "item 3",count: 0, active: false}
]

const dataActive = data.find( el=> el.active === true);
let isFound = false;
//you have to consider the edge cases if you take this process in consideration
const newMappedData = data.map(el => {
    if(el.active && !isFound){
      isFound = true;
      data[data.indexOf(el) + 1].active = true;
      //any kind of identifier that says the data is to be filtered out
      return false;
  }
  return el;
});

const filtered = newMappedData.filter(el => el != false)
console.log(filtered)


问:
SQL sub-queries not returning expected result
```<code>Select name
from instructor
where dept_name = 'Comp. Sci.' and ID in
    (select ID
     from course
     where title != 'Intro. to Computer Science')
</code>```

With this input I want the output to be the instructors who never taught "Intro. to Computer Science but the output is all instructors from CS rather than just the 1 Professor Brant who has not taught Intro to Computer Science. What am I doing wrong?

答:
Use NOT EXISTS:

```<code>select i.name
from instructor i
where i.dept_name = 'Comp. Sci.'
and not exists (
  select 1
  from teaches t inner join course c
  on c.course_id = t.course_id
  where t.id = i.id and c.title = 'Intro. to Computer Science'
)
</code>```

or group by instructor and set the condition in the HAVING clause:

```<code>select i.name
from instructor i
inner join teaches t on t.id = i.id
inner join course c on c.course_id = t.course_id
where i.dept_name = 'Comp. Sci.'
group by i.id, i.name
having count(case when c.title = 'Intro. to Computer Science' then 1 end) = 0
</code>```

Body:
Select name
from instructor
where dept_name = 'Comp. Sci.' and ID in
    (select ID
     from course
     where title != 'Intro. to Computer Science')

With this input I want the output to be the instructors who never taught "Intro. to Computer Science but the output is all instructors from CS rather than just the 1 Professor Brant who has not taught Intro to Computer Science. What am I doing wrong?

Body:
Use NOT EXISTS:

select i.name
from instructor i
where i.dept_name = 'Comp. Sci.'
and not exists (
  select 1
  from teaches t inner join course c
  on c.course_id = t.course_id
  where t.id = i.id and c.title = 'Intro. to Computer Science'
)

or group by instructor and set the condition in the HAVING clause:

select i.name
from instructor i
inner join teaches t on t.id = i.id
inner join course c on c.course_id = t.course_id
where i.dept_name = 'Comp. Sci.'
group by i.id, i.name
having count(case when c.title = 'Intro. to Computer Science' then 1 end) = 0


问:
How to install Oracle Client Library from a Jupyter Notebook with Python?
I am trying to establish a connection from a Jupyter Notebook using the following Python code:

```<code>!pip install cx_Oracle --upgrade
import cx_Oracle
dsn = cx_Oracle.makedsn("<myhost>", 1521, service_name="<myservice>")
connection = cx_Oracle.connect("<myuser>", "<mypassword>", dsn, encoding="UTF-8")
</code>```

And get this error:

DatabaseError                             Traceback (most recent call
  last)  in
        1 dsn = cx_Oracle.makedsn("", 1521, service_name="")
  ----> 2 connection = cx_Oracle.connect("", "", dsn, encoding="UTF-8")

DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library:
  "libclntsh.so: cannot open shared object file: No such file or
  directory". See
  https://oracle.github.io/odpi/doc/installation.html#linux for help

In the link, there is no information on how to install the library in Linux using Python from the Jupyter Notebook. How can I do such an installation?

答:
I strongly expect you'll need to install the Oracle client libraries before starting Jupyter, because the OS library search path needs to contain the client library directory, and you can't set this inside a running process.  The ODPI-C link does contain the steps you need to follow.  You can install the latest Instant Client ZIP or RPM "Basic" package.

The cx_Oracle installation manual is here: https://cx-oracle.readthedocs.io/en/latest/user_guide/installation.html#installing-cx-oracle-on-linux

Body:
I am trying to establish a connection from a Jupyter Notebook using the following Python code:

!pip install cx_Oracle --upgrade
import cx_Oracle
dsn = cx_Oracle.makedsn("<myhost>", 1521, service_name="<myservice>")
connection = cx_Oracle.connect("<myuser>", "<mypassword>", dsn, encoding="UTF-8")

And get this error:

DatabaseError                             Traceback (most recent call
  last)  in
        1 dsn = cx_Oracle.makedsn("", 1521, service_name="")
  ----> 2 connection = cx_Oracle.connect("", "", dsn, encoding="UTF-8")

DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library:
  "libclntsh.so: cannot open shared object file: No such file or
  directory". See
  https://oracle.github.io/odpi/doc/installation.html#linux for help

In the link, there is no information on how to install the library in Linux using Python from the Jupyter Notebook. How can I do such an installation?


问:
iphone coredata setValue not working inside if statement
I have my coredata working fine, but when I put a setValue inside an if, it doesn't work,

this is the code>

```<code>-(void) salvalo {

StaffManagerAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *newDay;
newDay = [NSEntityDescription insertNewObjectForEntityForName:@"DaysAttendance"
                                       inManagedObjectContext:context];

[newDay setValue:startday forKey:@"start"];
[newDay setValue:today forKey:@"datef"];
[newDay setValue:myNumber forKey:@"empID"];
[newDay setValue:myNumber2 forKey:@"intID"];
//[newDay setValue:internet forKey:@"sinch"];

NSError *error;
[context save:&error];

if ([internet isEqualToString:@"YES"] ) {
    [self insertJson];

    [newDay setValue:internet forKey:@"sinch"];

}
else {
    [newDay setValue:@"NO" forKey:@"sinch"];

}

//[self.view removeFromSuperview];
[self dismissModalViewControllerAnimated:YES];

      }
</code>```

please note that when I use the code inside the if in the commented part

//[newDay setValue:internet forKey:@"sinch"];

, it saves normally that value (YES/NO) to the coredata, but inside the if, it doesnt work, even if I put al the delegate and context stuff inside the if,,

so what is the problem? how to fix it?

thanks a lot!

答:
The line [context save:&error]; is  before the if statements.

You may be setting the new value properly, just not saving.  The problem might just be this oversight.

Body:
I have my coredata working fine, but when I put a setValue inside an if, it doesn't work,

this is the code>

-(void) salvalo {

StaffManagerAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *newDay;
newDay = [NSEntityDescription insertNewObjectForEntityForName:@"DaysAttendance"
                                       inManagedObjectContext:context];

[newDay setValue:startday forKey:@"start"];
[newDay setValue:today forKey:@"datef"];
[newDay setValue:myNumber forKey:@"empID"];
[newDay setValue:myNumber2 forKey:@"intID"];
//[newDay setValue:internet forKey:@"sinch"];

NSError *error;
[context save:&error];

if ([internet isEqualToString:@"YES"] ) {
    [self insertJson];

    [newDay setValue:internet forKey:@"sinch"];

}
else {
    [newDay setValue:@"NO" forKey:@"sinch"];

}

//[self.view removeFromSuperview];
[self dismissModalViewControllerAnimated:YES];

      }

please note that when I use the code inside the if in the commented part

//[newDay setValue:internet forKey:@"sinch"];

, it saves normally that value (YES/NO) to the coredata, but inside the if, it doesnt work, even if I put al the delegate and context stuff inside the if,,

so what is the problem? how to fix it?

thanks a lot!


问:
How to print every third character of a string? java
I am trying to print every 3rd character of a string so an example would be:
  123456 returns 36

But my code below returns 14

public String getEveryThird() {
    String newString = "";

    for (int i = 0; i < string.length(); i++) {

        if (i % 3 == 0) {
            newString += (string.charAt(i));
        }
    }

    return newString;
}
```

答:
Good try. The only problem is you choose the wrong remainder of the division since elements start from 0.

Try this condition:

```<code>if (i % 3 == 2)
</code>```

Body:
Good try. The only problem is you choose the wrong remainder of the division since elements start from 0.

Try this condition:

if (i % 3 == 2)


问:
Could not increase number of max_open_files to more than 4096 (request: 4214)
I have MariaDB + Nginx on Linux Debian 9(stretch).
After installing MariaDB it and trying to start it, I got the error saying:
[Warning] Could not increase number of max_open_files to more than 4096 (request: 4214).
So I googled it and it told me that I should change LimiNOFILE to 10000 in /etc/systemd/system/mysql.service. I did that, did deamon-reload and it did absolutely nothing. I am still getting the same error message. I tried reinstalling MariaDB but that didn't help either. I also added LimitMEMLOCK=10000 at the very end of my file, that didn't change anything.

Full traceback:

Link

Thank you in advance

答:
Server settings like openfile_files_limits have no effect, if the operating system limits the number of open files, and will always result in an error. Since the server by default is running as user mysql, it can't change the system values (and there is also no code in the server which changes these limits).

Default value of open files on a Linux system is by default 1024, and can be determined by

```<code>$> ulimit -n
1024
</code>```

So in case you have root privileges or you're in the sudo'ers list, just increase this value. man ulimit will give you more information.

Body:
Server settings like openfile_files_limits have no effect, if the operating system limits the number of open files, and will always result in an error. Since the server by default is running as user mysql, it can't change the system values (and there is also no code in the server which changes these limits).

Default value of open files on a Linux system is by default 1024, and can be determined by

$> ulimit -n
1024

So in case you have root privileges or you're in the sudo'ers list, just increase this value. man ulimit will give you more information.


问:
ArrayList<String[]> won't add more than one item
I'm trying to create an ArrayList of String[], but can't get it to add more than one item. Ultimately I want to extract the items from the ArrayList and send them to a JTable. The program is 5 separate classes, but here's the applicable code for this issue:

```<code>    static JComboBox<String> foodChoice;
    DefaultTableModel foodList;
    static String[] newFood;
    static List<String[]> foodData;
    JTextField newFoodText, portionText, carbsText;

public Main() {
        void createFood() {

            String[] foodProperties = new String[3];
            foodProperties[0] = newFoodText.getText();
            foodProperties[1] = portionText.getText();
            foodProperties[2] = carbsText.getText();
            Main.createFood(foodProperties);
            }

    static void createFood(String[] foodArray) {
            foodData = new ArrayList<String[]>();
            foodData.add(foodArray);
            foodChoice.addItem(foodArray[0]);
        }

        void addFoodToTable() {

            String[] s = new String[3];
            s = (String[]) foodData.get(foodChoice.getSelectedIndex());
            System.out.println(foodData.get(0));
            System.out.println(foodData.get(1));
        }
</code>```

addFoodToTable gets called with a button click. So the issue I'm having is that (based on the sysouts) I will get a pointer address to the first entry in the ArrayList, but then a Null Pointer Exception stating that it is out of bounds for Length 0 when it tries to print the second one to console. This is obviously after calling createFood() 3 or four times in order to populate foodData. I can provide additional code if required, it's just too much to place in whole into this post. Thanks!

答:
Every time you call createFood(String[] foodArray) you create a new List instead of just adding the incoming item to the existing list.

Create the ArrayList in a different place and remove the line from the createFood method and it should work fine.

Body:
I'm trying to create an ArrayList of String[], but can't get it to add more than one item. Ultimately I want to extract the items from the ArrayList and send them to a JTable. The program is 5 separate classes, but here's the applicable code for this issue:

    static JComboBox<String> foodChoice;
    DefaultTableModel foodList;
    static String[] newFood;
    static List<String[]> foodData;
    JTextField newFoodText, portionText, carbsText;

public Main() {
        void createFood() {

            String[] foodProperties = new String[3];
            foodProperties[0] = newFoodText.getText();
            foodProperties[1] = portionText.getText();
            foodProperties[2] = carbsText.getText();
            Main.createFood(foodProperties);
            }

    static void createFood(String[] foodArray) {
            foodData = new ArrayList<String[]>();
            foodData.add(foodArray);
            foodChoice.addItem(foodArray[0]);
        }

        void addFoodToTable() {

            String[] s = new String[3];
            s = (String[]) foodData.get(foodChoice.getSelectedIndex());
            System.out.println(foodData.get(0));
            System.out.println(foodData.get(1));
        }

addFoodToTable gets called with a button click. So the issue I'm having is that (based on the sysouts) I will get a pointer address to the first entry in the ArrayList, but then a Null Pointer Exception stating that it is out of bounds for Length 0 when it tries to print the second one to console. This is obviously after calling createFood() 3 or four times in order to populate foodData. I can provide additional code if required, it's just too much to place in whole into this post. Thanks!


问:
Full outer join like functionality but merging columns
TableA

```<code>id  | symbolA
 1       m
 2       n
 4       o
</code>```

TableB

```<code>id  | symbolB
 2       p
 3       q
 5       r
</code>```

I'd like the following result:

```<code>id    |  symbolA     | symbolB
2          n              p
1          m              NULL
4          o              NULL
3          NULL           q
5          NULL           r
</code>```

This is what I've already tried:

```<code>SELECT
  TableA.id,
  TableB.id,
  TableA.symbolA,
  TableB.symbolB
FROM
  TableA
FULL OUTER JOIN
  TableB
ON
  TableA.id = TableB.id

NewTable
TableA.id | TableA.symbolA | TableB.id | TableA.symbolB
    2             n             2               p
    1             m             NULL            NULL
    4             o             NULL            NULL
    NULL       NULL             3               q
    NULL       NULL             5               r
</code>```

I've already tried a full outer join in combination with a coalesce but it doesn't exactly give me the the above desired output. The language is BigQuery, though I'm hoping there's nothing idiosyncratic about my request that wouldn't make it SQL language agnostic. Thanks.

答:
You are almost there. You just need to merge the two id columns.

For this, you can use coalesce():

```<code>select
    coalesce(a.id, b.id) id,
    a.symbola,
    b.symbolb
from tablea a
full outer join tableb b on a.id = b.id
</code>```

The following syntax that joins with using should also work (most databases that support full join allow this):

```<code>select
    id,
    a.symbola,
    b.symbolb
from tablea a
full outer join tableb b using(id)
</code>```

Body:
TableA

id  | symbolA
 1       m
 2       n
 4       o

TableB

id  | symbolB
 2       p
 3       q
 5       r

I'd like the following result:

id    |  symbolA     | symbolB
2          n              p
1          m              NULL
4          o              NULL
3          NULL           q
5          NULL           r

This is what I've already tried:

SELECT
  TableA.id,
  TableB.id,
  TableA.symbolA,
  TableB.symbolB
FROM
  TableA
FULL OUTER JOIN
  TableB
ON
  TableA.id = TableB.id

NewTable
TableA.id | TableA.symbolA | TableB.id | TableA.symbolB
    2             n             2               p
    1             m             NULL            NULL
    4             o             NULL            NULL
    NULL       NULL             3               q
    NULL       NULL             5               r

I've already tried a full outer join in combination with a coalesce but it doesn't exactly give me the the above desired output. The language is BigQuery, though I'm hoping there's nothing idiosyncratic about my request that wouldn't make it SQL language agnostic. Thanks.

Body:
You are almost there. You just need to merge the two id columns.

For this, you can use coalesce():

select
    coalesce(a.id, b.id) id,
    a.symbola,
    b.symbolb
from tablea a
full outer join tableb b on a.id = b.id

The following syntax that joins with using should also work (most databases that support full join allow this):

select
    id,
    a.symbola,
    b.symbolb
from tablea a
full outer join tableb b using(id)


问:
Error in parsing xml from web service
I have my xml file as a response in result.getProperty(0).

The code is as follows:

```<code>SoapObject result=(SoapObject)envelope.bodyIn;
System.out.println("value of result " + result);
</code>```

How can I store this xml in result.getProperty(0) into my sdcard/any other location so that I can parse it using SAXParser?

Regards,

sneha

答: The getProperty(int)-method returns an Object. If this Object is a String, the SAXParser supports parsing XML from a String: Link

Title: Error in parsing xml from web service

Body:
I have my xml file as a response in result.getProperty(0).

The code is as follows:

SoapObject result=(SoapObject)envelope.bodyIn;
System.out.println("value of result " + result);

How can I store this xml in result.getProperty(0) into my sdcard/any other location so that I can parse it using SAXParser?

Regards,

sneha


问:
tidyverse - filtering within a nested column/list based on number of NA's per row
Trying to extend my own workflow (from columns) here: [1] tidyverse - delete a column within a nested column/list to filtering within a nested column/list, I found this potential solution: [2] Use filter() (and other dplyr functions) inside nested data frames with map()

My problem is that I want to filter in each "nest" on those rows that are not completely NA (i.e. I want to keep any row that has at least one non-missing value.

However, the simple solution in [2] doesn't work for me, probably because I want to filter on the sum of NA's per row, which might involve another map function within the filter.

(Note: I'm using the current github version of dplyr within tidyverse which offers some new experimental functions, like condense - which I'm using below, but I think that's not relevant for my problem/question).

I have the following data:

Data:

```<code>library(tidyverse)
library(corrr)

dat <- data.frame(grp = rep(1:4, each = 25),
                  Q1 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q2 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q3 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q4 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q5 = sample(c(NA), 100, replace = TRUE),
                  Q6 = sample(c(1:5, NA), 100, replace = TRUE))
</code>```

I now calculate the correlations of Q1 to Q6 per group and delete the rowname column.

```<code>cor_dat <- dat %>%
  group_by(grp) %>%
  condense(cor = correlate(cur_data()) %>%
         select(-rowname)) %>%
  ungroup()
</code>```

But adding this line to my pipeline doesn't work:

```<code>cor_dat <- cor_dat %>%
  mutate(cor = map(cor, ~ filter(., sum(is.na(.)) != ncol(.))))
</code>```

I also tried, but this doesn't work either:

```<code>cor_dat <- cor_dat %>%
      mutate(cor = map(cor, ~ filter(., !all(is.na(.)))))
</code>```

Expected outcome in my data would be that the fifth row in each nest is filtered out.

答:
Here, we can use filter_all

```<code>library(dplyr)
library(purrr)
cor_dat <- cor_dat %>%
               mutate(cor = map(cor, ~ .x %>%
                              filter_all(any_vars(!is.na(.)))))
cor_dat
# A tibble: 4 x 2
#    grp cor
#  <int> <list>
#1     1 <tibble [5 × 6]>
#2     2 <tibble [5 × 6]>
#3     3 <tibble [5 × 6]>
#4     4 <tibble [5 × 6]>

cor_dat$cor[[1]]
# A tibble: 5 x 6
#       Q1      Q2      Q3      Q4    Q5      Q6
#    <dbl>   <dbl>   <dbl>   <dbl> <dbl>   <dbl>
#1 NA      -0.226   0.288  -0.0536    NA  0.581
#2 -0.226  NA      -0.382   0.212     NA  0.0274
#3  0.288  -0.382  NA      -0.0772    NA -0.153
#4 -0.0536  0.212  -0.0772 NA         NA  0.0831
#5  0.581   0.0274 -0.153   0.0831    NA NA
</code>```

Or if we need to use filter then create the logic with rowSums

```<code>cor_dat %>%
       mutate(cor = map(cor, ~ .x %>%
                                  filter(rowSums(is.na(.)) < ncol(.))))
</code>```

data

```<code>cor_dat <- dat %>%
   group_by(grp) %>%
   condense(cor = correlate(cur_data()) %>%
                 select(-rowname)) %>%
   ungroup
</code>```

Body:
Trying to extend my own workflow (from columns) here: [1] tidyverse - delete a column within a nested column/list to filtering within a nested column/list, I found this potential solution: [2] Use filter() (and other dplyr functions) inside nested data frames with map()

My problem is that I want to filter in each "nest" on those rows that are not completely NA (i.e. I want to keep any row that has at least one non-missing value.

However, the simple solution in [2] doesn't work for me, probably because I want to filter on the sum of NA's per row, which might involve another map function within the filter.

(Note: I'm using the current github version of dplyr within tidyverse which offers some new experimental functions, like condense - which I'm using below, but I think that's not relevant for my problem/question).

I have the following data:

Data:

library(tidyverse)
library(corrr)

dat <- data.frame(grp = rep(1:4, each = 25),
                  Q1 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q2 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q3 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q4 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q5 = sample(c(NA), 100, replace = TRUE),
                  Q6 = sample(c(1:5, NA), 100, replace = TRUE))

I now calculate the correlations of Q1 to Q6 per group and delete the rowname column.

cor_dat <- dat %>%
  group_by(grp) %>%
  condense(cor = correlate(cur_data()) %>%
         select(-rowname)) %>%
  ungroup()

But adding this line to my pipeline doesn't work:

cor_dat <- cor_dat %>%
  mutate(cor = map(cor, ~ filter(., sum(is.na(.)) != ncol(.))))

I also tried, but this doesn't work either:

cor_dat <- cor_dat %>%
      mutate(cor = map(cor, ~ filter(., !all(is.na(.)))))

Expected outcome in my data would be that the fifth row in each nest is filtered out.

Body:
Here, we can use filter_all

library(dplyr)
library(purrr)
cor_dat <- cor_dat %>%
               mutate(cor = map(cor, ~ .x %>%
                              filter_all(any_vars(!is.na(.)))))
cor_dat
# A tibble: 4 x 2
#    grp cor
#  <int> <list>
#1     1 <tibble [5 × 6]>
#2     2 <tibble [5 × 6]>
#3     3 <tibble [5 × 6]>
#4     4 <tibble [5 × 6]>

cor_dat$cor[[1]]
# A tibble: 5 x 6
#       Q1      Q2      Q3      Q4    Q5      Q6
#    <dbl>   <dbl>   <dbl>   <dbl> <dbl>   <dbl>
#1 NA      -0.226   0.288  -0.0536    NA  0.581
#2 -0.226  NA      -0.382   0.212     NA  0.0274
#3  0.288  -0.382  NA      -0.0772    NA -0.153
#4 -0.0536  0.212  -0.0772 NA         NA  0.0831
#5  0.581   0.0274 -0.153   0.0831    NA NA

Or if we need to use filter then create the logic with rowSums

cor_dat %>%
       mutate(cor = map(cor, ~ .x %>%
                                  filter(rowSums(is.na(.)) < ncol(.))))

data

cor_dat <- dat %>%
   group_by(grp) %>%
   condense(cor = correlate(cur_data()) %>%
                 select(-rowname)) %>%
   ungroup


问:
How to force the gravity of bubbles in D3.js
In the code below, I need to make the bubbles with the highest values float to the left of the screen, but I have no deep knowledge of D3.js and I can't find a way to do this.

My code

```<code><script type="text/javascript">

     dataset = {
        "children": [{"Name":"Olives","Count":10},
            {"Name":"Tea","Count":8},
            {"Name":"Mashed Potatoes","Count":6},
            {"Name":"Boiled Potatoes","Count":5},
            {"Name":"Milk","Count":4},
            {"Name":"Chicken Salad","Count":4},
            {"Name":"Vanilla Ice Cream","Count":2},
            {"Name":"Cocoa","Count":7}];

    var diameter = 600;
    var color = d3.scaleOrdinal(d3.schemeCategory20);

    var bubble = d3.pack(dataset)
        .size([diameter, diameter])
        .padding(1.5);

    var svg = d3.select("body")
        .append("svg")
        .attr("width", diameter)
        .attr("height", diameter)
        .attr("class", "bubble");

    var nodes = d3.hierarchy(dataset)
        .sum(function(d) { return d.Count; });

    var node = svg.selectAll(".node")
        .data(bubble(nodes).descendants())
        .enter()
        .filter(function(d){
            return  !d.children
        })
        .append("g")
        .attr("class", "node")
        .attr("transform", function(d) {
            return "translate(" + d.x + "," + d.y + ")";
        });

    node.append("title")
        .text(function(d) {
            return d.Name + ": " + d.Count;
        });

    node.append("circle")
        .attr("r", function(d) {
            return d.r;
        })
        .style("fill", function(d,i) {
            return color(i);
        });

    node.append("text")
        .attr("dy", ".2em")
        .style("text-anchor", "middle")
        .text(function(d) {
            return d.data.Name.substring(0, d.r / 3);
        })
        .attr("font-family", "sans-serif")
        .attr("font-size", function(d){
            return d.r/5;
        })
        .attr("fill", "white");

    node.append("text")
        .attr("dy", "1.3em")
        .style("text-anchor", "middle")
        .text(function(d) {
            return d.data.Count;
        })
        .attr("font-family",  "Gill Sans", "Gill Sans MT")
        .attr("font-size", function(d){
            return d.r/5;
        })
        .attr("fill", "white");

    d3.select(self.frameElement)
        .style("height", diameter + "px");

</script>
</code>```

Edit in JS Fiddle

The code produces this result

I need the bubbles with the highest values to be on the left, as in the image below.

What property or function of D3.js can I use to control the severity of the bubbles as I need them?
Thanks!

答:
There's not a function specifically in d3.pack for this. d3.force allows you specify x and y positions based on the data's value, and could achieve the result you are looking for.

The force simulation has an .x and .y function that is based on the data's count, and then to avoid overlaps, the .collide function adjusts the circles positions based on their radius (plus a small paddding of 3px).

```<code> var simulation = d3.forceSimulation(nodes)
        .force("forceX", d3.forceX().strength(.051).x(d => xScale(d.Count)))
        .force("forceY", d3.forceY().strength(.051).y(d => yScale(d.Count)))
        .force('collision', d3.forceCollide().radius(d => rScale(d.Count) + 3))
</code>```

dataset = {
        "children": [{"Name":"Olives","Count":10},
            {"Name":"Tea","Count":8},
            {"Name":"Mashed Potatoes","Count":6},
            {"Name":"Boiled Potatoes","Count":5},
            {"Name":"Milk","Count":4},
            {"Name":"Chicken Salad","Count":4},
            {"Name":"Vanilla Ice Cream","Count":2},
            {"Name":"Cocoa","Count":7}]
    }

    let nodes = dataset.children

    var width = 600;
    var height = 600;
    var margin = 50
    var color = d3.scaleOrdinal(d3.schemeCategory20);

    let extentCount = d3.extent(nodes, d => d.Count)
    let maxRadius = 100

    let yScale = d3.scaleLinear()
     .domain(extentCount)
     .range([height - maxRadius, maxRadius])

    let xScale = d3.scaleLinear()
     .domain(extentCount)
     .range([(width - maxRadius), maxRadius])

    let rScale = d3.scaleSqrt()
     .domain(extentCount)
     .range([5, maxRadius])

    var svg = d3.select("body")
        .append("svg")
        .attr("width", width + margin + margin)
        .attr("height", height + margin + margin)
        .attr("class", "bubble");

    var g = svg.append("g")
     .attr("transform", "translate(" + margin + "," + margin + ")")

    var simulation = d3.forceSimulation(nodes)
        .force("forceX", d3.forceX().strength(.051).x(d => xScale(d.Count)))
        .force("forceY", d3.forceY().strength(.051).y(d => yScale(d.Count)))
        .force('collision', d3.forceCollide().radius(d => rScale(d.Count) + 3))
      .on("tick", function(d){
            node
                .attr("cx", function(d){ return d.x; })
                .attr("cy", function(d){ return d.y; })
          })
      .stop()

    for (var i = 0; i < 120; i++) {
      simulation.tick()
    }

    var node = g.selectAll(".node")
        .data(nodes)
        .enter()
        .append("g")
        .attr("class", "node")
        .attr("transform", function(d) {
            return "translate(" + d.x + "," + d.y + ")";
        });

    node.append("title")
        .text(function(d) {
            return d.Name + ": " + d.Count;
        });

    node.append("circle")
        .attr("r", d => rScale(d.Count))
        .style("fill", function(d,i) {
            return color(i);
        });

    node.append("text")
        .attr("dy", ".2em")
        .style("text-anchor", "middle")
        .text(function(d) {
            return d.Name.substring(0, rScale(d.Count) / 3);
        })
        .attr("font-family", "sans-serif")
        .attr("font-size", function(d){
            return rScale(d.Count)/5;
        })
        .attr("fill", "white");

    node.append("text")
        .attr("dy", "1.3em")
        .style("text-anchor", "middle")
        .text(function(d) {
            return d.Count;
        })
        .attr("font-family",  "Gill Sans", "Gill Sans MT")
        .attr("font-size", function(d){
            return d.r/5;
        })
        .attr("fill", "white");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script></code>```

Body:
In the code below, I need to make the bubbles with the highest values float to the left of the screen, but I have no deep knowledge of D3.js and I can't find a way to do this.

My code

Edit in JS Fiddle

The code produces this result

I need the bubbles with the highest values to be on the left, as in the image below.

What property or function of D3.js can I use to control the severity of the bubbles as I need them?
Thanks!

Body:
There's not a function specifically in d3.pack for this. d3.force allows you specify x and y positions based on the data's value, and could achieve the result you are looking for.

The force simulation has an .x and .y function that is based on the data's count, and then to avoid overlaps, the .collide function adjusts the circles positions based on their radius (plus a small paddding of 3px).

 var simulation = d3.forceSimulation(nodes)
        .force("forceX", d3.forceX().strength(.051).x(d => xScale(d.Count)))
        .force("forceY", d3.forceY().strength(.051).y(d => yScale(d.Count)))
        .force('collision', d3.forceCollide().radius(d => rScale(d.Count) + 3))

dataset = {
        "children": [{"Name":"Olives","Count":10},
            {"Name":"Tea","Count":8},
            {"Name":"Mashed Potatoes","Count":6},
            {"Name":"Boiled Potatoes","Count":5},
            {"Name":"Milk","Count":4},
            {"Name":"Chicken Salad","Count":4},
            {"Name":"Vanilla Ice Cream","Count":2},
            {"Name":"Cocoa","Count":7}]
    }

    let nodes = dataset.children

    var width = 600;
    var height = 600;
    var margin = 50
    var color = d3.scaleOrdinal(d3.schemeCategory20);

    let extentCount = d3.extent(nodes, d => d.Count)
    let maxRadius = 100

    let yScale = d3.scaleLinear()
     .domain(extentCount)
     .range([height - maxRadius, maxRadius])

    let xScale = d3.scaleLinear()
     .domain(extentCount)
     .range([(width - maxRadius), maxRadius])

    let rScale = d3.scaleSqrt()
     .domain(extentCount)
     .range([5, maxRadius])

    var svg = d3.select("body")
        .append("svg")
        .attr("width", width + margin + margin)
        .attr("height", height + margin + margin)
        .attr("class", "bubble");

    var g = svg.append("g")
     .attr("transform", "translate(" + margin + "," + margin + ")")

    var simulation = d3.forceSimulation(nodes)
        .force("forceX", d3.forceX().strength(.051).x(d => xScale(d.Count)))
        .force("forceY", d3.forceY().strength(.051).y(d => yScale(d.Count)))
        .force('collision', d3.forceCollide().radius(d => rScale(d.Count) + 3))
      .on("tick", function(d){
            node
                .attr("cx", function(d){ return d.x; })
                .attr("cy", function(d){ return d.y; })
          })
      .stop()

    for (var i = 0; i < 120; i++) {
      simulation.tick()
    }

    var node = g.selectAll(".node")
        .data(nodes)
        .enter()
        .append("g")
        .attr("class", "node")
        .attr("transform", function(d) {
            return "translate(" + d.x + "," + d.y + ")";
        });

    node.append("title")
        .text(function(d) {
            return d.Name + ": " + d.Count;
        });

    node.append("circle")
        .attr("r", d => rScale(d.Count))
        .style("fill", function(d,i) {
            return color(i);
        });

    node.append("text")
        .attr("dy", ".2em")
        .style("text-anchor", "middle")
        .text(function(d) {
            return d.Name.substring(0, rScale(d.Count) / 3);
        })
        .attr("font-family", "sans-serif")
        .attr("font-size", function(d){
            return rScale(d.Count)/5;
        })
        .attr("fill", "white");

    node.append("text")
        .attr("dy", "1.3em")
        .style("text-anchor", "middle")
        .text(function(d) {
            return d.Count;
        })
        .attr("font-family",  "Gill Sans", "Gill Sans MT")
        .attr("font-size", function(d){
            return d.r/5;
        })
        .attr("fill", "white");

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>


问:
Disable untitled editor improvement - first line name in the title
Is there any to revert/disable the newest change for the untitled tab name (https://code.visualstudio.com/updates/v1_42#_untitled-editor-improvements)  </p>

<p>I would prefer to the untitled-1 than the first sentence line. </p>

答:
As your link says:

Note: If the first line is empty or does not contain any words, the
  title will fall back to Untitled-* as before.

I don't think there is a way to disable it other than to have that first line blank until you do give it a name.

The request for a setting to disable the current functionality is tracked here: https://github.com/microsoft/vscode/issues/90378 (Config to limit/disable the new Untitled tab auto-naming) or https://github.com/microsoft/vscode/issues/90495

you could upvote that issue.

----------  update, coming in v1.43:

A new setting workbench.editor.untitled.labelFormat lets you control
  whether untitled editors should use the file contents as the title or
  not. Possible values are content or name. Configure
  'workbench.editor.untitled.labelFormat': 'name' for the previous
  behavior, where untitled editors would have a short title, such as
  Untitled-1.

When pasting text into an untitled editor, VS Code now automatically
  tries to detect the language mode from the first line of text. For
  example, pasting XML will set the XML mode automatically upon paste if
  the first line contains the typical XML header .

Body:
Is there any to revert/disable the newest change for the untitled tab name (https://code.visualstudio.com/updates/v1_42#_untitled-editor-improvements)

I would prefer to the untitled-1 than the first sentence line.


问:
How to import a helper class in buildSrc/build.gradle.kts, settings.gradle.kts, and build.gradle.kts?
I'd like to create a class to help me loading different types of properties (local.properties, gradle.properties, $GRADLE_HOME/gradle.properties, environment variables, system properties, and custom properties files (maybe in other formats like yml, xml, etc.).

Also, I'd like to use this in my buildSrc/build.gradle.kts, settings.gradle.kts, and build.gradle.kts.

Please consider that we are using Gradle 6.+.

A simple implementation of this class would be (the full implementation would be a lot of more powerful):

plugins/properties/build.gradle.kts:

```<code>package com.example

object Properties {
    val environmentVariables = System.getenv()
}
</code>```

How can we successfully import this Properties class in all of those files (buildSrc/build.gradle.kts, settings.gradle.kts, build.gradle.kts) and use it from there? Something like:

println(com.example.Properties.environmentVariables["my.property"])

Can we do that creating this class inside of a plugin and applying it from there? Without pre-compiling and releasing the plugin? Maybe something like:

apply("plugins/properties/build.gradle.kts")

How would it be a minimal implementation for this?

I tried different approaches but I'm not being able to find a way that work with those 3 files altogether.

答:
I'm not completely satisfied with this approach but maybe it can help others.
I wasn't able to reuse a class but a function in all places, like this:

settings.gradle.kts

```<code>apply("plugin/properties/build.gradle.kts")
@Suppress("unchecked_cast", "nothing_to_inline")
inline fun <T> uncheckedCast(target: Any?): T = target as T
val getProperty = uncheckedCast<(key: String) -> String>(extra["getProperty"])
println(getProperty("group"))
</code>```

buildSrc/build.gradle.kts

```<code>apply("../plugin/properties/build.gradle.kts")
@Suppress("unchecked_cast", "nothing_to_inline")
inline fun <T> uncheckedCast(target: Any?): T = target as T
val getProperty = uncheckedCast<(key: String) -> String>(extra["getProperty"])
println(getProperty("group"))
</code>```

build.gradle.kts

```<code>// Can be used inside of the file
apply("plugin/properties/build.gradle.kts")
@Suppress("unchecked_cast", "nothing_to_inline")
inline fun <T> uncheckedCast(target: Any?): T = target as T
val getProperty = uncheckedCast<(key: String) -> String>(extra["getProperty"])
println(getProperty("group"))

buildScript {
    // Since the other getProperty is not visible here we need to do this again.
    apply("plugin/properties/build.gradle.kts")
    @Suppress("unchecked_cast", "nothing_to_inline")
    inline fun <T> uncheckedCast(target: Any?): T = target as T
    val getProperty = uncheckedCast<(key: String) -> String>(extra["getProperty"])
    println(getProperty("group"))
}
</code>```

plugin/properties/build.gradle.kts

```<code>import java.io.File
import java.nio.file.Path
import java.nio.file.Paths
import java.util.Properties as JavaProperties
import org.gradle.api.initialization.ProjectDescriptor

object Properties {

    lateinit var rootProjectAbsolutePath : String

    val local: JavaProperties by lazy {
        loadProperties(JavaProperties(), Paths.get(rootProjectAbsolutePath, "local.properties").toFile())
    }

    val environment by lazy {
        System.getenv()
    }

    val system: JavaProperties = JavaProperties()

    val gradle: JavaProperties by lazy {
        loadProperties(JavaProperties(), Paths.get(rootProjectAbsolutePath, "gradle.properties").toFile())
    }

    val globalGradle: JavaProperties by lazy {
        loadProperties(JavaProperties(), Paths.get(System.getProperty("user.home"), ".gradle", "gradle.properties").toFile())
    }

    fun containsKey(vararg keys: String): Boolean {
        if (keys.isNullOrEmpty()) return false

        keys.forEach {
            when {
                local.containsKey(it) -> return true
                environment.containsKey(it) -> return true
                system.containsKey(it) -> return true
                gradle.containsKey(it) -> return true
                globalGradle.containsKey(it) -> return true
            }
        }

        return false
    }

    fun get(vararg keys: String): String {
        return this.getAndCast<String>(*keys) ?: throw IllegalArgumentException("Property key(s) ${keys} not found.")
    }

    fun getOrNull(vararg keys: String): String? {
        return getAndCast<String>(*keys)
    }

    inline fun <reified R> getOrDefault(vararg keys: String, default: R?): R? {
        return getAndCast<R>(*keys) ?: default
    }

    inline fun <reified R> getAndCast(vararg keys: String): R? {
        if (keys.isNullOrEmpty()) return null

        keys.forEach {
            val value = when {
                local.containsKey(it) -> local[it]
                environment.containsKey(it) -> environment[it]
                system.containsKey(it) -> system[it]
                gradle.containsKey(it) -> gradle[it]
                globalGradle.containsKey(it) -> globalGradle[it]
                else -> null
            }

            // TODO Improve the casting using Jackson
            if (value != null) return value as R
        }

        return null
    }

    private fun loadProperties(target: JavaProperties, file: File): JavaProperties {
        if (file.canRead()) {
            file.inputStream().use { target.load(it) }
        }

        return target
    }
}

if (rootProject.name == "buildSrc") {
    Properties.rootProjectAbsolutePath = rootDir.parent
} else {
    Properties.rootProjectAbsolutePath = rootDir.absolutePath
}

extra["getProperty"] = {key: String -> Properties.get(key)}
</code>```

Body:
I'd like to create a class to help me loading different types of properties (local.properties, gradle.properties, $GRADLE_HOME/gradle.properties, environment variables, system properties, and custom properties files (maybe in other formats like yml, xml, etc.).

Also, I'd like to use this in my buildSrc/build.gradle.kts, settings.gradle.kts, and build.gradle.kts.

Please consider that we are using Gradle 6.+.

A simple implementation of this class would be (the full implementation would be a lot of more powerful):

plugins/properties/build.gradle.kts:

package com.example

object Properties {
    val environmentVariables = System.getenv()
}

How can we successfully import this Properties class in all of those files (buildSrc/build.gradle.kts, settings.gradle.kts, build.gradle.kts) and use it from there? Something like:

println(com.example.Properties.environmentVariables["my.property"])

Can we do that creating this class inside of a plugin and applying it from there? Without pre-compiling and releasing the plugin? Maybe something like:

apply("plugins/properties/build.gradle.kts")

How would it be a minimal implementation for this?

I tried different approaches but I'm not being able to find a way that work with those 3 files altogether.

Body:
I'm not completely satisfied with this approach but maybe it can help others.
I wasn't able to reuse a class but a function in all places, like this:

settings.gradle.kts

apply("plugin/properties/build.gradle.kts")
@Suppress("unchecked_cast", "nothing_to_inline")
inline fun <T> uncheckedCast(target: Any?): T = target as T
val getProperty = uncheckedCast<(key: String) -> String>(extra["getProperty"])
println(getProperty("group"))

buildSrc/build.gradle.kts

apply("../plugin/properties/build.gradle.kts")
@Suppress("unchecked_cast", "nothing_to_inline")
inline fun <T> uncheckedCast(target: Any?): T = target as T
val getProperty = uncheckedCast<(key: String) -> String>(extra["getProperty"])
println(getProperty("group"))

build.gradle.kts

// Can be used inside of the file
apply("plugin/properties/build.gradle.kts")
@Suppress("unchecked_cast", "nothing_to_inline")
inline fun <T> uncheckedCast(target: Any?): T = target as T
val getProperty = uncheckedCast<(key: String) -> String>(extra["getProperty"])
println(getProperty("group"))

buildScript {
    // Since the other getProperty is not visible here we need to do this again.
    apply("plugin/properties/build.gradle.kts")
    @Suppress("unchecked_cast", "nothing_to_inline")
    inline fun <T> uncheckedCast(target: Any?): T = target as T
    val getProperty = uncheckedCast<(key: String) -> String>(extra["getProperty"])
    println(getProperty("group"))
}

plugin/properties/build.gradle.kts

import java.io.File
import java.nio.file.Path
import java.nio.file.Paths
import java.util.Properties as JavaProperties
import org.gradle.api.initialization.ProjectDescriptor

object Properties {

    lateinit var rootProjectAbsolutePath : String

    val local: JavaProperties by lazy {
        loadProperties(JavaProperties(), Paths.get(rootProjectAbsolutePath, "local.properties").toFile())
    }

    val environment by lazy {
        System.getenv()
    }

    val system: JavaProperties = JavaProperties()

    val gradle: JavaProperties by lazy {
        loadProperties(JavaProperties(), Paths.get(rootProjectAbsolutePath, "gradle.properties").toFile())
    }

    val globalGradle: JavaProperties by lazy {
        loadProperties(JavaProperties(), Paths.get(System.getProperty("user.home"), ".gradle", "gradle.properties").toFile())
    }

    fun containsKey(vararg keys: String): Boolean {
        if (keys.isNullOrEmpty()) return false

        keys.forEach {
            when {
                local.containsKey(it) -> return true
                environment.containsKey(it) -> return true
                system.containsKey(it) -> return true
                gradle.containsKey(it) -> return true
                globalGradle.containsKey(it) -> return true
            }
        }

        return false
    }

    fun get(vararg keys: String): String {
        return this.getAndCast<String>(*keys) ?: throw IllegalArgumentException("Property key(s) ${keys} not found.")
    }

    fun getOrNull(vararg keys: String): String? {
        return getAndCast<String>(*keys)
    }

    inline fun <reified R> getOrDefault(vararg keys: String, default: R?): R? {
        return getAndCast<R>(*keys) ?: default
    }

    inline fun <reified R> getAndCast(vararg keys: String): R? {
        if (keys.isNullOrEmpty()) return null

        keys.forEach {
            val value = when {
                local.containsKey(it) -> local[it]
                environment.containsKey(it) -> environment[it]
                system.containsKey(it) -> system[it]
                gradle.containsKey(it) -> gradle[it]
                globalGradle.containsKey(it) -> globalGradle[it]
                else -> null
            }

            // TODO Improve the casting using Jackson
            if (value != null) return value as R
        }

        return null
    }

    private fun loadProperties(target: JavaProperties, file: File): JavaProperties {
        if (file.canRead()) {
            file.inputStream().use { target.load(it) }
        }

        return target
    }
}

if (rootProject.name == "buildSrc") {
    Properties.rootProjectAbsolutePath = rootDir.parent
} else {
    Properties.rootProjectAbsolutePath = rootDir.absolutePath
}

extra["getProperty"] = {key: String -> Properties.get(key)}


问:
try-catch blocks with the return type
If I have a method that returns something, like

```<code>public DataTable ReturnSomething()
{
   try
   {
      //logic here
     return ds.Tables[0];
   }
   catch (Exception e)
   {
      ErrorString=e.Message;
   }
}
</code>```

This produces compiler error, obviously because catch{} block does not return anything.

So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?

答: It depends on you application. You can return null, an empty DataTable or whatever is suitable under circumstances.

OwnerDisplayName: Julia

LastEditorDisplayName: Daniel L

ContentLicense: CC BY-SA 2.5

Title: try-catch blocks with the return type

Body:
If I have a method that returns something, like

public DataTable ReturnSomething()
{
   try
   {
      //logic here
     return ds.Tables[0];
   }
   catch (Exception e)
   {
      ErrorString=e.Message;
   }
}

This produces compiler error, obviously because catch{} block does not return anything.

So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?

OwnerDisplayName: Anton Gogolev


问:
Trying to filter an array from a JSON file with a condition
This is probably a simple thing but I'm a novice and very confused.

```<code>  const filteredFloors = state.cfAllFloors.json.filter(floor => {
    return floor.fields.building.fields.slug === 'Library'
  })
</code>```

I would like to change the condition on this object to first check if the building exists, if it does, then check to see if it matches 'Library'.

I keep getting "TypeError: Cannot read property 'fields' of undefined" and I suspect it is because some of the array items don't have this property.

答:
```<code>const filteredFloors = state.cfAllFloors.json.filter(floor => {
    return floor && floor.fields && floor.fields.building && floor.fields.building.fields && floor.fields.building.fields.slug === 'Library'
  })
</code>```

will return false if any of the properties in that chain are null or if the final .slug is not equal to 'Library'.

A null value is not "truthy" and thus checking the object will return false if it is null or true if it has any value.

Body:
This is probably a simple thing but I'm a novice and very confused.

  const filteredFloors = state.cfAllFloors.json.filter(floor => {
    return floor.fields.building.fields.slug === 'Library'
  })

I would like to change the condition on this object to first check if the building exists, if it does, then check to see if it matches 'Library'.

I keep getting "TypeError: Cannot read property 'fields' of undefined" and I suspect it is because some of the array items don't have this property.

Body:
const filteredFloors = state.cfAllFloors.json.filter(floor => {
    return floor && floor.fields && floor.fields.building && floor.fields.building.fields && floor.fields.building.fields.slug === 'Library'
  })

will return false if any of the properties in that chain are null or if the final .slug is not equal to 'Library'.

A null value is not "truthy" and thus checking the object will return false if it is null or true if it has any value.


问:
Page count of Pdf with Java
at the moment I am using itext to read the page count of a pdf. This takes quite long because the lib seems to scan the whole file.

Is the page information somewhere in the header of the pdf, or is a full filescan needed?

答:
```<code>PdfReader document = new PdfReader(new FileInputStream(new File("filename")));
int noPages = document.getNumberOfPages();
</code>```

above is the process for counting the pdf pages

Title: Page count of Pdf with Java

Body:
PdfReader document = new PdfReader(new FileInputStream(new File("filename")));
int noPages = document.getNumberOfPages();

above is the process for counting the pdf pages


问:
Bash test value of last function equal to zero
Using blueutil to try to connect or disconnect my headphones, when you test using the --is-connected it returns either a 0 or 1. I want to use that to either connect or disconnect the headphones, but I keep getting a "0: command not found" error.</p>

```<code>blueutil --is-connected ac-90-85-3e-0d-04
if $? -eq 0
  then
    blueutil --connect ac-90-85-3e-0d-04
  else
    blueutil --disconnect ac-90-85-3e-0d-04
fi
</code>```

答:
The shell doesn't do comparisons by itself; that's the job of the test command:

```<code>if test $? -eq 0
</code>```

though all if does is look at the exit status of its condition list; you can call blueutil directly from that list.

```<code>if blueutil --is-connected ac-90-85-3e-0d-04
  then
    blueutil --connect ac-90-85-3e-0d-04
  else
    blueutil --disconnect ac-90-85-3e-0d-04
fi
</code>```

Body:
Using blueutil to try to connect or disconnect my headphones, when you test using the --is-connected it returns either a 0 or 1. I want to use that to either connect or disconnect the headphones, but I keep getting a "0: command not found" error.

blueutil --is-connected ac-90-85-3e-0d-04
if $? -eq 0
  then
    blueutil --connect ac-90-85-3e-0d-04
  else
    blueutil --disconnect ac-90-85-3e-0d-04
fi

Body:
The shell doesn't do comparisons by itself; that's the job of the test command:

if test $? -eq 0

though all if does is look at the exit status of its condition list; you can call blueutil directly from that list.

if blueutil --is-connected ac-90-85-3e-0d-04
  then
    blueutil --connect ac-90-85-3e-0d-04
  else
    blueutil --disconnect ac-90-85-3e-0d-04
fi


问:
Adjust horizontal scrolling div to content
I'm developing a web with horizontal scrolling sections. For that I have used only CSS. My code rotates the container to make the horizontal scrolling the 'natural' one. What I would like is to adjust the width of the container to the images it contains, so it doesn't allow you to scroll further than the images. Here's my html and css code

.slide {
  height: 80vh;
  background-size: auto 100vh;
  background-repeat: repeat-x;
  width: 2000vw;
}

.wrapper {
  display: flex;
  flex-direction: row;
  width: 2000vw;
  transform: rotate(90deg) translateY(-80vh);
  transform-origin: top left;
}

.outer-wrapper {
  width: 80vh;
  height: 100vw;
  transform: rotate(-90deg) translateX(-80vh);
  transform-origin: top left;
  overflow-y: scroll;
  overflow-x: hidden;
  position: absolute;
  scrollbar-width: none;
  -ms-overflow-style: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div *ngIf="ready" class="container-fluid" id="projects">
  <div class="outer-wrapper">
    <div class="wrapper">
      <div class="slide one">
        <img *ngFor="let image of images" class="img-fluid" [src]="image">
      </div>
    </div>
  </div>
</div></code>```

I have tried changing a lot of combinations of the css but none of them will work for more than one fixed screen size

答:
Which one is closer?

http://deneskellner.com/stackoverflow-examples/60270600/scrollit.html

http://deneskellner.com/stackoverflow-examples/60270600/scrollit-2.html

In the first one I removed your "slide one" div and used the img tags directly inside the wrapper. Also, removed the width setting from .wrapper class.

In the second one, I used divs and background images. They're now huge, covering the screen, and for this to happen, a few things needed to change in the .slide class.

If this is what you wanted to achieve, I'm going to pimp this post a bit so others see what's going on. But I guess it has the desired effect. If not, let's work on it.

(Picture samples are from instagram.com and the original owner is Vola Udabe Randri, aka olaizolav - in case you were wondering)

Body:
I'm developing a web with horizontal scrolling sections. For that I have used only CSS. My code rotates the container to make the horizontal scrolling the 'natural' one. What I would like is to adjust the width of the container to the images it contains, so it doesn't allow you to scroll further than the images. Here's my html and css code

.slide {
  height: 80vh;
  background-size: auto 100vh;
  background-repeat: repeat-x;
  width: 2000vw;
}

.wrapper {
  display: flex;
  flex-direction: row;
  width: 2000vw;
  transform: rotate(90deg) translateY(-80vh);
  transform-origin: top left;
}

.outer-wrapper {
  width: 80vh;
  height: 100vw;
  transform: rotate(-90deg) translateX(-80vh);
  transform-origin: top left;
  overflow-y: scroll;
  overflow-x: hidden;
  position: absolute;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

I have tried changing a lot of combinations of the css but none of them will work for more than one fixed screen size


问:
What is the differences between bind model and contain cakephp?
What is the differences between bind model and contain cakephp? any one have idea please share with me.. I am new to cakephp </p>

答:
Note: this answer relates to version 1.3 of CakePHP which is no longer supported.

One of the most powerful features of CakePHP is the ability to link relational mapping provided by the model. In CakePHP, the links between models are handled through associations.
If you set up these associations in your model, then when you retrieve your data Cake will automagically retrieve associated data too.

The containable behavior allows you to filter and limit model find operations (assuming you have set up your model associations)

https://book.cakephp.org/1.3/en/The-Manual/Core-Behaviors/Containable.html

bind and unbind are useful for changing model associations on the fly:

https://book.cakephp.org/1.3/en/The-Manual/Developing-with-CakePHP/Models.html#creating-and-destroying-associations-on-the-fly