问:
regeneratorRuntime is not defined rete.js
Well i am able to find a solution for my problem. I am trying to use Rete.js in Next.js with Typescript. I am seeing the following error:

regeneratorRuntime is not defined

Here are my configuration's

package.json

```<code>"dependencies": {
    "@types/next": "^9.0.0",
    "@types/react": "^16.9.19",
    "next": "^9.2.1",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "rete": "^1.4.3-rc.1",
    "rete-area-plugin": "^0.2.1",
    "rete-connection-plugin": "^0.9.0",
    "rete-dock-plugin": "^0.2.1",
    "rete-react-render-plugin": "^0.2.0"
  },
"devDependencies": {
    "@babel/plugin-transform-runtime": "^7.8.3",
    "@types/node": "^13.7.1",
    "typescript": "^3.7.5"
  }
}
</code>```

tsconfig.json

```<code>{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "jsx": "preserve",
    "lib": [
      "dom",
      "es2017"
    ],
    "module": "esnext",
    "moduleResolution": "node",
    "noEmit": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "preserveConstEnums": true,
    "removeComments": false,
    "skipLibCheck": true,
    "sourceMap": true,
    "strict": true,
    "target": "esnext",
    "forceConsistentCasingInFileNames": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "isolatedModules": true
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ]
}
</code>```

.babelrc

```<code>{
    "presets": ["next/babel"],
    "plugins": [
        [
          "@babel/plugin-transform-runtime",
          {
            "absoluteRuntime": false,
            "corejs": false,
            "helpers": true,
            "regenerator": true,
            "useESModules": false,
            "version": "7.0.0-beta.0"
          }
        ]
    ]
 }
</code>```

I have also tried to install core-js and regenerator-runtime and tried it as:

```<code>import "core-js/stable";
import "regenerator-runtime/runtime";
</code>```

But nothing worked for me. Can you suggest something that can resolve my issue.

答:
There is no need for core-js and regenerator-runtime to be installed. @babel/plugin-transform-runtime is providing the runtime that is required. I was just missing a basic thing, not adding the @babel/preset-env. I was supposing that next/babel includes all the things required for .babelrc file but that was not the case. Here is the final .babelrc file that worked for me.

```<code>{
    "presets": [
        "@babel/preset-env",
        "next/babel"
      ],
      "plugins": [
        ["@babel/plugin-transform-runtime"]
      ]
}
</code>```

Body:
Well i am able to find a solution for my problem. I am trying to use Rete.js in Next.js with Typescript. I am seeing the following error:

regeneratorRuntime is not defined

Here are my configuration's

package.json

"dependencies": {
    "@types/next": "^9.0.0",
    "@types/react": "^16.9.19",
    "next": "^9.2.1",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "rete": "^1.4.3-rc.1",
    "rete-area-plugin": "^0.2.1",
    "rete-connection-plugin": "^0.9.0",
    "rete-dock-plugin": "^0.2.1",
    "rete-react-render-plugin": "^0.2.0"
  },
"devDependencies": {
    "@babel/plugin-transform-runtime": "^7.8.3",
    "@types/node": "^13.7.1",
    "typescript": "^3.7.5"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "jsx": "preserve",
    "lib": [
      "dom",
      "es2017"
    ],
    "module": "esnext",
    "moduleResolution": "node",
    "noEmit": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "preserveConstEnums": true,
    "removeComments": false,
    "skipLibCheck": true,
    "sourceMap": true,
    "strict": true,
    "target": "esnext",
    "forceConsistentCasingInFileNames": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "isolatedModules": true
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ]
}

.babelrc

{
    "presets": ["next/babel"],
    "plugins": [
        [
          "@babel/plugin-transform-runtime",
          {
            "absoluteRuntime": false,
            "corejs": false,
            "helpers": true,
            "regenerator": true,
            "useESModules": false,
            "version": "7.0.0-beta.0"
          }
        ]
    ]
 }

I have also tried to install core-js and regenerator-runtime and tried it as:

import "core-js/stable";
import "regenerator-runtime/runtime";

But nothing worked for me. Can you suggest something that can resolve my issue.

Body:
There is no need for core-js and regenerator-runtime to be installed. @babel/plugin-transform-runtime is providing the runtime that is required. I was just missing a basic thing, not adding the @babel/preset-env. I was supposing that next/babel includes all the things required for .babelrc file but that was not the case. Here is the final .babelrc file that worked for me.

{
    "presets": [
        "@babel/preset-env",
        "next/babel"
      ],
      "plugins": [
        ["@babel/plugin-transform-runtime"]
      ]
}


来源: stackexchange

问:
Conditional formatting a whole column based on the value of another column
I would like to apply conditional formatting to all of my column D. If Column D is < or > then the value in F by 150 (in the same row), I want it to highlight red. If the value of D is within the 150 above of below of the value in F then I want it to highlight green.

For example: D2 (360) is more than 150 more than F2 (88), so I want it to highlight red.
D10 (200) if within the 150 more or less range than F10 (275) so I want it to highlight green.

Below is the picture for the fields

Fields and Data

答:
Format your cells all green. Then apply CF to cells where the difference is greater than 150 to colour those cells red. Here is the formula to use.</p>

