问:
How to Auto Submit Form Using JS
I want to add code auto Auto Submit Form using JS once the page finish load
I need it submit the inputs values too
Submit and the captcha response works good when I click manually automatic work but didnt submit with  input "g-recaptcha-response" value
```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://www.google.com/recaptcha/api.js?render=<?php echo $captcha_site_key ?>"></script>
</head>
    <form action="check.php" id="myform" method="POST">
    <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
    <input type="Submit" name="Submit">
</form>
<script>
    grecaptcha.ready(function() {
        grecaptcha.execute('<?php echo $captcha_site_key ?>', {action:'validate_captcha'})
                  .then(function(token) {
            document.getElementById('g-recaptcha-response').value = token;
        });
    });
</script>
<script type="text/javascript">
window.onload = function(){
  document.getElementById("myform").submit();
}
</script>

</body>
</html>
</code>```

答:
Thanks for @Mosia Thabo for helping me

The JS code is

explain :- first setAttribute('value', 'token');

then wait 1 second then submit myform

```<code><script type="text/javascript">
    document.getElementById('g-recaptcha-response')..setAttribute("value", token);

</script>
<script type="text/javascript">
window.onload=function(){
    window.setTimeout(document.myform.submit.bind(document.myform), 100);
};
 </script>
</code>```

Title: How to Auto Submit Form Using JS

Body:
I want to add code auto Auto Submit Form using JS once the page finish load
I need it submit the inputs values too
Submit and the captcha response works good when I click manually automatic work but didnt submit with  input "g-recaptcha-response" value

<!DOCTYPE html>

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

    <form action="check.php" id="myform" method="POST">
    <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
    <input type="Submit" name="Submit">
</form>

Body:
Thanks for @Mosia Thabo for helping me

The JS code is

explain :- first setAttribute('value', 'token');

then wait 1 second then submit myform

<script type="text/javascript">
    document.getElementById('g-recaptcha-response')..setAttribute("value", token);

</script>
<script type="text/javascript">
window.onload=function(){
    window.setTimeout(document.myform.submit.bind(document.myform), 100);
};
 </script>


来源: stackexchange

问:
Cannot get DOM events on component in host component
I have a Vue component that contains a list of objects named lines.  I build a table from those lines using different components based on the line type.  This works perfectly.  Here's a stripped down version of the component:

```<code><template>
  <table>
    <tr v-for="line in lines"
        :key="line.key"
        :is="componentForType[line.eventType] || 'LogLine'"
        v-bind="line"
    />
  </table>
</template>

<script>
  export default {
    name: 'DebugLog',
    components: {
      LogLine,
      FormattedLogLine,
      UserDebug,
      Limits
    },
    data () {
      return {
        lines: [],
        selectedKey: null,
        componentForType: {
          'USER_DEBUG' : 'UserDebug',
          'LIMIT_USAGE_FOR_NS' : 'Limits',
          'EXCEPTION_THROWN' : 'FormattedLogLine',
          'FATAL_ERROR' : 'FormattedLogLine'
        }

      }
    },
    mounted() {
      // code that loads this.lines
    }
  }
</script>
</code>```

Now I want to be able to click any row of the table, and have the row become "selected", meaning that I want store line.key in this.selectedKey and use CSS to render that line differently.  But I can't get the events working.  Here's the updated <template>; nothing else is changed:

```<code><template>
  <table>
    <tr v-for="line in lines"
        :key="line.key"
        :is="componentForType[line.eventType] || 'LogLine'"
        v-bind="line"
        :class="{selected: line.key == selectedKey}"
        @click.capture="selectedKey = line.key"
    />
  </table>
</template>
</code>```

I've added the last 2 properties on the tr element - a dynamic class binding and a click event handler to set this.selectedKey to the active line's key.  But it isn't working.  I replaced the @click handler code with console.log(line.key) and nothing is logged, which tells me that my @click handler is never firing.  I originally wrote it with out the .capture modifier, but tried adding the modifier when the original didn't work.

Is vue.js stopping propagation from the child component to the parent?  Can I not bind the click event on the tr since it :is another vue component?  Or is there something else going on?  The examples I've found in the docs are much simpler and I'm not sure they correspond to my situation.  The various child components are not binding any click events.  I'd prefer to handle the event entirely in the parent as shown, since I will have a number of types of child component, and I don't want to have to implement click handlers in each.

Update: Looking at my child components, I note that each contains a tr tag that must effectively replace the tr in the parent template.  For example, my most basic component is LogLine, shown here:

```<code><template>
  <tr>
    <td>{{timeStamp}}</td>
    <td>{{eventType}}</td>
    <td>{{lineNumber}}</td>
    <td>{{lineData}}</td>
  </tr>
</template>

<script>
  export default {
    name: 'LogLine',
    props: ['timeStamp', 'eventType', 'lineData', 'lineNumber'],
    data: function () {
      return {}
    }
  }
</script>
</code>```

So I'm guessing that the binding in the parent isn't actually binding on the tr in the DOM; it's just binding on the Vue component, listening for a click event to be sent from the child with $emit; and that each child component will need to bind @click on its tr and emit it to the parent.  Assuming I'm right, is there any shortcut I can use from the parent template to have vue forward the DOM events?  Any other option I'm missing besides binding click in every child component?

答:
@Jacob Goh's use of v-on="$listeners" is simple and allows forwarding of all DOM events in one action, but I wanted to document an approach I tried on my own for completeness.  I will be switching to Jacob's solution in my component.  I am now using Husam's .native modifier in the parent as it is more suitable to my particular use case.

I was able to make my component work by editing each child component, capturing the click event and re-emitting it.  For example:

```<code><template>
  <tr @click="$emit('click')">
    <td>{{timeStamp}}</td>
    <td>{{eventType}}</td>
    <td>{{lineNumber}}</td>
    <td>{{lineData}}</td>
  </tr>
</template>

<script>
  export default {
    name: 'LogLine',
    props: ['timeStamp', 'eventType', 'lineData', 'lineNumber'],
    data: function () {
      return {}
    }
  }
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a Vue component that contains a list of objects named lines.  I build a table from those lines using different components based on the line type.  This works perfectly.  Here's a stripped down version of the component:

<template>

</template>

Now I want to be able to click any row of the table, and have the row become "selected", meaning that I want store line.key in this.selectedKey and use CSS to render that line differently.  But I can't get the events working.  Here's the updated <template>; nothing else is changed:

<template>

</template>

I've added the last 2 properties on the tr element - a dynamic class binding and a click event handler to set this.selectedKey to the active line's key.  But it isn't working.  I replaced the @click handler code with console.log(line.key) and nothing is logged, which tells me that my @click handler is never firing.  I originally wrote it with out the .capture modifier, but tried adding the modifier when the original didn't work.

Is vue.js stopping propagation from the child component to the parent?  Can I not bind the click event on the tr since it :is another vue component?  Or is there something else going on?  The examples I've found in the docs are much simpler and I'm not sure they correspond to my situation.  The various child components are not binding any click events.  I'd prefer to handle the event entirely in the parent as shown, since I will have a number of types of child component, and I don't want to have to implement click handlers in each.

Update: Looking at my child components, I note that each contains a tr tag that must effectively replace the tr in the parent template.  For example, my most basic component is LogLine, shown here:

<template>

    {{timeStamp}}
    {{eventType}}
    {{lineNumber}}
    {{lineData}}

</template>

So I'm guessing that the binding in the parent isn't actually binding on the tr in the DOM; it's just binding on the Vue component, listening for a click event to be sent from the child with $emit; and that each child component will need to bind @click on its tr and emit it to the parent.  Assuming I'm right, is there any shortcut I can use from the parent template to have vue forward the DOM events?  Any other option I'm missing besides binding click in every child component?

Body:
@Jacob Goh's use of v-on="$listeners" is simple and allows forwarding of all DOM events in one action, but I wanted to document an approach I tried on my own for completeness.  I will be switching to Jacob's solution in my component.  I am now using Husam's .native modifier in the parent as it is more suitable to my particular use case.

I was able to make my component work by editing each child component, capturing the click event and re-emitting it.  For example:

<template>
  <tr @click="$emit('click')">
    <td>{{timeStamp}}</td>
    <td>{{eventType}}</td>
    <td>{{lineNumber}}</td>
    <td>{{lineData}}</td>
  </tr>
</template>

<script>
  export default {
    name: 'LogLine',
    props: ['timeStamp', 'eventType', 'lineData', 'lineNumber'],
    data: function () {
      return {}
    }
  }
</script>


问:
Python socket server, is there a way for user to input the port on terminal?
I have an assignment that wants me to create a socket program that have to user input the port number on terminal. So instead of the port being defined in the program, the port should be defined by:
$ python3 socket_program.py < port_number > &

Is there a way to do this?

答:
Yes, use sys to access arguments passed into your script. Here's an example of taking the first argument passed into your script and assigning it to a variable called port.</p>

```<code>import sys
if len(sys.argv) > 1:
  port = int(sys.argv[1])
else:
  port = 3000
</code>```

Body:
Yes, use sys to access arguments passed into your script. Here's an example of taking the first argument passed into your script and assigning it to a variable called port.

import sys
if len(sys.argv) > 1:
  port = int(sys.argv[1])
else:
  port = 3000


问:
Pluck or Something else?
DB::table('mobil')->where('id',$id)->first().

I ever try it, but it give me all columns data. The problem is, In this Mobil table I have name, status, des, model and Id. The data that I need is name, status, and des. Can you help me to make a code to take some data that I need and it must one row. It must first row

答:
You can pass columns name as array in ->first() method

```<code>DB::table('mobil')
    ->where('id', $id)
    ->first(['name', 'status', 'des'])
</code>```

Title: Pluck or Something else?

Body:
You can pass columns name as array in ->first() method

DB::table('mobil')
    ->where('id', $id)
    ->first(['name', 'status', 'des'])


问:
Why does a GraphQL query return null?
I have an graphql/apollo-server/graphql-yoga endpoint. This endpoint exposes data returned from a database (or a REST endpoint or some other service).

I know my data source is returning the correct data -- if I log the result of the call to the data source inside my resolver, I can see the data being returned. However, my GraphQL field(s) always resolve to null.

If I make the field non-null, I see the following error inside the errors array in the response:

Cannot return null for non-nullable field

Why is GraphQL not returning the data?

答:
There's two common reasons your field or fields are resolving to null: 1) returning data in the wrong shape inside your resolver; and 2) not using Promises correctly.

Note: if you're seeing the following error:

Cannot return null for non-nullable field

the underlying issue is that your field is returning null. You can still follow the steps outlined below to try to resolve this error.

The following examples will refer to this simple schema:

```<code>type Query {
  post(id: ID): Post
  posts: [Post]
}

