问:
Azure DevOps - Select distinct IterationPath (workitems table)
I am trying to make in Python a distinct of all the possibilities of the IterationPath field and I am not able to obtain such data. I tried to use UNNEST to get the array it is in but I was unsuccessful. Can anyone help me with this?</p>

```<code>query_wiql = Wiql(query="""\
SELECT distinct [System.IterationPath] FROM workitems
""")
</code>```

答:
If you're trying to get all the possibilities of the IterationPath field in current team project, you can try:

```<code>SELECT
        [System.IterationPath]
FROM workitems
WHERE
        [System.TeamProject] = @project
ORDER BY [System.ChangedDate] DESC
</code>```

And if you want to get all the possibilities of the IterationPath field in current organization, you can use:

```<code>SELECT
        [System.IterationPath]
FROM workitems
ORDER BY [System.ChangedDate] DESC
</code>```

If you don't want the order, you can delete the ORDER BY [System.ChangedDate] DESC. Hope it helps and if I misunderstand anything, feel free to correct me.

Body:
I am trying to make in Python a distinct of all the possibilities of the IterationPath field and I am not able to obtain such data. I tried to use UNNEST to get the array it is in but I was unsuccessful. Can anyone help me with this?

query_wiql = Wiql(query="""\
SELECT distinct [System.IterationPath] FROM workitems
""")

Body:
If you're trying to get all the possibilities of the IterationPath field in current team project, you can try:

SELECT
        [System.IterationPath]
FROM workitems
WHERE
        [System.TeamProject] = @project
ORDER BY [System.ChangedDate] DESC

And if you want to get all the possibilities of the IterationPath field in current organization, you can use:

SELECT
        [System.IterationPath]
FROM workitems
ORDER BY [System.ChangedDate] DESC

If you don't want the order, you can delete the ORDER BY [System.ChangedDate] DESC. Hope it helps and if I misunderstand anything, feel free to correct me.


来源: stackexchange

问:
Unexpected EOF - Terraform apply
I am new to Azure / Azure Devops and Terraform, I am getting the following error when im running terraform apply from an Azure DevOps Pipeline.

/home/vsts/work/_temp/38418e2b-b5e5-48c1-8579-69d937b85bfc.sh: line 9: unexpected EOF while looking for matching `"'
/home/vsts/work/_temp/38418e2b-b5e5-48c1-8579-69d937b85bfc.sh: line 10: syntax error: unexpected end of file

Here is the script I am trying to execute as part of a yaml pipeline. I can run the same code for UAT and Prod with no issues.

```<code>      - script: |
                terraform apply \
                  -auto-approve \
                  -var="client-id=$(client-id)" \
                  -var="client-secret=$(client-secret)" \
                  -var="subscription-id=$(subscription-id)" \
                  -var="tenant-id=$(tenant-id)" \
                  -var="application_name=transport" \
                  -var="environment_tag=dev" \
                  -var="location=northeurope" \
        workingDirectory: './deploy'
        displayName: 'Terraform apply'
</code>```

答:
If you are running on a Windows agent. You can try use '^'. For below example

```<code> - script: |
      terraform apply ^
         -auto-approve ^
         -var="client-id=$(client-id)" ^
          ....
</code>```

You can also try replacing '|' with '>'.

```<code>- script: >
    terraform apply \
      -auto-approve \
      -var="client-id=$(client-id)" \
</code>```

Please check this thread for more information.

ContentLicense: CC BY-SA 4.0

Title: Unexpected EOF - Terraform apply

Body:
I am new to Azure / Azure Devops and Terraform, I am getting the following error when im running terraform apply from an Azure DevOps Pipeline.

/home/vsts/work/_temp/38418e2b-b5e5-48c1-8579-69d937b85bfc.sh: line 9: unexpected EOF while looking for matching `"'
/home/vsts/work/_temp/38418e2b-b5e5-48c1-8579-69d937b85bfc.sh: line 10: syntax error: unexpected end of file

Here is the script I am trying to execute as part of a yaml pipeline. I can run the same code for UAT and Prod with no issues.

      - script: |
                terraform apply \
                  -auto-approve \
                  -var="client-id=$(client-id)" \
                  -var="client-secret=$(client-secret)" \
                  -var="subscription-id=$(subscription-id)" \
                  -var="tenant-id=$(tenant-id)" \
                  -var="application_name=transport" \
                  -var="environment_tag=dev" \
                  -var="location=northeurope" \
        workingDirectory: './deploy'
        displayName: 'Terraform apply'

Body:
If you are running on a Windows agent. You can try use '^'. For below example

 - script: |
      terraform apply ^
         -auto-approve ^
         -var="client-id=$(client-id)" ^
          ....

You can also try replacing '|' with '>'.

- script: >
    terraform apply \
      -auto-approve \
      -var="client-id=$(client-id)" \

Please check this thread for more information.


问:
Oracle PL/SQL get current timestamp number 19
Is there a way in Oralce PL/SQL to get the current timestamp as a NUMBER ?

Something like '1582185277302'

答:
Unix timestamps are in the UTC time zone. If your timestamp is in the UTC time zone then you can use:

( TRUNC( your_timestamp, 'MI' ) - DATE '1970-01-01' ) * 24 * 60 * 60 * 1000
+ EXTRACT( SECOND FROM your_timestamp ) * 1000
```

<p>If your timestamps have a time zone then:</p>

<pre class="lang-sql prettyprint-override"><code>( TRUNC( your_timestamp AT TIME ZONE 'UTC', 'MI' ) - DATE '1970-01-01' ) * 24 * 60 * 60 * 1000
+ EXTRACT( SECOND FROM your_timestamp ) * 1000
</code>```

If you need to handle leap seconds then you can use this answer.

Body:
Unix timestamps are in the UTC time zone. If your timestamp is in the UTC time zone then you can use:

( TRUNC( your_timestamp, 'MI' ) - DATE '1970-01-01' ) * 24 * 60 * 60 * 1000
+ EXTRACT( SECOND FROM your_timestamp ) * 1000

If your timestamps have a time zone then:

( TRUNC( your_timestamp AT TIME ZONE 'UTC', 'MI' ) - DATE '1970-01-01' ) * 24 * 60 * 60 * 1000
+ EXTRACT( SECOND FROM your_timestamp ) * 1000

If you need to handle leap seconds then you can use this answer.


问:
Why I get name 'url_link' is not defined error?
I have this part of code want to compare two files xls and json in json I have empty string and empty cell in xls == naan

```<code>if row["URL Link"] == "nan":
    global url_link
    url_link = ''

assert_equal_values(str(item["urlLink"]), url_link, "URL Link is not match!")
</code>```

got this error name

url_link is not defined

if I remove global  then I got

local variable 'url_link' referenced before assignment

```<code>if row["URL Link"] == "nan":
    url_link = ''
</code>```

答:
I found the solution row["URL Link"] need to be a string
so added str(row["URL Link"])</p>

Body:
I have this part of code want to compare two files xls and json in json I have empty string and empty cell in xls == naan

if row["URL Link"] == "nan":
    global url_link
    url_link = ''

assert_equal_values(str(item["urlLink"]), url_link, "URL Link is not match!")

got this error name

url_link is not defined

if I remove global  then I got

local variable 'url_link' referenced before assignment

if row["URL Link"] == "nan":
    url_link = ''


问:
On Initialization Failure in google play IAP?
I'm trying to create IAP in my app using google play console. I already uploaded an APK in the internal test track and added 1 product in Manage Product Tab. When I tried to run it in an android phone, OnInitializeFailed InitializationFailureReason:NoProductsAvailable appears in the logs. But when I run it in my editor, it returns OnInitialized:Pass.

Do I need to create an alpha/beta just to test IAP?

Editor Logs:

Android Mobile Logs:

```<code>Warning
Unavailable product book_1 -book_1
UnityEngine.Purchasing.Extension.UnityUtil:Update()

Log
OnInitializeFailed InitializationFailureReason:NoProductsAvailable
IAPManager:OnInitializeFailed(InitializationFailureReason)
UnityEngine.Purchasing.Extension.UnityUtil:Update()

Log
UnityIAP Promo: Clearing promo product metadata
UnityEngine.Purchasing.Extension.UnityUtil:Update()
</code>```

答:
It looks like you did not published a release to the internal test track. Press EDIT RELEASE button, scroll down. You will see several buttons: SAVE, REVIEW. After you press a REVIEW button, you will see a new page. Review a release and then press a START ROLLOUT button. This will make your app available for testers via Google Play. Make sure to complete all prerequisites, like in this answer: https://stackoverflow.com/a/50468247/2556378

However, this will not solve the problem, because in-app billing is available only after app is published to either Open or Closed test track, as per this article: https://developer.android.com/google/play/billing/billing_testing

Keep in mind, that the app itself and in-app products will still be available to testers only. I.e. you will still get an error unless logged in with tester account on the device.

Body:
I'm trying to create IAP in my app using google play console. I already uploaded an APK in the internal test track and added 1 product in Manage Product Tab. When I tried to run it in an android phone, OnInitializeFailed InitializationFailureReason:NoProductsAvailable appears in the logs. But when I run it in my editor, it returns OnInitialized:Pass.

Do I need to create an alpha/beta just to test IAP?

Editor Logs:

Android Mobile Logs:

Warning
Unavailable product book_1 -book_1
UnityEngine.Purchasing.Extension.UnityUtil:Update()

Log
OnInitializeFailed InitializationFailureReason:NoProductsAvailable
IAPManager:OnInitializeFailed(InitializationFailureReason)
UnityEngine.Purchasing.Extension.UnityUtil:Update()

Log
UnityIAP Promo: Clearing promo product metadata
UnityEngine.Purchasing.Extension.UnityUtil:Update()


问:
A way to send a Microsoft Teams chat message from SSIS
Is it possible to send an MS Teams chat message to one or more people or even to a Team Post from SSIS?

We have some processes that send notices via Email, but anymore email is just too busy and it would be nice to have a central location in Teams to have messages when certain items complete or fail via SSIS.

答:
Take help from following Link:
Following link help to send text message via sql server
Text message via SQL Server</p>


问:
Elasticsearch 5.2.2: terms aggregation case insensitive
I am attempting to do a case-insensitive aggregation on a keyword type field, but I'm having issues in getting this to work.

What I have tried so far is to add a custom analyzer called "lowercase" which uses the "keyword" tokenizer, and "lowercase" filter. I then added a field to the mapping called "use_lowercase" for the field I want to work with. I wanted to retain the existing "text" and "keyword" field components as well since I may want to search for the terms within the field.

Here is the index definition, including the custom analyzer:

```<code>PUT authors
{
  "settings": {
    "analysis": {
      "analyzer": {
        "lowercase": {
          "type": "custom",
          "tokenizer": "keyword",
          "filter": "lowercase"
        }
      }
    }
  },
  "mappings": {
    "famousbooks": {
      "properties": {
        "Author": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            },
            "use_lowercase": {
              "type": "text",
              "analyzer": "lowercase"
            }
          }
        }
      }
    }
  }
}
</code>```