```<code>=ABS(D2-F2)>150
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Format your cells all green. Then apply CF to cells where the difference is greater than 150 to colour those cells red. Here is the formula to use.

=ABS(D2-F2)>150


问:
Command to remove binding from IIS
In IIS if i want to remove a binding information, we can go to IIS then right click the required site and click edit bindings. Then select the required row from edit site binding popup and click remove button. The same thing i need a command to perform the same operation</p>

答:
You could use this command to remove binding from IIS.</p>

```<code>appcmd.exe set config  -section:system.applicationHost/sites /-"[name='Mysite'].bindings.[protocol='http',bindingInformation='*:80:example.se']" /commit:apphost
</code>```

Title: Command to remove binding from IIS

Body:
You could use this command to remove binding from IIS.

appcmd.exe set config  -section:system.applicationHost/sites /-"[name='Mysite'].bindings.[protocol='http',bindingInformation='*:80:example.se']" /commit:apphost


问:
React js Nested Loop array
Hi I need nelp for following json array loop.it likes that instagram or facebook post. I have a json nested array. I tried below code but it is not helped me. I need the view like that instagram post Below attached image.

I want get Profile,Likes,Comments,Post details separately through loop

Output:(for ex. If loop through Record1 means it get all nested item like (profile,Post..etc)).It print output like below image

Records1 :
     Profile
     Post
     likedetails
     commentdetails

Records2 :
     Profile
     Post
     likedetails
     commentdetails

Records3 :
     Profile
     Post
     likedetails
     commentdetails

Records4 :
     Profile
     Post
     likedetails
     commentdetails

Records5 :
     Profile
     Post
     likedetails
     commentdetails

```<code>render() {
  var Json={
     "AllPost":[
        {
           "User_Id":1,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"1",
                    "UserImage":"",
                    "Fullname":"Test",
                    "Username":"te"
                 }],
                 "Post":[{
                    "Post_Id":"1",
                    "UploadFile":"",
                    "Post_Caption":"Test",
                    "User_Id":"1"
                 }],
                 "likedetails":[{
                    "Post_Id":"1",
                    "LikeCount":"345"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":2,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"2",
                    "UserImage":"",
                    "Fullname":"Test",
                    "Username":"te"
                 }],
                 "Post":[{
                    "Post_Id":"2",
                    "UploadFile":"",
                    "Post_Caption":"Test",
                    "User_Id":"2"
                 }],
                 "likedetails":[{
                    "Post_Id":"12",
                    "LikeCount":"3452"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":3,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"3",
                    "UserImage":"",
                    "Fullname":"Test3",
                    "Username":"te3"
                 }],
                 "Post":[{
                    "Post_Id":"3",
                    "UploadFile":"",
                    "Post_Caption":"Test",
                    "User_Id":"3"
                 }],
                 "likedetails":[{
                    "Post_Id":"3",
                    "LikeCount":"345"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":4,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"4",
                    "UserImage":"",
                    "Fullname":"Test4",
                    "Username":"te4"
                 }],
                 "Post":[{
                    "Post_Id":"4",
                    "UploadFile":"",
                    "Post_Caption":"Test4",
                    "User_Id":"4"
                 }],
                 "likedetails":[{
                    "Post_Id":"4",
                    "LikeCount":"3454"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":5,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"5",
                    "UserImage":"",
                    "Fullname":"Test5",
                    "Username":"te5"
                 }],
                 "Post":[{
                    "Post_Id":"5",
                    "UploadFile":"",
                    "Post_Caption":"Test5",
                    "User_Id":"5"
                 }],
                 "likedetails":[{
                    "Post_Id":"5",
                    "LikeCount":"3455"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        }
     ]
  }

let arr=[];
Object.keys(Json.AllPost).forEach((records, index) => {

        Json.AllPost[records].forEach((obj, idx) => {
           arr.push(obj);
           console.log(arr);
        })
    });
</code>```

ex:
codepen:https://codepen.io/dotnet345/pen/oNXBxBM

答:
Did you mean something like this? Card view</p>

```<code>const BASE_URL = 'https://www.instagram.com/'userName'/?__a=1';
    Axios.get(BASE_URL)
        .then((res) => {
            console.log(res.data.graphql.user.edge_owner_to_timeline_media.edges[0].node.edge_media_to_caption.edges[0].node)
            this.setState({d: res.data.graphql.user.edge_owner_to_timeline_media.edges})
        });
</code>```

Title: React js Nested Loop array

Body:
Hi I need nelp for following json array loop.it likes that instagram or facebook post. I have a json nested array. I tried below code but it is not helped me. I need the view like that instagram post Below attached image.

I want get Profile,Likes,Comments,Post details separately through loop

Output:(for ex. If loop through Record1 means it get all nested item like (profile,Post..etc)).It print output like below image

Records1 :
     Profile
     Post
     likedetails
     commentdetails

Records2 :
     Profile
     Post
     likedetails
     commentdetails

Records3 :
     Profile
     Post
     likedetails
     commentdetails

Records4 :
     Profile
     Post
     likedetails
     commentdetails

Records5 :
     Profile
     Post
     likedetails
     commentdetails

render() {
  var Json={
     "AllPost":[
        {
           "User_Id":1,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"1",
                    "UserImage":"",
                    "Fullname":"Test",
                    "Username":"te"
                 }],
                 "Post":[{
                    "Post_Id":"1",
                    "UploadFile":"",
                    "Post_Caption":"Test",
                    "User_Id":"1"
                 }],
                 "likedetails":[{
                    "Post_Id":"1",
                    "LikeCount":"345"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":2,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"2",
                    "UserImage":"",
                    "Fullname":"Test",
                    "Username":"te"
                 }],
                 "Post":[{
                    "Post_Id":"2",
                    "UploadFile":"",
                    "Post_Caption":"Test",
                    "User_Id":"2"
                 }],
                 "likedetails":[{
                    "Post_Id":"12",
                    "LikeCount":"3452"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":3,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"3",
                    "UserImage":"",
                    "Fullname":"Test3",
                    "Username":"te3"
                 }],
                 "Post":[{
                    "Post_Id":"3",
                    "UploadFile":"",
                    "Post_Caption":"Test",
                    "User_Id":"3"
                 }],
                 "likedetails":[{
                    "Post_Id":"3",
                    "LikeCount":"345"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":4,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"4",
                    "UserImage":"",
                    "Fullname":"Test4",
                    "Username":"te4"
                 }],
                 "Post":[{
                    "Post_Id":"4",
                    "UploadFile":"",
                    "Post_Caption":"Test4",
                    "User_Id":"4"
                 }],
                 "likedetails":[{
                    "Post_Id":"4",
                    "LikeCount":"3454"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        },
        {
           "User_Id":5,
           "Username":"te",
           "Records":[
              {
                 "Profile":[{
                    "User_Id":"5",
                    "UserImage":"",
                    "Fullname":"Test5",
                    "Username":"te5"
                 }],
                 "Post":[{
                    "Post_Id":"5",
                    "UploadFile":"",
                    "Post_Caption":"Test5",
                    "User_Id":"5"
                 }],
                 "likedetails":[{
                    "Post_Id":"5",
                    "LikeCount":"3455"
                 }],
                 "commentdetails":[
                    {
                       "Comments":"testA",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testB",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testC",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testD",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    },
                    {
                       "Comments":"testE",
                       "Username": "te",
                       "Comment_Date":"12-12-12"
                    }
                 ]
              }
           ]
        }
     ]
  }

let arr=[];
Object.keys(Json.AllPost).forEach((records, index) => {

        Json.AllPost[records].forEach((obj, idx) => {
           arr.push(obj);
           console.log(arr);
        })
    });

ex:
codepen:https://codepen.io/dotnet345/pen/oNXBxBM

Body:
Did you mean something like this? Card view

const BASE_URL = 'https://www.instagram.com/'userName'/?__a=1';
    Axios.get(BASE_URL)
        .then((res) => {
            console.log(res.data.graphql.user.edge_owner_to_timeline_media.edges[0].node.edge_media_to_caption.edges[0].node)
            this.setState({d: res.data.graphql.user.edge_owner_to_timeline_media.edges})
        });


问:
TransactionManagementError “Transaction managed block ended with pending COMMIT/ROLLBACK" while making migrations in Django
When I make the migrations using python manage.py migrate manage  (yes it's Django 1.8 and I can't change it :/), the migrations (every single one I tested) always fail with the same error :

```<code>django.db.transaction.TransactionManagementError: Transaction managed block ended with pending COMMIT/ROLLBACK
</code>```

Here is the code from the migration file :

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Check expiry keys in Organization
        for org in Organization.objects.all():
            self.checkExpiryDate(org)
        # Check expiry keys in UserProfileRoleInOrganization
        for uprio in UserProfileRoleInOrganization.objects.all():
            self.checkExpiryDate(uprio)

    def checkExpiryDate(self, entity):
        # Check if expiry_date is consistent with apikey and fix it if necessary
        if not entity.date_has_changed:
            return
        date_in_key = entity.getExpiryDateInKey()
        if not date_in_key:
            return
        y = int(date_in_key[:4])
        m = int(date_in_key[4:-2])
        d = int(date_in_key[-2:])
        entity.expiry_date = datetime.datetime(y,m,d)
        entity.save()

    def backwards(self, orm):
        pass
```

I've seen some answers to other similar questions but no, I don't have any @commit.... decorator in my code.

May somebody help me please ?

答:
Delete the migrations folder and re run migrations
./manage.py makemigrations app
./manage.py migrate

or

You also can fake the migrations and reset it

Body:
When I make the migrations using python manage.py migrate manage  (yes it's Django 1.8 and I can't change it :/), the migrations (every single one I tested) always fail with the same error :

django.db.transaction.TransactionManagementError: Transaction managed block ended with pending COMMIT/ROLLBACK

Here is the code from the migration file :

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Check expiry keys in Organization
        for org in Organization.objects.all():
            self.checkExpiryDate(org)
        # Check expiry keys in UserProfileRoleInOrganization
        for uprio in UserProfileRoleInOrganization.objects.all():
            self.checkExpiryDate(uprio)

    def checkExpiryDate(self, entity):
        # Check if expiry_date is consistent with apikey and fix it if necessary
        if not entity.date_has_changed:
            return
        date_in_key = entity.getExpiryDateInKey()
        if not date_in_key:
            return
        y = int(date_in_key[:4])
        m = int(date_in_key[4:-2])
        d = int(date_in_key[-2:])
        entity.expiry_date = datetime.datetime(y,m,d)
        entity.save()

    def backwards(self, orm):
        pass

I've seen some answers to other similar questions but no, I don't have any @commit.... decorator in my code.

May somebody help me please ?


问:
Why a || a = 'bar' will get a reference error in javascript?
The code snippet is:

```<code>var a = 'foo'
a || a = 'bar'
</code>```

What I expected is that it can work normally which means a will be 'bar' finally.But I got an error

Uncaught SyntaxError: Invalid left-hand side in assignment.

According to the error,I thought maybe it is something wrong with the left hand side expression a || a.It seems that a || a is invalid here.But why?I turn to ecmascript language specification for help.In 12.15.1 Static Semantics: Early Errors, I find:

It is an early Reference Error if LeftHandSideExpression is neither an ObjectLiteral nor an ArrayLiteral and AssignmentTargetType of LeftHandSideExpression is invalid.

So, the AssignmentTargetType of LeftHandSideExpression a||a is invalid.But I am confused why a||a 's AssignmentTargetType is invalid.About this,the specification just said:

12.15.3 Static Semantics: AssignmentTargetType

AssignmentExpression:

YieldExpression

ArrowFunction

AsyncArrowFunction

LeftHandSideExpression = AssignmentExpression

LeftHandSideExpression AssignmentOperator AssignmentExpression

Return invalid.

I can't figure out why a||a 's AssignmentTargetType is invalid based on what is given.

My question is: Why a||a = 'bar' will get a reference error in javascript?If it is something with invalid AssignmentTargetType of LeftHandSideExpression,why a||a is invalid?

答:
Update: As @Teemu pointed out. Updated the comments.</p>

```<code>var a = 'foo'
a || a = 'bar' // a || a evaluates to 'foo', So it will be `'foo' = 'bar'` here

a || (a = 'bar') // will result to a is 'foo'

a = ''
a || (a = 'bar') // will result to a is 'bar'
</code>```

Body:
The code snippet is:

var a = 'foo'
a || a = 'bar'

What I expected is that it can work normally which means a will be 'bar' finally.But I got an error

Uncaught SyntaxError: Invalid left-hand side in assignment.

According to the error,I thought maybe it is something wrong with the left hand side expression a || a.It seems that a || a is invalid here.But why?I turn to ecmascript language specification for help.In 12.15.1 Static Semantics: Early Errors, I find:

It is an early Reference Error if LeftHandSideExpression is neither an ObjectLiteral nor an ArrayLiteral and AssignmentTargetType of LeftHandSideExpression is invalid.

So, the AssignmentTargetType of LeftHandSideExpression a||a is invalid.But I am confused why a||a 's AssignmentTargetType is invalid.About this,the specification just said:

12.15.3 Static Semantics: AssignmentTargetType

AssignmentExpression:

YieldExpression

ArrowFunction

AsyncArrowFunction

LeftHandSideExpression = AssignmentExpression

LeftHandSideExpression AssignmentOperator AssignmentExpression

Return invalid.

I can't figure out why a||a 's AssignmentTargetType is invalid based on what is given.

My question is: Why a||a = 'bar' will get a reference error in javascript?If it is something with invalid AssignmentTargetType of LeftHandSideExpression,why a||a is invalid?

Body:
Update: As @Teemu pointed out. Updated the comments.

var a = 'foo'
a || a = 'bar' // a || a evaluates to 'foo', So it will be `'foo' = 'bar'` here

a || (a = 'bar') // will result to a is 'foo'

a = ''
a || (a = 'bar') // will result to a is 'bar'


问:
CodeDeploy to ECS container name not found, but configuration seems correct
I am using AWS code pipeline in order to deploy a built docker image to ecs (fargate).

As you can see below, the imagedefinitions.json file created by the build points to a docker container by the name staging-core-api.

You will also note below that the task definition for the service linked to this deployment contains a docker image by the same name.

I have triple checked that the URI specified in imagedefinitions.json is correct.

From what I understand this is all that should be required in order for ecs to retrieve the docker image. However I keep getting the following error after deployment failure:

```<code>Invalid action configuration
The AWS ECS container staging-core-api does not exist
</code>```

The situation seems simple enough and it's totally unclear to me how to proceed in debugging the problem. Any insight would be very appreciated.

I attached the relevant files including the buildspec for the build below:

imagedefinitions.json

```<code>[{"name":"staging-core-api","imageUri":"263512868235.dkr.ecr.us-west-2.amazonaws.com/staging-core-api:369a521"}]
</code>```

buildspec.yml

```<code>version: 0.2
phases:
  pre_build:
    commands:
      - echo Logging in to Amazon ECR...
      - aws --version
      - $(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)
      - COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
      - IMAGE_TAG=${COMMIT_HASH:=latest}
  build:
    commands:
      - echo Build started on `date`
      - echo Building the Docker image...
      - docker build -t $REPOSITORY_URI:latest .
      - docker tag $REPOSITORY_URI:latest $REPOSITORY_URI:$IMAGE_TAG
  post_build:
    commands:
      - docker push $REPOSITORY_URI:latest
      - docker push $REPOSITORY_URI:$IMAGE_TAG
      - echo Writing image definitions file...
      - printf '[{"name":"%s","imageUri":"%s"}]' $CONTAINER_NAME $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json
      - cat imagedefinitions.json
artifacts:
    files: imagedefinitions.json
</code>```

taskdefinition.json

```<code>{
  "ipcMode": null,
  "executionRoleArn": "arn:aws:iam::263512868235:role/ecsTaskExecutionRole",
  "containerDefinitions": [
    {
      "dnsSearchDomains": null,
      "logConfiguration": {
        "logDriver": "awslogs",
        "secretOptions": null,
        "options": {
          "awslogs-group": "/ecs/core-api",
          "awslogs-region": "us-west-2",
          "awslogs-stream-prefix": "ecs"
        }
      },
      "entryPoint": null,
      "portMappings": [
        {
          "hostPort": 8080,
          "protocol": "tcp",
          "containerPort": 8080
        }
      ],
      "command": null,
      "linuxParameters": null,
      "cpu": 0,
      "environment": [],
      "resourceRequirements": null,
      "ulimits": null,
      "dnsServers": null,
      "mountPoints": [],
      "workingDirectory": null,
      "secrets": null,
      "dockerSecurityOptions": null,
      "memory": null,
      "memoryReservation": null,
      "volumesFrom": [],
      "stopTimeout": null,
      "image": "263512868235.dkr.ecr.us-west-2.amazonaws.com/staging-core-api",
      "startTimeout": null,
      "firelensConfiguration": null,
      "dependsOn": null,
      "disableNetworking": null,
      "interactive": null,
      "healthCheck": null,
      "essential": true,
      "links": null,
      "hostname": null,
      "extraHosts": null,
      "pseudoTerminal": null,
      "user": null,
      "readonlyRootFilesystem": null,
      "dockerLabels": null,
      "systemControls": null,
      "privileged": null,
      "name": "staging-core-api"
    }
  ],
  "placementConstraints": [],
  "memory": "512",
  "taskRoleArn": null,
  "compatibilities": [
    "EC2",
    "FARGATE"
  ],
  "taskDefinitionArn": "arn:aws:ecs:us-west-2:263512868235:task-definition/core-api:2",
  "family": "core-api",
  "requiresAttributes": [
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.logging-driver.awslogs"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "ecs.capability.execution-role-awslogs"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.ecr-auth"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.docker-remote-api.1.19"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "ecs.capability.execution-role-ecr-pull"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.docker-remote-api.1.18"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "ecs.capability.task-eni"
    }
  ],
  "pidMode": null,
  "requiresCompatibilities": [
    "FARGATE"
  ],
  "networkMode": "awsvpc",
  "cpu": "256",
  "revision": 2,
  "status": "ACTIVE",
  "inferenceAccelerators": null,
  "proxyConfiguration": null,
  "volumes": []
}
</code>```

答: Turns out that the ecs service configuration was using an old task definition instead of the latest one. If you feel like everything looks like it's configured right and you're getting this error message check to make sure your service is using the updated task definition. Keep in mind that when you create new task definitions it does not automatically start using them, or ask whether you would like to.</p>

Body:
I am using AWS code pipeline in order to deploy a built docker image to ecs (fargate).

As you can see below, the imagedefinitions.json file created by the build points to a docker container by the name staging-core-api.

You will also note below that the task definition for the service linked to this deployment contains a docker image by the same name.

I have triple checked that the URI specified in imagedefinitions.json is correct.

From what I understand this is all that should be required in order for ecs to retrieve the docker image. However I keep getting the following error after deployment failure:

Invalid action configuration
The AWS ECS container staging-core-api does not exist

The situation seems simple enough and it's totally unclear to me how to proceed in debugging the problem. Any insight would be very appreciated.

I attached the relevant files including the buildspec for the build below:

imagedefinitions.json

[{"name":"staging-core-api","imageUri":"263512868235.dkr.ecr.us-west-2.amazonaws.com/staging-core-api:369a521"}]

buildspec.yml

version: 0.2
phases:
  pre_build:
    commands:
      - echo Logging in to Amazon ECR...
      - aws --version
      - $(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)
      - COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
      - IMAGE_TAG=${COMMIT_HASH:=latest}
  build:
    commands:
      - echo Build started on `date`
      - echo Building the Docker image...
      - docker build -t $REPOSITORY_URI:latest .
      - docker tag $REPOSITORY_URI:latest $REPOSITORY_URI:$IMAGE_TAG
  post_build:
    commands:
      - docker push $REPOSITORY_URI:latest
      - docker push $REPOSITORY_URI:$IMAGE_TAG
      - echo Writing image definitions file...
      - printf '[{"name":"%s","imageUri":"%s"}]' $CONTAINER_NAME $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json
      - cat imagedefinitions.json
artifacts:
    files: imagedefinitions.json

taskdefinition.json

{
  "ipcMode": null,
  "executionRoleArn": "arn:aws:iam::263512868235:role/ecsTaskExecutionRole",
  "containerDefinitions": [
    {
      "dnsSearchDomains": null,
      "logConfiguration": {
        "logDriver": "awslogs",
        "secretOptions": null,
        "options": {
          "awslogs-group": "/ecs/core-api",
          "awslogs-region": "us-west-2",
          "awslogs-stream-prefix": "ecs"
        }
      },
      "entryPoint": null,
      "portMappings": [
        {
          "hostPort": 8080,
          "protocol": "tcp",
          "containerPort": 8080
        }
      ],
      "command": null,
      "linuxParameters": null,
      "cpu": 0,
      "environment": [],
      "resourceRequirements": null,
      "ulimits": null,
      "dnsServers": null,
      "mountPoints": [],
      "workingDirectory": null,
      "secrets": null,
      "dockerSecurityOptions": null,
      "memory": null,
      "memoryReservation": null,
      "volumesFrom": [],
      "stopTimeout": null,
      "image": "263512868235.dkr.ecr.us-west-2.amazonaws.com/staging-core-api",
      "startTimeout": null,
      "firelensConfiguration": null,
      "dependsOn": null,
      "disableNetworking": null,
      "interactive": null,
      "healthCheck": null,
      "essential": true,
      "links": null,
      "hostname": null,
      "extraHosts": null,
      "pseudoTerminal": null,
      "user": null,
      "readonlyRootFilesystem": null,
      "dockerLabels": null,
      "systemControls": null,
      "privileged": null,
      "name": "staging-core-api"
    }
  ],
  "placementConstraints": [],
  "memory": "512",
  "taskRoleArn": null,
  "compatibilities": [
    "EC2",
    "FARGATE"
  ],
  "taskDefinitionArn": "arn:aws:ecs:us-west-2:263512868235:task-definition/core-api:2",
  "family": "core-api",
  "requiresAttributes": [
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.logging-driver.awslogs"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "ecs.capability.execution-role-awslogs"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.ecr-auth"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.docker-remote-api.1.19"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "ecs.capability.execution-role-ecr-pull"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "com.amazonaws.ecs.capability.docker-remote-api.1.18"
    },
    {
      "targetId": null,
      "targetType": null,
      "value": null,
      "name": "ecs.capability.task-eni"
    }
  ],
  "pidMode": null,
  "requiresCompatibilities": [
    "FARGATE"
  ],
  "networkMode": "awsvpc",
  "cpu": "256",
  "revision": 2,
  "status": "ACTIVE",
  "inferenceAccelerators": null,
  "proxyConfiguration": null,
  "volumes": []
}


