问:
Get number of fragments in each primitive
Is there any way to get the count of fragments (pixels) before the depth test for each primitive (triangle)? I tried using opengl queries, but they seem to be very slow.

If there is no builtin mechanism I was considering using some image store or atomics mechanism, but I have no experience with these features. If that helps - I am able to get primitive id into the fragment shader easly, since none of my primitives share vertices.

答:
You want a fragment count before the depth test? There is no way to do that at all. Not in a guaranteed way.

See, while the specification states that depth tests happen after the fragment shader, it can be costly to run a complex FS whose results get discarded due to a simple test. So the "as if" rule allows implementations to attempt to perform fragment tests before the FS, if there would be no behavioral difference between them.

However, while there is an explicit mechanism to turn force early fragment tests, there is no reverse mechanism to preventing early tests. And without that, what you want is impossible.

Now, because early tests are an "as if" optimization, if your FS does something which requires executing the fragment shader before the depth test, then you would force the implementation to not optimize your FS execution. The problem is that the only act which would guarantee such a thing would be changing the value of gl_FragDepth. The depth test is required to respect the fragment shader's gl_FragDepth value, so the depth test must come after the FS's execution.

The problem is that modifying gl_FragDepth means changing the depth of the fragment you generate, which probably isn't what you want. Oh sure, it's possible that simply having gl_FragDepth = gl_FragCoord.z; at the top of your FS's main function is sufficient for an implementation to turn off early tests. But a particularly smart compiler might notice that this FS actually leaves the value of gl_FragDepth unchanged, since its default value really is gl_FragCoord.z. And therefore, it may still get early tests.

Even something like gl_FragDepth = gl_FragCoord.z + 0; could be optimized out; the compiler can see that you're adding nothing, after all.

If you're willing to assume that the compiler isn't smart enough to optimize gl_FragDepth = gl_FragCoord.z or some similar construction, then you can fabricate what you want using existing shader functionality. You can use atomic image load/store or SSBO functionality to increment the fragment counter. Helper invocations don't execute these operations, so you need not worry about that.

And if you really want a per-triangle/line/point fragment count, you can use gl_PrimitiveID to figure out which primitive you're on. This value will be increasing, starting at 0, unless a prior vertex processing stage did something to mess with it. If a geometry shader exists, then the value of gl_PrimitiveID is undefined unless the GS writes a value to it for that primitive. Tessellation shaders can even discard primitives, which can impact the implicit gl_PrimitiveID's value in the fragment shader.

But if you're not playing around with those stages, then gl_PrimitiveID will be a reasonable value.


来源: stackexchange

问:
How to fix RuntimeError "Expected object of scalar type Float but got scalar type Double for argument"?
I'm trying to train a classifier via PyTorch. However, I am experiencing problems with training when I feed the model with training data.
I get this error on y_pred = model(X_trainTensor):

RuntimeError: Expected object of scalar type Float but got scalar type Double for argument #4 'mat1'

Here are key parts of my code:

# Hyper-parameters
D_in = 47  # there are 47 parameters I investigate
H = 33
D_out = 2  # output should be either 1 or 0
```

<pre class="lang-py prettyprint-override"><code># Format and load the data
y = np.array( df['target'] )
X = np.array( df.drop(columns = ['target'], axis = 1) )
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.8)  # split training/test data

X_trainTensor = torch.from_numpy(X_train) # convert to tensors
y_trainTensor = torch.from_numpy(y_train)
X_testTensor = torch.from_numpy(X_test)
y_testTensor = torch.from_numpy(y_test)
</code>```

# Define the model
model = torch.nn.Sequential(
    torch.nn.Linear(D_in, H),
    torch.nn.ReLU(),
    torch.nn.Linear(H, D_out),
    nn.LogSoftmax(dim = 1)
)
```

<pre class="lang-py prettyprint-override"><code># Define the loss function
loss_fn = torch.nn.NLLLoss()
</code>```

for i in range(50):
    y_pred = model(X_trainTensor)
    loss = loss_fn(y_pred, y_trainTensor)
    model.zero_grad()
    loss.backward()
    with torch.no_grad():
        for param in model.parameters():
            param -= learning_rate * param.grad
```

答:
The issue can be fixed by setting the datatype of input to Double i.e torch.float32

I hope the issue came because your datatype is torch.float64.

You can avoid such situations either while setting the data, as explained in one of other answers or make the model type also to the same as of your data. i.e use either float64 or float32.

For debug, print obj.dtype and check for consistency.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to train a classifier via PyTorch. However, I am experiencing problems with training when I feed the model with training data.
I get this error on y_pred = model(X_trainTensor):

RuntimeError: Expected object of scalar type Float but got scalar type Double for argument #4 'mat1'

Here are key parts of my code:

# Hyper-parameters
D_in = 47  # there are 47 parameters I investigate
H = 33
D_out = 2  # output should be either 1 or 0

# Format and load the data
y = np.array( df['target'] )
X = np.array( df.drop(columns = ['target'], axis = 1) )
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.8)  # split training/test data

X_trainTensor = torch.from_numpy(X_train) # convert to tensors
y_trainTensor = torch.from_numpy(y_train)
X_testTensor = torch.from_numpy(X_test)
y_testTensor = torch.from_numpy(y_test)

# Define the model
model = torch.nn.Sequential(
    torch.nn.Linear(D_in, H),
    torch.nn.ReLU(),
    torch.nn.Linear(H, D_out),
    nn.LogSoftmax(dim = 1)
)

# Define the loss function
loss_fn = torch.nn.NLLLoss()

for i in range(50):
    y_pred = model(X_trainTensor)
    loss = loss_fn(y_pred, y_trainTensor)
    model.zero_grad()
    loss.backward()
    with torch.no_grad():
        for param in model.parameters():
            param -= learning_rate * param.grad


问:
Heroku Connect, detect salesforce update in postgres
So I have an app taking advantages of Heroku Connect to sync datas between platforms.
I need to find a way to detect when an update has been made by Salesforce (or at least, when the sync has been executed). I'm using sequelize in nodejs, but of course the hooks don't work since heroku connect works directly on the DB and doesn't use the ORM.
So I'm wondering what are my options here.</p>

答:
The solutions that come to my mind (likely there are more):

check out the Heroku Connect system tables like _trigger_log. This table will give you an exact log of the actions HC took (updates/insert/deletes) with information about the record. Yes, you would need to poll it :)

Postgres brings it's own queue-system with LISTEN and NOTIFY. You an write your own database-trigger that will react on change in the salesforce tables, and have a listening/worker-process on the LISTEN queue in PostgreSQL.


问:
AppSync BatchPutItem not saving items
I'm trying to batch put a number of items to DynamoDB using AppSync. When I call the resolver it throws no errors but nothing is saved to the database.

Schema

```<code>type BoxScore @model {
  id: ID!
  userId: String!
  gameVariant: String!
  complete: Boolean!
  failFact: BoxScoreFact @connection
  totalCorrect: Int!
}

type BoxScoreFact @model {
  id: ID!
  left: Int!
  right: Int!
  gameVariant: String!
  timestamp: Int!
  correct: Boolean!
}

input BatchAddCreateBoxScoreFactInput {
  id: ID
  left: Int!
  right: Int!
  gameVariant: String!
  timestamp: Int!
  correct: Boolean!
  boxScoreFactBoxScoreId: ID!
}
</code>```

IAM Role:

```<code>        "Effect": "Allow",
        "Action": [
            "dynamodb:DeleteItem",
            "dynamodb:GetItem",
            "dynamodb:PutItem",
            "dynamodb:Query",
            "dynamodb:Scan",
            "dynamodb:UpdateItem",
            "dynamodb:BatchGetItem",
            "dynamodb:BatchWriteItem"
        ],
</code>```

Resolver:

```<code>#set($factsdata = [])
#foreach($item in ${ctx.args.facts})
    $util.qr($factsdata.add($util.dynamodb.toMapValues($item)))
#end

{
    "version" : "2018-05-29",
    "operation" : "BatchPutItem",
    "tables" : {
        "TABLENAME": $utils.toJson($factsdata)
    }
}
</code>```

Call from AppSync playground:

Response mapping template:

```<code>  #if($ctx.error)
      ## Append a GraphQL error for that field in the GraphQL response
      $utils.error($ctx.error.message, $ctx.error.message)
  #end

  {
      "boxScoreFacts": $util.toJson({"res": "no error", "ctx": $ctx}),
  }
</code>```

Output template from Function test run:

DynamoDB Table

Where TABLENAME is set equal to the DynamoDB table name that is displayed in the DDB console. So something like BoxScoreFact-woieieie99392-prod.

The table is always empty and the response is null. This is lifted almost straight out of the example from the docs. Also, I should note, that putting one item using the normal create graphql function does put an item to the intended table.

What am I missing here?

答:
It doesn't look like the mandatory id is being passed among your variables. You can try setting it automatically in your resolver:

```<code>#set($factsdata = [])
#foreach($item in ${ctx.args.facts})
    $util.qr($item.put("id", $util.defaultIfNullOrBlank($item.id, $util.autoId())))
    $util.qr($factsdata.add($util.dynamodb.toMapValues($item)))
#end

{
    "version" : "2018-05-29",
    "operation" : "BatchPutItem",
    "tables" : {
        "TABLENAME": $utils.toJson($factsdata)
    }
}
</code>```

Title: AppSync BatchPutItem not saving items

Body:
I'm trying to batch put a number of items to DynamoDB using AppSync. When I call the resolver it throws no errors but nothing is saved to the database.

Schema

type BoxScore @model {
  id: ID!
  userId: String!
  gameVariant: String!
  complete: Boolean!
  failFact: BoxScoreFact @connection
  totalCorrect: Int!
}

type BoxScoreFact @model {
  id: ID!
  left: Int!
  right: Int!
  gameVariant: String!
  timestamp: Int!
  correct: Boolean!
}

input BatchAddCreateBoxScoreFactInput {
  id: ID
  left: Int!
  right: Int!
  gameVariant: String!
  timestamp: Int!
  correct: Boolean!
  boxScoreFactBoxScoreId: ID!
}

IAM Role:

        "Effect": "Allow",
        "Action": [
            "dynamodb:DeleteItem",
            "dynamodb:GetItem",
            "dynamodb:PutItem",
            "dynamodb:Query",
            "dynamodb:Scan",
            "dynamodb:UpdateItem",
            "dynamodb:BatchGetItem",
            "dynamodb:BatchWriteItem"
        ],

Resolver:

#set($factsdata = [])
#foreach($item in ${ctx.args.facts})
    $util.qr($factsdata.add($util.dynamodb.toMapValues($item)))
#end

{
    "version" : "2018-05-29",
    "operation" : "BatchPutItem",
    "tables" : {
        "TABLENAME": $utils.toJson($factsdata)
    }
}

Call from AppSync playground:

Response mapping template:

  #if($ctx.error)
      ## Append a GraphQL error for that field in the GraphQL response
      $utils.error($ctx.error.message, $ctx.error.message)
  #end

  {
      "boxScoreFacts": $util.toJson({"res": "no error", "ctx": $ctx}),
  }

Output template from Function test run:

DynamoDB Table

Where TABLENAME is set equal to the DynamoDB table name that is displayed in the DDB console. So something like BoxScoreFact-woieieie99392-prod.

The table is always empty and the response is null. This is lifted almost straight out of the example from the docs. Also, I should note, that putting one item using the normal create graphql function does put an item to the intended table.

What am I missing here?

Body:
It doesn't look like the mandatory id is being passed among your variables. You can try setting it automatically in your resolver:

#set($factsdata = [])
#foreach($item in ${ctx.args.facts})
    $util.qr($item.put("id", $util.defaultIfNullOrBlank($item.id, $util.autoId())))
    $util.qr($factsdata.add($util.dynamodb.toMapValues($item)))
#end

{
    "version" : "2018-05-29",
    "operation" : "BatchPutItem",
    "tables" : {
        "TABLENAME": $utils.toJson($factsdata)
    }
}


问:
React Native/ Find and apply nth child of flatlist background color?
How to set nth child of flatlist color validation in react native.

I have one for loop condition and I got the nth value of empty part in flatlist. How to apply nth child flatlist style

答:
The object of the callback in renderItem contains a property named index. It will allow you to do this.

You can use this to colorize per nth row. By using the modulo operator. i.e.:

Default background color is blue but it's red every 3rd element:

```<code><FlatList
  data={YOUR_DATA}
  keyExtractor={(item, index) => index}
  renderItem={({item, index}) => (
    <View style={{ backgroundColor: index % 3 === 0 ? 'red' : 'blue' }}>
      <Text>{item.message}</Text>
    </View>
  )}