Now I add 2 records with the same Author, but with different case:

```<code>POST authors/famousbooks/1
{
  "Book": "The Mysterious Affair at Styles",
  "Year": 1920,
  "Price": 5.92,
  "Genre": "Crime Novel",
  "Author": "Agatha Christie"
}

POST authors/famousbooks/2
{
  "Book": "And Then There Were None",
  "Year": 1939,
  "Price": 6.99,
  "Genre": "Mystery Novel",
  "Author": "Agatha christie"
}
</code>```

So far so good. Now if I do a terms aggregation based on Author,

```<code>GET authors/famousbooks/_search
{
  "size": 0,
  "aggs": {
    "authors-aggs": {
      "terms": {
        "field": "Author.use_lowercase"
      }
    }
  }
}
</code>```

I get the following result:

```<code>{
  "error": {
    "root_cause": [
      {
        "type": "illegal_argument_exception",
        "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [Author.use_lowercase] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory."
      }
    ],
    "type": "search_phase_execution_exception",
    "reason": "all shards failed",
    "phase": "query",
    "grouped": true,
    "failed_shards": [
      {
        "shard": 0,
        "index": "authors",
        "node": "yxcoq_eKRL2r6JGDkshjxg",
        "reason": {
          "type": "illegal_argument_exception",
          "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [Author.use_lowercase] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory."
        }
      }
    ],
    "caused_by": {
      "type": "illegal_argument_exception",
      "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [Author.use_lowercase] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory."
    }
  },
  "status": 400
}
</code>```

So it seems to me that the aggregation is thinking that the search field is text instead of keyword, and hence giving me the fielddata warning. I would think that ES would be sophisticated enough to recognize that the terms field is in fact a keyword (via custom analyzer) and therefore aggregate-able, but that doesn't appear to be the case.

If I add "fielddata":true to the mapping for Author, the aggregation then works fine, but I'm hesitant to do this given the dire warnings of high heap usage when setting this value.

Is there a best practice for doing this type of insensitive keyword aggregation? I was hoping I could just say "type":"keyword", "filter":"lowercase" in the mappings section but that is not available it seems.

It feels like I'm having to use too big of a stick to get this to work if I go the "fielddata":true route. Any help on this would be appreciated!

答:
It seems this is not possible by default,(without "lowercase" normalizer) but without this you can use a trick - translate the string in a case insensitive regex match.

e.g. for string "bar" - a case insensitive regex would be "[bB][aA][rR]"

I used a python helper for doing this:

```<code>def case_insensitive_regex_from_string(v):
    if not v:
        return v
    zip_obj = zip(itertools.cycle('['), v, v.swapcase(), itertools.cycle(']'))
    return ''.join(''.join(x) for x in zip_obj)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am attempting to do a case-insensitive aggregation on a keyword type field, but I'm having issues in getting this to work.

What I have tried so far is to add a custom analyzer called "lowercase" which uses the "keyword" tokenizer, and "lowercase" filter. I then added a field to the mapping called "use_lowercase" for the field I want to work with. I wanted to retain the existing "text" and "keyword" field components as well since I may want to search for the terms within the field.

Here is the index definition, including the custom analyzer:

PUT authors
{
  "settings": {
    "analysis": {
      "analyzer": {
        "lowercase": {
          "type": "custom",
          "tokenizer": "keyword",
          "filter": "lowercase"
        }
      }
    }
  },
  "mappings": {
    "famousbooks": {
      "properties": {
        "Author": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            },
            "use_lowercase": {
              "type": "text",
              "analyzer": "lowercase"
            }
          }
        }
      }
    }
  }
}

Now I add 2 records with the same Author, but with different case:

POST authors/famousbooks/1
{
  "Book": "The Mysterious Affair at Styles",
  "Year": 1920,
  "Price": 5.92,
  "Genre": "Crime Novel",
  "Author": "Agatha Christie"
}

POST authors/famousbooks/2
{
  "Book": "And Then There Were None",
  "Year": 1939,
  "Price": 6.99,
  "Genre": "Mystery Novel",
  "Author": "Agatha christie"
}

So far so good. Now if I do a terms aggregation based on Author,

GET authors/famousbooks/_search
{
  "size": 0,
  "aggs": {
    "authors-aggs": {
      "terms": {
        "field": "Author.use_lowercase"
      }
    }
  }
}

I get the following result:

{
  "error": {
    "root_cause": [
      {
        "type": "illegal_argument_exception",
        "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [Author.use_lowercase] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory."
      }
    ],
    "type": "search_phase_execution_exception",
    "reason": "all shards failed",
    "phase": "query",
    "grouped": true,
    "failed_shards": [
      {
        "shard": 0,
        "index": "authors",
        "node": "yxcoq_eKRL2r6JGDkshjxg",
        "reason": {
          "type": "illegal_argument_exception",
          "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [Author.use_lowercase] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory."
        }
      }
    ],
    "caused_by": {
      "type": "illegal_argument_exception",
      "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [Author.use_lowercase] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory."
    }
  },
  "status": 400
}

So it seems to me that the aggregation is thinking that the search field is text instead of keyword, and hence giving me the fielddata warning. I would think that ES would be sophisticated enough to recognize that the terms field is in fact a keyword (via custom analyzer) and therefore aggregate-able, but that doesn't appear to be the case.

If I add "fielddata":true to the mapping for Author, the aggregation then works fine, but I'm hesitant to do this given the dire warnings of high heap usage when setting this value.

Is there a best practice for doing this type of insensitive keyword aggregation? I was hoping I could just say "type":"keyword", "filter":"lowercase" in the mappings section but that is not available it seems.

It feels like I'm having to use too big of a stick to get this to work if I go the "fielddata":true route. Any help on this would be appreciated!

Body:
It seems this is not possible by default,(without "lowercase" normalizer) but without this you can use a trick - translate the string in a case insensitive regex match.

e.g. for string "bar" - a case insensitive regex would be "[bB][aA][rR]"

I used a python helper for doing this:

def case_insensitive_regex_from_string(v):
    if not v:
        return v
    zip_obj = zip(itertools.cycle('['), v, v.swapcase(), itertools.cycle(']'))
    return ''.join(''.join(x) for x in zip_obj)


问:
How do you fight design complexity?
I often find myself fighting overengineering -- the person in charge of designing the software comes up with an architecture that's, way, way overcomplicated.

It's all fine and dandy to have all the esoteric features that users will never know about and get that sense of achievement when you're doing something that all the magazine articles are telling you is the latest, cool thing, but we are going to spend half of our  engineering time on this monument to our cleverness, and not, you know, the actual product that our users need and upper management expects to be completed within a reasonable or at least a bounded time frame.

And you'll probably just have to revert back to the simpler solution anyway when you start running out of time, that is, if you get that chance.

We've all heard the refrain: Keep It Simple, Stupid™.

How do you fight with overcomplexity in your team?

One example I've had to work with repeatedly lately is when the decision has been made to go to a fully denormalized database design rather than an RDBMS. "because it's faster!" Fully denormalized databases are really hard to get right, and are only appropriate for really specialized data problems like Flickr or ebay, and which can be extremely expensive in terms of developer time relative to the rest of your development.

答:
Do the people involved have enough time and incentive to find a simple solution? Without care, complexity will increase. If you spend most of your time trying to do the quickest possible bug fix or feature addition then saying "keep it simple" will not be  enough. </p>

<p>Ensure that there are some people on the team with war wounds from  maintaining large programs, and people with experience of refactoring, and then give them time to sort the software out. If you can arrange that certain features and opportunities are out of scope, that will help people remove unneeded code. If you want a metric, aim to reduce lines of code; but try not to obsess over it. Improve the test coverage; consider eliminating bits of code which are hard to test. </p>

OwnerDisplayName: ʞɔıu

ContentLicense: CC BY-SA 2.5

Title: How do you fight design complexity?

LastEditorDisplayName: philippe

Body:
Do the people involved have enough time and incentive to find a simple solution? Without care, complexity will increase. If you spend most of your time trying to do the quickest possible bug fix or feature addition then saying "keep it simple" will not be  enough.

Ensure that there are some people on the team with war wounds from  maintaining large programs, and people with experience of refactoring, and then give them time to sort the software out. If you can arrange that certain features and opportunities are out of scope, that will help people remove unneeded code. If you want a metric, aim to reduce lines of code; but try not to obsess over it. Improve the test coverage; consider eliminating bits of code which are hard to test.

OwnerDisplayName: Dickon Reed


问:
NavLink not adding 'active' class attribute in a react-app
React apps using create-react-app have this problem where NavLink doesn't add active class attribute.
Tried lots of solutions like adding exact attribute inside NavLink but none worked so far.</p>

```<code>    import {NavLink} from 'react-router-dom';

    return (
        <nav>
            <NavLink to='/user/feed'>Feed</NavLink>
            <NavLink to='/user/messages'>Messages</NavLink>
        </nav>
    )
</code>```

答:
Finally a solution. Run below command in your react-app directory and restart your app.</p>

```<code>npm i path-to-regexp@1.7.0 -S
</code>```

Body:
React apps using create-react-app have this problem where NavLink doesn't add active class attribute.
Tried lots of solutions like adding exact attribute inside NavLink but none worked so far.

    import {NavLink} from 'react-router-dom';

    return (

            <NavLink to='/user/feed'>Feed</NavLink>
            <NavLink to='/user/messages'>Messages</NavLink>

    )

Body:
Finally a solution. Run below command in your react-app directory and restart your app.

npm i path-to-regexp@1.7.0 -S


问:
Laravel and displaying errors in Placeholder
I have a question regarding error displaying in laravel. So I want errors to be displayed in placeholders. I have done it, however, there is another problem. When I open the page I do not see placeholders so the user cannot get which input is for name and surname and etc.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="{{asset('css/signup.css')}}">

    <!DOCTYPE html>

 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Login</title>

        <form action="{{url('/register')}}" method='post'>
        {{csrf_field()}}
        <input name='name' id='name'value='@if(!$errors->first("name")){{old("name")}}@endif' placeholder="{{$errors->first('name')}}">
        <input name='surname'  value='@if(!$errors->first("surname")){{old("surname")}}@endif' placeholder="{{$errors->first('surname')}}">
        <input name='email'    value='@if(!$errors->first("email")){{old("email")}}@endif' placeholder="{{$errors->first('email')}}">
        <input name='age'      value='@if(!$errors->first("age")){{old("age")}}@endif' placeholder="{{$errors->first('age')}}">
        <input name='password' value='@if(!$errors->first("password")){{old("password")}}@endif' type='password' placeholder='{{$errors->first("password")}}'>
        <input name='confirm'  value='@if(!$errors->first("confirm")){{old("confirm")}}@endif' type='password' placeholder='{{$errors->first("confirm")}}'>
        <button class='btn btn-danger'>Save</button>
    </form>

```