问:
recursive method that checks if a string is palindrome in java
the input: "mnkknm" where n=0
the output: flag is always equal 1 while it should be equal 3
and it returns -1
what is the problem ?
note : palindrome means for example if the Reverse of malayalam is also
malayalam then its palindrome
another note : i should write the code recursive as it's a homework

```<code>public static int PalindromeCheck(String x , int n)
{

int flag =0;
if (n+1 !=x.length()/2)
{
char s = x.charAt(n);
char y = x.charAt(x.length()-1-n);
if (s==y)
{    flag++;
System.out.println(flag); // i write it to check the value of the flag
}

return  flag+PalindromeCheck(x,n+1) ;
}

if (flag==x.length()/2)
{
return 1;}
else{
return -1;
}
</code>```

答:
First, I would create a helped method with that recursive signature (the public function should just take a String). And we can test for null and the empty string as special cases there. Like,

```<code>public static boolean isPalindrome(String x) {
    if (x == null) {
        return false;
    } else if (x.isEmpty()) {
        return true;
    }
    return isPalindrome(x, 0);
}
</code>```

Then your current method seems close, but you want to compare n with a less than operator to the half of the length of x. Then test that the character matches on the right hand side (offset by n from x.length() but we need a -1 because of zero based indexing). Also, the method should return a boolean (and I fixed the name). Like