type Post {
  id: ID
  title: String
  body: String
}
</code>```

Returning data in the wrong shape

Our schema, along with the requested query, defines the "shape" of the data object in the response returned by our endpoint. By shape, we mean what properties objects have, and whether those properties' values' are scalar values, other objects, or arrays of objects or scalars.

In the same way a schema defines the shape of the total response, the type of an individual field defines the shape of that field's value. The shape of the data we return in our resolver must likewise match this expected shape. When it doesn't, we frequently end up with unexpected nulls in our response.

Before we dive into specific examples, though, it's important to grasp how GraphQL resolves fields.

Understanding default resolver behavior

While you certainly can write a resolver for every field in your schema, it's often not necessary because GraphQL.js uses a default resolver when you don't provide one.

At a high level, what the default resolver does is simple: it looks at the value the parent field resolved to and if that value is a JavaScript object, it looks for a property on that Object with the same name as the field being resolved. If it finds that property, it resolves to the value of that property. Otherwise, it resolves to null.

Let's say in our resolver for the post field, we return the value { title: 'My First Post', bod: 'Hello World!' }. If we don't write resolvers for any of the fields on the Post type, we can still request the post:

```<code>query {
  post {
    id
    title
    body
  }
}
</code>```

and our response will be

```<code>{
  "data": {
    "post" {
      "id": null,
      "title": "My First Post",
      "body": null,
    }
  }
}
</code>```

The title field was resolved even though we didn't provide a resolver for it because the default resolver did the heavy lifting -- it saw there was a property named title on the Object the parent field (in this case post) resolved to and so it just resolved to that property's value. The id field resolved to null because the object we returned in our post resolver did not have an id property. The body field also resolved to null because of a typo -- we have a property called bod instead of body!

Pro tip: If bod is not a typo but what an API or database actually returns, we can always write a resolver for the body field to match our schema. For example: (parent) => parent.bod

One important thing to keep in mind is that in JavaScript, almost everything is an Object. So if the post field resolves to a String or a Number, the default resolver for each of the fields on the Post type will still try to find an appropriately named property on the parent object, inevitably fail and return null. If a field has an object type but you return something other than object in its resolver (like a String or an Array), you will not see any error about the type mismatch but the child fields for that field will inevitably resolve to null.

Common Scenario #1: Wrapped Responses

If we're writing the resolver for the post query, we might fetch our code from some other endpoint, like this:

```<code>function post (root, args) {
  // axios
  return axios.get(`http://SOME_URL/posts/${args.id}`)
    .then(res => res.data);

  // fetch
  return fetch(`http://SOME_URL/posts/${args.id}`)
    .then(res => res.json());

  // request-promise-native
  return request({
    uri: `http://SOME_URL/posts/${args.id}`,
    json: true
  });
}
</code>```

The post field has the type Post, so our resolver should return an object with properties like id,  title and body. If this is what our API returns, we're all set. However, it's common for the response to actually be an object which contains additional metadata. So the object we actually get back from the endpoint might look something like this:

```<code>{
  "status": 200,
  "result": {
    "id": 1,
    "title": "My First Post",
    "body": "Hello world!"
  },
}
</code>```

In this case, we can't just return the response as-is and expect the default resolver to work correctly, since the object we're returning doesn't have the id , title and body properties we need. Our resolver isn't needs to do something like:

```<code>function post (root, args) {
  // axios
  return axios.get(`http://SOME_URL/posts/${args.id}`)
    .then(res => res.data.result);

  // fetch
  return fetch(`http://SOME_URL/posts/${args.id}`)
    .then(res => res.json())
    .then(data => data.result);

  // request-promise-native
  return request({
    uri: `http://SOME_URL/posts/${args.id}`,
    json: true
  })
    .then(res => res.result);
}
</code>```

Note: The above example fetches data from another endpoint; however, this sort of wrapped response is also very common when using a database driver directly (as opposed to using an ORM)! For example, if you're using node-postgres, you'll get a Result object that includes properties like rows,  fields, rowCount and command. You'll need to extract the appropriate data from this response before returning it inside your resolver.

Common Scenario #2: Array Instead of Object

What if we fetch a post from the database, our resolver might look something like this:

```<code>function post(root, args, context) {
  return context.Post.find({ where: { id: args.id } })
}
</code>```

where Post is some model we're injecting through the context. If we're using sequelize, we might call findAll. mongoose and typeorm have find. What these methods have in common is that while they allow us to specify a WHERE condition, the Promises they return still resolve to an array instead of a single object. While there's probably only one post in your database with a particular ID, it's still wrapped in an array when you call one of these methods. Because an Array is still an Object, GraphQL will not resolve the post field as null. But it will resolve all of the child fields as null because it won't be able to find the appropriately named properties on the array.

You can easily fix this scenario by just grabbing the first item in the array and returning that in your resolver:

```<code>function post(root, args, context) {
  return context.Post.find({ where: { id: args.id } })
    .then(posts => posts[0])
}
</code>```

If you're fetching data from another API, this is frequently the only option. On the other hand, if you're using an ORM, there's often a different method that you can use (like findOne) that will explicitly return only a single row from the DB (or null if it doesn't exist).

```<code>function post(root, args, context) {
  return context.Post.findOne({ where: { id: args.id } })
}
</code>```

A special note on INSERT and UPDATE calls: We often expect methods that insert or update a row or model instance to return the inserted or updated row. Often they do, but some methods don't. For example, sequelize's upsert method resolves to a boolean, or tuple of the the upserted record and a boolean (if the returning option is set to true). mongoose's findOneAndUpdate resolves to an object with a value property that contains the modified row. Consult your ORM's documentation and parse the result appropriately before returning it inside your resolver.

Common Scenario #3: Object Instead of Array

In our schema, the posts field's type is a List of Posts, which means its resolver needs to return an Array of objects (or a Promise that resolves to one). We might fetch the posts like this:

```<code>function posts (root, args) {
  return fetch('http://SOME_URL/posts')
    .then(res => res.json())
}
</code>```

However, the actual response from our API might be an object that wraps the the array of posts:

```<code>query {
  post {
    id
    title
    body
  }
}
</code>```0

We can't return this object in our resolver because GraphQL is expecting an Array. If we do, the field will resolve to null and we'll see an error included in our response like:

Expected Iterable, but did not find one for field Query.posts.

Unlike the two scenarios above, in this case GraphQL is able to explicitly check the type of the value we return in our resolver and will throw if it's not an Iterable like an Array.

Like we discussed in the first scenario, in order to fix this error, we have to transform the response into the appropriate shape, for example:

```<code>query {
  post {
    id
    title
    body
  }
}
</code>```1

Not Using Promises Correctly

GraphQL.js makes use of the Promise API under the hood. As such, a resolver can return some value (like { id: 1, title: 'Hello!' }) or it can return a Promise that will resolve to that value. For fields that have a List type, you may also return an array of Promises. If a Promise rejects, that field will return null and the appropriate error will be added to the errors array in the response. If a field has an Object type, the value the Promise resolves to is what will be passed down as the parent value to the resolvers of any child fields.

A Promise is an "object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value." The next few scenarios outline some common pitfalls encountered when dealing with Promises inside resolvers. However, if you're not familiar with Promises and the newer async/await syntax, it's highly recommended you spend some time reading up on the fundamentals.

Note: the next few examples refer to a getPost function. The implementation details of this function are not important -- it's just a function that returns a Promise, which will resolve to a post object.

Common Scenario #4: Not Returning a Value

A working resolver for the post field might looks like this:

```<code>query {
  post {
    id
    title
    body
  }
}
</code>```2

getPosts returns a Promise and we're returning that Promise. Whatever that Promise resolves to will become the value our field resolves to. Looking good!

But what happens if we do this:

```<code>function post(root, args) {
  getPost(args.id)
}
</code>```

We're still creating a Promise that will resolve to a post. However, we're not returning the Promise, so GraphQL is not aware of it and it will not wait for it to resolve. In JavaScript functions without an explicit return statement implicitly return undefined. So our function creates a Promise and then immediately returns undefined, causing GraphQL to return null for the field.

If the Promise returned by getPost rejects, we won't see any error listed in our response either -- because we didn't return the Promise, the underlying code doesn't care about whether it resolves or rejects. In fact, if the Promise rejects, you'll see an
UnhandledPromiseRejectionWarning in your server console.

Fixing this issue is simple -- just add the return.

Common Scenario #5: Not chaining Promises correctly

You decide to log the result of your call to getPost, so you change your resolver to look something like this:

```<code>function post(root, args) {
  return getPost(args.id)
    .then(post => {
      console.log(post)
    })
}
</code>```

When you run your query, you see the result logged in your console, but GraphQL resolves the field to null. Why?

When we call then on a Promise, we're effectively taking the value the Promise resolved to and returning a new Promise. You can think of it kind of like Array.map except for Promises. then can return a value, or another Promise. In either case, what's returned inside of then is "chained" onto the original Promise. Multiple Promises can be chained together like this by using multiple thens. Each Promise in the chain is resolved in sequence, and the final value is what's effectively resolved as the value of the original Promise.

In our example above, we returned nothing inside of the then, so the Promise resolved to undefined, which GraphQL converted to a null. To fix this, we have to return the posts:

```<code>function post(root, args) {
  return getPost(args.id)
    .then(post => {
      console.log(post)
      return post // <----
    })
}
</code>```

If you have multiple Promises you need to resolve inside your resolver, you have to chain them correctly by using then and returning the correct value. For example, if we need to call two other asynchronous functions (getFoo and getBar) before we can call getPost, we can do:

```<code>function post(root, args) {
  return getFoo()
    .then(foo => {
      // Do something with foo
      return getBar() // return next Promise in the chain
    })
    .then(bar => {
      // Do something with bar
      return getPost(args.id) // return next Promise in the chain
    })
</code>```

Pro tip: If you're struggling with correctly chaining Promises, you may find async/await syntax to be cleaner and easier to work with.

Common Scenario #6

Before Promises, the standard way to handle asynchronous code was to use callbacks, or functions that would be called once the asynchronous work was completed. We might, for example, call mongoose's findOne method like this:

```<code>function post(root, args) {
  return Post.findOne({ where: { id: args.id } }, function (err, post) {
    return post
  })
</code>```

The problem here is two-fold. One, a value that's returned inside a callback isn't used for anything (i.e. it's not passed to the underlying code in any way). Two, when we use a callback, Post.findOne doesn't return a Promise; it just returns undefined. In this example, our callback will be called, and if we log the value of post we'll see whatever was returned from the database. However, because we didn't use a Promise, GraphQL doesn't wait for this callback to complete -- it takes the return value (undefined) and uses that.

Most more popular libraries, including mongoose support Promises out of the box. Those that don't frequently have complimentary "wrapper" libraries that add this functionality. When working with GraphQL resolvers, you should avoid using methods that utilize a callback, and instead use ones that return Promises.

Pro tip: Libraries that support both callbacks and Promises frequently overload their functions in such a way that if a callback is not provided, the function will return a Promise. Check the library's documentation for details.

If you absolutely have to use a callback, you can also wrap the callback in a Promise:

```<code>function post(root, args) {
  return new Promise((resolve, reject) => {
    Post.findOne({ where: { id: args.id } }, function (err, post) {
      if (err) {
        reject(err)
      } else {
        resolve(post)
      }
    })
  })
</code>```

Title: Why does a GraphQL query return null?

Body:
There's two common reasons your field or fields are resolving to null: 1) returning data in the wrong shape inside your resolver; and 2) not using Promises correctly.

Note: if you're seeing the following error:

Cannot return null for non-nullable field

the underlying issue is that your field is returning null. You can still follow the steps outlined below to try to resolve this error.

The following examples will refer to this simple schema:

type Query {
  post(id: ID): Post
  posts: [Post]
}

type Post {
  id: ID
  title: String
  body: String
}

Returning data in the wrong shape

Our schema, along with the requested query, defines the "shape" of the data object in the response returned by our endpoint. By shape, we mean what properties objects have, and whether those properties' values' are scalar values, other objects, or arrays of objects or scalars.

In the same way a schema defines the shape of the total response, the type of an individual field defines the shape of that field's value. The shape of the data we return in our resolver must likewise match this expected shape. When it doesn't, we frequently end up with unexpected nulls in our response.

Before we dive into specific examples, though, it's important to grasp how GraphQL resolves fields.

Understanding default resolver behavior

While you certainly can write a resolver for every field in your schema, it's often not necessary because GraphQL.js uses a default resolver when you don't provide one.

At a high level, what the default resolver does is simple: it looks at the value the parent field resolved to and if that value is a JavaScript object, it looks for a property on that Object with the same name as the field being resolved. If it finds that property, it resolves to the value of that property. Otherwise, it resolves to null.

Let's say in our resolver for the post field, we return the value { title: 'My First Post', bod: 'Hello World!' }. If we don't write resolvers for any of the fields on the Post type, we can still request the post:

query {
  post {
    id
    title
    body
  }
}

and our response will be

{
  "data": {
    "post" {
      "id": null,
      "title": "My First Post",
      "body": null,
    }
  }
}

The title field was resolved even though we didn't provide a resolver for it because the default resolver did the heavy lifting -- it saw there was a property named title on the Object the parent field (in this case post) resolved to and so it just resolved to that property's value. The id field resolved to null because the object we returned in our post resolver did not have an id property. The body field also resolved to null because of a typo -- we have a property called bod instead of body!

Pro tip: If bod is not a typo but what an API or database actually returns, we can always write a resolver for the body field to match our schema. For example: (parent) => parent.bod

One important thing to keep in mind is that in JavaScript, almost everything is an Object. So if the post field resolves to a String or a Number, the default resolver for each of the fields on the Post type will still try to find an appropriately named property on the parent object, inevitably fail and return null. If a field has an object type but you return something other than object in its resolver (like a String or an Array), you will not see any error about the type mismatch but the child fields for that field will inevitably resolve to null.

Common Scenario #1: Wrapped Responses

If we're writing the resolver for the post query, we might fetch our code from some other endpoint, like this:

function post (root, args) {
  // axios
  return axios.get(`http://SOME_URL/posts/${args.id}`)
    .then(res => res.data);

  // fetch
  return fetch(`http://SOME_URL/posts/${args.id}`)
    .then(res => res.json());

  // request-promise-native
  return request({
    uri: `http://SOME_URL/posts/${args.id}`,
    json: true
  });
}

The post field has the type Post, so our resolver should return an object with properties like id,  title and body. If this is what our API returns, we're all set. However, it's common for the response to actually be an object which contains additional metadata. So the object we actually get back from the endpoint might look something like this:

{
  "status": 200,
  "result": {
    "id": 1,
    "title": "My First Post",
    "body": "Hello world!"
  },
}

In this case, we can't just return the response as-is and expect the default resolver to work correctly, since the object we're returning doesn't have the id , title and body properties we need. Our resolver isn't needs to do something like:

function post (root, args) {
  // axios
  return axios.get(`http://SOME_URL/posts/${args.id}`)
    .then(res => res.data.result);

  // fetch
  return fetch(`http://SOME_URL/posts/${args.id}`)
    .then(res => res.json())
    .then(data => data.result);

  // request-promise-native
  return request({
    uri: `http://SOME_URL/posts/${args.id}`,
    json: true
  })
    .then(res => res.result);
}

Note: The above example fetches data from another endpoint; however, this sort of wrapped response is also very common when using a database driver directly (as opposed to using an ORM)! For example, if you're using node-postgres, you'll get a Result object that includes properties like rows,  fields, rowCount and command. You'll need to extract the appropriate data from this response before returning it inside your resolver.

Common Scenario #2: Array Instead of Object

What if we fetch a post from the database, our resolver might look something like this:

function post(root, args, context) {
  return context.Post.find({ where: { id: args.id } })
}

where Post is some model we're injecting through the context. If we're using sequelize, we might call findAll. mongoose and typeorm have find. What these methods have in common is that while they allow us to specify a WHERE condition, the Promises they return still resolve to an array instead of a single object. While there's probably only one post in your database with a particular ID, it's still wrapped in an array when you call one of these methods. Because an Array is still an Object, GraphQL will not resolve the post field as null. But it will resolve all of the child fields as null because it won't be able to find the appropriately named properties on the array.

You can easily fix this scenario by just grabbing the first item in the array and returning that in your resolver:

function post(root, args, context) {
  return context.Post.find({ where: { id: args.id } })
    .then(posts => posts[0])
}

If you're fetching data from another API, this is frequently the only option. On the other hand, if you're using an ORM, there's often a different method that you can use (like findOne) that will explicitly return only a single row from the DB (or null if it doesn't exist).

function post(root, args, context) {
  return context.Post.findOne({ where: { id: args.id } })
}

A special note on INSERT and UPDATE calls: We often expect methods that insert or update a row or model instance to return the inserted or updated row. Often they do, but some methods don't. For example, sequelize's upsert method resolves to a boolean, or tuple of the the upserted record and a boolean (if the returning option is set to true). mongoose's findOneAndUpdate resolves to an object with a value property that contains the modified row. Consult your ORM's documentation and parse the result appropriately before returning it inside your resolver.

Common Scenario #3: Object Instead of Array

In our schema, the posts field's type is a List of Posts, which means its resolver needs to return an Array of objects (or a Promise that resolves to one). We might fetch the posts like this:

function posts (root, args) {
  return fetch('http://SOME_URL/posts')
    .then(res => res.json())
}

However, the actual response from our API might be an object that wraps the the array of posts:

{
  "count": 10,
  "next": "http://SOME_URL/posts/?page=2",
  "previous": null,
  "results": [
    {
      "id": 1,
      "title": "My First Post",
      "body" "Hello World!"
    },
    ...
  ]
}

We can't return this object in our resolver because GraphQL is expecting an Array. If we do, the field will resolve to null and we'll see an error included in our response like:

Expected Iterable, but did not find one for field Query.posts.

Unlike the two scenarios above, in this case GraphQL is able to explicitly check the type of the value we return in our resolver and will throw if it's not an Iterable like an Array.

Like we discussed in the first scenario, in order to fix this error, we have to transform the response into the appropriate shape, for example:

function posts (root, args) {
  return fetch('http://SOME_URL/posts')
    .then(res => res.json())
    .then(data => data.results)
}

Not Using Promises Correctly

GraphQL.js makes use of the Promise API under the hood. As such, a resolver can return some value (like { id: 1, title: 'Hello!' }) or it can return a Promise that will resolve to that value. For fields that have a List type, you may also return an array of Promises. If a Promise rejects, that field will return null and the appropriate error will be added to the errors array in the response. If a field has an Object type, the value the Promise resolves to is what will be passed down as the parent value to the resolvers of any child fields.

A Promise is an "object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value." The next few scenarios outline some common pitfalls encountered when dealing with Promises inside resolvers. However, if you're not familiar with Promises and the newer async/await syntax, it's highly recommended you spend some time reading up on the fundamentals.

Note: the next few examples refer to a getPost function. The implementation details of this function are not important -- it's just a function that returns a Promise, which will resolve to a post object.

Common Scenario #4: Not Returning a Value

A working resolver for the post field might looks like this:

function post(root, args) {
  return getPost(args.id)
}

getPosts returns a Promise and we're returning that Promise. Whatever that Promise resolves to will become the value our field resolves to. Looking good!

But what happens if we do this:

function post(root, args) {
  getPost(args.id)
}

We're still creating a Promise that will resolve to a post. However, we're not returning the Promise, so GraphQL is not aware of it and it will not wait for it to resolve. In JavaScript functions without an explicit return statement implicitly return undefined. So our function creates a Promise and then immediately returns undefined, causing GraphQL to return null for the field.

If the Promise returned by getPost rejects, we won't see any error listed in our response either -- because we didn't return the Promise, the underlying code doesn't care about whether it resolves or rejects. In fact, if the Promise rejects, you'll see an
UnhandledPromiseRejectionWarning in your server console.

Fixing this issue is simple -- just add the return.

Common Scenario #5: Not chaining Promises correctly

You decide to log the result of your call to getPost, so you change your resolver to look something like this:

function post(root, args) {
  return getPost(args.id)
    .then(post => {
      console.log(post)
    })
}

When you run your query, you see the result logged in your console, but GraphQL resolves the field to null. Why?

When we call then on a Promise, we're effectively taking the value the Promise resolved to and returning a new Promise. You can think of it kind of like Array.map except for Promises. then can return a value, or another Promise. In either case, what's returned inside of then is "chained" onto the original Promise. Multiple Promises can be chained together like this by using multiple thens. Each Promise in the chain is resolved in sequence, and the final value is what's effectively resolved as the value of the original Promise.

In our example above, we returned nothing inside of the then, so the Promise resolved to undefined, which GraphQL converted to a null. To fix this, we have to return the posts:

function post(root, args) {
  return getPost(args.id)
    .then(post => {
      console.log(post)
      return post // <----
    })
}

If you have multiple Promises you need to resolve inside your resolver, you have to chain them correctly by using then and returning the correct value. For example, if we need to call two other asynchronous functions (getFoo and getBar) before we can call getPost, we can do:

function post(root, args) {
  return getFoo()
    .then(foo => {
      // Do something with foo
      return getBar() // return next Promise in the chain
    })
    .then(bar => {
      // Do something with bar
      return getPost(args.id) // return next Promise in the chain
    })

Pro tip: If you're struggling with correctly chaining Promises, you may find async/await syntax to be cleaner and easier to work with.

Common Scenario #6

Before Promises, the standard way to handle asynchronous code was to use callbacks, or functions that would be called once the asynchronous work was completed. We might, for example, call mongoose's findOne method like this:

function post(root, args) {
  return Post.findOne({ where: { id: args.id } }, function (err, post) {
    return post
  })

The problem here is two-fold. One, a value that's returned inside a callback isn't used for anything (i.e. it's not passed to the underlying code in any way). Two, when we use a callback, Post.findOne doesn't return a Promise; it just returns undefined. In this example, our callback will be called, and if we log the value of post we'll see whatever was returned from the database. However, because we didn't use a Promise, GraphQL doesn't wait for this callback to complete -- it takes the return value (undefined) and uses that.

Most more popular libraries, including mongoose support Promises out of the box. Those that don't frequently have complimentary "wrapper" libraries that add this functionality. When working with GraphQL resolvers, you should avoid using methods that utilize a callback, and instead use ones that return Promises.

Pro tip: Libraries that support both callbacks and Promises frequently overload their functions in such a way that if a callback is not provided, the function will return a Promise. Check the library's documentation for details.

If you absolutely have to use a callback, you can also wrap the callback in a Promise:

function post(root, args) {
  return new Promise((resolve, reject) => {
    Post.findOne({ where: { id: args.id } }, function (err, post) {
      if (err) {
        reject(err)
      } else {
        resolve(post)
      }
    })
  })


问:
Retrieve records based on Date
I have a date column in my table.
Is there any way in mysql to retrieve record based on date excluding the time part?

I have tried appending * but does not seems to work.

SELECT * FROM myTable where filterDate="2010-08-01 *"

Is there any way to do it like this rather then filtering it by using between?

Thanks.

答:
```<code>SELECT * FROM myTable where filterDate LIKE "%2010-08-01 %"
</code>```

ContentLicense: CC BY-SA 3.0

Title: Retrieve records based on Date


问:
Is it a good idea to add a WebService Request inside a Custom View?
So I have lets say I have a requirement where whenever the specific button is pressed, I should call a webservice to send some logs.

This button is present for multiple screens, so I though why not place it inside a CustomView View and call the webservice from there?

Then I'll just add this custom view to the xml layout and I don't have to worry about a thing anymore. Is it a good idea?

If it's not can someone suggest a better solution? Thanks.

答:
As for your existing architecture (MVP), it is better to put the logic in the Presenter, actually there should not be any logic on the View (in your case, custom view) aside from taking input (eg: click of a button), and providing output.

Assuming you set a click listener on your button (well of course):

```<code>button.setOnClickListener { yourPresenter.doSomeAction() }
</code>```

and in YourPresenter:

```<code>fun doSomeAction() {
   //do necessary action for the button
   //after that, send logs
}
</code>```

Following these pattern, you can easily make unit tests on your presenter like test if the logs is actually called, (you can also specify exact input).

Note: If you're using Clean Architecture, I recommend to put it on the domain layer (Interactor/UseCase) as Presentation Layer doesn't care what and when to log.

Body:
As for your existing architecture (MVP), it is better to put the logic in the Presenter, actually there should not be any logic on the View (in your case, custom view) aside from taking input (eg: click of a button), and providing output.

Assuming you set a click listener on your button (well of course):

button.setOnClickListener { yourPresenter.doSomeAction() }

and in YourPresenter:

fun doSomeAction() {
   //do necessary action for the button
   //after that, send logs
}

Following these pattern, you can easily make unit tests on your presenter like test if the logs is actually called, (you can also specify exact input).

Note: If you're using Clean Architecture, I recommend to put it on the domain layer (Interactor/UseCase) as Presentation Layer doesn't care what and when to log.


问:
print!() executes after the input is entered
i want to know why the print!() macro here executes after the read_line

```<code>// ./src/main.rs
use std::io;

fn main() {
    print!("Input : ");
    let stdin = io::stdin();
    let mut input = String::new();
    stdin.read_line(&mut input).expect("Couldn't read_line");
}
</code>```

This code prints out :

```<code>   heyy
   Input :
</code>```

But i expect :

```<code>Input : heyy
</code>```

答:
You can read the Rust documentation here: https://doc.rust-lang.org/std/macro.print.html

Specifically, this line:

"Note that stdout is frequently line-buffered by default so it may be necessary to use io::stdout().flush() to ensure the output is emitted immediately.

This is pretty common when working with the terminal in most languages. stdout is buffered on almost all terminals. You can turn it off on some AFAIK but you're better of just either calling flush as they suggest or I believe most terminals will flush their output if you write a new line to it.

Body:
i want to know why the print!() macro here executes after the read_line

// ./src/main.rs
use std::io;

fn main() {
    print!("Input : ");
    let stdin = io::stdin();
    let mut input = String::new();
    stdin.read_line(&mut input).expect("Couldn't read_line");
}

This code prints out :

   heyy
   Input :

But i expect :

Input : heyy


问:
Inferred generic function typechecks as a return type but not an argument type
I'm learning about SYB and rank n types, and came across a confusing case of what seems like the monomorphism restriction.

I wrote a function to find the shallowest entry that matches a predicate. Instead of a reducing function, I wanted to accept a more predicate-like function using Alternative, and transform it into a generic function myself. I decided to omit the type annotation in the let block to see how the monomorphism reduction would affect the type in this implementation:

```<code>shallowest :: (Alternative f, Typeable b) => (b -> f a) -> GenericQ (f a)
shallowest p z =
  let op = (empty `mkQ` p) in
    op z <|> foldl (<|>) empty (gmapQ op z)
</code>```

This produces an error that suggests that the ambiguity in the let binding prevents the typechecker from solving the constraint Data a1.

```<code>Error: • Couldn't match type ‘d’ with ‘a1’
  ‘d’ is a rigid type variable bound by
    a type expected by the context:
      forall d. Data d => d -> m a
  ‘a1’ is a rigid type variable bound by
    the type signature for:
      shallowest :: (b -> m a) -> GenericQ (m a)
</code>```

(Other bodies like head (gmapQ op z) cause an explicit error about ambiguity for the let binding along the lines of "Could not deduce (Typeable a0) arising from a use of ‘mkQ’"; I also haven't figured out why the above form doesn't).

The type error goes away when we add an annotation in the let block for op :: GenericQ (f a) (requiring ScopedTypeVariables).

However, I'm confused that it seems the Data constraint on op can be inferred: the follow typechecks when it's the return type:

```<code>shallowest p = let { op = (empty `mkQ` p) } in op
</code>```

What's the difference? Both cases require op to be forall d. Data d => d -> f a; the only difference I see is that the first is in an argument position and the second is in a return position.

答:
Preliminary notes: Given the evidence presented here, I will assume you are using:

type GenericQ r = forall a . Data a => a -> r from syb, and

gmapQ :: Data a => (forall d. Data d => d -> u) -> a -> [u] from Data.Data.

Please let me know me if I'm mistaken about that. Also, any foralls in what follows will be written explicitly.

There is more than meets the eye here. As Li-yao Xia suggests, it is a matter of generalisation involving the type of op. There are three relevant facts about your first definition of shallowest:

Before generalisation, the inferred type of op is Data d => d -> f a. Given the Data d constraint, Rule 1 of the monomorphism restriction (see subsection 4.5.5 of the Report) means d in this type cannot be generalised.

In the body of shallowest, op shows up in two places. The first one is op z, with z :: a1 being bound and constrained at top level by the signature of shallowest. The upshot is that this occurrence of op does not require generalisation of the argument type: as far as it is concerned, the type of op could be forall f a. a1 -> f a, monomorphic in the type variable a1 (I took this terminology from subsection 4.5.4 of the Report).

The other occurrence, though, is gmapQ op z. gmapQ has a rank-2 type, requiring a polymorphic argument. That being so, this occurrence requires generalisation of the argument type of op, as noted at the end of Li-yao Xia's answer.

#1 and #3 are contradictory requirements, and so you get a type error, which can be avoided either by disabling the monomorphism restriction or by demanding op to be polymorphic on the argument type with a signature. Thanks to the other occurrence of op described in #2, the situation is reported as a mismatch involving the two occurrences.

Here follows a more minimal extended example, which might help to see what is going on. (If you are going to plop the following snippets into GHCi, besides -XRankNTypes you should also set -XMonomorphismRestriction and -XNoExtendedDefaultRules in order to see the same results.)

This is a function with a rank-2 type, which will play the role of gmapQ:

```<code>glub :: (forall x. Show x => x -> String) -> String
glub f = f 7
</code>```

Now let's try a scenario similar to that involving shallowest...

```<code>foo1 :: forall a. Show a => a -> String
foo1 x = bar x ++ glub bar
  where
  bar = show
</code>```

... and there is your error:

```<code><interactive>:506:23: error:
    • Couldn't match type ‘x’ with ‘a’
      ‘x’ is a rigid type variable bound by
        a type expected by the context:
          forall x. Show x => x -> String
        at <interactive>:506:18-25
      ‘a’ is a rigid type variable bound by
        the type signature for:
          foo1 :: forall a. Show a => a -> String
        at <interactive>:505:1-38
      Expected type: x -> String
        Actual type: a -> String
    • In the first argument of ‘glub’, namely ‘bar’
      In the second argument of ‘(++)’, namely ‘glub bar’
      In the expression: bar x ++ glub bar
    • Relevant bindings include
        bar :: a -> String (bound at <interactive>:508:3)
        x :: a (bound at <interactive>:506:5)
        foo1 :: a -> String (bound at <interactive>:506:1)
</code>```

Adding a wildcard where the signature of bar should go gives an additional error which is slightly more suggestive:

```<code>foo2 :: forall a. Show a => a -> String
foo2 x = bar x ++ glub bar
  where
  bar :: _
  bar = show
</code>```

```<code>• Found type wildcard ‘_’ standing for ‘a -> String’
  Where: ‘a’ is a rigid type variable bound by
           the type signature for:
             foo2 :: forall a. Show a => a -> String
           at <interactive>:511:1-38
  To use the inferred type, enable PartialTypeSignatures
• In the type signature: bar :: _
  In an equation for ‘foo2’:
      foo2 x
        = bar x ++ glub bar
        where
            bar :: _
            bar = show
• Relevant bindings include
    x :: a (bound at <interactive>:512:5)
    foo2 :: a -> String (bound at <interactive>:512:1)
</code>```

Note how the wildcard "standing for a -> String" is stated as a separate fact from a being bound by the type signature of foo2. I believe that corresponds to the distinction bewteen monomorphic in a type variable and polymorphic that I alluded to in point #2 above.

Giving bar a polymorphic type signature makes it work:

```<code>foo3 :: forall a. Show a => a -> String
foo3 x = bar x ++ glub bar
  where
  bar :: forall b. Show b => b -> String
  bar = show
</code>```

And so does making the definition of bar pointful, which evades the monomorphism restriction by making it a "function binding" rather than a "simple pattern binding":

```<code>foo4 :: forall a. Show a => a -> String
foo4 x = bar x ++ glub bar
  where
  bar x = show x
</code>```

For the sake of completeness, it is worth noting that no constraint on the type means no monomorphism restriction:

```<code>foo5 :: forall a. Show a => a -> String
foo5 x = bar x ++ glub bar
  where
  bar = const "bar"
</code>```

A related situation involves using bar twice, but without a rank-2 function:

```<code>foo6 x y = bar x ++ bar y
  where
  bar = show
</code>```

Which type will GHC infer for foo6?

```<code>GHCi> :t foo6
foo6 :: Show a => a -> a -> [Char]
</code>```

The arguments get the same type, as doing otherwise would require generalisation of bar, which requires a type signature (or pointfullness, etc.):

```<code>foo1 :: forall a. Show a => a -> String
foo1 x = bar x ++ glub bar
  where
  bar = show
</code>```0

```<code>foo1 :: forall a. Show a => a -> String
foo1 x = bar x ++ glub bar
  where
  bar = show
</code>```1

Since I didn't mention it yet, here is an analogue to your second shallowest:

```<code>foo1 :: forall a. Show a => a -> String
foo1 x = bar x ++ glub bar
  where
  bar = show
</code>```2

It is worth emphasising that bar is not actually being generalised here: it is monomorphic in the type variable a. We can still break this example, by messing with foo7 rather than with bar:

```<code>foo9 = bar
  where
  bar :: _
  bar = show
</code>```

In this case, bar is not generalised, and neither is foo (now pointfree and without a signature). That means the monomorphic type variable is never resolved. In terms of Rule 2 of the monomorphism restriction, it becomes an ambiguous type variable:

```<code>    <interactive>:718:14: error:
        • Found type wildcard ‘_’ standing for ‘a0 -> String’
          Where: ‘a0’ is an ambiguous type variable
          To use the inferred type, enable PartialTypeSignatures
        • In the type signature: bar :: _
          In an equation for ‘foo9’:
              foo9
                = bar
                where
                    bar :: _
                    bar = show
        • Relevant bindings include
            foo9 :: a0 -> String (bound at <interactive>:716:5)

<interactive>:719:13: error:
    • Ambiguous type variable ‘a0’ arising from a use of ‘show’
      prevents the constraint ‘(Show a0)’ from being solved.
      Relevant bindings include
        bar :: a0 -> String (bound at <interactive>:719:7)
        foo9 :: a0 -> String (bound at <interactive>:716:5)
      Probable fix: use a type annotation to specify what ‘a0’ should be.
      These potential instances exist:
        instance Show a => Show (ZipList a)
          -- Defined in ‘Control.Applicative’
        instance Show Constr -- Defined in ‘Data.Data’
        instance Show ConstrRep -- Defined in ‘Data.Data’
        ...plus 64 others
        ...plus 250 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In the expression: show
      In an equation for ‘bar’: bar = show
      In an equation for ‘foo9’:
          foo9
            = bar
            where
                bar :: _
                bar = show
</code>```

Adding a type signature to bar in the definition of foo9 won't help -- it just changes the point from which the error is reported. Changing bar to something without a constraint does eliminate the error, as it makes it possible to generalise both bar and foo.

Body:
I'm learning about SYB and rank n types, and came across a confusing case of what seems like the monomorphism restriction.

I wrote a function to find the shallowest entry that matches a predicate. Instead of a reducing function, I wanted to accept a more predicate-like function using Alternative, and transform it into a generic function myself. I decided to omit the type annotation in the let block to see how the monomorphism reduction would affect the type in this implementation:

shallowest :: (Alternative f, Typeable b) => (b -> f a) -> GenericQ (f a)
shallowest p z =
  let op = (empty `mkQ` p) in
    op z <|> foldl (<|>) empty (gmapQ op z)

This produces an error that suggests that the ambiguity in the let binding prevents the typechecker from solving the constraint Data a1.

Error: • Couldn't match type ‘d’ with ‘a1’
  ‘d’ is a rigid type variable bound by
    a type expected by the context:
      forall d. Data d => d -> m a
  ‘a1’ is a rigid type variable bound by
    the type signature for:
      shallowest :: (b -> m a) -> GenericQ (m a)

(Other bodies like head (gmapQ op z) cause an explicit error about ambiguity for the let binding along the lines of "Could not deduce (Typeable a0) arising from a use of ‘mkQ’"; I also haven't figured out why the above form doesn't).

The type error goes away when we add an annotation in the let block for op :: GenericQ (f a) (requiring ScopedTypeVariables).

However, I'm confused that it seems the Data constraint on op can be inferred: the follow typechecks when it's the return type:

shallowest p = let { op = (empty `mkQ` p) } in op

What's the difference? Both cases require op to be forall d. Data d => d -> f a; the only difference I see is that the first is in an argument position and the second is in a return position.

Body:
Preliminary notes: Given the evidence presented here, I will assume you are using:

type GenericQ r = forall a . Data a => a -> r from syb, and

gmapQ :: Data a => (forall d. Data d => d -> u) -> a -> [u] from Data.Data.

Please let me know me if I'm mistaken about that. Also, any foralls in what follows will be written explicitly.

There is more than meets the eye here. As Li-yao Xia suggests, it is a matter of generalisation involving the type of op. There are three relevant facts about your first definition of shallowest:

Before generalisation, the inferred type of op is Data d => d -> f a. Given the Data d constraint, Rule 1 of the monomorphism restriction (see subsection 4.5.5 of the Report) means d in this type cannot be generalised.

In the body of shallowest, op shows up in two places. The first one is op z, with z :: a1 being bound and constrained at top level by the signature of shallowest. The upshot is that this occurrence of op does not require generalisation of the argument type: as far as it is concerned, the type of op could be forall f a. a1 -> f a, monomorphic in the type variable a1 (I took this terminology from subsection 4.5.4 of the Report).

The other occurrence, though, is gmapQ op z. gmapQ has a rank-2 type, requiring a polymorphic argument. That being so, this occurrence requires generalisation of the argument type of op, as noted at the end of Li-yao Xia's answer.

#1 and #3 are contradictory requirements, and so you get a type error, which can be avoided either by disabling the monomorphism restriction or by demanding op to be polymorphic on the argument type with a signature. Thanks to the other occurrence of op described in #2, the situation is reported as a mismatch involving the two occurrences.

Here follows a more minimal extended example, which might help to see what is going on. (If you are going to plop the following snippets into GHCi, besides -XRankNTypes you should also set -XMonomorphismRestriction and -XNoExtendedDefaultRules in order to see the same results.)

This is a function with a rank-2 type, which will play the role of gmapQ:

glub :: (forall x. Show x => x -> String) -> String
glub f = f 7

Now let's try a scenario similar to that involving shallowest...

foo1 :: forall a. Show a => a -> String
foo1 x = bar x ++ glub bar
  where
  bar = show

... and there is your error:

<interactive>:506:23: error:
    • Couldn't match type ‘x’ with ‘a’
      ‘x’ is a rigid type variable bound by
        a type expected by the context:
          forall x. Show x => x -> String
        at <interactive>:506:18-25
      ‘a’ is a rigid type variable bound by
        the type signature for:
          foo1 :: forall a. Show a => a -> String
        at <interactive>:505:1-38
      Expected type: x -> String
        Actual type: a -> String
    • In the first argument of ‘glub’, namely ‘bar’
      In the second argument of ‘(++)’, namely ‘glub bar’
      In the expression: bar x ++ glub bar
    • Relevant bindings include
        bar :: a -> String (bound at <interactive>:508:3)
        x :: a (bound at <interactive>:506:5)
        foo1 :: a -> String (bound at <interactive>:506:1)

Adding a wildcard where the signature of bar should go gives an additional error which is slightly more suggestive:

foo2 :: forall a. Show a => a -> String
foo2 x = bar x ++ glub bar
  where
  bar :: _
  bar = show

• Found type wildcard ‘_’ standing for ‘a -> String’
  Where: ‘a’ is a rigid type variable bound by
           the type signature for:
             foo2 :: forall a. Show a => a -> String
           at <interactive>:511:1-38
  To use the inferred type, enable PartialTypeSignatures
• In the type signature: bar :: _
  In an equation for ‘foo2’:
      foo2 x
        = bar x ++ glub bar
        where
            bar :: _
            bar = show
• Relevant bindings include
    x :: a (bound at <interactive>:512:5)
    foo2 :: a -> String (bound at <interactive>:512:1)

Note how the wildcard "standing for a -> String" is stated as a separate fact from a being bound by the type signature of foo2. I believe that corresponds to the distinction bewteen monomorphic in a type variable and polymorphic that I alluded to in point #2 above.

Giving bar a polymorphic type signature makes it work:

foo3 :: forall a. Show a => a -> String
foo3 x = bar x ++ glub bar
  where
  bar :: forall b. Show b => b -> String
  bar = show

And so does making the definition of bar pointful, which evades the monomorphism restriction by making it a "function binding" rather than a "simple pattern binding":

foo4 :: forall a. Show a => a -> String
foo4 x = bar x ++ glub bar
  where
  bar x = show x

For the sake of completeness, it is worth noting that no constraint on the type means no monomorphism restriction:

foo5 :: forall a. Show a => a -> String
foo5 x = bar x ++ glub bar
  where
  bar = const "bar"

A related situation involves using bar twice, but without a rank-2 function:

foo6 x y = bar x ++ bar y
  where
  bar = show

Which type will GHC infer for foo6?

GHCi> :t foo6
foo6 :: Show a => a -> a -> [Char]

The arguments get the same type, as doing otherwise would require generalisation of bar, which requires a type signature (or pointfullness, etc.):

foo7 x y = bar x ++ bar y
  where
  bar :: forall a. Show a => a -> String
  bar = show

GHCi> :t foo7
foo7 :: (Show a1, Show a2) => a1 -> a2 -> [Char]

Since I didn't mention it yet, here is an analogue to your second shallowest:

foo8 :: forall a. Show a => a -> String
foo8 x = bar x
  where
  bar = show

It is worth emphasising that bar is not actually being generalised here: it is monomorphic in the type variable a. We can still break this example, by messing with foo7 rather than with bar:

foo9 = bar
  where
  bar :: _
  bar = show

In this case, bar is not generalised, and neither is foo (now pointfree and without a signature). That means the monomorphic type variable is never resolved. In terms of Rule 2 of the monomorphism restriction, it becomes an ambiguous type variable:

    <interactive>:718:14: error:
        • Found type wildcard ‘_’ standing for ‘a0 -> String’
          Where: ‘a0’ is an ambiguous type variable
          To use the inferred type, enable PartialTypeSignatures
        • In the type signature: bar :: _
          In an equation for ‘foo9’:
              foo9
                = bar
                where
                    bar :: _
                    bar = show
        • Relevant bindings include
            foo9 :: a0 -> String (bound at <interactive>:716:5)

<interactive>:719:13: error:
    • Ambiguous type variable ‘a0’ arising from a use of ‘show’
      prevents the constraint ‘(Show a0)’ from being solved.
      Relevant bindings include
        bar :: a0 -> String (bound at <interactive>:719:7)
        foo9 :: a0 -> String (bound at <interactive>:716:5)
      Probable fix: use a type annotation to specify what ‘a0’ should be.
      These potential instances exist:
        instance Show a => Show (ZipList a)
          -- Defined in ‘Control.Applicative’
        instance Show Constr -- Defined in ‘Data.Data’
        instance Show ConstrRep -- Defined in ‘Data.Data’
        ...plus 64 others
        ...plus 250 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In the expression: show
      In an equation for ‘bar’: bar = show
      In an equation for ‘foo9’:
          foo9
            = bar
            where
                bar :: _
                bar = show

Adding a type signature to bar in the definition of foo9 won't help -- it just changes the point from which the error is reported. Changing bar to something without a constraint does eliminate the error, as it makes it possible to generalise both bar and foo.


问:
MS Detours - DetourAttach fails
Feeling stupid here but why is this code giving me a syntax error in Visual
Studio when trying to compile it?

```<code>    DetourAttach(&(PVOID&)true_create_file, create_file);
</code>```

The compiler complains with (underlining the & after PVOID)

Error (active)    E0018   expected a ')'

The code is literally copied from the Detours example page. I'm assuming it is because my containing file has a .c extension and is thus compiled as C by VS while the example has a .cpp extension and is compiled as C++.

I'm not entirely sure what's going on in this line with all the casting. Why doesn't the C compiler like it and how do I get it to compile this line?

Here's the complete listing of the code:

```<code>#include <Windows.h>
#include "detours.h"
#pragma comment(lib, "detours.lib")

static HANDLE(WINAPI *true_create_file) (LPCSTR file, DWORD access,
    DWORD share, LPSECURITY_ATTRIBUTES sec, DWORD disp, DWORD flags,
    HANDLE tmpl) = CreateFileA;

HANDLE WINAPI create_file(LPCSTR file, DWORD access, DWORD share,
    LPSECURITY_ATTRIBUTES sec, DWORD disp, DWORD flags, HANDLE tmpl) {
}

int hook_create_file() {
    DetourTransactionBegin();
    DetourUpdateThread(GetCurrentThread());
    /* syntax error */
    DetourAttach(&(PVOID&)true_create_file, create_file);
    DetourTransactionCommit();
}
</code>```

PVOID is defined as

typedef void *PVOID;

答:
The &(PVOID&) part: cast the parameter to a reference to a pointer to void first, and then taking the address of that. As comment point out, you compile it as C, but the reference operation do not exist in C. So the compiler recognizes "&" as taking address, but only ")" behind it, then get the expected a ')' error.

Since PVOID& doesn't make sense here, just to increase readability. You could use PVOIDinstead of PVOID& here:

```<code>DetourAttach(&(PVOID)true_create_file, create_file);
</code>```

You could also get the DetourAttach function details from here.

Title: MS Detours - DetourAttach fails

Body:
Feeling stupid here but why is this code giving me a syntax error in Visual
Studio when trying to compile it?

    DetourAttach(&(PVOID&)true_create_file, create_file);

The compiler complains with (underlining the & after PVOID)

Error (active)    E0018   expected a ')'

The code is literally copied from the Detours example page. I'm assuming it is because my containing file has a .c extension and is thus compiled as C by VS while the example has a .cpp extension and is compiled as C++.

I'm not entirely sure what's going on in this line with all the casting. Why doesn't the C compiler like it and how do I get it to compile this line?

Here's the complete listing of the code:

#include <Windows.h>
#include "detours.h"
#pragma comment(lib, "detours.lib")

static HANDLE(WINAPI *true_create_file) (LPCSTR file, DWORD access,
    DWORD share, LPSECURITY_ATTRIBUTES sec, DWORD disp, DWORD flags,
    HANDLE tmpl) = CreateFileA;

HANDLE WINAPI create_file(LPCSTR file, DWORD access, DWORD share,
    LPSECURITY_ATTRIBUTES sec, DWORD disp, DWORD flags, HANDLE tmpl) {
}

int hook_create_file() {
    DetourTransactionBegin();
    DetourUpdateThread(GetCurrentThread());
    /* syntax error */
    DetourAttach(&(PVOID&)true_create_file, create_file);
    DetourTransactionCommit();
}

PVOID is defined as

typedef void *PVOID;

Body:
The &(PVOID&) part: cast the parameter to a reference to a pointer to void first, and then taking the address of that. As comment point out, you compile it as C, but the reference operation do not exist in C. So the compiler recognizes "&" as taking address, but only ")" behind it, then get the expected a ')' error.

Since PVOID& doesn't make sense here, just to increase readability. You could use PVOIDinstead of PVOID& here:

DetourAttach(&(PVOID)true_create_file, create_file);

You could also get the DetourAttach function details from here.


问:
Style error when using Material ExposedDropdownMenu
When I try to use

```<code>@style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu
</code>```

Android Studio asks me to create a style

```<code><android.support.design.widget.TextInputLayout
        style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Type frais"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginLeft="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginEnd="8dp"
        >

    <AutoCompleteTextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />
</android.support.design.widget.TextInputLayout>
</code>```

I expect to see a ExposedDropdownMenu style in the TextInputLayout, but actually Android Studio asks me to create this style

答:
The Exposed Dropdown Menu material component has been introduced in the release version:

1.1.0-alpha06

Dark Theme, exposed dropdown menu, badges, and more!

Source: https://github.com/material-components/material-components-android/releases/tag/1.1.0-alpha06

Body:
When I try to use

@style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu

Android Studio asks me to create a style

<android.support.design.widget.TextInputLayout
        style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Type frais"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginLeft="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginEnd="8dp"
        >

    <AutoCompleteTextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />
</android.support.design.widget.TextInputLayout>

I expect to see a ExposedDropdownMenu style in the TextInputLayout, but actually Android Studio asks me to create this style


问:
TensorFlow: Why should my image tensor shape equal my label tensor shape?
I wish to do semantic segmentation using TensorFlow 1.12. I create a dataset using from_generator(), where my generator is as follows:

```<code>def train_sample_fetcher():
    return sample_fetcher()

def val_sample_fetcher():
    return sample_fetcher(is_validations=True)

def sample_fetcher(is_validations=False):
    sample_names = [filename[:-4] for filename in os.listdir(DIR_DATASET + "ndarrays/")]
    if not is_validations: sample_names = sample_names[:int(len(sample_names) * TRAIN_VAL_SPLIT)]
    else: sample_names = sample_names[int(len(sample_names) * TRAIN_VAL_SPLIT):]
    for sample_name in sample_names:
        rgb = tf.image.decode_jpeg(tf.read_file(DIR_DATASET + sample_name + ".jpg"))
        rgb = tf.image.resize_images(rgb, (HEIGHT, WIDTH))
        #d = tf.image.decode_jpeg(tf.read_file(DIR_DATASET + "depth/" + sample_name + ".jpg"))
        #d = tf.image.resize_images(d, (HEIGHT, WIDTH))
        #rgbd = tf.concat([rgb,d], axis=2)
        onehots = tf.convert_to_tensor(np.load(DIR_DATASET + "ndarrays/" + sample_name + ".npy"), dtype=tf.float32)
        yield tf.stack([rgb, onehots])
</code>```

In other words, I have a label tensor containing a one-hot label vector of length 21 (21 classes) for every pixel. However, this is not permitted according to this stack trace:

```<code>Traceback (most recent call last):
  File "semantic_fpn.py", line 89, in <module>
    callbacks=[checkpoint_full, checkpoint_weights, tensorboard])
  File ".../site-packages/tensorflow/python/keras/engine/training.py", line 1574, in fit
    steps=validation_steps)
  File ".../site-packages/tensorflow/python/keras/engine/training.py", line 975, in _standardize_user_data
    next_element = x.get_next()
  File ".../site-packages/tensorflow/python/data/ops/iterator_ops.py", line 623, in get_next
    return self._next_internal()
  File ".../site-packages/tensorflow/python/data/ops/iterator_ops.py", line 564, in _next_internal
    output_shapes=self._flat_output_shapes)
  File ".../site-packages/tensorflow/python/ops/gen_dataset_ops.py", line 2266, in iterator_get_next_sync
    _six.raise_from(_core._status_to_exception(e.code, message), None)
  File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.UnknownError: InvalidArgumentError: Shapes of all inputs must match: values[0].shape = [512,512,3] != values[1].shape = [512,512,21] [Op:Pack] name: stack
</code>```

Why is this not allowed? How can I circumvent this?

答:
tf.stack operation tries to merge N rank K tensors into one rank (K+1) tensors. In other words, it tries to join a sequence of tensors along new axis and therefore, other axis of tensors should be the same.

Can simply return a pair yield rgb, onehots out of your generator.

Body:
I wish to do semantic segmentation using TensorFlow 1.12. I create a dataset using from_generator(), where my generator is as follows:

def train_sample_fetcher():
    return sample_fetcher()

def val_sample_fetcher():
    return sample_fetcher(is_validations=True)

def sample_fetcher(is_validations=False):
    sample_names = [filename[:-4] for filename in os.listdir(DIR_DATASET + "ndarrays/")]
    if not is_validations: sample_names = sample_names[:int(len(sample_names) * TRAIN_VAL_SPLIT)]
    else: sample_names = sample_names[int(len(sample_names) * TRAIN_VAL_SPLIT):]
    for sample_name in sample_names:
        rgb = tf.image.decode_jpeg(tf.read_file(DIR_DATASET + sample_name + ".jpg"))
        rgb = tf.image.resize_images(rgb, (HEIGHT, WIDTH))
        #d = tf.image.decode_jpeg(tf.read_file(DIR_DATASET + "depth/" + sample_name + ".jpg"))
        #d = tf.image.resize_images(d, (HEIGHT, WIDTH))
        #rgbd = tf.concat([rgb,d], axis=2)
        onehots = tf.convert_to_tensor(np.load(DIR_DATASET + "ndarrays/" + sample_name + ".npy"), dtype=tf.float32)
        yield tf.stack([rgb, onehots])

In other words, I have a label tensor containing a one-hot label vector of length 21 (21 classes) for every pixel. However, this is not permitted according to this stack trace:

Traceback (most recent call last):
  File "semantic_fpn.py", line 89, in <module>
    callbacks=[checkpoint_full, checkpoint_weights, tensorboard])
  File ".../site-packages/tensorflow/python/keras/engine/training.py", line 1574, in fit
    steps=validation_steps)
  File ".../site-packages/tensorflow/python/keras/engine/training.py", line 975, in _standardize_user_data
    next_element = x.get_next()
  File ".../site-packages/tensorflow/python/data/ops/iterator_ops.py", line 623, in get_next
    return self._next_internal()
  File ".../site-packages/tensorflow/python/data/ops/iterator_ops.py", line 564, in _next_internal
    output_shapes=self._flat_output_shapes)
  File ".../site-packages/tensorflow/python/ops/gen_dataset_ops.py", line 2266, in iterator_get_next_sync
    _six.raise_from(_core._status_to_exception(e.code, message), None)
  File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.UnknownError: InvalidArgumentError: Shapes of all inputs must match: values[0].shape = [512,512,3] != values[1].shape = [512,512,21] [Op:Pack] name: stack

Why is this not allowed? How can I circumvent this?


问:
Curl will not write errors out to a file
I am looking to build an application that will tell the user if the port/address is open. I am unable to write failures to the file though.

I have tried using Curl to do this.

```<code>curl google.com:8099 --fail --show-error >”C:\Users\Ryan Lambert\Desktop\Curl.txt” && echo Success. || echo Fail.
</code>```

Need to have errors come through in the file but file is empty. Running this in command line.

答:
You want stderror, not stdout

For example:

curl sosdlfjsdlfkj 2> log.something.error

This would write the errors to the error log.

Body:
I am looking to build an application that will tell the user if the port/address is open. I am unable to write failures to the file though.

I have tried using Curl to do this.

curl google.com:8099 --fail --show-error >”C:\Users\Ryan Lambert\Desktop\Curl.txt” && echo Success. || echo Fail.

Need to have errors come through in the file but file is empty. Running this in command line.


问:
How to connect to localhost and external database from docker container
I have two docker containers, nginx and php, from which I want to access mysql server running on host machine and sql server on remote machine.

Have tried change the network type from "bridge" to "host" but it returns errors.

```<code>version: '2'

services:
    web:
        image: nginx:latest
        ports:
            - "8080:80"
        volumes:
            - /var/www/:/code
            - ./site.conf:/etc/nginx/conf.d/default.conf
        networks:
            - mynetwork
    php:
        image: php:fpm
        volumes:
            - /var/www/:/code
        networks:
           - mynetwork
networks:
    mynetwork:
       driver: bridge
</code>```

I'm expecting php code running in my containers can connect to those two databases.

Note: I don't using docker run to run container, instead I'm using docker-compose up -d so I just want to edit the docker-compose.yml file.

答:
Just make sure the container can access the external database by going online.Bridge" and "host network type can do.
First, you need to make sure you have a correct mysql grant rule, such as %.
1\You can use the ip of the host to access the mysql on the host from the inside of the container.
2\Other mysql instances that belong to the same LAN as the host, access from the container can also be accessed using the LAN ip on the mysql instance.
Ensure the ping is normal,Make sure the ping is working, otherwise your docker installation may have problems, such as problems from iptables.</p>

Body:
I have two docker containers, nginx and php, from which I want to access mysql server running on host machine and sql server on remote machine.

Have tried change the network type from "bridge" to "host" but it returns errors.

version: '2'

services:
    web:
        image: nginx:latest
        ports:
            - "8080:80"
        volumes:
            - /var/www/:/code
            - ./site.conf:/etc/nginx/conf.d/default.conf
        networks:
            - mynetwork
    php:
        image: php:fpm
        volumes:
            - /var/www/:/code
        networks:
           - mynetwork
networks:
    mynetwork:
       driver: bridge

I'm expecting php code running in my containers can connect to those two databases.

Note: I don't using docker run to run container, instead I'm using docker-compose up -d so I just want to edit the docker-compose.yml file.


问:
NodeJS SRCDS View log of grandchild process
I am writing an app to handle my server and be able to log all the output to a file. I am just at the stage where I am seeing all of the output first, but it looks like I am not getting output from the child process that my first child process creates. Here is my code:

run.js

```<code>const {spawn} = require('child_process')

const server = spawn('bash', ['srcds_run'])

console.log('spawned ' + server.pid)

server.stdout.on('data', data => {
    process.stdout.write(data)
})

server.stderr.on('data', data => {
    process.stdout.write(data)
})

server.stdin.on('data', data => {
    process.stdout.write(data)
})
</code>```

In the console, it prints everything until the srcds_run script passes it on to srcds_linux which is the main server process. Once it passes it on, there is no longer any output, but the process is started and the server is up.

Here is an example of how the process tree looks.

https://i.linkjay.io/JBipdX.png

And how it runs in node

https://i.linkjay.io/YzmhIL.png

It will print anything from srcds_run, but not srcds_linux.

Logaddress is not an option here either.

Any help would be appreciated. Thanks.

答:
Found out the solution!

srcds_run is a bash script that eventually starts the binary srcds_linux.

I found out that I could use node-pty to start srcds_run which would start srcds_linux in that pty. From there, I would have access to the bash process as if it were a child_process. You can manage stdio, and manage the process itself.

Code example:

```<code>const pty = require('node-pty')
const path = require('path')

const folder = '/home/local/folders/servers/gmod'
const binary = 'srcds_run'

const args = ['-gamemode sandbox', '+map gm_flatgrass']

const proc = pty.spawn('bash', [path.join(folder, binary)].concat(args), {
    cwd: folder
})

proc.on('data', (data) => {
    console.log('out: ' + data)
})
</code>```

Hope this helps anyone in the future!

Body:
I am writing an app to handle my server and be able to log all the output to a file. I am just at the stage where I am seeing all of the output first, but it looks like I am not getting output from the child process that my first child process creates. Here is my code:

run.js

const {spawn} = require('child_process')

const server = spawn('bash', ['srcds_run'])

console.log('spawned ' + server.pid)

server.stdout.on('data', data => {
    process.stdout.write(data)
})

server.stderr.on('data', data => {
    process.stdout.write(data)
})

server.stdin.on('data', data => {
    process.stdout.write(data)
})

In the console, it prints everything until the srcds_run script passes it on to srcds_linux which is the main server process. Once it passes it on, there is no longer any output, but the process is started and the server is up.

Here is an example of how the process tree looks.

https://i.linkjay.io/JBipdX.png

And how it runs in node

https://i.linkjay.io/YzmhIL.png

It will print anything from srcds_run, but not srcds_linux.

Logaddress is not an option here either.

Any help would be appreciated. Thanks.

Body:
Found out the solution!

srcds_run is a bash script that eventually starts the binary srcds_linux.

I found out that I could use node-pty to start srcds_run which would start srcds_linux in that pty. From there, I would have access to the bash process as if it were a child_process. You can manage stdio, and manage the process itself.

Code example:

const pty = require('node-pty')
const path = require('path')

const folder = '/home/local/folders/servers/gmod'
const binary = 'srcds_run'

const args = ['-gamemode sandbox', '+map gm_flatgrass']

const proc = pty.spawn('bash', [path.join(folder, binary)].concat(args), {
    cwd: folder
})

proc.on('data', (data) => {
    console.log('out: ' + data)
})

Hope this helps anyone in the future!


问:
Specific Order Sorting within a List
I'm trying to sort items within a list in a specific order, most mainly card value order such as 2 being the lowest and A being the highest.

Thanks

答:
Use sorted function with a custom key function:-

```<code>sorted(string_name, key=order)
</code>```

A custom key function is supplied to customize the sort order of the function. i.e. now characters will be sorted in
23456789JQKA this order.

EXAMPLE

```<code>order = "23456789JQKA"
print(*sorted("KA2J32535", key=order.index),sep='')
</code>```

OUTPUT

```<code>223355JKA
</code>```

P.S.:- I have converted the result into a string, if you don't want such you can remove the *  and sep='' from the print()

Title: Specific Order Sorting within a List

Body:
Use sorted function with a custom key function:-

sorted(string_name, key=order)

A custom key function is supplied to customize the sort order of the function. i.e. now characters will be sorted in
23456789JQKA this order.

EXAMPLE

order = "23456789JQKA"
print(*sorted("KA2J32535", key=order.index),sep='')

OUTPUT

223355JKA

P.S.:- I have converted the result into a string, if you don't want such you can remove the *  and sep='' from the print()


问:
Deleting Apollo Client cache for a given query and every set of variables
I have a filtered list of items based on a getAllItems query, which takes a filter and an order by option as arguments.

After creating a new item, I want to delete the cache for this query, no matter what variables were passed. I don't know how to do this.

I don't think updating the cache is an option. Methods mentionned in Apollo Client documentation (Updating the cache after a mutation, refetchQueries and update) all seem to need a given set of variables, but since the filter is a complex object (with some text information), I would need to update the cache for every given set of variables that were previously submitted. I don't know how to do this. Plus, only the server does know how this new item impact pagination and ordering.

I don't think fetch-policy (for instance setting it to cache-and-network) is what I'm looking for, because if accessing the network is what I want after having created a new item, when I'm just filtering the list (typing in a string to search), I want to stay with the default behavior (cache-only).

client.resetStore would reset the store for all type of queries (not only the getAllItems query), so I don't think it's what I'm looking for either.

I'm pretty sure I'm missing something here.

答:
ngrx like</p>

```<code>resolvers = {
    removeTask(
       parent,
       { id },
       { cache, getCacheKey }: { cache: InMemoryCache | any; getCacheKey: any }
     ) {
       const key = getCacheKey({ __typename: "Task", id });
       const { [key]: deleted, ...data } = cache.data.data;
       cache.data.data = { ...data };
       return id;
     }
}
</code>```

Body:
ngrx like

resolvers = {
    removeTask(
       parent,
       { id },
       { cache, getCacheKey }: { cache: InMemoryCache | any; getCacheKey: any }
     ) {
       const key = getCacheKey({ __typename: "Task", id });
       const { [key]: deleted, ...data } = cache.data.data;
       cache.data.data = { ...data };
       return id;
     }
}


问:
How to change ckeditor toolbar background color (to black) and button/icon foreground color (to white)?
How can the background of CKEditor be changed to black, and the icons be changed to white -- for a dark website?

Using CKEditor 4 (4.11.4, source code version).

The background of the editor can be changed to black, but the buttons/icons become very dim and barely visible.

In [ckeditor_directory_path]/skins/moono-lisa/skin.js:
baseColor = colorBrightness( uiColor, -1 ),

In [ckeditor_directory_path]/skins/moono-lisa/config.js:
config.uiColor = '#000000';

This changes the editor background to black, but also results in dim buttons/icons. The icons need to be a brighter colour in order to be visible.

How can the icons be made white (#FFFFFF)?

There is a similar question, but the answer was not helpful. How to change ckeditor icons color

Hopefully in this case (using the "moono-lisa" skin), it is possible to change the background and button/icon colours using only CSS/Javascript/etc. and not create an entire set of graphical icons. The moono-lisa skin does not have an 'icons' directory (as other instructions regarding CKEditor version 3 have suggested): https://ckeditor.com/old/forums/CKEditor-3.x/How-change-toolbar-icon

So I don't know what the next step should be. Thanks in advance for your help.

(Update: edited to remove "tinyMCE" tags. I was going to warn other users not to use tinyMCE -- its "multiple editors per page" functionality is a nightmare to set up and the official documentation for tinyMCE 4 is cheerfully wrong. Numerous Stack Overflow topics only add to the confusion with no apparent correct answer. After days of wasted effort to work around several other tinyMCE issues, there seems to be no solution, hence I finally switched to CKEditor. But the deficiencies of tinyMCE are a separate issue. Hopefully CKEditor is a better option, although the documentation for basic features like background/icon colors, etc., aren't much of an improvement over tinyMCE -- which leads me here to ask this question...)

答:
I've found two answers:

Moono Dark

Moono Dark Biskrem

Hope this helps someone looking for alternatives. If you have further thoughts about the question itself, that's also great, too; please add a comment. :)


问:
Assign role to user
I have a problem with assign role to user. I'm using .net Core 2.1

I changed the registration method. During registration, I assign the role of "Admin" to the user being created.

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {

                var db = new ApplicationDbContext(_optionsBuilder.Options);
                var email = db.Users.Where(s => s.Email == Input.Email);
                if (email.Count() != 0)
                {
                    ViewData["duplicateEmail"] = "Email is already taken";
                    return Page();
                }

                var user = new IdentityUser { UserName = Input.UserName, Email = Input.Email };
                var result = await _userManager.CreateAsync(user, Input.Password);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                        $"Please confirm your account by clicking here.");
                    //#############

                    if(!await _roleManager.RoleExistsAsync("Admin"))
                    {
                       await _userManager.AddToRoleAsync(user, "Admin");
                    }

                    //################
                    await _signInManager.SignInAsync(user, isPersistent: false);
                    return LocalRedirect(returnUrl);
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }
    }
```

<p>I added only code between hashtags.</p>

<p>After starting the application, when i click registration, i see</p>

<p><img src="https://i.ibb.co/BLbj37V/Przechwytywanie.jpg" alt="Issue"></p>

<p>I tried to add</p>

<pre class="lang-cs prettyprint-override"><code>services.AddIdentity<IdentityUser,IdentityRole>()
        .AddDefaultUI()
        .AddEntityFrameworkStores<ApplicationDbContext>();
</code>```

to
startup

but it does not work.

How i'm doinw wrong?

答:
You need to inject RoleManager<IdentityRole> in RegisterModel like:

```<code> public class RegisterModel : PageModel
{
    private readonly RoleManager<IdentityRole> _roleManager;
    private readonly SignInManager<IdentityUser> _signInManager;
    private readonly UserManager<IdentityUser> _userManager;
    private readonly ILogger<RegisterModel> _logger;
    private readonly IEmailSender _emailSender;

    public RegisterModel(
         RoleManager<IdentityRole> roleManager,
        UserManager<IdentityUser> userManager,
        SignInManager<IdentityUser> signInManager,
        ILogger<RegisterModel> logger,
        IEmailSender emailSender)
    {
        _roleManager = roleManager;
        _userManager = userManager;
        _signInManager = signInManager;
        _logger = logger;
        _emailSender = emailSender;
    }
</code>```

Then try to add AddRoleManager to your configureServices like:

```<code>services.AddIdentity<IdentityUser, IdentityRole>()
    .AddRoleManager<RoleManager<IdentityRole>>()
    .AddDefaultUI()
    .AddDefaultTokenProviders()
    .AddEntityFrameworkStores<ApplicationDbContext>();
</code>```

Title: Assign role to user

Body:
I have a problem with assign role to user. I'm using .net Core 2.1

I changed the registration method. During registration, I assign the role of "Admin" to the user being created.

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {

                var db = new ApplicationDbContext(_optionsBuilder.Options);
                var email = db.Users.Where(s => s.Email == Input.Email);
                if (email.Count() != 0)
                {
                    ViewData["duplicateEmail"] = "Email is already taken";
                    return Page();
                }

                var user = new IdentityUser { UserName = Input.UserName, Email = Input.Email };
                var result = await _userManager.CreateAsync(user, Input.Password);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                        $"Please confirm your account by clicking here.");
                    //#############

                    if(!await _roleManager.RoleExistsAsync("Admin"))
                    {
                       await _userManager.AddToRoleAsync(user, "Admin");
                    }

                    //################
                    await _signInManager.SignInAsync(user, isPersistent: false);
                    return LocalRedirect(returnUrl);
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }
    }