答:
Update

```<code> <input name='name' id='name'value='@if(!$errors->first("name")){{old("name")}}@endif' placeholder="{{$errors->first('name')}}">
</code>```

to

```<code> <input name='name' id='name'value='@if(!$errors->first("name")){{old("name")}}@endif' placeholder="{{$errors->has('name') ? $errors->first('name') : 'Name' }}">
</code>```

Same way update for other input tags too.

Body:
Update

 <input name='name' id='name'value='@if(!$errors->first("name")){{old("name")}}@endif' placeholder="{{$errors->first('name')}}">

to

 <input name='name' id='name'value='@if(!$errors->first("name")){{old("name")}}@endif' placeholder="{{$errors->has('name') ? $errors->first('name') : 'Name' }}">

Same way update for other input tags too.


问:
Installing Haskell on Windows, cabal config
I'm installing Haskell on Windows based on the instructions at https://www.haskell.org/platform/ and looking at step 3, it says, Modify your cabal config file (you can verify the location by running "cabal user-config init") to contain the following lines:

```<code>extra-prog-path: C:\Program Files\Haskell Platform\8.0.2\msys\usr\bin
extra-lib-dirs: C:\Program Files\Haskell Platform\8.0.2\mingw\lib
extra-include-dirs: C:\Program Files\Haskell Platform\8.0.2\mingw\include
</code>```

But the auto generated config file contains e.g.

```<code>extra-prog-path: C:\Users\w\AppData\Roaming\cabal\bin
</code>```

So that's a different value for one of the suggested variables.

Is this intentional?

What should I do, paste the lines from step 3 at the start of the file, the end of the file, overwrite the existing lines or skip step 3 altogether?

答:
I have cabal-install version 2.4.1.0. As proposed in https://www.haskell.org/cabal/users-guide/nix-local-build.html and contrary to the installing instructions at https://www.haskell.org/platform/windows.html, I'm using one single extra-prog-path line containing a comma separated list of paths:

extra-prog-path: C:\Users\...\AppData\Roaming\cabal\bin,C:\Program Files\Haskell Platform\8.6.5\msys\usr\bin

Reason: Like this, at least the command cabal user-config diff gives reasonable results.

```<code>C:\>cabal user-config diff
+ extra-include-dirs: C:\Program Files\Haskell Platform\8.6.5\mingw\include
+ extra-lib-dirs: C:\Program Files\Haskell Platform\8.6.5\mingw\lib
- extra-prog-path: C:\Users\...\AppData\Roaming\cabal\bin
+ extra-prog-path: C:\Users\...\Roaming\cabal\bin,C:\Program Files\Haskell Platform\8.6.5\msys\usr\bin
+ logs-dir: C:\Users\...\AppData\Roaming\cabal\logs
</code>```

If I'd follow the installing instructions and use two extra-prog-path lines, then  cabal user-config diff would ignore the second one. I'm not sure however if this matters.

Body:
I'm installing Haskell on Windows based on the instructions at https://www.haskell.org/platform/ and looking at step 3, it says, Modify your cabal config file (you can verify the location by running "cabal user-config init") to contain the following lines:

extra-prog-path: C:\Program Files\Haskell Platform\8.0.2\msys\usr\bin
extra-lib-dirs: C:\Program Files\Haskell Platform\8.0.2\mingw\lib
extra-include-dirs: C:\Program Files\Haskell Platform\8.0.2\mingw\include

But the auto generated config file contains e.g.

extra-prog-path: C:\Users\w\AppData\Roaming\cabal\bin

So that's a different value for one of the suggested variables.

Is this intentional?

What should I do, paste the lines from step 3 at the start of the file, the end of the file, overwrite the existing lines or skip step 3 altogether?

Body:
I have cabal-install version 2.4.1.0. As proposed in https://www.haskell.org/cabal/users-guide/nix-local-build.html and contrary to the installing instructions at https://www.haskell.org/platform/windows.html, I'm using one single extra-prog-path line containing a comma separated list of paths:

extra-prog-path: C:\Users\...\AppData\Roaming\cabal\bin,C:\Program Files\Haskell Platform\8.6.5\msys\usr\bin

Reason: Like this, at least the command cabal user-config diff gives reasonable results.

C:\>cabal user-config diff
+ extra-include-dirs: C:\Program Files\Haskell Platform\8.6.5\mingw\include
+ extra-lib-dirs: C:\Program Files\Haskell Platform\8.6.5\mingw\lib
- extra-prog-path: C:\Users\...\AppData\Roaming\cabal\bin
+ extra-prog-path: C:\Users\...\Roaming\cabal\bin,C:\Program Files\Haskell Platform\8.6.5\msys\usr\bin
+ logs-dir: C:\Users\...\AppData\Roaming\cabal\logs

If I'd follow the installing instructions and use two extra-prog-path lines, then  cabal user-config diff would ignore the second one. I'm not sure however if this matters.


问:
Sort GridView by column name
I am making a GridView and assigning it to the View property of a ListView. The ListView's ItemsSource is bound to an ObservableCollection<Entry>. Entry is a model in my MVVM application, and it contains a List<KeyValuePair<string,string>>. It also has an indexer which fetches the first KeyValurPair<string,string>'s Value property (from the list) which matches the indexer parameter. So it's much like a dictionary.

Now here's how I am making the GridView.

```<code>foreach (Column column in category.Columns.Where(c => c.IsVisibleInTable)) {
    var gridViewColumn = new GridViewColumn {
                                                Header = column.Name,
                                                DisplayMemberBinding = new Binding($"[{column.Name}].Value")
                                            };
    gridView.Columns.Add(gridViewColumn);
}
</code>```

Column is also a model but that's not really relevant here.

Now I want to tell the GridView to sort based on the first column. But I can't use the DefaultView of the ItemsSource and add a SortDescription to it because SortDescription expects a Property name whereas I am not binding to a property name but instead to an indexer.

So how can I sort based on the second column?

答:
here is sorting algo

iN gridview pass this two parameter aspx
AllowSorting="true"
  OnSorting="OnSorting"

private string SortDirection
        {
            get { return ViewState["SortDirection"] != null ? ViewState["SortDirection"].ToString() : "ASC"; }
            set { ViewState["SortDirection"] = value; }
        }
        protected void OnSorting(object sender, GridViewSortEventArgs e)
        {
            this.BindGrid(e.SortExpression);
        }

here we have to place the code
`  private void BindGrid(string sortExpression = null)
        {
            conn.Open();

```<code>        SqlCommand cmd = new SqlCommand("SELECT * from [test].[dbo].[myform] order by name", conn);
        SqlDataAdapter sda = new SqlDataAdapter();

        cmd.Connection = conn;
        sda.SelectCommand = cmd;
        using (DataTable dt = new DataTable())
        {
            sda.Fill(dt);
            if (sortExpression != null)
            {
                DataView dv = dt.AsDataView();
                this.SortDirection = this.SortDirection == "ASC" ? "DESC" : "ASC";
                dv.Sort = sortExpression + " " + this.SortDirection;
                GridView2.DataSource = dv;
            }
            else
            {
                GridView2.DataSource = dt;
            }
            GridView2.DataBind();
            conn.Close();

        }

    }`
</code>```

Title: Sort GridView by column name

Body:
I am making a GridView and assigning it to the View property of a ListView. The ListView's ItemsSource is bound to an ObservableCollection<Entry>. Entry is a model in my MVVM application, and it contains a List<KeyValuePair<string,string>>. It also has an indexer which fetches the first KeyValurPair<string,string>'s Value property (from the list) which matches the indexer parameter. So it's much like a dictionary.

Now here's how I am making the GridView.

foreach (Column column in category.Columns.Where(c => c.IsVisibleInTable)) {
    var gridViewColumn = new GridViewColumn {
                                                Header = column.Name,
                                                DisplayMemberBinding = new Binding($"[{column.Name}].Value")
                                            };
    gridView.Columns.Add(gridViewColumn);
}

Column is also a model but that's not really relevant here.

Now I want to tell the GridView to sort based on the first column. But I can't use the DefaultView of the ItemsSource and add a SortDescription to it because SortDescription expects a Property name whereas I am not binding to a property name but instead to an indexer.

So how can I sort based on the second column?

Body:
here is sorting algo

iN gridview pass this two parameter aspx
AllowSorting="true"
  OnSorting="OnSorting"

private string SortDirection
        {
            get { return ViewState["SortDirection"] != null ? ViewState["SortDirection"].ToString() : "ASC"; }
            set { ViewState["SortDirection"] = value; }
        }
        protected void OnSorting(object sender, GridViewSortEventArgs e)
        {
            this.BindGrid(e.SortExpression);
        }

here we have to place the code
`  private void BindGrid(string sortExpression = null)
        {
            conn.Open();

        SqlCommand cmd = new SqlCommand("SELECT * from [test].[dbo].[myform] order by name", conn);
        SqlDataAdapter sda = new SqlDataAdapter();

        cmd.Connection = conn;
        sda.SelectCommand = cmd;
        using (DataTable dt = new DataTable())
        {
            sda.Fill(dt);
            if (sortExpression != null)
            {
                DataView dv = dt.AsDataView();
                this.SortDirection = this.SortDirection == "ASC" ? "DESC" : "ASC";
                dv.Sort = sortExpression + " " + this.SortDirection;
                GridView2.DataSource = dv;
            }
            else
            {
                GridView2.DataSource = dt;
            }
            GridView2.DataBind();
            conn.Close();

        }

    }`


问:
library module and google-services.json files
I am already using an application(has app module) which uses conversations.im as the base. This application has free, paid etc product flavors and debug and release build types. This project already has firebase integration and has 2 applications integrated. I have one google-services.json file in the root directory of the app module.

Now I want to move away from conversations.im(ejabber) and want to implement a separate chat component using cloud firestore. I have created this component as an android library module which I will use in my existing app module.

I want to have separate chat data for this chat library for debug and release types. This will require me to have unique application ids for this library module. But documentation says I cannot have applicationId in a library module.

I am confused where to keep the google-services.json files, in library module or in the app module which will use the chat library module. Looks like can't keep in library because of limitation. And if I keep in app module, library chat module can't work as a separate module in itself.

How should I go about this setup so that I could use different google-services.json files for debug and release types and at the same time make this new module as a library.

答:
I have sorted this.

I had to create separate project to keep my firestore chat data for staging and production separate. This is because firebase console does not show the firestore chat data application wise. It shows the chat data project wise. Therefore irrespective of your app's build-variants, data will always flow into one firestore db. And just in case we want to keep our test and production data clean, creating a new firebase project is the only way out.

Thanks everyone for reading the question.


问:
NIFI Workflow Failure Entry
I have got few processors like Select Hive and Put HDFS and I need a contemporary way to insert a Hive Query into a table when any of the processor fails in the workflow. </p>

<p>P.S I tried connecting all the failure entries via funnel but any better thought will be appreciated. </p>