```<code>private static boolean isPalindrome(String x, int n) {
    if (n < x.length() / 2) {
        if (x.charAt(n) != x.charAt(x.length() - n - 1)) {
            return false;
        }
        return isPalindrome(x, n + 1);
    }
    return true;
}
</code>```

Body:
the input: "mnkknm" where n=0
the output: flag is always equal 1 while it should be equal 3
and it returns -1
what is the problem ?
note : palindrome means for example if the Reverse of malayalam is also
malayalam then its palindrome
another note : i should write the code recursive as it's a homework

public static int PalindromeCheck(String x , int n)
{

int flag =0;
if (n+1 !=x.length()/2)
{
char s = x.charAt(n);
char y = x.charAt(x.length()-1-n);
if (s==y)
{    flag++;
System.out.println(flag); // i write it to check the value of the flag
}

return  flag+PalindromeCheck(x,n+1) ;
}

if (flag==x.length()/2)
{
return 1;}
else{
return -1;
}

Body:
First, I would create a helped method with that recursive signature (the public function should just take a String). And we can test for null and the empty string as special cases there. Like,

public static boolean isPalindrome(String x) {
    if (x == null) {
        return false;
    } else if (x.isEmpty()) {
        return true;
    }
    return isPalindrome(x, 0);
}

Then your current method seems close, but you want to compare n with a less than operator to the half of the length of x. Then test that the character matches on the right hand side (offset by n from x.length() but we need a -1 because of zero based indexing). Also, the method should return a boolean (and I fixed the name). Like

private static boolean isPalindrome(String x, int n) {
    if (n < x.length() / 2) {
        if (x.charAt(n) != x.charAt(x.length() - n - 1)) {
            return false;
        }
        return isPalindrome(x, n + 1);
    }
    return true;
}


问:
arithmatic operators as a function input (C++)
Let's say I have a function

```<code>#include <iostream>
int do_math (num_1, num_2, "*"){
....
}
</code>```

Where the code takes the inputs and applies the operator in the function to obtain the result of the calculation.

I'm not sure how to incorporate the arithmetic operator in the function to do the calculation. I was thinking of using the operator value from the ASCII table, but I was hoping maybe I can somehow incorporate istringstream method to do that. Any suggestions?

答:
It can be done as well through templates

```<code>template<typename Input, typename BinaryOp>
auto do_math(Input a, Input b, BinaryOp op)
{
   return op(a,b);
}
</code>```

This can be called like so:

```<code>auto res = do_math(5, 4, std::plus<int>());
</code>```

Body:
Let's say I have a function

#include <iostream>
int do_math (num_1, num_2, "*"){
....
}

Where the code takes the inputs and applies the operator in the function to obtain the result of the calculation.

I'm not sure how to incorporate the arithmetic operator in the function to do the calculation. I was thinking of using the operator value from the ASCII table, but I was hoping maybe I can somehow incorporate istringstream method to do that. Any suggestions?

Body:
It can be done as well through templates

template<typename Input, typename BinaryOp>
auto do_math(Input a, Input b, BinaryOp op)
{
   return op(a,b);
}

This can be called like so:

auto res = do_math(5, 4, std::plus<int>());


问:
WP Content Not Loading in Editor
Content is not loading in the content editor on the admin side. It is working in one location and not working in another location. Please check the below image of the content editor section.

答:
There is a common error that occurs in the WordPress editor, where the text color is reset to white and the buttons needed to make changes on your editor in WordPress and its content go missing.

Simple options to fix the WordPress error

Clear the browser cache

Deactivate plugins

Clear the browser cache

To clear cache from your Chrome browser:

Open the browser and click on a button with three dots at the top
right corner of the browser window.

Place the mouse pointer on ‘More tools’ and click on ‘Clear browsing
data’.

Select a time range from the dropdown and click the ‘clear data’
button.

To clear cache from your Mozilla Firefox browser:

Open the browser and click on the menu button at the upper right
corner.

Select Options from the menu.

In the Privacy section, click on Clear your recent history. From the
drop-down menu next to a Time range to clear, select Everything, then
click on Clear Now.

Hopefully, one of the above-mentioned solutions helped you fix WordPress issue and revert your text editor to its normal state. However, if you are still unable to fix it feel free to contact.

Title: WP Content Not Loading in Editor


问:
How can I resolve the "unary operator expected" error in the script?

expr: syntax error

  h2.sh: line 13: [: -gt: unary operator expected

```<code>#!/bin/sh

FILE=merchant.xml

OLDTIME=3600

CURTIME=$date
FILETIME=($date -r File)
TIMEDIFF=$(expr $CURTIME - $FILETIME)

if ["$TIMEDIFF" -gt "$OLDTIME" ]; then
   echo "File is older, do stuff here" | mail -s "hello" hardik.pahwa@guemstiger.de
fi
</code>```

答:
please add space here

```<code>if ["$TIMEDIFF" -gt "$OLDTIME" ]; then
    ^
</code>```

It should be like

```<code>if [ "$TIMEDIFF" -gt "$OLDTIME" ]; then
</code>```

Body:
expr: syntax error

  h2.sh: line 13: [: -gt: unary operator expected

#!/bin/sh

FILE=merchant.xml

OLDTIME=3600

CURTIME=$date
FILETIME=($date -r File)
TIMEDIFF=$(expr $CURTIME - $FILETIME)

if ["$TIMEDIFF" -gt "$OLDTIME" ]; then
   echo "File is older, do stuff here" | mail -s "hello" hardik.pahwa@guemstiger.de
fi

Body:
please add space here

if ["$TIMEDIFF" -gt "$OLDTIME" ]; then
    ^

It should be like

if [ "$TIMEDIFF" -gt "$OLDTIME" ]; then


问:
Azure Sphere (Seeed Studio) updated to 20.01 but now can not enable developer mode
I moved my device to retail eval for 20.01 but now can not deploy an app from Visual Studio 2019.

When I run

azsphere device enable-development

output is (note id's have deliberately been corrupted for posting here):

Getting device group 'Development' for product 'MyProduct'.
Device ID: '3EA5EF04079999999999999999999999999999999999999247A0BC6D3702B776291F647A96B8183CE07C1817D02CDD95B0D8B8E5428D1A201A8C34137935'
Downloading device capability configuration.
Setting device group to 'Development' with ID '9fc999999994a76-8982-50c4da0278c8'.
Successfully disabled application updates.
Enabling application development capability on attached device.
Applying device capability configuration to device.
error: The device did not accept the device capability configuration. Please check the Azure Sphere OS on your device is up to date using 'azsphere device show-deployment-status'.
When I do:

azsphere device show-deployment-status

C:\WINDOWS\system32>azsphere device show-deployment-status
Your device is running Azure Sphere OS version 20.01.
The Azure Sphere Security Service is targeting this device with Azure Sphere OS version 19.11.
warn: Your device is running an older Azure Sphere OS version (20.01). It has not yet started receiving the available update to version 19.11.
warn: Your device is connected to Wi-Fi. If the over-the-air update does not begin, reset your device and try again.
Go to aka.ms/AzureSphereUpgradeGuidance for further advice and support.
What do I need to do to unlock the device?

Thanks, Dave

答:
Ok, a colleague helped me figure out the solution and I have written it up at https://github.com/gloveboxes/Enabling-Developer-Mode-on-Azure-Sphere-20.01

Cheers Dave


问:
Cannot make grpc-gateway .gw.pb and there is no error
I've written this simple go server and client which client sends two numbers, and the server replies with the sum, and it works. Now I'm trying to set up a grpc-gateway using grpc API configuration and change the client's request from GRPC to rest.

I am using this tutorial and in the below section, I can not create gw, while there is no error:

protoc -I/usr/local/include -I. \
  -I$GOPATH/src \
  -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
  --grpc-gateway_out=logtostderr=true,grpc_api_configuration=path/to/your_service.yaml:. \
  path/to/your_service.proto
```

<p>I used this: </p>

<pre class="lang-sh prettyprint-override"><code>protoc -I/usr/local/include -I.   -I$GOPATH/src   -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --grpc-gateway_out=logtostderr=true,grpc_api_configuration=$GOPATH/src/grpc-test/sum.yaml:. ./sum.proto
</code>```

and after this problem I searched and I found this way, which is neither working (no error and no output!):

protoc -I/usr/local/include -I. -I$GOPATH/src -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --plugin=protoc-gen-grpc-gateway=$GOPATH/bin/protoc-gen-grpc-gateway  --grpc-gateway_out=logtostderr=true,grpc_api_configuration=sum.yaml:. ./sum.proto

```

<p>I run this in the grpc-test directory which has the below tree:</p>

<p><img src="https://i.stack.imgur.com/h75Zg.png" alt="grpc-test tree"></p>

<p>So, what am I doing wrong?</p>

<p>Edit:
so this is my sum.yaml:</p>

```type: google.api.Service
config_version: 3

http:
  rules:
    - selector: example.YourService.Echo
      post: /v1/example/echo
      body: "*"
```

<p>And this is sum.proto:</p>

```syntax = "proto3";

service ComputeSum {
    rpc ComputeSum (SumRequest) returns (ResultReply) {
    }
}

message SumRequest {
    int32 firstOperand = 1;
    int32 secondOperand = 2;
}

message ResultReply {
    int32 result = 1;
}
```

答:
The problem is with the selector in, it should be ComputeSum.ComputeSum.
I asked this question in grpc-channel in Gophers slack, and Johan Brandhorst helped me with this.

Body:
I've written this simple go server and client which client sends two numbers, and the server replies with the sum, and it works. Now I'm trying to set up a grpc-gateway using grpc API configuration and change the client's request from GRPC to rest.

I am using this tutorial and in the below section, I can not create gw, while there is no error:

protoc -I/usr/local/include -I. \
  -I$GOPATH/src \
  -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
  --grpc-gateway_out=logtostderr=true,grpc_api_configuration=path/to/your_service.yaml:. \
  path/to/your_service.proto

I used this:

protoc -I/usr/local/include -I.   -I$GOPATH/src   -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --grpc-gateway_out=logtostderr=true,grpc_api_configuration=$GOPATH/src/grpc-test/sum.yaml:. ./sum.proto

and after this problem I searched and I found this way, which is neither working (no error and no output!):

protoc -I/usr/local/include -I. -I$GOPATH/src -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --plugin=protoc-gen-grpc-gateway=$GOPATH/bin/protoc-gen-grpc-gateway  --grpc-gateway_out=logtostderr=true,grpc_api_configuration=sum.yaml:. ./sum.proto

I run this in the grpc-test directory which has the below tree:

So, what am I doing wrong?

Edit:
so this is my sum.yaml:

type: google.api.Service
config_version: 3

http:
  rules:
    - selector: example.YourService.Echo
      post: /v1/example/echo
      body: "*"

And this is sum.proto:

syntax = "proto3";

service ComputeSum {
    rpc ComputeSum (SumRequest) returns (ResultReply) {
    }
}

message SumRequest {
    int32 firstOperand = 1;
    int32 secondOperand = 2;
}

message ResultReply {
    int32 result = 1;
}


问:
AS3 - How to find the position of an object relative to the stage?
If I have a rectangle on the stage, how do I find its top left tip (x,y) and the bottom right tip (x,y) in relation to the stage? It strange how I can't find this on google! </p>

答:
localToGlobal(point) of DisplayObject Converts the point object from the display object's (local) coordinates to the Stage (global) coordinates.

```<code>// assuming (0, 0) is top left
var topLeftStage:Point = myDisplayObject.localToGlobal(new Point(0, 0));

// bottom right
var bottomRightStage:Point = myDisplayObject.localToGlobal(new Point(width, height));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
localToGlobal(point) of DisplayObject Converts the point object from the display object's (local) coordinates to the Stage (global) coordinates.

// assuming (0, 0) is top left
var topLeftStage:Point = myDisplayObject.localToGlobal(new Point(0, 0));

// bottom right
var bottomRightStage:Point = myDisplayObject.localToGlobal(new Point(width, height));


问:
Why are my global styles not working in a vue.js 2 app
I have a very weird issue. In a freshly generated vue.js project with the Vue CLI my scss files are not working properly. I am using scss configured in vue.config.js like this:

```<code>module.exports = {
  css: {
    loaderOptions: {
      sass: {
        prependData: `
          @import "@/scss/all.scss";
        `
      }
    }
  }
};
</code>```

I have multiple files in the scss folder which are okay until the moment I am using the scoped keyword in a single file component for example my nav. And then my global styles are ignored for some reason:

```<code><template>
  <div class="nav">
    <ul class="nav__menu">
      <li class="nav__item">
        <span>item</span>
      </li>
      <li class="nav__item">
        <span>item</span>
      </li>
      <li class="nav__item">
        <span>item</span>
      </li>
      <li class="nav__item">
        <span>item</span>
      </li>
    </ul>
  </div>
</template>

<script>
export default {};
</script>
<style lang="scss" scoped>
 .nav {
   /* Permalink - use to edit and share this gradient: https://colorzilla.com/gradient-editor/#1e5799+0,00c2a9+100 */
   background: rgb(30, 87, 153); /* Old browsers */
   background: -moz-linear-gradient(
     top,
     rgba(30, 87, 153, 1) 0%,
     rgba(0, 194, 169, 1) 100%
   ); /* FF3.6-15 */
   background: -webkit-linear-gradient(
     top,
     rgba(30, 87, 153, 1) 0%,
     rgba(0, 194, 169, 1) 100%
   ); /* Chrome10-25,Safari5.1-6 */
   background: linear-gradient(
     to bottom,
     rgba(30, 87, 153, 1) 0%,
     rgba(0, 194, 169, 1) 100%
   ); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
   filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1e5799', endColorstr='#00c2a9',GradientType=0 ); /* IE6-9 */
   border-radius: 15px;
   color: #fff;
   height: calc(100vh - 8px);
   padding: 10px;
   position: fixed;
   top: 4px;
   left: 4px;
   width: 200px;
   z-index: 5;
 }
</style>
</code>```

global styles:

```<code>// not working
html {
  background: black;
  box-sizing: border-box;
  font-size: 13px;

  // but this is working
  *,
  *::before,
  *::after {
    box-sizing: inherit;
  }
}
</code>```

This have never happened to me until now. Is there something I am missing, because I can't see it :(
Thanks in advance.

I am on Manjaro Linux 18.1.5, with node.js 10.16.0 and npm 6.13.1 if that can help.

答:
For future readers - I found the problem... scss files are not imported to a component if it doesn't contain a nonempty style tag.

Found out that it's pretty much a bad idea for every scss file to be imported in all of the components, because it will lead to a very big css file in the end with a lot of unused/duplicated code.

So now I am using the 'global' scss files for just variables and mixins and everything runs smooth.

Body:
I have a very weird issue. In a freshly generated vue.js project with the Vue CLI my scss files are not working properly. I am using scss configured in vue.config.js like this:

module.exports = {
  css: {
    loaderOptions: {
      sass: {
        prependData: `
          @import "@/scss/all.scss";
        `
      }
    }
  }
};

I have multiple files in the scss folder which are okay until the moment I am using the scoped keyword in a single file component for example my nav. And then my global styles are ignored for some reason:

<template>

        item

        item

        item

        item

</template>

global styles:

// not working
html {
  background: black;
  box-sizing: border-box;
  font-size: 13px;

  // but this is working
  *,
  *::before,
  *::after {
    box-sizing: inherit;
  }
}

This have never happened to me until now. Is there something I am missing, because I can't see it :(
Thanks in advance.

I am on Manjaro Linux 18.1.5, with node.js 10.16.0 and npm 6.13.1 if that can help.


问:
Do @Transactional annotated methods wait for a successful commit in Spring?
When using a @Transactional annotated method in Spring, is the returning of the annotated method synchronized to the successful commit of the underlying database transaction?

(This is assuming that the transaction will in fact commit after returning, which might not be the case depending on the selected propagation method.)

If waiting for a commit is not the default behavior, is there any way to enable it, either via configuration or otherwise?

The motivation for my question is that I would like to implement a reliable "store and forward"-type endpoint which only returns a response to the client after the effects of the call have been committed to stable storage. Is this possible with @Transactional at all?

答: I used the parameter isolation = Isolation.SERIALIZABLE, so a method would finish after the transaction has actually committed. (By the way, I put the @Transactional above a controller method in a Spring boot project.)


问:
Failed to import defined modules in __init__.py
My directory looks like this :

```<code>- HttpExample:
    - __init__.py
    - DBConnection.py
    - getLatlong.py
</code>```

I want to import DBConnection and import getLatlong in __init__.py. There is no error in my __init__.py until I run it, I received :

System.Private.CoreLib: Exception while executing function: Functions.HttpExample. System.Private.CoreLib: Result: Failure
  Exception: ModuleNotFoundError: No module named 'getLatlong'

I'm trying to use function in getLatlong to use the information input by user from __init__.py to getLatlong. Below is the code:

__init__.py :

```<code>from getLatlong import result
from DBConnection import blobService, container_name, account_key, file_path

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    section = req.params.get('section')
    bound = req.params.get('bound')
    km_location = req.params.get('km_location')
    location = req.params.get('location')
    if not section:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            section = req_body.get('section')

    if section and bound and km_location:

        result(section, km_location, bound, location).getResult() #HERE

        return func.HttpResponse(f"Hello {section}, {bound}!")

    #elif section is None or bound is None or km_location is None:
    #    return func.HttpResponse("All values are mandatory!")
</code>```

I am also receiving compile error at getLatlong to import DBConnection to this class. The following values will pass to getLatlong.py. The code :

```<code>from DBConnection import blobService, container_name, account_key, file_path #Another import error here says : Unable to import DBConnection

class result:
    def __init__(self, section, bound, km_location, location):
        self.section = section
        self.bound = bound
        self.km_location = km_location
        self.location = location

    def getResult(self):

        print(self.section)
        print(self.bound)
        print(self.km_location)
        print(self.location)
</code>```

I've tried every way to import these files before I lost my mind..

答:
You get these errors, because Python does not know where to look for the files you want to import. Depending on which Python version you are using, I see three ways to solve this:

You could add HttpExample to your PYTHONPATH and than your imports should work as you have them currently.

Another way would be to use the sys module and append the path to HttpExample, e.g.

```<code>import sys
sys.path.append('PATH/TO/HttpExample')
</code>```

But you would have to do this in all files, where you want to import something from the parent folder.

Or you use relative imports, which have been available since Python 2.5 (See PEP238). Those are only available in modules, but as you have your __init__.py file, it should work. For relative imports you are using dots . to tell Python where to look for the import. One dot . tells Python to look for the desired import in the parent folder. You could also use .. to go up two levels. But one level should be enough in your case.

So in your case changing your code to this, should solve your problem.

In __init.py__:

```<code>from .getLatlong import result
from .DBConnection import blobService, container_name, account_key, file_path
</code>```

In getLangLong.py:

```<code>from .DBConnection import blobService, container_name, account_key, file_path
</code>```

Body:
My directory looks like this :

- HttpExample:
    - __init__.py
    - DBConnection.py
    - getLatlong.py

I want to import DBConnection and import getLatlong in __init__.py. There is no error in my __init__.py until I run it, I received :

System.Private.CoreLib: Exception while executing function: Functions.HttpExample. System.Private.CoreLib: Result: Failure
  Exception: ModuleNotFoundError: No module named 'getLatlong'

I'm trying to use function in getLatlong to use the information input by user from __init__.py to getLatlong. Below is the code:

__init__.py :

from getLatlong import result
from DBConnection import blobService, container_name, account_key, file_path

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    section = req.params.get('section')
    bound = req.params.get('bound')
    km_location = req.params.get('km_location')
    location = req.params.get('location')
    if not section:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            section = req_body.get('section')

    if section and bound and km_location:

        result(section, km_location, bound, location).getResult() #HERE

        return func.HttpResponse(f"Hello {section}, {bound}!")

    #elif section is None or bound is None or km_location is None:
    #    return func.HttpResponse("All values are mandatory!")

I am also receiving compile error at getLatlong to import DBConnection to this class. The following values will pass to getLatlong.py. The code :

from DBConnection import blobService, container_name, account_key, file_path #Another import error here says : Unable to import DBConnection

class result:
    def __init__(self, section, bound, km_location, location):
        self.section = section
        self.bound = bound
        self.km_location = km_location
        self.location = location

    def getResult(self):

        print(self.section)
        print(self.bound)
        print(self.km_location)
        print(self.location)

I've tried every way to import these files before I lost my mind..

Body:
You get these errors, because Python does not know where to look for the files you want to import. Depending on which Python version you are using, I see three ways to solve this:

You could add HttpExample to your PYTHONPATH and than your imports should work as you have them currently.

Another way would be to use the sys module and append the path to HttpExample, e.g.

import sys
sys.path.append('PATH/TO/HttpExample')

But you would have to do this in all files, where you want to import something from the parent folder.

Or you use relative imports, which have been available since Python 2.5 (See PEP238). Those are only available in modules, but as you have your __init__.py file, it should work. For relative imports you are using dots . to tell Python where to look for the import. One dot . tells Python to look for the desired import in the parent folder. You could also use .. to go up two levels. But one level should be enough in your case.

So in your case changing your code to this, should solve your problem.

In __init.py__:

from .getLatlong import result
from .DBConnection import blobService, container_name, account_key, file_path

In getLangLong.py:

from .DBConnection import blobService, container_name, account_key, file_path


问:
I want to manipulate the state present in React class component in a helper function. I want to achieve the same in Typescript
I want to achieve below javascript code in typescript. I have a class component with a state which makes a call to the external helper method to modify. I need to call checkAuthentication  method present in helper.ts file and pass the context of 'this', as well as accessing the checkAuthentication method in my class component.

Class component: Home.tsx

```<code>import { checkAuthentication } from './routes/login/helper';

class Home extends React.Component<any> {
  constructor(props: any) {
    super(props);
    console.log(props);
    this.state = { authenticated: null };
    this.checkAuthentication = checkAuthentication.bind(this);
  }
  async componentDidMount() {
    this.checkAuthentication();
  }
  render() {
    return (
        <></>
    )
  }
}
</code>```

Helper.ts file contains the checkAuthentication method which modifies the state present inside Home.tsx file

```<code>async function checkAuthentication() {
  const authenticated = await this.props.auth.isAuthenticated();
  if (authenticated !== this.state.authenticated) {
    if (authenticated && !this.state.userinfo) {
      const userinfo = await this.props.auth.getUser();
      this.setState({ authenticated});
    } else {
      this.setState({ authenticated });
    }
  }
}
</code>```

答:
If it doesn't work out of the box (and if it works in JS then it should, unless it's a type-checking error that requires changing no-implicit-this or similar), then you could do the following:

```<code>function checkAuthentication(that: React.Component<any>) {
  return async function () {
    const authenticated = await that.props.auth.isAuthenticated();
    if (authenticated !== that.state.authenticated) {
      if (authenticated && !that.state.userinfo) {
        const userinfo = await that.props.auth.getUser();
        that.setState({ authenticated});
      } else {
        that.setState({ authenticated });
      }
    }
  }
}
</code>```

And in your class:

```<code>this.checkAuthentication = checkAuthentication(this);
</code>```

Body:
I want to achieve below javascript code in typescript. I have a class component with a state which makes a call to the external helper method to modify. I need to call checkAuthentication  method present in helper.ts file and pass the context of 'this', as well as accessing the checkAuthentication method in my class component.

Class component: Home.tsx

import { checkAuthentication } from './routes/login/helper';

class Home extends React.Component<any> {
  constructor(props: any) {
    super(props);
    console.log(props);
    this.state = { authenticated: null };
    this.checkAuthentication = checkAuthentication.bind(this);
  }
  async componentDidMount() {
    this.checkAuthentication();
  }
  render() {
    return (
        <></>
    )
  }
}

Helper.ts file contains the checkAuthentication method which modifies the state present inside Home.tsx file

async function checkAuthentication() {
  const authenticated = await this.props.auth.isAuthenticated();
  if (authenticated !== this.state.authenticated) {
    if (authenticated && !this.state.userinfo) {
      const userinfo = await this.props.auth.getUser();
      this.setState({ authenticated});
    } else {
      this.setState({ authenticated });
    }
  }
}

Body:
If it doesn't work out of the box (and if it works in JS then it should, unless it's a type-checking error that requires changing no-implicit-this or similar), then you could do the following:

function checkAuthentication(that: React.Component<any>) {
  return async function () {
    const authenticated = await that.props.auth.isAuthenticated();
    if (authenticated !== that.state.authenticated) {
      if (authenticated && !that.state.userinfo) {
        const userinfo = await that.props.auth.getUser();
        that.setState({ authenticated});
      } else {
        that.setState({ authenticated });
      }
    }
  }
}

And in your class:

this.checkAuthentication = checkAuthentication(this);


问:
Javascript get status from service
I develop a web application that is getting user updates from a web service (that is in another domain) I want to get the updates every 10 seconds.

For calling the service for the first time I dynamically insert a script in the page. The service is JSONP. Then I would like to define a trigger that insert a script from 10 to 10 seconds to get the updates. Is this correct? Can I do that without affecting the user experience on the website? I mean the site performance ... it will be great if I could do the call async and when I have the results I will update the status.

Is there any better solution for accessing the remote services. Is there an efficient way of dynamically reusing the same script using a trigger? I am pretty new to Javascript. Can you give me a short sample how can I define a trigger that calls a remote web service? ... or if there is a better solution.

答:
I would make use of JavaScript's setInterval method

```<code>function getUpdate () {
    //AJAX goes here
}

var myInterval = setInterval(getUpdate,10000);
</code>```

This way you'll need to inject the script-tag only once.

Title: Javascript get status from service

Body:
I would make use of JavaScript's setInterval method

function getUpdate () {
    //AJAX goes here
}

var myInterval = setInterval(getUpdate,10000);

This way you'll need to inject the script-tag only once.


问:
How to configure "react-i18next" with translation files in GatsbyJS. Always having missing key error
I need to get translations from a Gatsbyjs project.
Reading all documentation, see that everybody uses react-i18next, but many diferent ways to configure, specially if you're running this over GatsbyJS.

I've tried everything, and always got a missing key error. What am I doing wrong?

First of all, I created a component, called i18n :

```<code>    import i18n from 'i18next';
    import { useEffect } from "react"
    import { initReactI18next } from 'react-i18next';
    import Backend from 'i18next-xhr-backend';

     i18n.use(Backend)
          .use(initReactI18next)
          .init({
            lng: 'en',
            fallbackLng: 'en',
            debug: true,
            resources: {
              "backend": {
                loadPath: '/locales/{{lng}}/{{ns}}.json'
              }
            },
            interpolation: {
              escapeValue: false, // not needed for react as it escapes by default
            },
            ns: ["brands"],
            defaultNS: 'brands',
            keySeparator:false,
            react: {
              wait: true,
            }
          })
  export default i18n;
</code>```

Afterwards, I reuse this component in one of my pages

```<code>import i18n from '../../components/i18n'
    ...
const { t } = useTranslation();
    ...
{t("brands:NIKE")}
...
</code>```

This is one translation file:

```<code>/src/locales/en/brands.json
</code>```

The content of brands.json file is:

```<code>{ NIKE:"Nike" }
</code>```

Despite all, I got the following error

```<code>i18next::translator: missingKey brands:NIKE
</code>```

答: You don't need to give {t("brands:NIKE")}, simply use {t("NIKE")} and also give lng attribute value to equal the translated file name  in i18n  file.</p>

Body:
I need to get translations from a Gatsbyjs project.
Reading all documentation, see that everybody uses react-i18next, but many diferent ways to configure, specially if you're running this over GatsbyJS.

I've tried everything, and always got a missing key error. What am I doing wrong?

First of all, I created a component, called i18n :

    import i18n from 'i18next';
    import { useEffect } from "react"
    import { initReactI18next } from 'react-i18next';
    import Backend from 'i18next-xhr-backend';

     i18n.use(Backend)
          .use(initReactI18next)
          .init({
            lng: 'en',
            fallbackLng: 'en',
            debug: true,
            resources: {
              "backend": {
                loadPath: '/locales/{{lng}}/{{ns}}.json'
              }
            },
            interpolation: {
              escapeValue: false, // not needed for react as it escapes by default
            },
            ns: ["brands"],
            defaultNS: 'brands',
            keySeparator:false,
            react: {
              wait: true,
            }
          })
  export default i18n;

Afterwards, I reuse this component in one of my pages

import i18n from '../../components/i18n'
    ...
const { t } = useTranslation();
    ...
{t("brands:NIKE")}
...

This is one translation file:

/src/locales/en/brands.json

The content of brands.json file is:

{ NIKE:"Nike" }

Despite all, I got the following error

i18next::translator: missingKey brands:NIKE


问:
Convert nested list into dataframe, with 0 if value is missing
I want to convert:
[['S1', 'S2', 'S6'], ['S1', 'S2', 'S3', 'S4', 'S5'], ['S1', 'S2', 'S5'], ['S1', 'S2', 'S4', 'S5']] into a DataFrame with labels as 'S1','S2','S3','S4','S5', 'S6' and
If the value is not contained then that should be replaced by 0 otherwise 1.

```<code> 'S1','S2','S3','S4','S5','S6'
1 |  1     1   0    0     0    1
2 | 1     1   1   1     1     0
3 | 1     1   0   0     1     0
4 | 1     1   0   1     1     0
</code>```

This command is not good enough:

```<code>data = pd.DataFrame(res, columns = ['S1','S2','S3','S4','S5'])

     S1  S2  S3    S4    S5
0    S1  S2  S6  None  None
1    S1  S2  S3    S4    S5
2    S1  S2  S5  None  None
3    S1  S2  S4    S5  None
4    S1  S2  S4    S5  None
</code>```

答:
First, convert from lists ['S1', 'S2', 'S6'] into dicts {'S1': 1, 'S2': 1, 'S6': 1}. We can construct a data frame from that, and Pandas will correctly put everything in the right place. Any values that are missing will be assigned NaN (and their columns will be set to a float dtype). To counter that, we'll fill the missing values with zeroes, then convert everything back to ints. So, assuming your data is in data:

```<code>pd.DataFrame([{k:1 for k in l} for l in data]).fillna(0).astype(int)
</code>```

EDIT: If you don't like your columns to be in a seemingly random order, you can pass the columns keyword argument as you did in your attempt.

Body:
I want to convert:
[['S1', 'S2', 'S6'], ['S1', 'S2', 'S3', 'S4', 'S5'], ['S1', 'S2', 'S5'], ['S1', 'S2', 'S4', 'S5']] into a DataFrame with labels as 'S1','S2','S3','S4','S5', 'S6' and
If the value is not contained then that should be replaced by 0 otherwise 1.

 'S1','S2','S3','S4','S5','S6'
1 |  1     1   0    0     0    1
2 | 1     1   1   1     1     0
3 | 1     1   0   0     1     0
4 | 1     1   0   1     1     0

This command is not good enough:

data = pd.DataFrame(res, columns = ['S1','S2','S3','S4','S5'])

     S1  S2  S3    S4    S5
0    S1  S2  S6  None  None
1    S1  S2  S3    S4    S5
2    S1  S2  S5  None  None
3    S1  S2  S4    S5  None
4    S1  S2  S4    S5  None

Body:
First, convert from lists ['S1', 'S2', 'S6'] into dicts {'S1': 1, 'S2': 1, 'S6': 1}. We can construct a data frame from that, and Pandas will correctly put everything in the right place. Any values that are missing will be assigned NaN (and their columns will be set to a float dtype). To counter that, we'll fill the missing values with zeroes, then convert everything back to ints. So, assuming your data is in data:

pd.DataFrame([{k:1 for k in l} for l in data]).fillna(0).astype(int)

EDIT: If you don't like your columns to be in a seemingly random order, you can pass the columns keyword argument as you did in your attempt.


问:
Edited video does not saving as mp4 format android studio
I am developing a video editing app using kotlin and android. In application code it to, after video edited, video saves automatically to external storage. When triggered save() method video saves in 3gp format(can not open). After long time,it automatically convert to mp4 and working sometimes. there is no error either.
After saving video, I start intent to preview that video.It works fine with edited video.

save() method:

```<code>    fun saveVideo() {

    if (ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
        == PackageManager.PERMISSION_GRANTED
    ) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        ) {

        } else {

            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                RECORD_REQUEST_CODE
            );
        }

        val values = ContentValues(3)
        values.put(MediaStore.Video.Media.TITLE, "trimmed")
        values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4")
        getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
    }
}
</code>```

ScreenShot of gallery:

I cannot find any bug or anything. any one have a clue? what is the matter?

答:
missing line: </p>

```<code>            mediaMetadataRetriever.setDataSource(this, uri)
</code>```

Body:
I am developing a video editing app using kotlin and android. In application code it to, after video edited, video saves automatically to external storage. When triggered save() method video saves in 3gp format(can not open). After long time,it automatically convert to mp4 and working sometimes. there is no error either.
After saving video, I start intent to preview that video.It works fine with edited video.

save() method:

    fun saveVideo() {

    if (ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
        == PackageManager.PERMISSION_GRANTED
    ) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        ) {

        } else {

            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                RECORD_REQUEST_CODE
            );
        }

        val values = ContentValues(3)
        values.put(MediaStore.Video.Media.TITLE, "trimmed")
        values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4")
        getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
    }
}