/>
</code>```

Body:
The object of the callback in renderItem contains a property named index. It will allow you to do this.

You can use this to colorize per nth row. By using the modulo operator. i.e.:

Default background color is blue but it's red every 3rd element:

<FlatList
  data={YOUR_DATA}
  keyExtractor={(item, index) => index}
  renderItem={({item, index}) => (
    <View style={{ backgroundColor: index % 3 === 0 ? 'red' : 'blue' }}>
      <Text>{item.message}</Text>
    </View>
  )}
/>


问:
Determining if the neighbours of a value in an array add up to a set value?
I'm making a simple addition maths game and was wondering how to implement the following.

Say I have this array:

int[] numbers = { 9, 2, 1, 1, 2, 9 };

and I want the user to insert a value of, say, 2 somewhere in the array so that a bunch of consecutively placed numbers in the array including the newly placed value add up to a target value, say, 8. I'll call this combination of numbers a combo.

I want the user to be able to place the 8 anywhere in that array. since 2 + 1 + 1 + 2 = 6 the user should be able to place it anywhere in between those outer 9's.

A proper placement could be {9, 2, *2*, 1, 1, 2, 9} or {9, *2*, 2, 1, 1, 2, 9} for example.

Now the issue I am having implementing this is that I can only get it to work when you place the 2 on the outer sides of a combo, so like in the second example above this paragraph, and not like in the first one.

I do this by:

Looking up the value from the array at startIndex

Add this value to the currentSum

See if the currentSum == targetValue : combo found

Else if the currentSum > targetValue : combo not found

Else set startIndex += 1 (or -1 if placed at the other end) and repeat

But that only solves the issue when the newly placed value is at the outer bounds of a combo.

I realise that I could brute-force my way around this problem by adding up each the contents of each potential sub-array containing the newly-placed value, and then seeing if one of those adds up to the target value of 8, but I am looking for something more elegant.

答:
You can do this by making an array of the summations left and right of your filled in value, stopping the calculation once you reach (or exceed) your target. In this case, I'm using -1 to mark values that don't need to be considered. Consider your example:

```<code>nums = { 9, 2, *2*, 1, 1, 2, 9 }
</code>```

becomes

```<code>sums = { -1, 2, 0, 1, 2, 4, -1 }
</code>```

Now, you can either find (8 - value) in this sequence, meaning your inserted value is at the start or end, or a combination of two values to the right and left of your insertion index that add up to (8 - value). Those are the indexes you're looking for. The reason I'm not counting the inserted value for the sums is that that would cause it to be counted double; it's easier to add it after the fact.

The useful part of this is that you're always only checking around the inserted value.
Consider the next example, still looking for an 8:

```<code>nums = { 3, 4, 3, *2*, 1, 2, 4, 1, 5 }
</code>```

becomes

```<code>sums = { -1, 7, 3, *0*, 1, 3, 7, -1, -1 }
</code>```

While your array is still 9 values long, you already know you only have 6 of those left to check.

Body:
You can do this by making an array of the summations left and right of your filled in value, stopping the calculation once you reach (or exceed) your target. In this case, I'm using -1 to mark values that don't need to be considered. Consider your example:

nums = { 9, 2, *2*, 1, 1, 2, 9 }

becomes

sums = { -1, 2, 0, 1, 2, 4, -1 }

Now, you can either find (8 - value) in this sequence, meaning your inserted value is at the start or end, or a combination of two values to the right and left of your insertion index that add up to (8 - value). Those are the indexes you're looking for. The reason I'm not counting the inserted value for the sums is that that would cause it to be counted double; it's easier to add it after the fact.

The useful part of this is that you're always only checking around the inserted value.
Consider the next example, still looking for an 8:

nums = { 3, 4, 3, *2*, 1, 2, 4, 1, 5 }

becomes

sums = { -1, 7, 3, *0*, 1, 3, 7, -1, -1 }

While your array is still 9 values long, you already know you only have 6 of those left to check.


问:
Why is pip installing an incompatible package version?
I am using pip 20.0.2 on Ubuntu, and installing a bunch of requirements from a requirements file. For some reason, pip is deciding to install idna==2.9(link), even though that is not a compatible version with one of my directly listed dependencies. So I used python -m pipdeptree -r within the virtualenv that I'm installing everything to, and I see this listed for idna:

```<code>idna==2.9
  - cryptography==2.3.1 [requires: idna>=2.1]
  - requests==2.22.0 [requires: idna>=2.5,<2.9]
    - requests-oauthlib==1.3.0 [requires: requests>=2.0.0]
      - social-auth-core==3.2.0 [requires: requests-oauthlib>=0.6.1]
        - social-auth-app-django==2.1.0 [requires: social-auth-core>=1.2.0]
    - responses==0.10.9 [requires: requests>=2.0]
    - social-auth-core==3.2.0 [requires: requests>=2.9.1]
      - social-auth-app-django==2.1.0 [requires: social-auth-core>=1.2.0]
</code>```

As we can see, my two direct dependencies (cryptography and requests), are what require idna. According to those, it looks like pip should decide to install 2.8, because it is the latest version that will fulfill the constraints.

Why is pip instead installing idna 2.9, as indicated by the top line of that output, and this error message when running pip install -r requirements.txt:

```<code>ERROR: requests 2.22.0 has requirement idna<2.9,>=2.5, but you'll have idna 2.9 which is incompatible.
</code>```

EDIT: the contents of requirements.txt and it's children, as requested in the comments:

```<code># requirements.txt
-r requirements/requirements-base.txt
-r requirements/requirements-testing.txt

# requirements-base.txt
cryptography~=2.3.1
pyjwt~=1.6.4
requests~=2.22.0
social-auth-app-django~=2.1.0

# requirements-testing.txt
hypothesis~=3.87.0
pytest~=3.6.2
pytest-django~=3.3.2
pytest-cov~=2.5.1
responses~=0.10.5
</code>```

Edit 2: I've created a minimally viable example. For this example, here is requirements.txt:

```<code>cryptography~=2.3.1
requests~=2.22.0
</code>```

And here are the commands I ran from start to finish in a fresh directory:

```<code>virtualenv -p python3.6 -v venv
source venv/bin/activate
pip install -r requirements.txt --no-cache-dir
</code>```

And the full output:

```<code>Collecting cryptography~=2.3.1
  Downloading cryptography-2.3.1-cp34-abi3-manylinux1_x86_64.whl (2.1 MB)
     |████████████████████████████████| 2.1 MB 2.0 MB/s
Collecting requests~=2.22.0
  Downloading requests-2.22.0-py2.py3-none-any.whl (57 kB)
     |████████████████████████████████| 57 kB 18.5 MB/s
Collecting asn1crypto>=0.21.0
  Downloading asn1crypto-1.3.0-py2.py3-none-any.whl (103 kB)
     |████████████████████████████████| 103 kB 65.4 MB/s
Collecting idna>=2.1
  Downloading idna-2.9-py2.py3-none-any.whl (58 kB)
     |████████████████████████████████| 58 kB 71.4 MB/s
Collecting six>=1.4.1
  Downloading six-1.14.0-py2.py3-none-any.whl (10 kB)
Collecting cffi!=1.11.3,>=1.7
  Downloading cffi-1.14.0-cp36-cp36m-manylinux1_x86_64.whl (399 kB)
     |████████████████████████████████| 399 kB 30.3 MB/s
Collecting urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1
  Downloading urllib3-1.25.8-py2.py3-none-any.whl (125 kB)
     |████████████████████████████████| 125 kB 46.7 MB/s
Collecting certifi>=2017.4.17
  Downloading certifi-2019.11.28-py2.py3-none-any.whl (156 kB)
     |████████████████████████████████| 156 kB 65.1 MB/s
Collecting chardet<3.1.0,>=3.0.2
  Downloading chardet-3.0.4-py2.py3-none-any.whl (133 kB)
     |████████████████████████████████| 133 kB 60.8 MB/s
Collecting pycparser
  Downloading pycparser-2.19.tar.gz (158 kB)
     |████████████████████████████████| 158 kB 25.0 MB/s
Building wheels for collected packages: pycparser
  Building wheel for pycparser (setup.py) ... done
  Created wheel for pycparser: filename=pycparser-2.19-py2.py3-none-any.whl size=111031 sha256=030a1449dd5902f2f03e9e2f8f9cc6760503136a9243e965237a1ece1196502a
  Stored in directory: /tmp/pip-ephem-wheel-cache-c_dx8qi5/wheels/c6/6b/83/2608afaa57ecfb0a66ac89191a8d9bad71c62ca55ee499c2d0