答:
It's a good way to use funnel. I would recommend you to make a different process group for handling errors. Mainly for a better monitoring later and flow lisibility, like this :

You can also use input and output port that give you a good visibility and you can handle each errors differently.

for exemple :

make outpout port in your main flow :

handle each error in a different process group, with input port :

then rely both :

Title: NIFI Workflow Failure Entry

Body:
I have got few processors like Select Hive and Put HDFS and I need a contemporary way to insert a Hive Query into a table when any of the processor fails in the workflow.

P.S I tried connecting all the failure entries via funnel but any better thought will be appreciated.


问:
What React useCallback do when I pass. an object in first argument
I am fixing an infinite loop when using react with useEffect and useCallback.

```<code>const fetchApi =useCallback(()=>{
    setIsLoading(true)
      fetchDataFunction({
        resolve(res) {
          setFetchData(fromJS(res))
          setIsLoading(false)
        }
      })
},[param])
useEffect(()=>{
    fetchApi()
},[fetchApi])

</code>```

It is causing an infinite loop. However, if I change the code as shown below

```<code>const fetchApi = useCallback({
    fetchApiFunc() {
      setIsLoading(true)
      fetchDataFunction({
        resolve(res) {
          setFetchData(fromJS(res))
          setIsLoading(false)
        }
      })
    }
  },[params])
  const { fetchApiFunc } = fetchApi
  useEffect(() => {
    fetchApiFunc()
  }, [fetchApiFunc])
</code>```

the problem is fixed. But I still do not understand what it does when the object in first params in useCallback.

Thank you.

答:
If you start using React-Hooks, and your component might need a life cycle method at some point. And, that is when you start using useEffect() (a.k.a Effect Hook). Then boom!!, you have encountered an infinite loop behavior, and you have no idea why the hell is that. If that happens, this article will explain to you why, and how can you prevent.

Where is the problem?
The “useEffect()”, will run after the initial render, then invoke the "fetchApiFunc()”.
Inside the   "fetchApiFunc()”, it will update the state “name” on line Then it will trigger the component to re-render again.
As a result, “useEffect()” will run again and update the state. Next, the whole process repeats again, and you're trapped inside an infinite loop.

“You can tell React to skip applying an effect if certain values haven’t changed between re-renders. To do so, pass an array as an optional second argument to useEffect”, from the official here: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects

Body:
I am fixing an infinite loop when using react with useEffect and useCallback.

const fetchApi =useCallback(()=>{
    setIsLoading(true)
      fetchDataFunction({
        resolve(res) {
          setFetchData(fromJS(res))
          setIsLoading(false)
        }
      })
},[param])
useEffect(()=>{
    fetchApi()
},[fetchApi])

It is causing an infinite loop. However, if I change the code as shown below

const fetchApi = useCallback({
    fetchApiFunc() {
      setIsLoading(true)
      fetchDataFunction({
        resolve(res) {
          setFetchData(fromJS(res))
          setIsLoading(false)
        }
      })
    }
  },[params])
  const { fetchApiFunc } = fetchApi
  useEffect(() => {
    fetchApiFunc()
  }, [fetchApiFunc])

the problem is fixed. But I still do not understand what it does when the object in first params in useCallback.

Thank you.


问:
I can not install my Android app to my phone
I am new in android app development.
I made an android app. When I run it from Android Studio to my phone it works perfectly.
Then I back it up to my SD card and try to install it and it gives me an  "Installation failed" message.
I tried using various phones but it didn't work.

What is the problem actually?
What should I do to install my app on other phones (regarding the SDK version)?

答: You need to build APK file to run the app on different devices and take a backup. The debug file can't be backed up and shared with other devices. The steps of how to build an APK file are given below. Please follow steps and it will work as you expect.


问:
Set accessibilityLabel on UIMenuItem
I am trying to set the accessibilityLabel of a UIMenuItem and it seems to have no effect. VoiceOver simply reads the title of the item no matter what:

```<code>    let foo = UIMenuItem(title: "foo", action: #selector(doSomething))
    item.isAccessibilityElement = true
    item.accessibilityLabel = "bar"
</code>```

For this item, VoiceOver reads "foo" instead of "bar."  Also, the accessibilityHint seems to be ignored as well.

答:
The UIMenuItem element is actually a UICalloutBarButton private class containing a UIButtonLabel (iOS 13) and, as is, you can't custom its a11y properties even if you can easily code it (informal protocol).

That's insane because, in order to vend an a11y app, you MUST adapt it to the users and that's definitely not the case here.

However, a workaround may be implemented as follows to reach your goal:

Render the menu controller inaccessible (a11yTraits = .none).

Get the menu controller frame (menuFrame property) for the next step.

Create an accessible element that wraps the menu when displayed (UIAccessibilityElement init + accessibilityFrameInContainerSpace).

For this new accessible element, create a11y custom actions that match each element of the [menuItems] ⟹ here you can provide the VoiceOver label.

It would have been better to create an accessible element for each menuItem (and then provide a better customization) but I didn't find out the way to get the frame of each individual item.

And, unfortunately, this problem is still current for the last 3 years.

⚠ ⬛◼▪ EDIT  ▪◼⬛ ⚠ (2020/03/19)

I wrote a Developer Technical Support Incident (no 731229763) for this problem and here's the answer from Apple:

Our engineers have reviewed your request and have determined that you are experiencing a known issue for which there is no known workaround at this time.

I submitted a bug report entitled VoiceOver: accessibilityLabel can't be implemented on a UIMenuItem element with the reference FB7623526.

Now, you know why accessibilityLabel is useless and without effects on a UIMenuItem element.

Title: Set accessibilityLabel on UIMenuItem

Body:
I am trying to set the accessibilityLabel of a UIMenuItem and it seems to have no effect. VoiceOver simply reads the title of the item no matter what:

    let foo = UIMenuItem(title: "foo", action: #selector(doSomething))
    item.isAccessibilityElement = true
    item.accessibilityLabel = "bar"

For this item, VoiceOver reads "foo" instead of "bar."  Also, the accessibilityHint seems to be ignored as well.


问:
cashfree payment gateway not returning any data after successful payment
i am using cashfree payment gateway in my website (using php sdk of cashfree payment gateway) , its working fine on local but on upload to server not returning any data to $_POST after payment complete , but on local i am getting values in $_POST , here my return page code , i dont think its coding issue , i am using cpanel can anyone tel server configuration if required:</p>

```<code>     $secretKey = "";
     print_r($_POST); //its returning array() on server and on local array( [orderId] => 1_2834_5
     [orderAmount] => 1.00 [referenceId] => 93724505 [txStatus] => SUCCESS [paymentMode] =>
     AIRTEL_MONEY)
</code>```

答: thank you guys for all your reply, finally i found that on return page signature was not matching  its because i used http://to_return_page_link as return page url and my site has ssl so it redirects to https:// and after successful payment on return page it was not returning any data on $_post as i also used https:// on payment gateway , so as i changed http to https on code (where i mentioned return page url) its done , now working fine.</p>

Body:
i am using cashfree payment gateway in my website (using php sdk of cashfree payment gateway) , its working fine on local but on upload to server not returning any data to $_POST after payment complete , but on local i am getting values in $_POST , here my return page code , i dont think its coding issue , i am using cpanel can anyone tel server configuration if required:

     $secretKey = "";
     print_r($_POST); //its returning array() on server and on local array( [orderId] => 1_2834_5
     [orderAmount] => 1.00 [referenceId] => 93724505 [txStatus] => SUCCESS [paymentMode] =>
     AIRTEL_MONEY)


问:
why is filebeat unable to connect to logstash
I am trying to send a log4net log to logstash to get parsed and then end up in elasticsearch. I have added the port to the windows firewall security setting and allow all connection, both to 5044 and 9600.

In the filebeat log, i get this error

```<code>pipeline/output.go:100  Failed to connect to backoff(async(tcp://[http://hostname:5044]:5044)): lookup http://hostname:5044: no such host
</code>```

Filebeat.yml (Logstash section)

```<code>#----------------------------- Logstash output --------------------------------
output.logstash:
  # The Logstash hosts
  hosts: ["http://hostname:5044"]

  # Optional SSL. By default is off.
  # List of root certificates for HTTPS server verifications
  #ssl.certificate_authorities: ["/etc/pki/root/ca.pem"]

  # Certificate for SSL client authentication
  #ssl.certificate: "/etc/pki/client/cert.pem"

  # Client Certificate Key
  #ssl.key: "/etc/pki/client/cert.key"

#================================ Processors =====================================
</code>```

Logstash.yml

I have set the http.host to 0.0.0.0

```<code># ------------ Metrics Settings --------------
#
# Bind address for the metrics REST endpoint
#
 http.host: "0.0.0.0"
#
# Bind port for the metrics REST endpoint, this option also accept a range
# (9600-9700) and logstash will pick up the first available ports.
#
# http.port: 9600-9700
</code>```

Logstash Filter Config

```<code>input {
  beats {
    port => "5044"
  }
}

filter {
    if [type] == "log4net" {
        grok {
            match => [ "message", "%{TIMESTAMP_ISO8601:timestamp} \[%{NUMBER:threadid}\] %{WORD:level}\s*%{DATA:class} \[%{DATA:NDC}\]\s+-\s+%{GREEDYDATA:message}" ]
        }
        date {
            match => ["timestamp", "MMM d HH:mm:ss", "MMM dd HH:mm:ss"]
            remove_field => ["timestamp"]
        }
        mutate {
            update => {
                "type" => "log4net-logs"
            }
        }
    }
}

output {
  elasticsearch {
    hosts => ["http://hostname:9200"]
    index => "%{[@metadata][beat]}-%{[@metadata][version]}-%{+YYYY.MM.dd}"
    #user => "elastic"
    #password => "changeme"
  }
}
</code>```

答:
You can try using hostname:</p>

```<code>hosts: ["hostname:5044"]
</code>```

Body:
I am trying to send a log4net log to logstash to get parsed and then end up in elasticsearch. I have added the port to the windows firewall security setting and allow all connection, both to 5044 and 9600.

In the filebeat log, i get this error