ScreenShot of gallery:

I cannot find any bug or anything. any one have a clue? what is the matter?

Body:
missing line:

            mediaMetadataRetriever.setDataSource(this, uri)


问:
Why here StartCorotine() is necessary
```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FirePistol : MonoBehaviour {

    public GameObject TheGun;
    public GameObject MuzzleFlash;
    public AudioSource GunFire;
    public bool IsFiring = false;

    void Update () {
        if (Input.GetButtonDown("Fire1"))
        {
            if (IsFiring == false)
            {
                StartCoroutine(FiringPistol());
            }
        }

    }

    IEnumerator FiringPistol ()
    {
        IsFiring = true;
        TheGun.GetComponent<Animation>().Play("PistolShot");
        MuzzleFlash.SetActive(true);
        MuzzleFlash.GetComponent<Animation>().Play("MuzzleAnim");
        GunFire.Play();
        yield return new WaitForSeconds(0.5f);
        IsFiring = false;
    }
}
</code>```

I am writing a gun mechanic And
I wonder why we need
yield return new WaitForSeconds(0.5f);  .What is the difference without this command  .It's really unnecessary to write this code coz the time is short .Afterall , will it be an error like scene crash after i deleting this code ?Any help is greatly appreciated !

答:
In general: Every method returning IEnumerator has to contain at least one yield statement. In Unity you have to use StartCoroutine to run an IEnumerator as Coroutine.