I added only code between hashtags.

After starting the application, when i click registration, i see

I tried to add

services.AddIdentity<IdentityUser,IdentityRole>()
        .AddDefaultUI()
        .AddEntityFrameworkStores<ApplicationDbContext>();

to
startup

but it does not work.

How i'm doinw wrong?

Body:
You need to inject RoleManager<IdentityRole> in RegisterModel like:

 public class RegisterModel : PageModel
{
    private readonly RoleManager<IdentityRole> _roleManager;
    private readonly SignInManager<IdentityUser> _signInManager;
    private readonly UserManager<IdentityUser> _userManager;
    private readonly ILogger<RegisterModel> _logger;
    private readonly IEmailSender _emailSender;

    public RegisterModel(
         RoleManager<IdentityRole> roleManager,
        UserManager<IdentityUser> userManager,
        SignInManager<IdentityUser> signInManager,
        ILogger<RegisterModel> logger,
        IEmailSender emailSender)
    {
        _roleManager = roleManager;
        _userManager = userManager;
        _signInManager = signInManager;
        _logger = logger;
        _emailSender = emailSender;
    }

Then try to add AddRoleManager to your configureServices like:

services.AddIdentity<IdentityUser, IdentityRole>()
    .AddRoleManager<RoleManager<IdentityRole>>()
    .AddDefaultUI()
    .AddDefaultTokenProviders()
    .AddEntityFrameworkStores<ApplicationDbContext>();