pipeline/output.go:100  Failed to connect to backoff(async(tcp://[http://hostname:5044]:5044)): lookup http://hostname:5044: no such host

Filebeat.yml (Logstash section)

#----------------------------- Logstash output --------------------------------
output.logstash:
  # The Logstash hosts
  hosts: ["http://hostname:5044"]

  # Optional SSL. By default is off.
  # List of root certificates for HTTPS server verifications
  #ssl.certificate_authorities: ["/etc/pki/root/ca.pem"]

  # Certificate for SSL client authentication
  #ssl.certificate: "/etc/pki/client/cert.pem"

  # Client Certificate Key
  #ssl.key: "/etc/pki/client/cert.key"

#================================ Processors =====================================

Logstash.yml

I have set the http.host to 0.0.0.0

# ------------ Metrics Settings --------------
#
# Bind address for the metrics REST endpoint
#
 http.host: "0.0.0.0"
#
# Bind port for the metrics REST endpoint, this option also accept a range
# (9600-9700) and logstash will pick up the first available ports.
#
# http.port: 9600-9700

Logstash Filter Config

input {
  beats {
    port => "5044"
  }
}

filter {
    if [type] == "log4net" {
        grok {
            match => [ "message", "%{TIMESTAMP_ISO8601:timestamp} \[%{NUMBER:threadid}\] %{WORD:level}\s*%{DATA:class} \[%{DATA:NDC}\]\s+-\s+%{GREEDYDATA:message}" ]
        }
        date {
            match => ["timestamp", "MMM d HH:mm:ss", "MMM dd HH:mm:ss"]
            remove_field => ["timestamp"]
        }
        mutate {
            update => {
                "type" => "log4net-logs"
            }
        }
    }
}

output {
  elasticsearch {
    hosts => ["http://hostname:9200"]
    index => "%{[@metadata][beat]}-%{[@metadata][version]}-%{+YYYY.MM.dd}"
    #user => "elastic"
    #password => "changeme"
  }
}

Body:
You can try using hostname:

hosts: ["hostname:5044"]


问:
App crash while using react Navigation@4.02

import React, {Component} from 'react';
import {View} from 'react-native';
import {  createStackNavigator,createAppContainer } from 'react-navigation';
import Splash from './Components/Splash';
import MainScreen from './Components/MainScreen';

const BasedNavigator=createStackNavigator({
    Splash:Splash,
    MainScreen:MainScreen,
},
{
  initialRouteName: 'Splash',
}
)

const Container=createAppContainer(BasedNavigator);

class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Container />
      </View>
    );
  }
}

const styles = {
  container: {
    flex: 1,
  },
};

export default App;```

when i add react navigation@4.02 it start crashing..i m using before react-navigation@4.02 it work correctly for me before,after @4.02  now i don't understand why it does not work

答:
I got the same error after using the modules

```<code>"react-native-gesture-handler": "^1.6.0",
"react-native-reanimated": "^1.7.0",
"react-native-screens": "^2.0.0-beta.8",
</code>```

Please try

```<code>$ react-native link react-native-gesture-handler
$ react-native link react-native-reanimated
$ react-native link react-native-screens
</code>```

the solution is working for me.

and the other reason can be

React-navigation Doc

Body:
import React, {Component} from 'react';
import {View} from 'react-native';
import {  createStackNavigator,createAppContainer } from 'react-navigation';
import Splash from './Components/Splash';
import MainScreen from './Components/MainScreen';

const BasedNavigator=createStackNavigator({
    Splash:Splash,
    MainScreen:MainScreen,
},
{
  initialRouteName: 'Splash',
}
)

const Container=createAppContainer(BasedNavigator);

class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Container />
      </View>
    );
  }
}

const styles = {
  container: {
    flex: 1,
  },
};

export default App;

when i add react navigation@4.02 it start crashing..i m using before react-navigation@4.02 it work correctly for me before,after @4.02  now i don't understand why it does not work

Body:
I got the same error after using the modules

"react-native-gesture-handler": "^1.6.0",
"react-native-reanimated": "^1.7.0",
"react-native-screens": "^2.0.0-beta.8",

Please try

$ react-native link react-native-gesture-handler
$ react-native link react-native-reanimated
$ react-native link react-native-screens

the solution is working for me.

and the other reason can be

React-navigation Doc


问:
How to generate HTML report from jacoco.exec?
We have a Maven project which has submodules. There is one parent pom.xml
and each and every sub projects are made into a war file. Each and every submodule has unit test cases and reports generated from Jacoco.

The existing reports show unit test coverage of individual modules but we need to provide integration test-wide code coverage on Tomcat. What we did was we installed jacoco agent in Tomcat folder and configured it to to generate jacoco.exec. When I import jacoco.exec using EclEmma plugin we see the code coverage.

Is there any way to generate report from standalone jacoco.exec without source code?

答:
Download Jacoco agent Zip file from the following URL:
https://www.jacoco.org/jacoco/  select the version that suits your needs.

Create folder with suitable name, I have mine located at "C:\jacoco". Extract the contents of the Zip file there.

Open CMD and go to C:\jacoco

Use the following command:

java -jar jacococli.jar report --classfiles path/of/the/class/files path/of/the/.exec file --html html/report/location --name nameOfTheReport

Note:

  1. -jar : I have kept jacococli.jar in Jacoco.

  2. --classfiles : Path of the compiled java files.

  3.  Path of the exec file.

  4. --name : Name of HTML report Title (Heading)

Java code coverage report will be generated at your mentioned location.


问:
Unable to use graql on commandline
So I am using grakn core 1.5.7 on Ubuntu 18.04.

I want to use graql command.With older versions of grakn it was quite good to have a graql executable available.Here is the command i am using from inside my grakn folder.

```<code>graql console --keyspace prec --file ./schema.gql
</code>```

However in newer versions on and after 1.5.7,I cannot find the same.

I had a look on the bugs section of grakn and i found this to be close but not much related issue. Following which i tried replacing graql to grakn but now i am getting this error

```<code>io.grpc.StatusRuntimeException: UNIMPLEMENTED: Method not found: session.SessionService/open
    at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:233)
    at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:214)
    at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:139)
    at grakn.protocol.session.SessionServiceGrpc$SessionServiceBlockingStub.open(SessionServiceGrpc.java:273)
    at grakn.client.GraknClient$Session.<init>(GraknClient.java:165)
    at grakn.client.GraknClient$Session.<init>(GraknClient.java:136)
    at grakn.client.GraknClient.session(GraknClient.java:123)
    at grakn.core.console.ConsoleSession.<init>(ConsoleSession.java:90)
    at grakn.core.console.GraknConsole.run(GraknConsole.java:99)
    at grakn.core.console.GraknConsole.main(GraknConsole.java:140)
</code>```

Cannot understand what is the resolution for the same

答: As of Grakn Core 1.5.0, the graql console command has been removed in favor of a combined command: grakn console -k mykeyspace...

Title: Unable to use graql on commandline

Body:
So I am using grakn core 1.5.7 on Ubuntu 18.04.

I want to use graql command.With older versions of grakn it was quite good to have a graql executable available.Here is the command i am using from inside my grakn folder.

graql console --keyspace prec --file ./schema.gql

However in newer versions on and after 1.5.7,I cannot find the same.

I had a look on the bugs section of grakn and i found this to be close but not much related issue. Following which i tried replacing graql to grakn but now i am getting this error

io.grpc.StatusRuntimeException: UNIMPLEMENTED: Method not found: session.SessionService/open
    at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:233)
    at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:214)
    at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:139)
    at grakn.protocol.session.SessionServiceGrpc$SessionServiceBlockingStub.open(SessionServiceGrpc.java:273)
    at grakn.client.GraknClient$Session.<init>(GraknClient.java:165)
    at grakn.client.GraknClient$Session.<init>(GraknClient.java:136)
    at grakn.client.GraknClient.session(GraknClient.java:123)
    at grakn.core.console.ConsoleSession.<init>(ConsoleSession.java:90)
    at grakn.core.console.GraknConsole.run(GraknConsole.java:99)
    at grakn.core.console.GraknConsole.main(GraknConsole.java:140)

Cannot understand what is the resolution for the same


问:
Deleting an image from android device?
I want to delete an image that user selects through

ACTION_GET_CONTENT

I am successfully able to select image and show it in recycleview,
I am selecting image like this:

```<code>switch (requestCode) {
        case 42:
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();

                InputStream inputStream = null;
                try {
                    inputStream = getBaseContext().getContentResolver().openInputStream(uri);
                    Bitmap bm = BitmapFactory.decodeStream(inputStream);

                    int maxHeight = 1920;
                    int maxWidth = 1920;

                    float scale = Math.min(((float) maxHeight / bm.getWidth()), ((float) maxWidth / bm.getHeight()));

                    Matrix matrix = new Matrix();
                    matrix.postScale(scale, scale);

                    Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);

                    saveImageToInternalStorage(bitmap, getFileName(uri));
                    bm.recycle();
                    bitmap.recycle();

                    finishActivity(42);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
    }