In your specific case: So you can delay your code by 0.5 seconds!

It is short but 0.5 is about 30 frames!

Someone using e.g. something like AutoClicker could jam the fire key each frame so he would cause significantly more damage then someone playing "normal" (due to physical limitations of your keyboard and finger ;) )

You are just avoiding that and limit down firing to a maximum of 2x per second.

In general - as usual - there are multiple ways to achieve that and you could go without Coroutines entirely but it makes coding so much cleaner and easier to maintain then doing everything in Update!

As some alternative examples for simple delays as here you could also either do a simple timer in Update

private float timer;

void Update ()
{
    if(timer > 0)
    {
        // reduce the timer by time passed since last frame
        timer -= Time.deltaTime;
    }
    else
    {
        if(Input.GetButtonDown("Fire1"))
        {
            FiringPistol();
            timer = 0.5f;
        }
    }
}

void FiringPistol()
{
    TheGun.GetComponent<Animation>().Play("PistolShot");
    MuzzleFlash.SetActive(true);
    MuzzleFlash.GetComponent<Animation>().Play("MuzzleAnim");
    GunFire.Play();
}
```

<p>or you can also use <code>Invoke</code> with a given delay.</p>

<pre class="lang-c# prettyprint-override"><code>bool canFire;

void Update ()
{
    if (Input.GetButtonDown("Fire1") && canFire)
    {
        FiringPistol();
    }
}

void FiringPistol()
{
    TheGun.GetComponent<Animation>().Play("PistolShot");
    MuzzleFlash.SetActive(true);
    MuzzleFlash.GetComponent<Animation>().Play("MuzzleAnim");
    GunFire.Play();

    Invoke(nameof(AfterCooldown), 0.5f);
}

void AfterCooldown()
{
    canFire = true;
}
</code>```