Successfully built pycparser
ERROR: requests 2.22.0 has requirement idna<2.9,>=2.5, but you'll have idna 2.9 which is incompatible.
Installing collected packages: asn1crypto, idna, six, pycparser, cffi, cryptography, urllib3, certifi, chardet, requests
Successfully installed asn1crypto-1.3.0 certifi-2019.11.28 cffi-1.14.0 chardet-3.0.4 cryptography-2.3.1 idna-2.9 pycparser-2.19 requests-2.22.0 six-1.14.0 urllib3-1.25.8
</code>```

答:
Pip does not have a dependency resolver. If you tell it to install package foo without any qualifications, you’re getting the newest version of foo, even if it conflicts with other packages you’ve already installed.

Other solutions like poetry exist which do have the logic to keep everything compatible. If you need this, consider using something like that instead of plain pip.

Body:
I am using pip 20.0.2 on Ubuntu, and installing a bunch of requirements from a requirements file. For some reason, pip is deciding to install idna==2.9(link), even though that is not a compatible version with one of my directly listed dependencies. So I used python -m pipdeptree -r within the virtualenv that I'm installing everything to, and I see this listed for idna:

idna==2.9
  - cryptography==2.3.1 [requires: idna>=2.1]
  - requests==2.22.0 [requires: idna>=2.5,<2.9]
    - requests-oauthlib==1.3.0 [requires: requests>=2.0.0]
      - social-auth-core==3.2.0 [requires: requests-oauthlib>=0.6.1]
        - social-auth-app-django==2.1.0 [requires: social-auth-core>=1.2.0]
    - responses==0.10.9 [requires: requests>=2.0]
    - social-auth-core==3.2.0 [requires: requests>=2.9.1]
      - social-auth-app-django==2.1.0 [requires: social-auth-core>=1.2.0]

As we can see, my two direct dependencies (cryptography and requests), are what require idna. According to those, it looks like pip should decide to install 2.8, because it is the latest version that will fulfill the constraints.

Why is pip instead installing idna 2.9, as indicated by the top line of that output, and this error message when running pip install -r requirements.txt:

ERROR: requests 2.22.0 has requirement idna<2.9,>=2.5, but you'll have idna 2.9 which is incompatible.

EDIT: the contents of requirements.txt and it's children, as requested in the comments:

# requirements.txt
-r requirements/requirements-base.txt
-r requirements/requirements-testing.txt

# requirements-base.txt
cryptography~=2.3.1
pyjwt~=1.6.4
requests~=2.22.0
social-auth-app-django~=2.1.0

# requirements-testing.txt
hypothesis~=3.87.0
pytest~=3.6.2
pytest-django~=3.3.2
pytest-cov~=2.5.1
responses~=0.10.5

Edit 2: I've created a minimally viable example. For this example, here is requirements.txt:

cryptography~=2.3.1
requests~=2.22.0

And here are the commands I ran from start to finish in a fresh directory:

virtualenv -p python3.6 -v venv
source venv/bin/activate
pip install -r requirements.txt --no-cache-dir

And the full output:

Collecting cryptography~=2.3.1
  Downloading cryptography-2.3.1-cp34-abi3-manylinux1_x86_64.whl (2.1 MB)
     |████████████████████████████████| 2.1 MB 2.0 MB/s
Collecting requests~=2.22.0
  Downloading requests-2.22.0-py2.py3-none-any.whl (57 kB)
     |████████████████████████████████| 57 kB 18.5 MB/s
Collecting asn1crypto>=0.21.0
  Downloading asn1crypto-1.3.0-py2.py3-none-any.whl (103 kB)
     |████████████████████████████████| 103 kB 65.4 MB/s
Collecting idna>=2.1
  Downloading idna-2.9-py2.py3-none-any.whl (58 kB)
     |████████████████████████████████| 58 kB 71.4 MB/s
Collecting six>=1.4.1
  Downloading six-1.14.0-py2.py3-none-any.whl (10 kB)
Collecting cffi!=1.11.3,>=1.7
  Downloading cffi-1.14.0-cp36-cp36m-manylinux1_x86_64.whl (399 kB)
     |████████████████████████████████| 399 kB 30.3 MB/s
Collecting urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1
  Downloading urllib3-1.25.8-py2.py3-none-any.whl (125 kB)
     |████████████████████████████████| 125 kB 46.7 MB/s
Collecting certifi>=2017.4.17
  Downloading certifi-2019.11.28-py2.py3-none-any.whl (156 kB)
     |████████████████████████████████| 156 kB 65.1 MB/s
Collecting chardet<3.1.0,>=3.0.2
  Downloading chardet-3.0.4-py2.py3-none-any.whl (133 kB)
     |████████████████████████████████| 133 kB 60.8 MB/s
Collecting pycparser
  Downloading pycparser-2.19.tar.gz (158 kB)
     |████████████████████████████████| 158 kB 25.0 MB/s
Building wheels for collected packages: pycparser
  Building wheel for pycparser (setup.py) ... done
  Created wheel for pycparser: filename=pycparser-2.19-py2.py3-none-any.whl size=111031 sha256=030a1449dd5902f2f03e9e2f8f9cc6760503136a9243e965237a1ece1196502a
  Stored in directory: /tmp/pip-ephem-wheel-cache-c_dx8qi5/wheels/c6/6b/83/2608afaa57ecfb0a66ac89191a8d9bad71c62ca55ee499c2d0
Successfully built pycparser
ERROR: requests 2.22.0 has requirement idna<2.9,>=2.5, but you'll have idna 2.9 which is incompatible.
Installing collected packages: asn1crypto, idna, six, pycparser, cffi, cryptography, urllib3, certifi, chardet, requests
Successfully installed asn1crypto-1.3.0 certifi-2019.11.28 cffi-1.14.0 chardet-3.0.4 cryptography-2.3.1 idna-2.9 pycparser-2.19 requests-2.22.0 six-1.14.0 urllib3-1.25.8


问:
Angular7, get ElementRef
i need to get ElementRef in child nodes.

my template

```<code><div #charts *ngFor="let tag of _tags">
  <jqxBulletChart
    style="margin-left: 10px; float: left;"
    [width]='50'
    [height]='350'
    [barSize]='"35%"'
    [labelsFormat]='"c"'
    [title]="''"
    description="{{tag.configuration.name}}"
    [showTooltip]='true'
    [labelsFormatFunction]="labelsFormatFunction"
    [tooltipFormatFunction]="tooltipFormatFunction" [ticks]='ticks'
    [ranges]='tag.value'
    [pointer]='pointer'
    [orientation]="'vertical'"
  >
  </jqxBulletChart>
</div>
</code>```

I call to

@ViewChildren('charts') infoCharts: ElementRef;

and get child

```<code>for (let chart of this.arrCharts) {
            console.log(chart);
            console.log(chart.nativeElement.lastChild)
            let child: jqxBulletChartComponent = chart.nativeElement.lastChild;
            console.log(child);
            console.log(+this.tags[count].displayValue);
            child.val(+this.tags[count].displayValue || 0);
            // child.val(20);
            count++;
        }
</code>```

but my "child"  should be ElementRef type, and i don't know how to do it

答:
Try this : </p>

```<code>import {AfterViewInit, Component, QueryList, ViewChildren, ElementRef} from '@angular/core';

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})

export class AppComponent {
  name = "Angular";
  @ViewChildren("charts") charts: QueryList<ElementRef>;

  ngAfterViewInit() {
    this.charts.forEach(c => console.log(c));
  }
}
</code>```

Title: Angular7, get ElementRef

Body:
i need to get ElementRef in child nodes.

my template

  <jqxBulletChart
    style="margin-left: 10px; float: left;"
    [width]='50'
    [height]='350'
    [barSize]='"35%"'
    [labelsFormat]='"c"'
    [title]="''"
    description="{{tag.configuration.name}}"
    [showTooltip]='true'
    [labelsFormatFunction]="labelsFormatFunction"
    [tooltipFormatFunction]="tooltipFormatFunction" [ticks]='ticks'
    [ranges]='tag.value'
    [pointer]='pointer'
    [orientation]="'vertical'"
  >
  </jqxBulletChart>

I call to

@ViewChildren('charts') infoCharts: ElementRef;

and get child

for (let chart of this.arrCharts) {
            console.log(chart);
            console.log(chart.nativeElement.lastChild)
            let child: jqxBulletChartComponent = chart.nativeElement.lastChild;
            console.log(child);
            console.log(+this.tags[count].displayValue);
            child.val(+this.tags[count].displayValue || 0);
            // child.val(20);
            count++;
        }

but my "child"  should be ElementRef type, and i don't know how to do it

Body:
Try this :

import {AfterViewInit, Component, QueryList, ViewChildren, ElementRef} from '@angular/core';

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})

export class AppComponent {
  name = "Angular";
  @ViewChildren("charts") charts: QueryList<ElementRef>;

  ngAfterViewInit() {
    this.charts.forEach(c => console.log(c));
  }
}


问:
Is there an kotlin equivalent of ?: java operator?
Reluctant kotlin newbie here.

Is there an kotlin equivalent of ?: java operator?

I tried searching on google. Most results talk about ?: (elvis operator) in kotlin.

Looking for a way to write this in kotlin:

```<code>//java example
//return condition ? a : b;
</code>```

答:
? : is a tenary operator which is currently not present in Kotlin. There are few discussions on adding this operator to the language e.g. KT-5823 Support ternary conditional operator 'foo ? a : b' .

The usual suggestion is to use an if statement as replacement.

Body:
Reluctant kotlin newbie here.

Is there an kotlin equivalent of ?: java operator?

I tried searching on google. Most results talk about ?: (elvis operator) in kotlin.

Looking for a way to write this in kotlin:

//java example
//return condition ? a : b;


问:
Flutter showDatePicker show year selection first
In Flutter, I use showDatePicker method to show the date picker, but how to open date picker that show/open the year selection by default, before going to select month & date?

答:
Set the property initialDatePickerMode to DatePickerMode.year (doc)

Code Sample:

showDatePicker(
   context: context,
   initialDatePickerMode: DatePickerMode.year,
   initialDate: initialDate,
   firstDate: DateTime(firstDate),
   lastDate: DateTime(lastDate),
);
```


问:
How to verify exception thrown using StepVerifier in project reactor
```<code>    def expectError() {

        StepVerifier.create(readDB())
                    .expectError(RuntimeException.class)
                    .verify();
    }

     private Mono<String> readDB() {
//        try {
            return Mono.just(externalService.get())
                    .onErrorResume(throwable -> Mono.error(throwable));

//        } catch (Exception e) {
//            return Mono.error(e);
//        }
    }

</code>```

unable to make it work if externalService.get throws Exception instead of return Mono.error. Is is always recommended to transform to Mono/Flow using try catch or is there any better way to verify such thrown exception?

答: Most of the time, if the user-provided code that throws an exception is provided as a lambda, exceptions can be translated to onError. But here you're directly throwing in the main thread, so that cannot happen

Body:
    def expectError() {

        StepVerifier.create(readDB())
                    .expectError(RuntimeException.class)
                    .verify();
    }

     private Mono<String> readDB() {
//        try {
            return Mono.just(externalService.get())
                    .onErrorResume(throwable -> Mono.error(throwable));

//        } catch (Exception e) {
//            return Mono.error(e);
//        }
    }

unable to make it work if externalService.get throws Exception instead of return Mono.error. Is is always recommended to transform to Mono/Flow using try catch or is there any better way to verify such thrown exception?


问:
switching views in iphone
i m making a client server program in which i want to switch from one view to another but i am getting an error in "clientserverprogram view.m" plz help</p>

```<code>"clientserverprogram view.h"

#import <UIKit/UIKit.h>

@class secondview;

@interface clientserverprogramViewController : UIViewController {

    IBOutlet UITextField *name;
    IBOutlet UITextView *filepath;
    IBOutlet UIButton *print;
    IBOutlet UIButton *settings;
    IBOutlet UIButton *cancel;
    IBOutlet UILabel *display;
    IBOutlet secondview *secondview;
}

-(IBAction) print;
-(IBAction) settings;
-(IBAction) cancel;

@property (nonatomic , retain) IBOutlet UITextField *name;
@property (nonatomic , retain) IBOutlet UITextView *filepath;

@property (nonatomic , retain) IBOutlet UILabel *display;
@end

"clientserverprogram view.m"

#import "clientserverprogramViewController.h"
#import "secondview.h"

@implementation clientserverprogramViewController

@synthesize  name ,filepath,display ;

-(IBAction) print {

    NSString *str = name.text;

    [display setText : str];

}

-(IBAction) settings {

    [self presentModalViewController: secondview animated: YES ];

"" error: expected expression before 'secondview'""

}

-(IBAction) cancel {

    exit(0);

}

- (void)dealloc {
    [super dealloc];
}

@end

"secondview.h"

#import <UIKit/UIKit.h>

@interface secondview : UIViewController {

    IBOutlet UIView *view;

    IBOutlet UIButton *back;

}

-(IBAction) back;

@end

""secondview.m""

#import "secondview.h"

@implementation secondview

-(IBAction) back {

    [self.parentViewController dismissModalViewControllerAnimated: YES];
}

- (void)dealloc {
    [super dealloc];
}

@end
</code>```