</code>```

Now I want to delete this image from users gallery but it should still be visible in the recyclerview

I get the photoPath as

```<code>content://com.android.providers.media.documents/document/image%3A5793
</code>```

答:
Try this, hope it will work for you

```<code>switch (requestCode) {
    case 42:
        if (resultCode == RESULT_OK) {
            Uri uri = data.getData();

            InputStream inputStream = null;
            try {
                inputStream = getBaseContext().getContentResolver().openInputStream(uri);
                Bitmap bm = BitmapFactory.decodeStream(inputStream);

                int maxHeight = 1920;
                int maxWidth = 1920;

                float scale = Math.min(((float) maxHeight / bm.getWidth()), ((float) maxWidth / bm.getHeight()));

                Matrix matrix = new Matrix();
                matrix.postScale(scale, scale);

                Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);

                saveImageToInternalStorage(bitmap, getFileName(uri));
                bm.recycle();
                bitmap.recycle();

                File file = new File(convertMediaUriToPath(uri)); // it will get the absolute path of your file from your URI
                if (file.delete()) // it will delete your actual file from storage, but not from any holder you placed it.
                     //Make a Toast that file is successfully deleted
                 else
                     //Make a Toast that file is not deleted
                finishActivity(42);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
}
</code>```

Method to get Absolute PATH

```<code>public String convertMediaUriToPath(Uri uri) {
    String [] proj={MediaStore.Images.Media.DATA};
    Cursor cursor = getContentResolver().query(uri, proj,  null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String path = cursor.getString(column_index);
    cursor.close();
    return path;
}
</code>```

Hope it will work for you:)
Let me know if its working or not.

Title: Deleting an image from android device?

Body:
I want to delete an image that user selects through

ACTION_GET_CONTENT

I am successfully able to select image and show it in recycleview,
I am selecting image like this:

switch (requestCode) {
        case 42:
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();

                InputStream inputStream = null;
                try {
                    inputStream = getBaseContext().getContentResolver().openInputStream(uri);
                    Bitmap bm = BitmapFactory.decodeStream(inputStream);

                    int maxHeight = 1920;
                    int maxWidth = 1920;

                    float scale = Math.min(((float) maxHeight / bm.getWidth()), ((float) maxWidth / bm.getHeight()));

                    Matrix matrix = new Matrix();
                    matrix.postScale(scale, scale);

                    Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);

                    saveImageToInternalStorage(bitmap, getFileName(uri));
                    bm.recycle();
                    bitmap.recycle();

                    finishActivity(42);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
    }

Now I want to delete this image from users gallery but it should still be visible in the recyclerview

I get the photoPath as

content://com.android.providers.media.documents/document/image%3A5793

Body:
Try this, hope it will work for you

switch (requestCode) {
    case 42:
        if (resultCode == RESULT_OK) {
            Uri uri = data.getData();

            InputStream inputStream = null;
            try {
                inputStream = getBaseContext().getContentResolver().openInputStream(uri);
                Bitmap bm = BitmapFactory.decodeStream(inputStream);

                int maxHeight = 1920;
                int maxWidth = 1920;

                float scale = Math.min(((float) maxHeight / bm.getWidth()), ((float) maxWidth / bm.getHeight()));

                Matrix matrix = new Matrix();
                matrix.postScale(scale, scale);

                Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);

                saveImageToInternalStorage(bitmap, getFileName(uri));
                bm.recycle();
                bitmap.recycle();

                File file = new File(convertMediaUriToPath(uri)); // it will get the absolute path of your file from your URI
                if (file.delete()) // it will delete your actual file from storage, but not from any holder you placed it.
                     //Make a Toast that file is successfully deleted
                 else
                     //Make a Toast that file is not deleted
                finishActivity(42);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
}

Method to get Absolute PATH

public String convertMediaUriToPath(Uri uri) {
    String [] proj={MediaStore.Images.Media.DATA};
    Cursor cursor = getContentResolver().query(uri, proj,  null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String path = cursor.getString(column_index);
    cursor.close();
    return path;
}

Hope it will work for you:)
Let me know if its working or not.


问:
How to calculate the clipping area of an image after scaling and translating
I have an image on a canvas and a ScaleTranform and a TranslateTransform attached to the image's RenderTranform. So with a bit of mouse event handling I can move and zoom the image within the 350 by 450 bounds of the canvas.

How would I calculate the clipping rectangle on the original BitmapImage, to that of the visible area on the screen, after some scaling and translation. I'd like to crop the original BitmapImage.

```<code><Border BorderBrush="Black" BorderThickness="2">
  <Canvas Name="canvas" ClipToBounds="True" Height="450" Width="350">
    <Image Name="image" Opacity="1" RenderTransformOrigin="0.5,0.5" Height="450" Width="350">
       <Image.Source>
          <BitmapImage UriSource="test.jpg"/>
       </Image.Source>
     </Image>
  </Canvas>
</Border>
</code>```

Thanks

答:
I would think it would be simple math to take the current ScaleTransform values and figure out what the actual size of the image is at the time, and then you know that you have a 350x450 box that you're going to crop out of that, you just need to use the current TranslateTransform to figure that out. Just keep in mind what you're using for the origins of these transforms, as that's what you need to calculate it from.

What I said above assumes that you have the ScaleTransform first in your RenderTransform and the TranslateTransform second. The order of operations does matter here.

Body:
I have an image on a canvas and a ScaleTranform and a TranslateTransform attached to the image's RenderTranform. So with a bit of mouse event handling I can move and zoom the image within the 350 by 450 bounds of the canvas.

How would I calculate the clipping rectangle on the original BitmapImage, to that of the visible area on the screen, after some scaling and translation. I'd like to crop the original BitmapImage.

<Border BorderBrush="Black" BorderThickness="2">
  <Canvas Name="canvas" ClipToBounds="True" Height="450" Width="350">
    <Image Name="image" Opacity="1" RenderTransformOrigin="0.5,0.5" Height="450" Width="350">
       <Image.Source>
          <BitmapImage UriSource="test.jpg"/>
       </Image.Source>
     </Image>
  </Canvas>
</Border>

Thanks


问:
How to write the MIN, MID, MAX enums in Google Sheets when trying to create gradient conditional formatting?
How can I use an InterpolationPointType enum in the following script?

See the commented lines with the hand pointers to see where I'm hitting an error: Invalid value at 'requests[0].add_conditional_format_rule.rule.gradient_rule.midpoint.type' (TYPE_ENUM)

I'm excited about what I'm designing here and think I'm close to achieving a script that can dynamically add color gradient conditional formatting to a Google Sheet.

But I haven't found a way around this enum problem even when looking at docs for ConditionalFormatRule, Gradient rules, and Add a conditional color gradient across a row.

```<code>function addGradients(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ss.getSheets();
  var sheet = ss.getSheetByName("temp");
  var requests = [];

  //Do this for as many ranges as needed:
  var myRange = Sheets.newGridRange();
  myRange.sheetId = sheet.getSheetId();
  myRange.startRowIndex = 12;
  myRange.endRowIndex = 24;
  myRange.startColumnIndex = 4;
  myRange.endColumnIndex = 4;
  var request1 = addGradientToRange(myRange);
  requests.push(request1);

  // Batch send the requests
  var batchUpdate = Sheets.newBatchUpdateSpreadsheetRequest();
  batchUpdate.requests = requests;
  var response = Sheets.Spreadsheets.batchUpdate(batchUpdate, ss.getId());
}

function addGradientToRange(myRange){
  var rule1GradientRule = Sheets.newGradientRule();
  var ptMax = Sheets.newInterpolationPoint();
  var ptMid = Sheets.newInterpolationPoint();
  var ptMin = Sheets.newInterpolationPoint();
  var colorGreen = Sheets.newColor();
  colorGreen.green = 1;
  var colorRed = Sheets.newColor();
  colorRed.red = 1;
  var colorWhite = Sheets.newColor();

  ptMax.color = colorGreen;
  ptMid.color = colorWhite;
  ptMin.color = colorRed;
  ptMax.type = "MAX";// What can I type here to set it to this enum?
  ptMid.type = "MID";// What can I type here to set it to this enum?
  ptMin.type = "MIN";// What can I type here to set it to this enum?
  rule1GradientRule.maxpoint = ptMax;
  rule1GradientRule.midpoint = ptMid;
  rule1GradientRule.minpoint = ptMin;

  var rule1 = Sheets.newConditionalFormatRule();
  rule1.ranges = [myRange];
  rule1.gradientRule = rule1GradientRule;

  var request1 = Sheets.newRequest();
  var addConditionalFormatRuleRequest1 = Sheets.newAddConditionalFormatRuleRequest();
  addConditionalFormatRuleRequest1.rule = rule1;
  addConditionalFormatRuleRequest1.index = 0;
  request1.addConditionalFormatRule = addConditionalFormatRuleRequest1;
  return request1;
}
</code>```

And if I don't specify the .type for each InterpolationPoint, I get this error: Invalid requests[0].addConditionalFormatRule: No interpolationPointType specified.

I've also tried ptMax.type = InterpolationPointType.Max;, but then I get error: ReferenceError: "InterpolationPointType" is not defined.

答:
I think there is a more modern method doing that (gradient conditional formatting), by using the ConditionalFormatRuleBuilder Class.
(See reference)
this is a general function that gets a sheet name and a range, and sets a new rule with 0 as mid point, green as max and red as min:

//add a general gradiant conditional formatting with max=green, mid=white, min=red background
function addGradientToRange(theSheet, myRange) {
  var sheet = SpreadsheetApp.getActive().getSheetByName(theSheet);
  var range = sheet.getRange(myRange);
  var rule = SpreadsheetApp.newConditionalFormatRule()
    .setGradientMaxpoint("#00FF00")
    .setGradientMidpointWithValue("#FFFFFF", SpreadsheetApp.InterpolationType.NUMBER, "0")
    .setGradientMinpoint("#FF0000")
    .setRanges([range])
    .build()
  var rules = sheet.getConditionalFormatRules();
  rules.push(rule);
  sheet.setConditionalFormatRules(rules);
}```

Hope that helps....

Body:
How can I use an InterpolationPointType enum in the following script?

See the commented lines with the hand pointers to see where I'm hitting an error: Invalid value at 'requests[0].add_conditional_format_rule.rule.gradient_rule.midpoint.type' (TYPE_ENUM)

I'm excited about what I'm designing here and think I'm close to achieving a script that can dynamically add color gradient conditional formatting to a Google Sheet.

But I haven't found a way around this enum problem even when looking at docs for ConditionalFormatRule, Gradient rules, and Add a conditional color gradient across a row.

function addGradients(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ss.getSheets();
  var sheet = ss.getSheetByName("temp");
  var requests = [];

  //Do this for as many ranges as needed:
  var myRange = Sheets.newGridRange();
  myRange.sheetId = sheet.getSheetId();
  myRange.startRowIndex = 12;
  myRange.endRowIndex = 24;
  myRange.startColumnIndex = 4;
  myRange.endColumnIndex = 4;
  var request1 = addGradientToRange(myRange);
  requests.push(request1);

  // Batch send the requests
  var batchUpdate = Sheets.newBatchUpdateSpreadsheetRequest();
  batchUpdate.requests = requests;
  var response = Sheets.Spreadsheets.batchUpdate(batchUpdate, ss.getId());
}

function addGradientToRange(myRange){
  var rule1GradientRule = Sheets.newGradientRule();
  var ptMax = Sheets.newInterpolationPoint();
  var ptMid = Sheets.newInterpolationPoint();
  var ptMin = Sheets.newInterpolationPoint();
  var colorGreen = Sheets.newColor();
  colorGreen.green = 1;
  var colorRed = Sheets.newColor();
  colorRed.red = 1;
  var colorWhite = Sheets.newColor();

  ptMax.color = colorGreen;
  ptMid.color = colorWhite;
  ptMin.color = colorRed;
  ptMax.type = "MAX";// What can I type here to set it to this enum?
  ptMid.type = "MID";// What can I type here to set it to this enum?
  ptMin.type = "MIN";// What can I type here to set it to this enum?
  rule1GradientRule.maxpoint = ptMax;
  rule1GradientRule.midpoint = ptMid;
  rule1GradientRule.minpoint = ptMin;

  var rule1 = Sheets.newConditionalFormatRule();
  rule1.ranges = [myRange];
  rule1.gradientRule = rule1GradientRule;

  var request1 = Sheets.newRequest();
  var addConditionalFormatRuleRequest1 = Sheets.newAddConditionalFormatRuleRequest();
  addConditionalFormatRuleRequest1.rule = rule1;
  addConditionalFormatRuleRequest1.index = 0;
  request1.addConditionalFormatRule = addConditionalFormatRuleRequest1;
  return request1;
}

And if I don't specify the .type for each InterpolationPoint, I get this error: Invalid requests[0].addConditionalFormatRule: No interpolationPointType specified.

I've also tried ptMax.type = InterpolationPointType.Max;, but then I get error: ReferenceError: "InterpolationPointType" is not defined.

Body:
I think there is a more modern method doing that (gradient conditional formatting), by using the ConditionalFormatRuleBuilder Class.
(See reference)
this is a general function that gets a sheet name and a range, and sets a new rule with 0 as mid point, green as max and red as min:

//add a general gradiant conditional formatting with max=green, mid=white, min=red background
function addGradientToRange(theSheet, myRange) {
  var sheet = SpreadsheetApp.getActive().getSheetByName(theSheet);
  var range = sheet.getRange(myRange);
  var rule = SpreadsheetApp.newConditionalFormatRule()
    .setGradientMaxpoint("#00FF00")
    .setGradientMidpointWithValue("#FFFFFF", SpreadsheetApp.InterpolationType.NUMBER, "0")
    .setGradientMinpoint("#FF0000")
    .setRanges([range])
    .build()
  var rules = sheet.getConditionalFormatRules();
  rules.push(rule);
  sheet.setConditionalFormatRules(rules);
}

Hope that helps....


问:
delete from mysql by join in second table
We have 2 tables below :

Table1

```<code>Name    roll     priority    count(*)
def     12       8           58
def     11       7           54
def     10       7           172
abc     12       7           2
abc     13       6           307
abc     11       6           3472
xyz     12       7           132
xyz     11       9           2345
xyz     12       9           1234
</code>```

Table2

```<code>name    roll    priority
abc     12      10
xyz     12      8
</code>```

 Source data image

And in above I need to delete all entry of priority >5 but delete the entry with match from Table2.

Means the entry in Table1 shouldn't be delete for priority 10 with name abc and roll 12 if same is in Table1.

答:
If you want to keep in table1 the entries that exists in table2, you can perform a left outer join.

Thoses entries can be SELECTed like this :

```<code>SELECT t1.*
FROM table1 t1
LEFT JOIN table2 t2
ON t1.Name = t2.name
WHERE t2.name IS NULL
    AND t1.priority > 5;
</code>```

And now, applying this join to a delete statement is quite the same :

```<code>DELETE t1
FROM table1 t1
LEFT JOIN table2 t2
    ON t1.Name = t2.name
WHERE t2.name IS NULL
    AND t1.priority > 5;
</code>```

Try it yourself

Body:
We have 2 tables below :

Table1

Name    roll     priority    count(*)
def     12       8           58
def     11       7           54
def     10       7           172
abc     12       7           2
abc     13       6           307
abc     11       6           3472
xyz     12       7           132
xyz     11       9           2345
xyz     12       9           1234

Table2

name    roll    priority
abc     12      10
xyz     12      8

 Source data image

And in above I need to delete all entry of priority >5 but delete the entry with match from Table2.

Means the entry in Table1 shouldn't be delete for priority 10 with name abc and roll 12 if same is in Table1.

Body:
If you want to keep in table1 the entries that exists in table2, you can perform a left outer join.

Thoses entries can be SELECTed like this :

SELECT t1.*
FROM table1 t1
LEFT JOIN table2 t2
ON t1.Name = t2.name
WHERE t2.name IS NULL
    AND t1.priority > 5;

And now, applying this join to a delete statement is quite the same :

DELETE t1
FROM table1 t1
LEFT JOIN table2 t2
    ON t1.Name = t2.name
WHERE t2.name IS NULL
    AND t1.priority > 5;

Try it yourself


问:
OraOLEDB.Oracle not showing in SQL Server Management Studio providers
I'm trying to add an Oracle server as a linked server to SQL Server. I've downloaded and installed Oracle's instant client and ODAC software. However, OraOLEDB.Oracle does not show up in the list of providers in SSMS. My machine is running Windows 7 (64 bit) and MSSQL Server 2008 R2.</p>

答: OraOLEDB provider is not installed with instant client. You have to install the full client.</p>


问:
MacVim remember my old settings
I have deleted my old .vimrc and .vim to configure vim from scratch. I have done it. But MacVim remembers my old settings, e.g. maps. Does it cache settings and plugins somewhere?</p>

答: MacVim has "Enable Quickstart" option in Preferences/Advanced and it caches settings for quick start if it is enabled. You should uncheck it to reset.</p>

Title: MacVim remember my old settings


问:
Is it possible to have a non-friend function which can only be found by ADL?
C++ has a feature, that in-class-defined friend functions can only be found by ADL (argument dependent lookup):

```<code>struct Foo {
    friend void fn(Foo) { } // fn can only be called by ADL, it won't be found by other lookup methods
};
</code>```

Is it possible to achieve the same for non-friend functions? I ask this, because sometimes, I'd like to have this "only found by ADL" feature, but I don't actually need friend access to the class internals.

(And a somewhat opinionated question: if this is not possible, what is the reason for this? Is this "only found by ADL" rule intentionally designed into the language?)

答:
It's only possible for friend functions, since they are the only functions for which this verbiage exists. Both the wording that makes functions invisible to ordinary name lookup, and the wording that considers them during ADL, is applied only to such friends.

This feature was actually introduced to replace another feature, that was deemed more problematic. N0777 is the paper detailing it. Templates used to inject their friend function names into scope when a template was instantiated, to be found by regular name lookup. That wasn't ideal and caused issues in overload resolution.

The feature was set to be removed, but it was the backbone of the Barton-Nackman trick, and so a solution was proposed that ultimately became what we know as inline friend functions being looked up by ADL only. It was tailored to facilitate the programming idiom.

Since no other wide-spread idiom that required such behavior was brought up since, this behavior wasn't extended to non-friend functions.

Body:
C++ has a feature, that in-class-defined friend functions can only be found by ADL (argument dependent lookup):

struct Foo {
    friend void fn(Foo) { } // fn can only be called by ADL, it won't be found by other lookup methods
};

Is it possible to achieve the same for non-friend functions? I ask this, because sometimes, I'd like to have this "only found by ADL" feature, but I don't actually need friend access to the class internals.

(And a somewhat opinionated question: if this is not possible, what is the reason for this? Is this "only found by ADL" rule intentionally designed into the language?)


问:
CakePHP Forgot Password / Ticket component help
I'm using the following tutorial to build a password reset form: http://bakery.cakephp.org/articles/eimermusic/2007/10/23/ticket-component-resetting-user-passwords

However when I submit the form I get the following error: Fatal error: Class 'Ticket' not found in /Users/cameron/Sites/thehive/app/controllers/components/tickets.php on line 60

And Line 60 is this: $ticketObj = new Ticket();

Any ideas what the problem is and how to fix it thanks?

答:
Models are not automatically available in components. One possible way to import your model class is:</p>

```<code>App::import('Model','Ticket');
</code>```

Body:
Models are not automatically available in components. One possible way to import your model class is:

App::import('Model','Ticket');


问:
Postgresql 11 Create or Replace Procedure GetMultipleResultSets(INOUT ref1 refcursor, INOUT ref2 refcursor); Automatic cursor deferencing using Npgsql
Requirement:
How to get back the multiple refcursor data from a postgresql 11 procedure (not a function) without using the fetch statement using npgsql 4.0 from ado.net.

Here is the sample which i have tried:

Postgresql Procedure:

```<code>CREATE OR REPLACE PROCEDURE public.GetMultipleResultSets(
    INOUT ref1 refcursor,
    INOUT ref2 refcursor)
LANGUAGE 'plpgsql'

AS $BODY$
begin
    open ref1 for
    select * from public."tblTestTable1";

    open ref2 for
    select * from public."tblTestTable2";
end;
$BODY$;
</code>```

C# Code using Npgsql 4.0:

```<code>    public DataSet ReturnAsDataSet(string procedureName)
    {
        this.dataSet = new DataSet();

        OpenConnection();
        NpgsqlTransaction objTransaction = this.Connection.BeginTransaction();

        NpgsqlDataAdapter adapter = new NpgsqlDataAdapter();
        NpgsqlCommand command = this.Connection.CreateCommand();

        try
        {
            NpgsqlParameter refCursorParam1 = new NpgsqlParameter("@ref1", NpgsqlTypes.NpgsqlDbType.Refcursor);
            refCursorParam1.Direction = ParameterDirection.InputOutput;
            refCursorParam1.Value = "ref1";
            command.Parameters.Add(refCursorParam1);

            refCursorParam2 = new NpgsqlParameter("@ref2", NpgsqlTypes.NpgsqlDbType.Refcursor);
            refCursorParam2.Direction = ParameterDirection.InputOutput;
            refCursorParam2.Value = "ref2";
            command.Parameters.Add(refCursorParam2);

            command.CommandText = "call " + procedureName + "(@ref1, @ref2)";
            command.Transaction = objTransaction;

            adapter.SelectCommand = command;
            adapter.Fill(dataSet);

            objTransaction.Commit();

        }

        catch (NpgsqlException ex)
        {
            if (objTransaction != null)
                objTransaction.Rollback();

            throw new Exception(ex.Message);
        }
        finally
        {
            CloseConnection();
            command.Dispose();
            objTransaction.Dispose();
        }

        return this.dataSet;
    }
</code>```

This code will return a table having the "ref1", "ref2" as the columns and "ref1" and "ref2" as the values inside it as follows:

enter image description here

But I need the actual result sets returned from the procedure.
How can I achieve it without manually fetching those refcursor data.
I mean without using "fetch all ref" statement how can we retrieve the data by executing either ExecuteReader() or adapter.Fill() methods as above.
Is there any automatic cursor dereferencing available in npgsql?

Please provide the answer if anyone knows.
Thanks for your help in advance.

答: This is currently not done for you by Npgsql, this issue tracks it. You can see this long discussions on the pros and cons of this. At the moment you'll have to call FETCH on the cursors yourself.</p>

Body:
Requirement:
How to get back the multiple refcursor data from a postgresql 11 procedure (not a function) without using the fetch statement using npgsql 4.0 from ado.net.

Here is the sample which i have tried:

Postgresql Procedure:

CREATE OR REPLACE PROCEDURE public.GetMultipleResultSets(
    INOUT ref1 refcursor,
    INOUT ref2 refcursor)
LANGUAGE 'plpgsql'

AS $BODY$
begin
    open ref1 for
    select * from public."tblTestTable1";

    open ref2 for
    select * from public."tblTestTable2";
end;
$BODY$;

C# Code using Npgsql 4.0:

    public DataSet ReturnAsDataSet(string procedureName)
    {
        this.dataSet = new DataSet();

        OpenConnection();
        NpgsqlTransaction objTransaction = this.Connection.BeginTransaction();

        NpgsqlDataAdapter adapter = new NpgsqlDataAdapter();
        NpgsqlCommand command = this.Connection.CreateCommand();

        try
        {
            NpgsqlParameter refCursorParam1 = new NpgsqlParameter("@ref1", NpgsqlTypes.NpgsqlDbType.Refcursor);
            refCursorParam1.Direction = ParameterDirection.InputOutput;
            refCursorParam1.Value = "ref1";
            command.Parameters.Add(refCursorParam1);

            refCursorParam2 = new NpgsqlParameter("@ref2", NpgsqlTypes.NpgsqlDbType.Refcursor);
            refCursorParam2.Direction = ParameterDirection.InputOutput;
            refCursorParam2.Value = "ref2";
            command.Parameters.Add(refCursorParam2);

            command.CommandText = "call " + procedureName + "(@ref1, @ref2)";
            command.Transaction = objTransaction;

            adapter.SelectCommand = command;
            adapter.Fill(dataSet);

            objTransaction.Commit();

        }

        catch (NpgsqlException ex)
        {
            if (objTransaction != null)
                objTransaction.Rollback();

            throw new Exception(ex.Message);
        }
        finally
        {
            CloseConnection();
            command.Dispose();
            objTransaction.Dispose();
        }

        return this.dataSet;
    }

This code will return a table having the "ref1", "ref2" as the columns and "ref1" and "ref2" as the values inside it as follows:

enter image description here

But I need the actual result sets returned from the procedure.
How can I achieve it without manually fetching those refcursor data.
I mean without using "fetch all ref" statement how can we retrieve the data by executing either ExecuteReader() or adapter.Fill() methods as above.
Is there any automatic cursor dereferencing available in npgsql?

Please provide the answer if anyone knows.
Thanks for your help in advance.


问:
Unexpected behavior while modifying the dictionary in python
I am trying to modify a dictionary object while iterating over it. But python will raise a RuntimeError saying that dictionary changed size during iteration to avoid unexpected behavior(this is expected).

```<code>>>> a = {1: 2, 2: 3}
>>> for key in a:
...     if key % 2 == 0:
...             a.pop(key)
...
3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
</code>```

But what actually surprised me is that even though the above code block exited with RuntimeError the dictionary a got modified.

```<code>>>> a
{1: 2}
</code>```

Why is that?. Is this behavior is documented somewhere?.

Below is my python version and implementation.

```<code>>>> import sys, platform
>>> sys.version_info
sys.version_info(major=3, minor=8, micro=0, releaselevel='final', serial=0)
>>> platform.python_implementation()
'CPython'
</code>```

答:
Probably is better to create a copy of the dict and have the gc do the rest.

b = {k:v for k,v in a.items() if k%2 != 0}
```

Body:
I am trying to modify a dictionary object while iterating over it. But python will raise a RuntimeError saying that dictionary changed size during iteration to avoid unexpected behavior(this is expected).

>>> a = {1: 2, 2: 3}
>>> for key in a:
...     if key % 2 == 0:
...             a.pop(key)
...
3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration

But what actually surprised me is that even though the above code block exited with RuntimeError the dictionary a got modified.

>>> a
{1: 2}

Why is that?. Is this behavior is documented somewhere?.

Below is my python version and implementation.

>>> import sys, platform
>>> sys.version_info
sys.version_info(major=3, minor=8, micro=0, releaselevel='final', serial=0)
>>> platform.python_implementation()
'CPython'


问:
Move Top cut corner to bottom using linear-gradient
Good morning,

I need assistance with the below attached image:

Cut corner

Using linear gradient how do I move the top cut corner to the bottom corner and make the top corner square/sharp like the other corners. Please see current css below:

```<code>body.page {
  background: url(../img/Login-bg.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
  font-size: 14px;
  align-items: center;
  padding-top: 50px;
  padding-bottom: 50px;
}

.cut-corner {
  position: relative;
  color: #4a4a4c;
  background-repeat: no-repeat;
  background-image: linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431),
    linear-gradient(to bottom left, transparent calc(50% - 0.5px), #bcd431 calc(50% - 0.5px), #bcd431 calc(50% + 0.5px), transparent calc(50% + 0.5px)), linear-gradient(transparent, transparent), linear-gradient(transparent, transparent);
  background-size: 1.5px 100%, 1.5px 100%, 100% 1.5px, 100% 1.5px, 65px 65px, 100% 100%, 100% 100%;
  background-position: 0% 0%, 100% 65px, -65px 0%, 0px 100%, 100% 0%, -65px 0%, 100% 65px;
  margin: 25px;
}

.cut-corner:after {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  top: 0;
  z-index: -1;
  opacity: 100%;
  background-repeat: no-repeat;
  background-image: linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431),
    linear-gradient(to bottom left, transparent calc(50% - 0.5px), #bcd431 calc(50% - 0.5px), #bcd431 calc(50% + 0.5px), transparent calc(50% + 0.5px)), linear-gradient(transparent, transparent), linear-gradient(transparent, transparent);
  background-size: 0.5px 100%, 1.5px 100%, 100% 0.5px, 100% 1.5px, 65px 65px, 100% 100%, 100% 100%;
  background-position: 0% 0%, 100% 65px, -65px 0%, 0px 100%, 100% 0%, -65px 0%, 100% 65px;
}
</code>```

HTML:

```<code><body class="page cut-corner">
...
</body>
</code>```

Any assistance would be greatly appreciated.

答:
You manage the cut in the background-position part like this

```<code>background-position: 0% 0%, 100% -65px, 0px 0%, -65px 100%, 100% 100%, -65px 50%, 100% 65px;
</code>```

As you can see between each coma, there are two values defined of which the first one determines the position of each border (top border, bottom border...) and the other value defines the length of the border, try playing with the values and you will be able to make the top border full length, the bottom border a bit shorter, move the right border a bit higher and move the diagonal line to the bottom, then just change this from bottom left to bottom right as a way to change the angle of the small diagonal line like this

```<code>background-image: linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431),
linear-gradient(to bottom right, transparent calc(50% - 0.5px), #bcd431 calc(50% - 0.5px), #bcd431 calc(50% + 0.5px), transparent calc(50% + 0.5px)), linear-gradient(transparent, transparent), linear-gradient(transparent, transparent);
</code>```

If you don't care about understanding it and just want to apply the code, here you go the entire code already modified (the only changes made are in cut-corner:after)

```<code>.cut-corner:after {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  top: 0;
  z-index: -1;
  opacity: 100%;
  background-repeat: no-repeat;
  background-image: linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431),
    linear-gradient(to bottom right, transparent calc(50% - 0.5px), #bcd431 calc(50% - 0.5px), #bcd431 calc(50% + 0.5px), transparent calc(50% + 0.5px)), linear-gradient(transparent, transparent), linear-gradient(transparent, transparent);
  background-size: 1px 100%, 1.5px 100%, 100% 1px, 100% 1.5px, 65px 65px, 100% 100%, 100% 100%;
  background-position: 0% 0%, 100% -65px, 0px 0%, -65px 100%, 100% 100%, -65px 50%, 100% 65px;
}
</code>```

Body:
Good morning,

I need assistance with the below attached image:

Cut corner

Using linear gradient how do I move the top cut corner to the bottom corner and make the top corner square/sharp like the other corners. Please see current css below:

body.page {
  background: url(../img/Login-bg.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
  font-size: 14px;
  align-items: center;
  padding-top: 50px;
  padding-bottom: 50px;
}

.cut-corner {
  position: relative;
  color: #4a4a4c;
  background-repeat: no-repeat;
  background-image: linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431),
    linear-gradient(to bottom left, transparent calc(50% - 0.5px), #bcd431 calc(50% - 0.5px), #bcd431 calc(50% + 0.5px), transparent calc(50% + 0.5px)), linear-gradient(transparent, transparent), linear-gradient(transparent, transparent);
  background-size: 1.5px 100%, 1.5px 100%, 100% 1.5px, 100% 1.5px, 65px 65px, 100% 100%, 100% 100%;
  background-position: 0% 0%, 100% 65px, -65px 0%, 0px 100%, 100% 0%, -65px 0%, 100% 65px;
  margin: 25px;
}

.cut-corner:after {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  top: 0;
  z-index: -1;
  opacity: 100%;
  background-repeat: no-repeat;
  background-image: linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431),
    linear-gradient(to bottom left, transparent calc(50% - 0.5px), #bcd431 calc(50% - 0.5px), #bcd431 calc(50% + 0.5px), transparent calc(50% + 0.5px)), linear-gradient(transparent, transparent), linear-gradient(transparent, transparent);
  background-size: 0.5px 100%, 1.5px 100%, 100% 0.5px, 100% 1.5px, 65px 65px, 100% 100%, 100% 100%;
  background-position: 0% 0%, 100% 65px, -65px 0%, 0px 100%, 100% 0%, -65px 0%, 100% 65px;
}

HTML:

...

Any assistance would be greatly appreciated.

Body:
You manage the cut in the background-position part like this

background-position: 0% 0%, 100% -65px, 0px 0%, -65px 100%, 100% 100%, -65px 50%, 100% 65px;

As you can see between each coma, there are two values defined of which the first one determines the position of each border (top border, bottom border...) and the other value defines the length of the border, try playing with the values and you will be able to make the top border full length, the bottom border a bit shorter, move the right border a bit higher and move the diagonal line to the bottom, then just change this from bottom left to bottom right as a way to change the angle of the small diagonal line like this

background-image: linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431),
linear-gradient(to bottom right, transparent calc(50% - 0.5px), #bcd431 calc(50% - 0.5px), #bcd431 calc(50% + 0.5px), transparent calc(50% + 0.5px)), linear-gradient(transparent, transparent), linear-gradient(transparent, transparent);

If you don't care about understanding it and just want to apply the code, here you go the entire code already modified (the only changes made are in cut-corner:after)

.cut-corner:after {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  top: 0;
  z-index: -1;
  opacity: 100%;
  background-repeat: no-repeat;
  background-image: linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431), linear-gradient(#bcd431, #bcd431),
    linear-gradient(to bottom right, transparent calc(50% - 0.5px), #bcd431 calc(50% - 0.5px), #bcd431 calc(50% + 0.5px), transparent calc(50% + 0.5px)), linear-gradient(transparent, transparent), linear-gradient(transparent, transparent);
  background-size: 1px 100%, 1.5px 100%, 100% 1px, 100% 1.5px, 65px 65px, 100% 100%, 100% 100%;
  background-position: 0% 0%, 100% -65px, 0px 0%, -65px 100%, 100% 100%, -65px 50%, 100% 65px;
}


问:
Convert plain text URLs to HTML hyperlink in PHP
I have a form in HTML, i ask the user to enter a url, once that happens it comes back in plain text in PHP. What i want to happen is that when they enter their URL and submit the link that they have entered will become clickable. This is the code i have. I hope this helps. </p>

```<code>
        <?php
             $firstname = $_POST['firstname'];
             $course = $_POST['course'];
             $projecturl = $_POST['projecturl'];

             echo "<p>You are <span class='textblue'> $firstname</span> and ";
             echo "your course at the college is: <span class='textblue'> $course </span></p> ";
            echo "your project url is: <span class='textblue'> $projecturl</span></p> ";
           echo   "a href=’google.com’>Google</a>” .
                    ?>

</code>```

答:
change echo statements like this

```<code>echo "<p>You are <span class='textblue'>.'"$firstname"'.</span> and ";
</code>```

Body:
I have a form in HTML, i ask the user to enter a url, once that happens it comes back in plain text in PHP. What i want to happen is that when they enter their URL and submit the link that they have entered will become clickable. This is the code i have. I hope this helps.

        <?php
             $firstname = $_POST['firstname'];
             $course = $_POST['course'];
             $projecturl = $_POST['projecturl'];

             echo "
You are  $firstname and ";
             echo "your course at the college is:  $course
 ";
            echo "your project url is:  $projecturl
 ";
           echo   "a href=’google.com’>Google” .
                    ?>

Body:
change echo statements like this

echo "<p>You are <span class='textblue'>.'"$firstname"'.</span> and ";