In general btw you should store the Animation references to not use GetComponent over and over again:

// if possible already reference these via the Inspector
[SerializeField] private Animation theGunAnimation;
[SerializeField] private Animation muzzleFlashAnimation;

private void Awake()
{
    // as fallback get them on runtime
    // since this is a fallback and in best case you already referenced these via the Inspector
    // we can save a bit of resources and use GetComponent
    // only in the case the fields are not already set
    // otherwise we can skip using GetComponent as we already have a reference
    if(!theGunAnimation) theGunAnimation = TheGun.GetComponent<Animation>();
    if(!muzzleFlashAnimation) muzzleFlashAnimation = MuzzleFlash.GetComponent<Animation>();
}
```

<p>then later you reuse them</p>

<pre class="lang-c# prettyprint-override"><code>theGunAnimation.Play("PistolShot");
MuzzleFlash.SetActive(true);
muzzleFlashAnimation.Play("MuzzleAnim");
GunFire.Play();
</code>```

Title: Why here StartCorotine() is necessary

Body:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FirePistol : MonoBehaviour {

    public GameObject TheGun;
    public GameObject MuzzleFlash;
    public AudioSource GunFire;
    public bool IsFiring = false;

    void Update () {
        if (Input.GetButtonDown("Fire1"))
        {
            if (IsFiring == false)
            {
                StartCoroutine(FiringPistol());
            }
        }

    }

    IEnumerator FiringPistol ()
    {
        IsFiring = true;
        TheGun.GetComponent<Animation>().Play("PistolShot");
        MuzzleFlash.SetActive(true);
        MuzzleFlash.GetComponent<Animation>().Play("MuzzleAnim");
        GunFire.Play();
        yield return new WaitForSeconds(0.5f);
        IsFiring = false;
    }
}