答:
I used your code and the problem here is your class name "secondview" and the instance you are making from it IBOutlet secondview *secondview are same. Please use different name for class names and the instances you create.

Always start with uppercase for class names and start with lowercase for class instances you create. Hence, your class name should be SecondView and you should write IBOutlet SecondView *secondView.

Or you should just use different names. Its very confusing.

ContentLicense: CC BY-SA 3.0

Title: switching views in iphone

Body:
i m making a client server program in which i want to switch from one view to another but i am getting an error in "clientserverprogram view.m" plz help

"clientserverprogram view.h"

#import <UIKit/UIKit.h>

@class secondview;

@interface clientserverprogramViewController : UIViewController {

    IBOutlet UITextField *name;
    IBOutlet UITextView *filepath;
    IBOutlet UIButton *print;
    IBOutlet UIButton *settings;
    IBOutlet UIButton *cancel;
    IBOutlet UILabel *display;
    IBOutlet secondview *secondview;
}

-(IBAction) print;
-(IBAction) settings;
-(IBAction) cancel;

@property (nonatomic , retain) IBOutlet UITextField *name;
@property (nonatomic , retain) IBOutlet UITextView *filepath;

@property (nonatomic , retain) IBOutlet UILabel *display;
@end

"clientserverprogram view.m"

#import "clientserverprogramViewController.h"
#import "secondview.h"

@implementation clientserverprogramViewController

@synthesize  name ,filepath,display ;

-(IBAction) print {

    NSString *str = name.text;

    [display setText : str];

}

-(IBAction) settings {

    [self presentModalViewController: secondview animated: YES ];

"" error: expected expression before 'secondview'""

}

-(IBAction) cancel {

    exit(0);

}

- (void)dealloc {
    [super dealloc];
}

@end

"secondview.h"

#import <UIKit/UIKit.h>

@interface secondview : UIViewController {

    IBOutlet UIView *view;

    IBOutlet UIButton *back;

}

-(IBAction) back;

@end

""secondview.m""

#import "secondview.h"

@implementation secondview

-(IBAction) back {

    [self.parentViewController dismissModalViewControllerAnimated: YES];
}

- (void)dealloc {
    [super dealloc];
}

@end


问:
Hosting sklearn - SVM Classifier on AWS Sagemaker
I have a model running on my jupyter notebook instance with very basic SVM classifier

```<code># Text lassifier - Algorithm - SVM
# fit the training dataset on the classifier
SVM = svm.SVC(C=1.0, kernel='linear', degree=3, gamma='auto',probability=True)
SVM.fit(Train_X_Tfidf,Train_Y)
# predict the labels on validation dataset
predictions_SVM = SVM.predict(Test_X_Tfidf)
# Use accuracy_score function to get the accuracy
print("SVM Accuracy Score -> ",accuracy_score(predictions_SVM, Test_Y)*100)
</code>```

Use Case : Host the model on Sagemaker and create an endpoint.Use the end point via Lambda for text classification

I saw AWS has few posts on creating an endpoint E.g. https://docs.aws.amazon.com/sagemaker/latest/dg/ex1-train-model.html but majority of the content is not applicable to scikit-learn : SVM

Is there an another approach I should be looking at ?

答: If your model is small enough, you can create a lambda function that loads the model and does predictions based on input passed in from user.</p>

Body:
I have a model running on my jupyter notebook instance with very basic SVM classifier

# Text lassifier - Algorithm - SVM
# fit the training dataset on the classifier
SVM = svm.SVC(C=1.0, kernel='linear', degree=3, gamma='auto',probability=True)
SVM.fit(Train_X_Tfidf,Train_Y)
# predict the labels on validation dataset
predictions_SVM = SVM.predict(Test_X_Tfidf)
# Use accuracy_score function to get the accuracy
print("SVM Accuracy Score -> ",accuracy_score(predictions_SVM, Test_Y)*100)

Use Case : Host the model on Sagemaker and create an endpoint.Use the end point via Lambda for text classification

I saw AWS has few posts on creating an endpoint E.g. https://docs.aws.amazon.com/sagemaker/latest/dg/ex1-train-model.html but majority of the content is not applicable to scikit-learn : SVM

Is there an another approach I should be looking at ?


问:
PL SQL identifier must be declared
Hey I am new to PL SQL and what I am trying to do is to get the user input and use it in the procedure.Hereby I have attached my code and the error message that I get. I realized that I get this error only for strings. Such as JAN FEB and IT_PROG,</p>

```<code>SQL> CREATE OR REPLACE PROCEDURE add_job_history AS
  2
  3   p_employee_id NUMBER (6);
  4   p_start_date DATE ;
  5   p_end_date DATE ;
  6   p_job_id VARCHAR2(10) ;
  7   p_department_id NUMBER ;
  8
  9  BEGIN
 10
 11    DBMS_OUTPUT.PUT_LINE ('Attempt to insert new record into Job History Database');
 12    --  DBMS_OUTPUT.PUT_LINE ('Number ' || &employee_id);
 13
 14
 15
 16    p_employee_id := &p_employee_id;
 17    p_start_date := &p_start_date;
 18    p_end_date := &p_end_date;
 19    p_job_id := &p_job_id;
 20    p_department_id := &p_department_id;
 21
 22
 23  INSERT INTO job_history(employee_id,start_date,end_date,job_id,department_id)
 24  VALUES (p_employee_id,p_start_date,p_end_date,p_job_id,p_department_id); -- try to insert new record
 25    COMMIT;
 26  END;
 27  /
Enter value for employee_id: 103
old  12:   --  DBMS_OUTPUT.PUT_LINE ('Number ' || &employee_id);
new  12:   --  DBMS_OUTPUT.PUT_LINE ('Number ' || 103);
old  16:   p_employee_id := &p_employee_id;
new  16:   p_employee_id := 103;
old  17:   p_start_date := &p_start_date;
new  17:   p_start_date := 03-JAN-06;
old  18:   p_end_date := &p_end_date;
new  18:   p_end_date := 02-FEB-20;
old  19:   p_job_id := &p_job_id;
new  19:   p_job_id := IT_PROG;
old  20:   p_department_id := &p_department_id;
new  20:   p_department_id := 60;

Warning: Procedure created with compilation errors.

SQL> show errors
Errors for PROCEDURE ADD_JOB_HISTORY:

LINE/COL ERROR
-------- -----------------------------------------------------------------
17/3     PL/SQL: Statement ignored
17/22    PLS-00201: identifier 'JAN' must be declared
18/3     PL/SQL: Statement ignored
18/20    PLS-00201: identifier 'FEB' must be declared
19/3     PL/SQL: Statement ignored
19/15    PLS-00201: identifier 'IT_PROG' must be declared
</code>```

答:
Instead of p_start_date := &p_start_date; you need to use p_start_date := TO_DATE('&p_start_date','DD-MON-YY'); because p_Start_Date is defined as a DATE and you are (sort of) attempting to assign a string to it.

Your clue would be where line 17 was resolved new  17:   p_start_date := 03-JAN-06; where you see the string presented without quotes in the assignment to the DATE variable.

You need TO_DATE in there so that you can account for the date format you have chosen.

Title: PL SQL identifier must be declared

Body:
Hey I am new to PL SQL and what I am trying to do is to get the user input and use it in the procedure.Hereby I have attached my code and the error message that I get. I realized that I get this error only for strings. Such as JAN FEB and IT_PROG,

SQL> CREATE OR REPLACE PROCEDURE add_job_history AS
  2
  3   p_employee_id NUMBER (6);
  4   p_start_date DATE ;
  5   p_end_date DATE ;
  6   p_job_id VARCHAR2(10) ;
  7   p_department_id NUMBER ;
  8
  9  BEGIN
 10
 11    DBMS_OUTPUT.PUT_LINE ('Attempt to insert new record into Job History Database');
 12    --  DBMS_OUTPUT.PUT_LINE ('Number ' || &employee_id);
 13
 14
 15
 16    p_employee_id := &p_employee_id;
 17    p_start_date := &p_start_date;
 18    p_end_date := &p_end_date;
 19    p_job_id := &p_job_id;
 20    p_department_id := &p_department_id;
 21
 22
 23  INSERT INTO job_history(employee_id,start_date,end_date,job_id,department_id)
 24  VALUES (p_employee_id,p_start_date,p_end_date,p_job_id,p_department_id); -- try to insert new record
 25    COMMIT;
 26  END;
 27  /
Enter value for employee_id: 103
old  12:   --  DBMS_OUTPUT.PUT_LINE ('Number ' || &employee_id);
new  12:   --  DBMS_OUTPUT.PUT_LINE ('Number ' || 103);
old  16:   p_employee_id := &p_employee_id;
new  16:   p_employee_id := 103;
old  17:   p_start_date := &p_start_date;
new  17:   p_start_date := 03-JAN-06;
old  18:   p_end_date := &p_end_date;
new  18:   p_end_date := 02-FEB-20;
old  19:   p_job_id := &p_job_id;
new  19:   p_job_id := IT_PROG;
old  20:   p_department_id := &p_department_id;
new  20:   p_department_id := 60;

Warning: Procedure created with compilation errors.

SQL> show errors
Errors for PROCEDURE ADD_JOB_HISTORY:

LINE/COL ERROR
-------- -----------------------------------------------------------------
17/3     PL/SQL: Statement ignored
17/22    PLS-00201: identifier 'JAN' must be declared
18/3     PL/SQL: Statement ignored
18/20    PLS-00201: identifier 'FEB' must be declared
19/3     PL/SQL: Statement ignored
19/15    PLS-00201: identifier 'IT_PROG' must be declared


问:
Why my sprintf with usb communication doesn't work very well?
I want to send double form uC to PC. For example: in the uC I have double pi=3.1415 after sent it to PC, the console (at the PC) should show 3.1415 . I need to convert double to char, so I used sprintf() to convert it. To be honest I'm not sure that sprintf() is converting double to char[], but it's my only idea. After sent pi to the PC my console shows: ?<00><00>4f<00>˙˙
 . There is my code:

```<code>#define F_CPU 16000000UL

#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <stdio.h>

void print_char(char letter)
{
    if( bit_is_set(UCSRA, UDRE) )
    {
        _delay_ms(10);
        UDR=letter;
        loop_until_bit_is_set(UCSRA, TXC);
    }
}

int main(void)
{
    UBRRL = 103; //9600 16mhz
    UCSRB = (1<<RXEN)|(1<<TXEN)|(1<<RXCIE);
    UCSRC = (1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);

    double pi=3.1415;
    char cpi[8];

    sprintf(cpi,"%#.4f", pi);

    while(1)
    {
        for(int i=0; i<8; i++) print_char(cpi[i]);

        UDR=0x0D;
        UDR=0x0A;
        _delay_ms(1000);
    }
}
</code>```

How can I fixed it, or how can I correctly convert double to char[].

答:
sprintf and friends are quite costly, in particular the full fledged versions with float support.  To this end, avr-libc provides different versions of vfprintf, where the default version does /not/ support float and just prints ? if it sees one.

If you want float support, link with

```<code>avr-gcc ... -Wl,-u,vfprintf -lprintf_flt
</code>```

see avr-libc: vfprintf.
Moreover, there is support for plain float conversion functions in stdlib.h.