I am writing a gun mechanic And
I wonder why we need
yield return new WaitForSeconds(0.5f);  .What is the difference without this command  .It's really unnecessary to write this code coz the time is short .Afterall , will it be an error like scene crash after i deleting this code ?Any help is greatly appreciated !

Body:
In general: Every method returning IEnumerator has to contain at least one yield statement. In Unity you have to use StartCoroutine to run an IEnumerator as Coroutine.

In your specific case: So you can delay your code by 0.5 seconds!

It is short but 0.5 is about 30 frames!

Someone using e.g. something like AutoClicker could jam the fire key each frame so he would cause significantly more damage then someone playing "normal" (due to physical limitations of your keyboard and finger ;) )

You are just avoiding that and limit down firing to a maximum of 2x per second.

In general - as usual - there are multiple ways to achieve that and you could go without Coroutines entirely but it makes coding so much cleaner and easier to maintain then doing everything in Update!

As some alternative examples for simple delays as here you could also either do a simple timer in Update

private float timer;

void Update ()
{
    if(timer > 0)
    {
        // reduce the timer by time passed since last frame
        timer -= Time.deltaTime;
    }
    else
    {
        if(Input.GetButtonDown("Fire1"))
        {
            FiringPistol();
            timer = 0.5f;
        }
    }
}

void FiringPistol()
{
    TheGun.GetComponent<Animation>().Play("PistolShot");
    MuzzleFlash.SetActive(true);
    MuzzleFlash.GetComponent<Animation>().Play("MuzzleAnim");
    GunFire.Play();
}

or you can also use Invoke with a given delay.

bool canFire;

void Update ()
{
    if (Input.GetButtonDown("Fire1") && canFire)
    {
        FiringPistol();
    }
}

void FiringPistol()
{
    TheGun.GetComponent<Animation>().Play("PistolShot");
    MuzzleFlash.SetActive(true);
    MuzzleFlash.GetComponent<Animation>().Play("MuzzleAnim");
    GunFire.Play();

    Invoke(nameof(AfterCooldown), 0.5f);
}

void AfterCooldown()
{
    canFire = true;
}

In general btw you should store the Animation references to not use GetComponent over and over again:

// if possible already reference these via the Inspector
[SerializeField] private Animation theGunAnimation;
[SerializeField] private Animation muzzleFlashAnimation;

private void Awake()
{
    // as fallback get them on runtime
    // since this is a fallback and in best case you already referenced these via the Inspector
    // we can save a bit of resources and use GetComponent
    // only in the case the fields are not already set
    // otherwise we can skip using GetComponent as we already have a reference
    if(!theGunAnimation) theGunAnimation = TheGun.GetComponent<Animation>();
    if(!muzzleFlashAnimation) muzzleFlashAnimation = MuzzleFlash.GetComponent<Animation>();
}

then later you reuse them

theGunAnimation.Play("PistolShot");
MuzzleFlash.SetActive(true);
muzzleFlashAnimation.Play("MuzzleAnim");
GunFire.Play();


问:
Text Highlights as CSS masks?
I'm wondering if it's possible to reproduce this text effect:

It should appear as if the text highlights were reducing the opacity of the images. I guess what you need is a copy of the background layer getting masked in the shapes/positions of the text highlights. But is there a way to really make these masks automatically resize/reposition according to the lines of text? Or any other way to achieve the effect?

This might better explain what I'm after:

答:
You can use mark tag of HTML using background color with opacity:

/*custom styling of higlihter*/
mark{
background: rgba(255, 255, 255, 0.38);
    color: black;
}
.wrap{
background-image: url("https://image.shutterstock.com/image-illustration/color-splash-series-background-design-260nw-587409425.jpg");
height: 230px;
width: 230px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
Do <mark>not forget to buy milk today</mark>
<div></code>```

Note: the mark tag is not supported in Internet Explorer 8 and earlier versions.

Another solution, using background and color on
 tag with gradient:

.wrap{
 background: grey;
 color: white;
 display: inline-block;
 background:url(https://thumbs.dreamstime.com/b/halloween-background-full-moon-creepy-house-flying-bats-halloween-background-full-moon-creepy-house-125024932.jpg);
 background-size: cover;
 height: 200px;
 width: 200px;
}
p{
font-size:20px;
    background-image: linear-gradient(to right, #ffffff00, #000000c9 , #ffffff00);
    text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap"><p>Don't play with<p></div></code>```

You can change the color accordingly.

Reference.

Title: Text Highlights as CSS masks?

Body:
You can use mark tag of HTML using background color with opacity:

/*custom styling of higlihter*/
mark{
background: rgba(255, 255, 255, 0.38);
    color: black;
}
.wrap{
background-image: url("https://image.shutterstock.com/image-illustration/color-splash-series-background-design-260nw-587409425.jpg");
height: 230px;
width: 230px;
}

<div class="wrap">
Do <mark>not forget to buy milk today</mark>
<div>

Note: the mark tag is not supported in Internet Explorer 8 and earlier versions.

Another solution, using background and color on <p> tag with gradient:

.wrap{
 background: grey;
 color: white;
 display: inline-block;
 background:url(https://thumbs.dreamstime.com/b/halloween-background-full-moon-creepy-house-flying-bats-halloween-background-full-moon-creepy-house-125024932.jpg);
 background-size: cover;
 height: 200px;
 width: 200px;
}
p{
font-size:20px;
    background-image: linear-gradient(to right, #ffffff00, #000000c9 , #ffffff00);
    text-align: center;
}

<div class="wrap"><p>Don't play with<p></div>

You can change the color accordingly.

Reference.


问:
How to display all items in a list without satisfying a particular condition in C#,ASP.NET CORE?
is it possible through FindAll()? I don't think so beacause FindAll() always need a condition right? Is there any possible way to do this?can anyone help please

This is my List

```<code>studentlist = new List<StudentModel>()
{
   new StudentModel{id=1,fname="john",lname="joseph",location="trivandrum",contact=786789876,email="j@gmail.com",password="a",roles="Employee" },
   new StudentModel{id=2,fname="sam",lname="joseph",location="kollam",contact=786789876,email="sam@gmail.com",password="b",roles="Admin" }
};

</code>```

答:
You can use Linq to do this. And if you want all which don't satisfying your condition, then negate it. It would something like this:

```<code>studentlist.Where(!yourCondition).ToList();
</code>```

You also can use the All() method:

```<code>studentlist.All(condition).ToList();
</code>```

But if you need all, simly bind(or however you want to display them) directly to your studentlist

Body:
is it possible through FindAll()? I don't think so beacause FindAll() always need a condition right? Is there any possible way to do this?can anyone help please

This is my List

studentlist = new List<StudentModel>()
{
   new StudentModel{id=1,fname="john",lname="joseph",location="trivandrum",contact=786789876,email="j@gmail.com",password="a",roles="Employee" },
   new StudentModel{id=2,fname="sam",lname="joseph",location="kollam",contact=786789876,email="sam@gmail.com",password="b",roles="Admin" }
};

Body:
You can use Linq to do this. And if you want all which don't satisfying your condition, then negate it. It would something like this:

studentlist.Where(!yourCondition).ToList();

You also can use the All() method:

studentlist.All(condition).ToList();

But if you need all, simly bind(or however you want to display them) directly to your studentlist