In the unlikely case you are using avr-gcc with support of 64-bit double: avr-libc does not support them, no matter which version of vfprintf you are linking.

Body:
I want to send double form uC to PC. For example: in the uC I have double pi=3.1415 after sent it to PC, the console (at the PC) should show 3.1415 . I need to convert double to char, so I used sprintf() to convert it. To be honest I'm not sure that sprintf() is converting double to char[], but it's my only idea. After sent pi to the PC my console shows: ?<00><00>4f<00>˙˙
 . There is my code:

#define F_CPU 16000000UL

#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <stdio.h>

void print_char(char letter)
{
    if( bit_is_set(UCSRA, UDRE) )
    {
        _delay_ms(10);
        UDR=letter;
        loop_until_bit_is_set(UCSRA, TXC);
    }
}

int main(void)
{
    UBRRL = 103; //9600 16mhz
    UCSRB = (1<<RXEN)|(1<<TXEN)|(1<<RXCIE);
    UCSRC = (1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);

    double pi=3.1415;
    char cpi[8];

    sprintf(cpi,"%#.4f", pi);

    while(1)
    {
        for(int i=0; i<8; i++) print_char(cpi[i]);

        UDR=0x0D;
        UDR=0x0A;
        _delay_ms(1000);
    }
}

How can I fixed it, or how can I correctly convert double to char[].

Body:
sprintf and friends are quite costly, in particular the full fledged versions with float support.  To this end, avr-libc provides different versions of vfprintf, where the default version does /not/ support float and just prints ? if it sees one.

If you want float support, link with

avr-gcc ... -Wl,-u,vfprintf -lprintf_flt

see avr-libc: vfprintf.
Moreover, there is support for plain float conversion functions in stdlib.h.

In the unlikely case you are using avr-gcc with support of 64-bit double: avr-libc does not support them, no matter which version of vfprintf you are linking.


问:
In PHP Remove several characters from the beginning of a String?
I need to find a specic line of text, from a text-file,
and then copy it to a new text-file:

1: I have a text file with several lines of text, eg:

```<code>JOHN
MIKE
BEN
*BJAMES
PETE
</code>```

2: So, I read that text-files contents into an array,
with each line of text, placed into a seperate element of the array.

3: Then I tested each element of the array,
to find the line that starts with, say: *B  ie:

```<code>if ( preg_match( "/^\*(B)/",$contents[$a] ) )
</code>```

Which works ok...

4: Then I copy (WRITE) that line of text, to a new text-file.

Q: So how can I remove the '*B' from that line of text,
BEFORE I WRITE it to the new text-file ?

答: With substr or preg_replace.

Body:
I need to find a specic line of text, from a text-file,
and then copy it to a new text-file:

1: I have a text file with several lines of text, eg:

JOHN
MIKE
BEN
*BJAMES
PETE

2: So, I read that text-files contents into an array,
with each line of text, placed into a seperate element of the array.

3: Then I tested each element of the array,
to find the line that starts with, say: *B  ie:

if ( preg_match( "/^\*(B)/",$contents[$a] ) )

Which works ok...

4: Then I copy (WRITE) that line of text, to a new text-file.

Q: So how can I remove the '*B' from that line of text,
BEFORE I WRITE it to the new text-file ?

Body: With substr or preg_replace.


问:
ios Unable to install dependency using Pods
I am trying to install AFNetworking using Pods. I've created a pod file and when I run pod install I get :

Unable to add a source with url
  https://github.com/CocoaPods/Specs.git named master-1. You can try
  adding it manually in ~/.cocoapods/repos or via pod repo add.

I tried cloning into ~/.cocoapods/reposbut it gives an error: fatal: destination path '.' already exists and is not an empty directory.

My PodFile:

```<code>source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '7.0'
pod 'AFNetworking', '~> 2.5'
</code>```

Any suggestions?

答:
Just remove master repo:

```<code>rm -fR ~/.cocoapods/repos/master
</code>```

After that, run:

```<code>pod setup
</code>```

Body:
I am trying to install AFNetworking using Pods. I've created a pod file and when I run pod install I get :

Unable to add a source with url
  https://github.com/CocoaPods/Specs.git named master-1. You can try
  adding it manually in ~/.cocoapods/repos or via pod repo add.

I tried cloning into ~/.cocoapods/reposbut it gives an error: fatal: destination path '.' already exists and is not an empty directory.

My PodFile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '7.0'
pod 'AFNetworking', '~> 2.5'

Any suggestions?

Body:
Just remove master repo:

rm -fR ~/.cocoapods/repos/master

After that, run:

pod setup


问:
HowTo create deep links with multiple NavHostFragments
The examples I found are either showing a single (nested) navigation graph which will be used for deep linking or they're showing nested navigation with multiple NavHostFragments but do not provide deep linking.

I have the following scenario:

MainActivity

Has the main-NavHostFragment which handles the main navigation to HomeFragment, PostsFragment, ProfileFragment. home, posts and profile should be shown in the bottom navigation.

PostFragment

The detail fragment for a post. It will be opened when we tap on a list item in PostsFragment. This layout has a NavHostFragment which handles the sub navigation regarding a post (PostDetailsFragment, PostCommentsFragment)

How can I provide deep links to myapp://post/{postId}/comments with multiple NavHostFragments?

Best,

Chris

答:
I don't think you need several nav host fragments. Please start looking into this project https://github.com/android/architecture-components-samples/tree/master/NavigationAdvancedSample, in particular these extensions: https://github.com/android/architecture-components-samples/blob/master/NavigationAdvancedSample/app/src/main/java/com/example/android/navigationadvancedsample/NavigationExtensions.kt.

Your activity layout should be similar to this one:

```<code>    <!-- Fragments Container -->

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_container"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/appBarLayout" />

    <!-- Bottom Navigation View -->

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_navigation_menu" />
</code>```

You can keep your deep links in nested graph of navigation graph mentioned in your manifest. In your nested graph, don't forget to mark your landing fragment with <deepLink.../>

Body:
I don't think you need several nav host fragments. Please start looking into this project https://github.com/android/architecture-components-samples/tree/master/NavigationAdvancedSample, in particular these extensions: https://github.com/android/architecture-components-samples/blob/master/NavigationAdvancedSample/app/src/main/java/com/example/android/navigationadvancedsample/NavigationExtensions.kt.

Your activity layout should be similar to this one:

    <!-- Fragments Container -->

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_container"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/appBarLayout" />

    <!-- Bottom Navigation View -->

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_navigation_menu" />

You can keep your deep links in nested graph of navigation graph mentioned in your manifest. In your nested graph, don't forget to mark your landing fragment with <deepLink.../>


问:
How to format JavaScript date to mm/dd/yyyy?
Im getting the date like 'Wed Nov 08 2017 00:00:00 GMT-0800 (Pacific Standard Time)' and putting the value in an input.

Is there a way to parse the datetime into a date, add five days to it, and then format it like mm/dd/yyyy?

I made a https://jsfiddle.net/ax6qqw0t/

startingDate = new Date(5/5/2017);
var adjustedDate = addDays(startingDate,13);
$('#max_products').val(adjustedDate);
```

答:
I'm sure you've solved this by now, but it looked like a fun one so I decided to take a stab at it using Intl.DateTimeFormat.

// get date for five days later
const date = 'Fri Dec 29 2017 00:00:00 GMT-0800 (Pacific Standard Time)';
const dateSet = new Date(date);
const fiveDaysLater = dateSet.setDate(dateSet.getDate() + 5);

// set up date formatting parameters
const ops = {year: 'numeric'};
ops.month = ops.day = '2-digit';

console.log(new Intl.DateTimeFormat([], ops).format(fiveDaysLater));```


问:
SSRS - how to filter or hide visibiltiy based on a single category of a grouped column
I am stuck on a issue that sounds not that complicated but did not find any proper solution so far. I know a bit about filtering and hide visibility but this one seems tricky to me.

I have a matrix showing the totals of different booking "systems" as grouped rows and a grouped column called "type" that shows me the two categories "bookings" and "errors".

What I want to achieve is whenever the certain category "errors" has no value, it shall hide or filter out this row.

design mode
preview mode

I tried to filter and hide visibility but it always takes the total of the whole group "type" not the total of its category "errors".

Do you see a way to do so on "errors" only?

Many thanks in advance.

Best regards

Alex

答:
The reason it's not working as you would expect is due to your column grouping that your error count is in. It's counting all the types, not just errors.

I believe it would work for you if you just check the Error types.

```<code>=IIF(SUM(IIF(Fields!type.Value = 'Errors', Fields!attempts.Value, 0)) > 0, False, True)
</code>```

This will SUM the Attempts where the Type = 'Errors' and hide if zero.

Body:
The reason it's not working as you would expect is due to your column grouping that your error count is in. It's counting all the types, not just errors.

I believe it would work for you if you just check the Error types.

=IIF(SUM(IIF(Fields!type.Value = 'Errors', Fields!attempts.Value, 0)) > 0, False, True)

This will SUM the Attempts where the Type = 'Errors' and hide if zero.


问:
Iterate table and return count of pairs on lists in Python
Having a column of people and a column of say locations of those people, where their locations are ordered by time, e.g.:

```<code>People=["A", "A", "B", "B", "B", "C", "C", "C"]
Location=["GA", "IL", "GA", "IL", "GA", "CA", "IL", "GA"]
</code>```

How would you program an iteration that returns this:

Change_of_location=["GA-IL","IL-GA","CA-IL] and count=[2, 2, 1], since the pair "GA-IL" appears twice etc. That is, the iteration should return the trips taken (change of location) based on rows of the people's locations.

答:
I will use a recipe based on the zip tool.</p>

```<code>people = ["A", "A", "B", "B", "B", "C", "C", "C"]
location = ["GA", "IL", "GA", "IL", "GA", "CA", "IL", "GA"]

chg_of_loc = {}

for first, second, loc1, loc2 in zip(people, people[1:], location, location[1:]):
    # if version(python) < 3.6 use format
    start_end = f'{loc1}-{loc2}'
    if first == second:
        chg_of_loc[start_end] = chg_of_loc.get(start_end, 0) + 1

print(f"Change={list(chg_of_loc.keys())} and count={list(chg_of_loc.values())}")
</code>```

Body:
Having a column of people and a column of say locations of those people, where their locations are ordered by time, e.g.:

People=["A", "A", "B", "B", "B", "C", "C", "C"]
Location=["GA", "IL", "GA", "IL", "GA", "CA", "IL", "GA"]

How would you program an iteration that returns this:

Change_of_location=["GA-IL","IL-GA","CA-IL] and count=[2, 2, 1], since the pair "GA-IL" appears twice etc. That is, the iteration should return the trips taken (change of location) based on rows of the people's locations.

Body:
I will use a recipe based on the zip tool.

people = ["A", "A", "B", "B", "B", "C", "C", "C"]
location = ["GA", "IL", "GA", "IL", "GA", "CA", "IL", "GA"]

chg_of_loc = {}

for first, second, loc1, loc2 in zip(people, people[1:], location, location[1:]):
    # if version(python) < 3.6 use format
    start_end = f'{loc1}-{loc2}'
    if first == second:
        chg_of_loc[start_end] = chg_of_loc.get(start_end, 0) + 1

print(f"Change={list(chg_of_loc.keys())} and count={list(chg_of_loc.values())}")


问:
R Remove row if column X is Na AND column B is not 'value'
I relativity new R and R Stack Overflow, so forgive me for my poor explanation

I am trying to remove all values with in the emp_length column that are Na AND the grade column with in the same row is equal to "C" OR "B"

```<code>fullData2_empData_rm <- fullData2[!is.na(fullData2$emp_length) ,]
          && (fullData2$grade != 'B' || fullData2$grade != 'C')
</code>```

So far I have been unsuccessful

I have made a basic JavaScrip example, in case my explanation is not very good.

Thanks

```<code>const remove (row) => {
  if(row.emp_length == null && (row.grade == 'C' || row.grade == 'B'{
      removeRow()
  }else{
    keepRow()
  }
}
</code>```

答:
We can remove the && and || to & and | as the &&/|| returns a single TRUE/FALSE as output

```<code>fullData2[!is.na(fullData2$emp_length) &
        (fullData2$grade != 'B' |fullData2$grade != 'C'),]
</code>```

Body:
I relativity new R and R Stack Overflow, so forgive me for my poor explanation

I am trying to remove all values with in the emp_length column that are Na AND the grade column with in the same row is equal to "C" OR "B"

fullData2_empData_rm <- fullData2[!is.na(fullData2$emp_length) ,]
          && (fullData2$grade != 'B' || fullData2$grade != 'C')

So far I have been unsuccessful

I have made a basic JavaScrip example, in case my explanation is not very good.

Thanks

const remove (row) => {
  if(row.emp_length == null && (row.grade == 'C' || row.grade == 'B'{
      removeRow()
  }else{
    keepRow()
  }
}

Body:
We can remove the && and || to & and | as the &&/|| returns a single TRUE/FALSE as output

fullData2[!is.na(fullData2$emp_length) &
        (fullData2$grade != 'B' |fullData2$grade != 'C'),]


问:
Python logging using custom timestamps (not current timestamp)
I am using the logging module in the following way:

```<code>logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    filename=my_filename,
                    filemode='w')
</code>```

and

```<code>logging.info("Set up logger")
</code>```

for writing. The output is:

```<code>2017-11-05 19:10:22,762 root      INFO     Set up logger
</code>```

QUESTION: instead of the current timestamp, I would like to have a past (or future, whatever) timestamp. So whenever I want to write something in the log, I can pass the date as argument with something like:

```<code>logging.info(msg="Set up logger", date='2010-01-01 19:10:22,762')
</code>```

in order to have

```<code>2010-01-01 19:10:22,762 root      INFO    Set up logger
</code>```

Any help?

答:
@m1keil's answer will work for simple cases, but gets cumbersome if you want, for example, to have multiple handlers which format the time in different ways, or if you don't need/want to specify the time every time you make a logging call, etc.  Here is a solution which is slightly more complicated, but is the "more correct way", and integrates better with the logging system's normal timestamp handling:

First, you need to create a log filter (filters have the ability to modify log records that pass through loggers they're attached to):

```<code>class TimestampFilter (logging.Filter):
    """
    This is a logging filter which will check for a `timestamp` attribute on a
    given LogRecord, and if present it will override the LogRecord creation time
    to be that of the timestamp (specified as a time.time()-style value).
    This allows one to override the date/time output for log entries by specifying
    `timestamp` in the `extra` option to the logging call.
    """

    def filter(self, record):
        if hasattr(record, 'timestamp'):
            record.created = record.timestamp
        return True
</code>```

Then, simply create an instance of the filter and add it to an appropriate logger instance:

```<code>logger = logging.getLogger(__name__)
filter = TimestampFilter()
logger.addFilter(filter)
</code>```

Then when you want to override the date/time of a log entry, when making the logging call, supply a timestamp in extra:

```<code>my_timestamp = time.time() + 86400  # Let's pretend it's tomorrow already
logger.warn("I am a warning from the future!", extra={'timestamp': my_timestamp})
</code>```

Body:
I am using the logging module in the following way:

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    filename=my_filename,
                    filemode='w')

and

logging.info("Set up logger")

for writing. The output is:

2017-11-05 19:10:22,762 root      INFO     Set up logger

QUESTION: instead of the current timestamp, I would like to have a past (or future, whatever) timestamp. So whenever I want to write something in the log, I can pass the date as argument with something like:

logging.info(msg="Set up logger", date='2010-01-01 19:10:22,762')

in order to have

2010-01-01 19:10:22,762 root      INFO    Set up logger

Any help?

Body:
@m1keil's answer will work for simple cases, but gets cumbersome if you want, for example, to have multiple handlers which format the time in different ways, or if you don't need/want to specify the time every time you make a logging call, etc.  Here is a solution which is slightly more complicated, but is the "more correct way", and integrates better with the logging system's normal timestamp handling:

First, you need to create a log filter (filters have the ability to modify log records that pass through loggers they're attached to):

class TimestampFilter (logging.Filter):
    """
    This is a logging filter which will check for a `timestamp` attribute on a
    given LogRecord, and if present it will override the LogRecord creation time
    to be that of the timestamp (specified as a time.time()-style value).
    This allows one to override the date/time output for log entries by specifying
    `timestamp` in the `extra` option to the logging call.
    """

    def filter(self, record):
        if hasattr(record, 'timestamp'):
            record.created = record.timestamp
        return True

Then, simply create an instance of the filter and add it to an appropriate logger instance:

logger = logging.getLogger(__name__)
filter = TimestampFilter()
logger.addFilter(filter)

Then when you want to override the date/time of a log entry, when making the logging call, supply a timestamp in extra:

my_timestamp = time.time() + 86400  # Let's pretend it's tomorrow already
logger.warn("I am a warning from the future!", extra={'timestamp': my_timestamp})


问:
ngOnInit not being called when Injectable class is Instantiated
Why isn't ngOnInit() called when an Injectable class is resolved?

Code

```<code>import {Injectable, OnInit} from 'angular2/core';
import { RestApiService, RestRequest } from './rest-api.service';

@Injectable()
export class MovieDbService implements OnInit {

    constructor(private _movieDbRest: RestApiService){
        window.console.log('FROM constructor()');
    }

    ngOnInit() {
         window.console.log('FROM ngOnInit()');
    }

}
</code>```

Console Output

```<code>FROM constructor()
</code>```

答: I had to call a function once my dataService was initialized, instead, I called it inside the constructor, that worked for me.</p>

Body:
Why isn't ngOnInit() called when an Injectable class is resolved?

Code

import {Injectable, OnInit} from 'angular2/core';
import { RestApiService, RestRequest } from './rest-api.service';

@Injectable()
export class MovieDbService implements OnInit {

    constructor(private _movieDbRest: RestApiService){
        window.console.log('FROM constructor()');
    }

    ngOnInit() {
         window.console.log('FROM ngOnInit()');
    }

}

Console Output

FROM constructor()


问:
System.NotSupportedException while calling Setup() in Moq
I'm trying to setup method OnChange in IOptionsMonitor from asp.net core. But it is not obvious for me, why Setup() doesn't work. Btw I saw similar examples here System.NotSupportedException: Unsupported expression: p => (p.UserProfileId == 1) And I have allmost the same. What is the reason of error?

Execution code:

```<code>var optionMonitorMock = new Mock<IOptionsMonitor<MyConfig>>();

optionMonitorMock
    .Setup(mock => mock.OnChange(It.IsAny<Action<MyConfig>>()));
</code>```

Code falls with exception:

System.NotSupportedException.
   Unsupported expression: mock => mock.OnChange< MyConfig>(It.IsAny< Action< MyConfig>>())
  Extension methods (here: OptionsMonitorExtensions.OnChange) may not be used in setup / verification expressions.

The asp.net's interface:

```<code>public interface IOptionsMonitor<out TOptions>
{
    TOptions CurrentValue { get; }
    TOptions Get(string name);
    IDisposable OnChange(Action<TOptions, string> listener);
}
</code>```

The model:

```<code>public class MyConfig
{
    public int Id { get; set; }
    public string Options { get; set; }
}
</code>```

答:
The interface only exposes IDisposable OnChange(Action<TOptions, string> listener); . Your exception says that

Extension methods (here: OptionsMonitorExtensions.OnChange) may not be
  used in setup / verification expressions.

So you are going to have to use Setup with that method.

```<code>optionMonitorMock
    .Setup(mock => mock.OnChange(It.IsAny<Action<MyConfig,string>>()));
</code>```

Body:
I'm trying to setup method OnChange in IOptionsMonitor from asp.net core. But it is not obvious for me, why Setup() doesn't work. Btw I saw similar examples here System.NotSupportedException: Unsupported expression: p => (p.UserProfileId == 1) And I have allmost the same. What is the reason of error?

Execution code:

var optionMonitorMock = new Mock<IOptionsMonitor<MyConfig>>();

optionMonitorMock
    .Setup(mock => mock.OnChange(It.IsAny<Action<MyConfig>>()));

Code falls with exception:

System.NotSupportedException.
   Unsupported expression: mock => mock.OnChange< MyConfig>(It.IsAny< Action< MyConfig>>())
  Extension methods (here: OptionsMonitorExtensions.OnChange) may not be used in setup / verification expressions.

The asp.net's interface:

public interface IOptionsMonitor<out TOptions>
{
    TOptions CurrentValue { get; }
    TOptions Get(string name);
    IDisposable OnChange(Action<TOptions, string> listener);
}

The model:

public class MyConfig
{
    public int Id { get; set; }
    public string Options { get; set; }
}

Body:
The interface only exposes IDisposable OnChange(Action<TOptions, string> listener); . Your exception says that

Extension methods (here: OptionsMonitorExtensions.OnChange) may not be
  used in setup / verification expressions.

So you are going to have to use Setup with that method.

optionMonitorMock
    .Setup(mock => mock.OnChange(It.IsAny<Action<MyConfig,string>>()));


问:
Parameter of Python function call is reserved word in Julia
I am playing around with the yfinance package (https://pypi.org/project/yfinance/) to learn Julia and ran into an issue with a parameter that is also a reserved word in Julia.

```<code>using PyCall

y = pyimport("yfinance")
data = y.download("SPY AAPL", start="2017-01-01", end="2017-04-30") # does not work
#data = y.download("SPY", start="2018-01-01")   #works
</code>```

Error message:

```<code>LoadError: syntax: unexpected "end"
in expression starting at C:\Users\user\Github\julia\using_python.jl:6
top-level scope at using_python.jl:6
</code>```

Does anybody have an idea how I can solve this?

Thanks!

答:
Interpolating a dictionary should work:</p>

```<code>data = y.download("SPY AAPL"; Dict(:start => "2017-01-01", :end => "2017-04-30")...)
</code>```

Body:
I am playing around with the yfinance package (https://pypi.org/project/yfinance/) to learn Julia and ran into an issue with a parameter that is also a reserved word in Julia.

using PyCall

y = pyimport("yfinance")
data = y.download("SPY AAPL", start="2017-01-01", end="2017-04-30") # does not work
#data = y.download("SPY", start="2018-01-01")   #works

Error message:

LoadError: syntax: unexpected "end"
in expression starting at C:\Users\user\Github\julia\using_python.jl:6
top-level scope at using_python.jl:6

Does anybody have an idea how I can solve this?

Thanks!

Body:
Interpolating a dictionary should work:

data = y.download("SPY AAPL"; Dict(:start => "2017-01-01", :end => "2017-04-30")...)


问:
Rewrite my simple Python code in a better mode
I have a function

```<code>def max_f(tup, val):
    max = tup[0](val)
    out = tup[0]
    for funz in tup:
        new = funz(val)
        if new > max:
            max = new
            out = funz
    return out
</code>```

and I would like to write it in a better way. I tried with

```<code>def max_f2(tup, val):
    return (max(funz(val) for funz in tup))
</code>```

but I should return a function, not a value. How could I?

These are some examples of correct outputs

```<code>tupleFunz=(lambda x: x + 3 ,lambda x: x * 2,lambda x: x % 2)
max_f(tupleFunz,4)(8) #=> 16
max_f(tupleFunz,1)(8) #=> 11
</code>```

答:
You can do this using max() and the key argument with a lambda function:

```<code>def max_f(tup, val):
    return max(tup, key=lambda x: x(val))
</code>```

Output:

```<code>>>> tupleFunz=(lambda x: x + 3 ,lambda x: x * 2,lambda x: x % 2)
>>> max_f(tupleFunz,4)(8)
16
>>> max_f(tupleFunz,1)(8)
11
</code>```

Body:
I have a function

def max_f(tup, val):
    max = tup[0](val)
    out = tup[0]
    for funz in tup:
        new = funz(val)
        if new > max:
            max = new
            out = funz
    return out

and I would like to write it in a better way. I tried with

def max_f2(tup, val):
    return (max(funz(val) for funz in tup))

but I should return a function, not a value. How could I?

These are some examples of correct outputs

tupleFunz=(lambda x: x + 3 ,lambda x: x * 2,lambda x: x % 2)
max_f(tupleFunz,4)(8) #=> 16
max_f(tupleFunz,1)(8) #=> 11

Body:
You can do this using max() and the key argument with a lambda function:

def max_f(tup, val):
    return max(tup, key=lambda x: x(val))

Output:

>>> tupleFunz=(lambda x: x + 3 ,lambda x: x * 2,lambda x: x % 2)
>>> max_f(tupleFunz,4)(8)
16
>>> max_f(tupleFunz,1)(8)
11


问:
Is it possible to give and Android App a configurable name?
Basically can the name of the app itself that is displayed when you are browsing apps, be changed to be a number of different values, without requiring a different apk for each name?</p>

答:
Yes, it's possible, you can have a look over here.

You can change app icon n app label programmatically within the app.


问:
Ansible, how to check if a variable is not null?
I have this var I a role that I use to add authorized keys to a linux user, so foo can either be a string with a single ssh public key or a list of multiple public keys.

By default foo is defined but empty so it can be tested even if the user doesn't set it, that way no related tasks are done if it's empty.

I'd normaly use when: foo or when: not foo and it was working great, except that now ansible trow a depreciation warning saying :

[DEPRECATION WARNING]: evaluating None as a bare variable, this
  behaviour will go away and you might need to add |bool to the
  expression in the future. Also see CONDITIONAL_BARE_VARS configuration
  toggle.. This feature will be removed in version 2.12. Deprecation
  warnings can be disabled by setting deprecation_warnings=False in
  ansible.cfg.

I tried when: foo|bool as mentionned but it returns false every time the variable is filled with a string that's not yes, true, Yes...

foo is defined doesn't work since the var is defined

foo != "" doesn't work because the var is null not a empty string

foo | length > 0 doesn't work because null doesn't have a length

I'm honestly out of ideas here.

答:
The thing you are looking for is the default filter, which helpfully has an alias d as in when: foo | d("") or even when: foo | d(False)

Just watch out, default normally only replaces null or None, and not the pythontic idea of truthiness. For that, you'll want to provide it a second argument foo | default("something-else", true) which works in the cases that foo is either null or "" (or likely 0 also)


问:
Why is gzip compression not working on IIS 8.5?
I am unable to get gzip compression working on IIS 8.5 on a Server 2012 R2 machine.  I have done some research and followed the instructions found in these posts:

How to enable GZIP compression in IIS 7.5

Compression in IIS 8.5 not successful, stating ALREADY_CONTENT_ENCODING

GZip Compression On IIS 7.5 is not working

gzip compression not working with IIS 8.5

Here is the relevant section of my config:

```<code><httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files" staticCompressionIgnoreHitFrequency="true">
    <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
    <!-- I have read that dynamic compression increases server CPU load.
    <dynamicTypes>
        <add mimeType="text/*" enabled="true"/>
        <add mimeType="message/*" enabled="true"/>
        <add mimeType="application/javascript" enabled="true"/>
        <add mimeType="*/*" enabled="false"/>
    </dynamicTypes>
    -->
    <staticTypes>
        <add mimeType="text/*" enabled="true" />
        <add mimeType="message/*" enabled="true" />
        <add mimeType="application/javascript" enabled="true" />
        <add mimeType="*/*" enabled="false" />
    </staticTypes>
</httpCompression>
<urlCompression doStaticCompression="true" doDynamicCompression="true" />
</code>```

Also, in IIS, I set compression to apply to anything larger than 256 bytes.  And I have performed iisreset.

Nonetheless, I don't see the compression mentioned in my dev console in Chrome or IE and PageSpeed still tells me to compress stuff.  What simple step have I missed?

答:
As mentioned in answers to one of the questions the OP links to, be sure to check for any anti-virus software running on the server. In my case it was ESET. None of the IIS compression settings had an effect until the relevant ESET settings were disabled.

I'm leaving out details of the settings- I did what seemed like a pretty blanket disable and left it to IT to figure out which exact setting was most appropriate for compression to still work while retaining security.

Body:
I am unable to get gzip compression working on IIS 8.5 on a Server 2012 R2 machine.  I have done some research and followed the instructions found in these posts:

How to enable GZIP compression in IIS 7.5

Compression in IIS 8.5 not successful, stating ALREADY_CONTENT_ENCODING

GZip Compression On IIS 7.5 is not working

gzip compression not working with IIS 8.5

Here is the relevant section of my config:

<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files" staticCompressionIgnoreHitFrequency="true">
    <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />

    <staticTypes>
        <add mimeType="text/*" enabled="true" />
        <add mimeType="message/*" enabled="true" />
        <add mimeType="application/javascript" enabled="true" />
        <add mimeType="*/*" enabled="false" />
    </staticTypes>
</httpCompression>
<urlCompression doStaticCompression="true" doDynamicCompression="true" />

Also, in IIS, I set compression to apply to anything larger than 256 bytes.  And I have performed iisreset.

Nonetheless, I don't see the compression mentioned in my dev console in Chrome or IE and PageSpeed still tells me to compress stuff.  What simple step have I missed?


问:
ASP.NET MVC model to JS object and back to C#
I'm trying to replace server side action call by javascript action call.

I have action in controller

```<code>public ActionResult MyTest(TestObj obj)
{
    return PartialView("test2");
}
</code>```

And my action call in view looks like this right now:

```<code><div id="TestDiv">
    @Html.Action("MyTest", "Home", new { obj = Model })
</div>
</code>```

So I tried to replace it by this js function

```<code><script>
    var jsModel =@Html.Raw(Json.Encode(Model));   @*'@serializer.Serialize(Model)';*@
    function newHope() {
        var url = '@Url.Action("MyTest", "Home")';
        $('#TestDiv').load(url, { obj: jsModel });
    }
</script>
</code>```

However all obj properties have default values when I'm sending obj via js and everything is OK when it's send from @Html.Action.

Any idea why biding not working with js model?

答:
Try doing this:

```<code><script>
    var jsModel =@Html.Raw(Json.Encode(Model));   @*'@serializer.Serialize(Model)';*@
    function newHope() {
        var url = '@Url.Action("MyTest", "Home")';
        $('#TestDiv').load(url, '{ obj: ' +jsModel +'}');

    }
</script>
</code>```

You need to stringify the entire payload so that it can be deserialezed properly. I have not tried it, so you might need to tweak it a bit.

Body:
I'm trying to replace server side action call by javascript action call.

I have action in controller

public ActionResult MyTest(TestObj obj)
{
    return PartialView("test2");
}

And my action call in view looks like this right now:

    @Html.Action("MyTest", "Home", new { obj = Model })

So I tried to replace it by this js function

However all obj properties have default values when I'm sending obj via js and everything is OK when it's send from @Html.Action.

Any idea why biding not working with js model?

Body:
Try doing this:

<script>
    var jsModel =@Html.Raw(Json.Encode(Model));   @*'@serializer.Serialize(Model)';*@
    function newHope() {
        var url = '@Url.Action("MyTest", "Home")';
        $('#TestDiv').load(url, '{ obj: ' +jsModel +'}');

    }
</script>

You need to stringify the entire payload so that it can be deserialezed properly. I have not tried it, so you might need to tweak it a bit.


问:
Correct usage of a Spinner, following material design guidelines
After reading the new design guidelines of Google's material design, I didn't found any clear solution for designing/displaying a spinner (http://developer.android.com/design/building-blocks/spinners.html) in material design.

The nearest would be something like this: http://material-design.storage.googleapis.com/publish/v_1/quantumexternal/0Bx4BSt6jniD7anplVHR3QkdNUHc/components_menus_behavior2.png - but I'm quite sure, there will be some better solution. Especially if it comes to spinner popups. Even so, I didn't find any spinner/menu element out of the Box in Android studio - so I think this would be custom control.

The best example I found is the above linked menu which covers the functionality of an spinner element.

What would you recommend, to display such an control and being in the range of material design.

答:
I wrote an article here:

There is No Material Design Spinner for Android

covering usage, styling, data-binding, etc. of the material design "spinner".


问:
PHP performance and redundancy
I have a section in my site where I do need to count the number of comments for a specific post.I actually already built a function for retrieving all the data in the comments DB table (function getComments).

the comments DB table structure is : id(PK) | authorId | datetime | postId | text

Now, since I just need to count them (the comments),I was wondering if,in term of server resources/redundancy is better to use :

```<code>$comments=new Comment();
$comments->getComments();
echo count($comments);
</code>```

Or I'm better build another function (apart from 'getComments')like :

```<code>function countComments($postid)
{
  //count comments per post
}
</code>```

thanks

Luca

答: See my answer in other thread: Zend_Db: How to get the number of rows from a table?</p>

Title: PHP performance and redundancy

Body:
I have a section in my site where I do need to count the number of comments for a specific post.I actually already built a function for retrieving all the data in the comments DB table (function getComments).

the comments DB table structure is : id(PK) | authorId | datetime | postId | text

Now, since I just need to count them (the comments),I was wondering if,in term of server resources/redundancy is better to use :

$comments=new Comment();
$comments->getComments();
echo count($comments);

Or I'm better build another function (apart from 'getComments')like :

function countComments($postid)
{
  //count comments per post
}

thanks

Luca


问:
sum of TOP N in Mysql
Below is my sample table. I want to get the TOP1 student for sum of score of each course

```<code>    create table SC(
SId varchar(10) comment "Student ID",
CId varchar(10) comment "Course ID",
score decimal(18,1) comment "Test Score");

insert into SC values('01' , '01' , 100);
insert into SC values('01' , '01' , 80);
insert into SC values('01' , '02' , 90);
insert into SC values('01' , '03' , 99);
insert into SC values('02' , '01' , 70);
insert into SC values('02' , '02' , 60);
insert into SC values('02' , '03' , 60);
insert into SC values('02' , '03' , 70);
</code>```

so the result would be:

I used below code but the score was not sum

```<code>SELECT SId,CId,sum(score)  from sc a
where 1 > (SELECT count(*) from sc where a.CId=CId and  a.score <score)
group by CId
ORDER BY CId
</code>```

I have Mysql 5.7, can you plz help?

答:
Use following query for the desired output.</p>

```<code>SELECT `SId`,`CId`,sum(`score`) from sc
GROUP BY `SID`,`CId`
ORDER BY `SId` ASC, `CId` ASC;
</code>```

Title: sum of TOP N in Mysql

Body:
Below is my sample table. I want to get the TOP1 student for sum of score of each course

    create table SC(
SId varchar(10) comment "Student ID",
CId varchar(10) comment "Course ID",
score decimal(18,1) comment "Test Score");

insert into SC values('01' , '01' , 100);
insert into SC values('01' , '01' , 80);
insert into SC values('01' , '02' , 90);
insert into SC values('01' , '03' , 99);
insert into SC values('02' , '01' , 70);
insert into SC values('02' , '02' , 60);
insert into SC values('02' , '03' , 60);
insert into SC values('02' , '03' , 70);

so the result would be:

I used below code but the score was not sum

SELECT SId,CId,sum(score)  from sc a
where 1 > (SELECT count(*) from sc where a.CId=CId and  a.score <score)
group by CId
ORDER BY CId

I have Mysql 5.7, can you plz help?

Body:
Use following query for the desired output.

SELECT `SId`,`CId`,sum(`score`) from sc
GROUP BY `SID`,`CId`
ORDER BY `SId` ASC, `CId` ASC;


问:
I'm not getting proper output for checking a string to be palindrome or not
I am not getting expected output while running the program

```<code>print('----------palindrome or not---------')
line=input('enter a line:-')
length=len(line)
a=0
if(length%2==0):
    length1=length/2
else:
    length1=(length+1)/2
for i in range (0,length-1):
    if(line[i]==line[length-2]):
        a+=1
if(a==length1):
    print("entered line is palindrome")
else:
    print("entered line is not palindrome")
</code>```

OUTPUT:

答:
You can just simply use the reversed() function on the input and check if both are same.

```<code>def palindrome(userinput):
    # reverse the text
    reversed_text = ''.join(reversed(userinput))

    # if user inputs blank
    if len(userinput) < 1:
        return False

    # check if reversed_text == userinput
    if (reversed_text == userinput):
        return True
    else:
        False

userinput = input()
text = palindrome(userinput)

if text:
    print('Entered line is palindrome')
else:
    print('Entered line is not palindrome')

</code>```

This works fine.

Body:
I am not getting expected output while running the program

print('----------palindrome or not---------')
line=input('enter a line:-')
length=len(line)
a=0
if(length%2==0):
    length1=length/2
else:
    length1=(length+1)/2
for i in range (0,length-1):
    if(line[i]==line[length-2]):
        a+=1
if(a==length1):
    print("entered line is palindrome")
else:
    print("entered line is not palindrome")

OUTPUT:

Body:
You can just simply use the reversed() function on the input and check if both are same.

def palindrome(userinput):
    # reverse the text
    reversed_text = ''.join(reversed(userinput))

    # if user inputs blank
    if len(userinput) < 1:
        return False

    # check if reversed_text == userinput
    if (reversed_text == userinput):
        return True
    else:
        False

userinput = input()
text = palindrome(userinput)

if text:
    print('Entered line is palindrome')
else:
    print('Entered line is not palindrome')

This works fine.


问:
apache CXF - with xml string
I am using CXF for web services.

I have an inner xml wrapped by an outher xml.
That is, I produce an xml:

```<code><aa><bb><cc>bla</cc></bb></aa>
</code>```

and than the CXF wraps it:

```<code><answer><aa><bb><cc>bla</cc></bb></aa></answer>
</code>```

As you can see, the < and > are escaped with < and >.

I wish that this doesn't happen.

Thank you very much.

答:
This behavior is by the definition of the xml syntax.

check e.g. http://en.wikipedia.org/wiki/XML

The characters "<" and "&" are key syntax markers and may never appear in content outside of a CDATA section.

There are five predefined entities: < represents "<", > represents ">", & represents "&", ' represents ', and " represents ".

You can try to wrap your inner xml inside a CDATA.

Title: apache CXF - with xml string

Body:
I am using CXF for web services.

I have an inner xml wrapped by an outher xml.
That is, I produce an xml:

<aa><bb><cc>bla</cc></bb></aa>

and than the CXF wraps it:

<answer><aa><bb><cc>bla</cc></bb></aa></answer>

As you can see, the < and > are escaped with < and >.

I wish that this doesn't happen.

Thank you very much.


问:
If True result based on a query output of 2 results
In column F I have the below formula which references the status of sheet 2 column G. The query formula produces 2 results populating cells F2 & F3. I want an "if" formula that if my query produces 2 cells containing yes, yes then say true but if it produces yes, no then produce false or no, no produce false.

This is the link to the sheet for reference. https://docs.google.com/spreadsheets/d/1C5xWlw9vMZMNhXprSCBZsNp0T9qMxvuooIP8I6JoI2Y/edit#gid=0

答:
delete F2:F range and paste this in F2 cell:

```<code>=ARRAYFORMULA(IFNA(VLOOKUP(A2:A&E2:E, QUERY({Sheet2!A2:A&Sheet2!B2:B,
 IF(Sheet2!G2:G="yes", 1, 0)},
 "select Col1,sum(Col2)
  where Col1 is not null
  group by Col1
  label sum(Col2)''"), 2, 0)=2))
</code>```

if Sheet2 jobs are not always in pairs use:

```<code>=ARRAYFORMULA(IFNA(VLOOKUP(A2:A&E2:E, QUERY({Sheet2!A2:A&Sheet2!B2:B,
 IF(Sheet2!G2:G="yes", 1, 0)},
 "select Col1,sum(Col2)
  where Col1 is not null
  group by Col1
  label sum(Col2)''"), 2, 0)=
 IFNA(VLOOKUP(A2:A&E2:E, QUERY({Sheet2!A2:A&Sheet2!B2:B,
 IF(Sheet2!G2:G="yes", 1, 0)},
 "select Col1,count(Col2)
  where Col1 is not null
  group by Col1
  label count(Col2)''"), 2, 0))))
</code>```

Body:
delete F2:F range and paste this in F2 cell:

=ARRAYFORMULA(IFNA(VLOOKUP(A2:A&E2:E, QUERY({Sheet2!A2:A&Sheet2!B2:B,
 IF(Sheet2!G2:G="yes", 1, 0)},
 "select Col1,sum(Col2)
  where Col1 is not null
  group by Col1
  label sum(Col2)''"), 2, 0)=2))

if Sheet2 jobs are not always in pairs use:

=ARRAYFORMULA(IFNA(VLOOKUP(A2:A&E2:E, QUERY({Sheet2!A2:A&Sheet2!B2:B,
 IF(Sheet2!G2:G="yes", 1, 0)},
 "select Col1,sum(Col2)
  where Col1 is not null
  group by Col1
  label sum(Col2)''"), 2, 0)=
 IFNA(VLOOKUP(A2:A&E2:E, QUERY({Sheet2!A2:A&Sheet2!B2:B,
 IF(Sheet2!G2:G="yes", 1, 0)},
 "select Col1,count(Col2)
  where Col1 is not null
  group by Col1
  label count(Col2)''"), 2, 0))))


问:
VBA AutoShapeType Ignored When Macro Runs
I have the following vba code:

```<code>Dim targetChart As Chart
Dim labelRange As Range

Set targetChart = Worksheets("Graph").ChartObjects("Chart 2").Chart
Set labelRange = Worksheets("Graph").Range("H3", "H" & lastrow)

With targetChart.SeriesCollection(4)
        .ApplyDataLabels
        With .DataLabels
            .Format.AutoShapeType = msoShapeRoundedRectangle
            .Format.TextFrame2.TextRange.InsertChartField msoChartFieldRange, labelRange.Address(External:=True), 0
            .ShowCategoryName = False
            .ShowRange = True
            .ShowSeriesName = False
            .ShowValue = False
        End With
    End With
</code>```

I want to format my data labels as rounded rectangles, but when I run the macro the .Format.AutoShapeType = msoShapeRoundedRectangle seems to not execute. When I step through the macro it doesn't throw an error so I am not sure what I am doing wrong. Everything else within the with statement works as intended.

The reason I have .ShowValue = False is because I am setting the data label values from a range.

答: In Excel's Help it says that both DataLabels.Format (the entire DataLabels collection) and DataLabel.Format (a single DataLabel) are read-only. Maybe what you're trying can't be done.

Body:
I have the following vba code:

Dim targetChart As Chart
Dim labelRange As Range

Set targetChart = Worksheets("Graph").ChartObjects("Chart 2").Chart
Set labelRange = Worksheets("Graph").Range("H3", "H" & lastrow)

With targetChart.SeriesCollection(4)
        .ApplyDataLabels
        With .DataLabels
            .Format.AutoShapeType = msoShapeRoundedRectangle
            .Format.TextFrame2.TextRange.InsertChartField msoChartFieldRange, labelRange.Address(External:=True), 0
            .ShowCategoryName = False
            .ShowRange = True
            .ShowSeriesName = False
            .ShowValue = False
        End With
    End With

I want to format my data labels as rounded rectangles, but when I run the macro the .Format.AutoShapeType = msoShapeRoundedRectangle seems to not execute. When I step through the macro it doesn't throw an error so I am not sure what I am doing wrong. Everything else within the with statement works as intended.

The reason I have .ShowValue = False is because I am setting the data label values from a range.


问:
How to update user inputted data into JSON
Using javascript, how would I go about creating a function that allows users to edit/update their user profile page (html) that is rendered from the Json file? The user first inputs their data into a page that requests the user response (js file in a routes folder) and then the Json file is rendered under profile html page through another js route.   </p>

```<code>    var data = require("../data.json");

    exports.addUser = function(request, response) {
        console.log(data);
        var name = request.query.name;
        var gender = request.query.gender;
        var height = request.query.height;
        var weight = request.query.weight;
        var newUser = {"name": name, "gender": gender, "height": height, "weight": weight};
        data.users.push(newUser);
        response.render('home');
    }

    // Get all of our user data
    var data = require('../data.json');

    exports.view = function(request, response){
        console.log(data);
        response.render('profile', data);
    };
</code>```

<p>My question is how would I create a function that allow users to make changes to their profile if they have already saved their information once? My app is about the gym with progress as one of the main focus. The user's first inputted information such as weight will not be the same as they progress through the gym, so I want to enable users to edit that information as they progress.   </p>

答:
normally you would have an "edit profile" page that retrieves the info from the server/database and then re-saves when you press the "save" button.

If you want this profile info available on other pages, you could also save your user profile json to localStorage.

Body:
Using javascript, how would I go about creating a function that allows users to edit/update their user profile page (html) that is rendered from the Json file? The user first inputs their data into a page that requests the user response (js file in a routes folder) and then the Json file is rendered under profile html page through another js route.

    var data = require("../data.json");

    exports.addUser = function(request, response) {
        console.log(data);
        var name = request.query.name;
        var gender = request.query.gender;
        var height = request.query.height;
        var weight = request.query.weight;
        var newUser = {"name": name, "gender": gender, "height": height, "weight": weight};
        data.users.push(newUser);
        response.render('home');
    }

    // Get all of our user data
    var data = require('../data.json');

    exports.view = function(request, response){
        console.log(data);
        response.render('profile', data);
    };

My question is how would I create a function that allow users to make changes to their profile if they have already saved their information once? My app is about the gym with progress as one of the main focus. The user's first inputted information such as weight will not be the same as they progress through the gym, so I want to enable users to edit that information as they progress.