问:
How to make Route based on a sub-domain MVC Core
How to make this
 - user1.domain.com goes to user1/index (not inside area)
 - user2.domain.com goes to user2/index (not inside area)

I mean's the

user1.domain.com/index

user2.domain.com/index

Are same view but different data depending on user{0}

using MVC Core 2.2

答:
There're several approaches depending on your needs.

How to make this - user1.domain.com goes to user1/index (not inside area) - user2.domain.com goes to user2/index (not inside area)

Rewrite/Redirect

One approach is to rewrite/redirect the url. If you don't like do it with nginx/iis, you could create an Application Level Rewrite Rule. For example, I create a sample route rule for your reference:

```<code>internal enum RouteSubDomainBehavior{ Redirect, Rewrite, }
internal class RouteSubDomainRule : IRule
{
    private readonly string _domainWithPort;
    private readonly RouteSubDomainBehavior _behavior;

    public RouteSubDomainRule(string domain, RouteSubDomainBehavior behavior)
    {
        this._domainWithPort = domain;
        this._behavior = behavior;
    }

    // custom this method according to your needs
    protected bool ShouldRewrite(RewriteContext context)
    {
        var req = context.HttpContext.Request;
        // only rewrite the url when it ends with target doamin
        if (!req.Host.Value.EndsWith(this._domainWithPort, StringComparison.OrdinalIgnoreCase)) { return false; }
        // if already rewrite, skip
        if(req.Host.Value.Length == this._domainWithPort.Length) { return false; }
        // ... add other condition to make sure only rewrite for the routes you wish, for example, skip the Hub
        return true;
    }

    public void ApplyRule(RewriteContext context)
    {
        if(!this.ShouldRewrite(context)) {
            context.Result = RuleResult.ContinueRules;
            return;
        }
        var req = context.HttpContext.Request;
        if(this._behavior == RouteSubDomainBehavior.Redirect){
            var newUrl = UriHelper.BuildAbsolute( req.Scheme, new HostString(this._domainWithPort), req.PathBase, req.Path, req.QueryString);
            var resp = context.HttpContext.Response;
            context.Logger.LogInformation($"redirect {req.Scheme}://{req.Host}{req.Path}?{req.QueryString} to {newUrl}");
            resp.StatusCode = 301;
            resp.Headers[HeaderNames.Location] = newUrl;
            context.Result = RuleResult.EndResponse;
        }
        else if (this._behavior == RouteSubDomainBehavior.Rewrite)
        {
            var host = req.Host.Value;
            var userStr = req.Host.Value.Substring(0, host.Length - this._domainWithPort.Length - 1);
            req.Host= new HostString(this._domainWithPort);
            var oldPath = req.Path;
            req.Path = $"/{userStr}{oldPath}";
            context.Logger.LogInformation($"rewrite {oldPath} as {req.Path}");
            context.Result = RuleResult.SkipRemainingRules;
        }
        else{
            throw new Exception($"unknow SubDomainBehavoir={this._behavior}");
        }
    }
}
</code>```

(Note I use Rewrite here. If you like, feel free to change it to RouteSubDomainBehavior.Redirect.)

And then invoke the rewriter middleware just after app.UseStaticFiles():

```<code>app.UseStaticFiles();
// note : the invocation order matters!
app.UseRewriter(new RewriteOptions().Add(new RouteSubDomainRule("domain.com:5001",RouteSubDomainBehavior.Rewrite)));

app.UseMvc(...)
</code>```

By this way,

user1.domain.com:5001/ will be rewritten as (or redirected to) domain.com:5001/user1

user1.domain.com:5001/Index will be rewritten as(or redirected to) domain.com:5001/user1/Index

user1.domain.com:5001/Home/Index will be rewritten as (or redirected to) domain.com:5001/user1//HomeIndex

static files like user1.domain.com:5001/lib/jquery/dist/jquery.min.js won't be rewritten/redirected because they're served by UseStaticFiles.

Another Approach Using IModelBinder

Although you can route it by rewritting/redirecting as above, I suspect what your real needs are binding parameters from Request.Host. If that's the case, I would suggest you should use IModelBinder instead.  For example, create a new [FromHost] BindingSource:

```<code>internal class FromHostAttribute : Attribute, IBindingSourceMetadata
{
    public static readonly BindingSource Instance = new BindingSource( "FromHostBindingSource", "From Host Binding Source", true, true);
    public BindingSource BindingSource {get{ return FromHostAttribute.Instance; }}
}
public class MyFromHostModelBinder : IModelBinder
{
    private readonly string _domainWithPort;

    public MyFromHostModelBinder()
    {
        this._domainWithPort = "domain.com:5001";  // in real project, use by Configuration/Options
    }

    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var req = bindingContext.HttpContext.Request;
        var host = req.Host.Value;
        var name = bindingContext.FieldName;
        var userStr = req.Host.Value.Substring(0, host.Length - this._domainWithPort.Length - 1);
        if (userStr == null) {
            bindingContext.ModelState.AddModelError(name, $"cannot get {name} from Host Domain");
        } else {
            var result = Convert.ChangeType(userStr, bindingContext.ModelType);
            bindingContext.Result = ModelBindingResult.Success(result);
        }
        return Task.CompletedTask;
    }

}
public class FromHostBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        if (context == null) { throw new ArgumentNullException(nameof(context)); }
        var has = context.BindingInfo?.BindingSource == FromHostAttribute.Instance;
        if(has){
            return new BinderTypeModelBinder(typeof(MyFromHostModelBinder));
        }
        return null;
    }
}
</code>```

Finally, insert this FromHostBinderProvider in your MVC binder providers.

```<code>services.AddMvc(otps =>{
    otps.ModelBinderProviders.Insert(0, new FromHostBinderProvider());
});
</code>```

Now you can get the user1.domain.com automatically by:

```<code>public IActionResult Index([FromHost] string username)
{
    ...
    return View(view_model_by_username);
}

public IActionResult Edit([FromHost] string username, string id)
{
    ...
    return View(view_model_by_username);
}
</code>```

Body:
There're several approaches depending on your needs.

How to make this - user1.domain.com goes to user1/index (not inside area) - user2.domain.com goes to user2/index (not inside area)

Rewrite/Redirect

One approach is to rewrite/redirect the url. If you don't like do it with nginx/iis, you could create an Application Level Rewrite Rule. For example, I create a sample route rule for your reference:

internal enum RouteSubDomainBehavior{ Redirect, Rewrite, }
internal class RouteSubDomainRule : IRule
{
    private readonly string _domainWithPort;
    private readonly RouteSubDomainBehavior _behavior;

    public RouteSubDomainRule(string domain, RouteSubDomainBehavior behavior)
    {
        this._domainWithPort = domain;
        this._behavior = behavior;
    }

    // custom this method according to your needs
    protected bool ShouldRewrite(RewriteContext context)
    {
        var req = context.HttpContext.Request;
        // only rewrite the url when it ends with target doamin
        if (!req.Host.Value.EndsWith(this._domainWithPort, StringComparison.OrdinalIgnoreCase)) { return false; }
        // if already rewrite, skip
        if(req.Host.Value.Length == this._domainWithPort.Length) { return false; }
        // ... add other condition to make sure only rewrite for the routes you wish, for example, skip the Hub
        return true;
    }

    public void ApplyRule(RewriteContext context)
    {
        if(!this.ShouldRewrite(context)) {
            context.Result = RuleResult.ContinueRules;
            return;
        }
        var req = context.HttpContext.Request;
        if(this._behavior == RouteSubDomainBehavior.Redirect){
            var newUrl = UriHelper.BuildAbsolute( req.Scheme, new HostString(this._domainWithPort), req.PathBase, req.Path, req.QueryString);
            var resp = context.HttpContext.Response;
            context.Logger.LogInformation($"redirect {req.Scheme}://{req.Host}{req.Path}?{req.QueryString} to {newUrl}");
            resp.StatusCode = 301;
            resp.Headers[HeaderNames.Location] = newUrl;
            context.Result = RuleResult.EndResponse;
        }
        else if (this._behavior == RouteSubDomainBehavior.Rewrite)
        {
            var host = req.Host.Value;
            var userStr = req.Host.Value.Substring(0, host.Length - this._domainWithPort.Length - 1);
            req.Host= new HostString(this._domainWithPort);
            var oldPath = req.Path;
            req.Path = $"/{userStr}{oldPath}";
            context.Logger.LogInformation($"rewrite {oldPath} as {req.Path}");
            context.Result = RuleResult.SkipRemainingRules;
        }
        else{
            throw new Exception($"unknow SubDomainBehavoir={this._behavior}");
        }
    }
}

(Note I use Rewrite here. If you like, feel free to change it to RouteSubDomainBehavior.Redirect.)

And then invoke the rewriter middleware just after app.UseStaticFiles():

app.UseStaticFiles();
// note : the invocation order matters!
app.UseRewriter(new RewriteOptions().Add(new RouteSubDomainRule("domain.com:5001",RouteSubDomainBehavior.Rewrite)));

app.UseMvc(...)

By this way,

user1.domain.com:5001/ will be rewritten as (or redirected to) domain.com:5001/user1

user1.domain.com:5001/Index will be rewritten as(or redirected to) domain.com:5001/user1/Index

user1.domain.com:5001/Home/Index will be rewritten as (or redirected to) domain.com:5001/user1//HomeIndex

static files like user1.domain.com:5001/lib/jquery/dist/jquery.min.js won't be rewritten/redirected because they're served by UseStaticFiles.

Another Approach Using IModelBinder

Although you can route it by rewritting/redirecting as above, I suspect what your real needs are binding parameters from Request.Host. If that's the case, I would suggest you should use IModelBinder instead.  For example, create a new [FromHost] BindingSource:

internal class FromHostAttribute : Attribute, IBindingSourceMetadata
{
    public static readonly BindingSource Instance = new BindingSource( "FromHostBindingSource", "From Host Binding Source", true, true);
    public BindingSource BindingSource {get{ return FromHostAttribute.Instance; }}
}
public class MyFromHostModelBinder : IModelBinder
{
    private readonly string _domainWithPort;

    public MyFromHostModelBinder()
    {
        this._domainWithPort = "domain.com:5001";  // in real project, use by Configuration/Options
    }

    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var req = bindingContext.HttpContext.Request;
        var host = req.Host.Value;
        var name = bindingContext.FieldName;
        var userStr = req.Host.Value.Substring(0, host.Length - this._domainWithPort.Length - 1);
        if (userStr == null) {
            bindingContext.ModelState.AddModelError(name, $"cannot get {name} from Host Domain");
        } else {
            var result = Convert.ChangeType(userStr, bindingContext.ModelType);
            bindingContext.Result = ModelBindingResult.Success(result);
        }
        return Task.CompletedTask;
    }

}
public class FromHostBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        if (context == null) { throw new ArgumentNullException(nameof(context)); }
        var has = context.BindingInfo?.BindingSource == FromHostAttribute.Instance;
        if(has){
            return new BinderTypeModelBinder(typeof(MyFromHostModelBinder));
        }
        return null;
    }
}

Finally, insert this FromHostBinderProvider in your MVC binder providers.

services.AddMvc(otps =>{
    otps.ModelBinderProviders.Insert(0, new FromHostBinderProvider());
});

Now you can get the user1.domain.com automatically by:

public IActionResult Index([FromHost] string username)
{
    ...
    return View(view_model_by_username);
}

public IActionResult Edit([FromHost] string username, string id)
{
    ...
    return View(view_model_by_username);
}


来源: stackexchange

问:
Redirect to another page on submit JavaScript
I am trying to integrate firebase auth in node js express based application.

But I am getting this error:

nexttick.js:45 Uncaught TypeError: Cannot read property 'redirect' of
  undefined

This is my register.js file:

```<code>signUpForm.addEventListener('submit', (e) => {
    e.preventDefault();

    //get user info
    const email = signUpForm["email"].value;
    const password = signUpForm["password"].value;

    //sign up the user
    auth.createUserWithEmailAndPassword(email, password).then((req, res) => {
        res.redirect('/');
    })
});

</code>```

Can anyone tell me what am I doing wrong?

答:
Well, firstly, a promise cannot return two or more values, here is an example

new Promise((res) => res(1, 2, 3, 4))
      .then((a, b, c, d) => console.log(a, b, c, d));```
</div>
</div>
</p>

<p>The same story with a rejection in the promise, the output can be only one argument</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>new Promise((_, rej) => rej(1, 2, 3, 4))
      .catch((a, b, c, d) => console.log(a, b, c, d));</code>```

Secondly, the method you use returns the <UserCredential> in the response, not the request, response. Here the link https://firebase.google.com/docs/reference/js/firebase.auth.Auth#create-user-with-email-and-password

How to make a redirect in a browser without express has already been suggested:
https://stackoverflow.com/a/60316794/1431312

ContentLicense: CC BY-SA 4.0

Body:
I am trying to integrate firebase auth in node js express based application.

But I am getting this error:

nexttick.js:45 Uncaught TypeError: Cannot read property 'redirect' of
  undefined

This is my register.js file:

signUpForm.addEventListener('submit', (e) => {
    e.preventDefault();

    //get user info
    const email = signUpForm["email"].value;
    const password = signUpForm["password"].value;

    //sign up the user
    auth.createUserWithEmailAndPassword(email, password).then((req, res) => {
        res.redirect('/');
    })
});

Can anyone tell me what am I doing wrong?

Body:
Well, firstly, a promise cannot return two or more values, here is an example

new Promise((res) => res(1, 2, 3, 4))
      .then((a, b, c, d) => console.log(a, b, c, d));

The same story with a rejection in the promise, the output can be only one argument

new Promise((_, rej) => rej(1, 2, 3, 4))
      .catch((a, b, c, d) => console.log(a, b, c, d));

Secondly, the method you use returns the <UserCredential> in the response, not the request, response. Here the link https://firebase.google.com/docs/reference/js/firebase.auth.Auth#create-user-with-email-and-password

How to make a redirect in a browser without express has already been suggested:
https://stackoverflow.com/a/60316794/1431312


问:
java.lang.ClassCastException: class net.sf.json.JSONObject cannot be cast to class net.sf.json.JSONArray
i have a problem with JSON.
an exception is thrown at this line in my code

```<code>String jsontxt = IOUtils.toString(new FileInputStream(Filename), "UTF-8");
JSONArray  root = (JSONArray) JSONSerializer.toJSON(jsontxt);
</code>```

jsontxt is a String where all my JSON is stored.

and for some reason i have this exception:

```<code>Exception in thread "main" java.lang.ClassCastException: class net.sf.json.JSONObject cannot be cast to class net.sf.json.JSONArray (net.sf.json.JSONObject and net.sf.json.JSONArray are in unnamed module of loader 'app')
</code>```

i validated my JSON file using Lint. Any idea where it might come from?

here is my JSON :

```<code>{
    "numero_de_permis": "A0001",
    "cycle": "2018-2020",
    "heures_transferees_du_cycle_precedent": 2,
    "activites": [{
            "description": "Cours sur la déontologie",
            "categorie": "cours",
            "heures": 14,
            "date": "2019-03-20"
        },
        {
            "description": "Séminaire sur l'architecture contemporaine",
            "categorie": "séminaire",
            "heures": 10,
            "date": "2019-01-07"
        },
        {
            "description": "Rédaction pour le magazine Architecture moderne",
            "categorie": "rédaction professionnelle",
            "heures": 6,
            "date": "2019-10-22"
        },
        {
            "description": "Participation à un groupe de discussion sur le partage des projets architecturaux de plus de 20 ans ",
            "categorie": "groupe de discussion",
            "heures": 6,
            "date": "2019-04-01"
        },
        {
            "description": "Visite d'établissements architecturaux",
            "categorie": "voyage",
            "heures": 2,
            "date": "2019-02-02"
        }
    ]
}
</code>```

the value of jsontxt is the same as my jsonfile meaning it loaded correctly:

```<code>{
    "numero_de_permis": "A0001",
    "cycle": "2018-2020",
    "heures_transferees_du_cycle_precedent": 2,
    "activites": [{
            "description": "Cours sur la déontologie",
            "categorie": "cours",
            "heures": 14,
            "date": "2019-03-20"
        },
        {
            "description": "Séminaire sur l'architecture contemporaine",
            "categorie": "séminaire",
            "heures": 10,
            "date": "2019-01-07"
        },
        {
            "description": "Rédaction pour le magazine Architecture moderne",
            "categorie": "rédaction professionnelle",
            "heures": 6,
            "date": "2019-10-22"
        },
        {
            "description": "Participation à un groupe de discussion sur le partage des projets architecturaux de plus de 20 ans ",
            "categorie": "groupe de discussion",
            "heures": 6,
            "date": "2019-04-01"
        },
        {
            "description": "Visite d'établissements architecturaux",
            "categorie": "voyage",
            "heures": 2,
            "date": "2019-02-02"
        }
    ]
}
</code>```

EDIT: i found a solution to my problem. thanks to Arnaud Claudel, i noticed that my JSON at the start was just  an object and not an array. so doing this fixed my error:

```<code>JSONObject  root = (JSONObject) JSONSerializer.toJSON(jsontxt);
</code>```

答:
The problem is that you have a JSON Object, not an array.

Therefore you can't cast it to a JSONArray, cast it to JSONObject.

Body:
i have a problem with JSON.
an exception is thrown at this line in my code

String jsontxt = IOUtils.toString(new FileInputStream(Filename), "UTF-8");
JSONArray  root = (JSONArray) JSONSerializer.toJSON(jsontxt);

jsontxt is a String where all my JSON is stored.

and for some reason i have this exception:

Exception in thread "main" java.lang.ClassCastException: class net.sf.json.JSONObject cannot be cast to class net.sf.json.JSONArray (net.sf.json.JSONObject and net.sf.json.JSONArray are in unnamed module of loader 'app')

i validated my JSON file using Lint. Any idea where it might come from?

here is my JSON :

{
    "numero_de_permis": "A0001",
    "cycle": "2018-2020",
    "heures_transferees_du_cycle_precedent": 2,
    "activites": [{
            "description": "Cours sur la déontologie",
            "categorie": "cours",
            "heures": 14,
            "date": "2019-03-20"
        },
        {
            "description": "Séminaire sur l'architecture contemporaine",
            "categorie": "séminaire",
            "heures": 10,
            "date": "2019-01-07"
        },
        {
            "description": "Rédaction pour le magazine Architecture moderne",
            "categorie": "rédaction professionnelle",
            "heures": 6,
            "date": "2019-10-22"
        },
        {
            "description": "Participation à un groupe de discussion sur le partage des projets architecturaux de plus de 20 ans ",
            "categorie": "groupe de discussion",
            "heures": 6,
            "date": "2019-04-01"
        },
        {
            "description": "Visite d'établissements architecturaux",
            "categorie": "voyage",
            "heures": 2,
            "date": "2019-02-02"
        }
    ]
}

the value of jsontxt is the same as my jsonfile meaning it loaded correctly:

{
    "numero_de_permis": "A0001",
    "cycle": "2018-2020",
    "heures_transferees_du_cycle_precedent": 2,
    "activites": [{
            "description": "Cours sur la déontologie",
            "categorie": "cours",
            "heures": 14,
            "date": "2019-03-20"
        },
        {
            "description": "Séminaire sur l'architecture contemporaine",
            "categorie": "séminaire",
            "heures": 10,
            "date": "2019-01-07"
        },
        {
            "description": "Rédaction pour le magazine Architecture moderne",
            "categorie": "rédaction professionnelle",
            "heures": 6,
            "date": "2019-10-22"
        },
        {
            "description": "Participation à un groupe de discussion sur le partage des projets architecturaux de plus de 20 ans ",
            "categorie": "groupe de discussion",
            "heures": 6,
            "date": "2019-04-01"
        },
        {
            "description": "Visite d'établissements architecturaux",
            "categorie": "voyage",
            "heures": 2,
            "date": "2019-02-02"
        }
    ]
}

EDIT: i found a solution to my problem. thanks to Arnaud Claudel, i noticed that my JSON at the start was just  an object and not an array. so doing this fixed my error:

JSONObject  root = (JSONObject) JSONSerializer.toJSON(jsontxt);


问:
Do ADO (TFS) dashboards support tabs?
I'm using ADO dashboards.( https://learn.microsoft.com/en-us/azure/devops/report/dashboards/overview?view=azure-devops ).
I want to have many different charts / query tile views, each serving a distinct purpose but they are all related to a project. Right now I have to create distinct dashboards for each. Is there a way to have tabs within one dashboard so i can still separate the views but not have to go to different dashboards all the time.</p>

答:
Sorry this is not available, we do not have tabs in the dashboard at the moment.

You may have to go to different dashboards and manually select/switch the view.

You could create a related user voice and vote up in our feature request page from Developer Community site. Our PM will kindly review your suggestion.

Title: Do ADO (TFS) dashboards support tabs?


问:
Streaming inner JSONArray records with Jackson avoiding memory collection
Been recently trying to dig into how to stream JSON content via an HTTP endpoint as I don't want to store the whole JSON in memory before sending the response.

However, I have some doubts related on how to do this and if my previous JSON schema has to change in order to cope with streaming and later parsing.

Currently what I have (and would like to still have doing streaming) is the following.

```<code>    {
        "content": [ // I don't want to wait for this array to be populated to flush it.
            {
                "key": "value",
                "yet": "another_value"
            }, // read individual nested record, flush it
            {
                "key": "valueagain",
                "yet": "another_value_in_here"
            } // read individual nested record, flush it
        ],
        "random": {
            "more": "fields",
            "in": {
                 "here": "yeah"
            }
        }
    }
</code>```

My doubt here is, is there a way (using Jackson or any other Java lib) to stream inner parts of a JSON without waiting for closing the value of a given key?

Let's say I want to start streaming

```<code>{
    "content": [
         ...
</code>```

And then all the contents following that...

```<code>{
        "key": "value",
        "yet": "another_value"
}
</code>```

Or the way of doing this is changing the overall result to this.

```<code>[
  {
    "key": "value",
    "yet": "another_value"
  },
  {
    "key": "valueagain",
    "yet": "another_value_in_here"
  },
  {
    "more": "fields",
    "in": {
      "here": "yeah"
    }
  }
]
</code>```

So, basically, having a JsonGenerator, would I be able to flush incomplete arrays such as in my example?

```<code>jGenerator.writeStartObject();
jGenerator.writeFieldName("content");
jGenerator.writeStartArray();
jGenerator.flush(); // initial stream, records incoming within next flush. Can this be streamed?

jGenerator.writeStartObject();
jGenerator.writeStringField("key", "value");
jGenerator.writeStringField("yet", "another_value");
jGenerator.writeEndObject();
jGenerator.flush(); // streaming individual JSON object

... so on so forth until array is complete ...

jGenerator.writeEndArray();
jsonGenerator.writeFieldName("random");
</code>```

答:
If you can get input stream to your Json without putting whole content in memory. For example you can have it saved on HDD and just get InputStream from File.

With jackson you can have something like this:

```<code>  private final JsonParser jp;

  public JsonArrayInputStreamWrapper(InputStream inputStream) throws IOException {
    this.jp = new JsonFactory().createParser(inputStream);
    setUpCursorToContentArray();
  }

  private void setUpCursorToContentArray() throws IOException {
    // validate if json contains "content" key
    do {
      if (jp.nextToken() == null)
        throw new JsonException("Provided input doesn't contain content.");
    } while (!"content".equals(jp.getText()));

    // set up coursor on first array that is found after "content"
    while (jp.nextToken() != JsonToken.START_ARRAY) {
      if (jp.currentToken() == null)
        // throw exception when there weren't any array
        throw new JsonException("Content input is malformed.");
    }
  }
</code>```

So my idea was to set up my coursor in the place where I'd like to start processing in the constructor of this so called wrapper. This way after successful initialization of object I can use hasNext() and next() for a change.

```<code>  @Override
  public boolean hasNext() {
    if(jp.isClosed()) {
      // has to be handled
    }
    return jp.nextToken() == JsonToken.START_OBJECT
  }

  @Override
  public Map next() {
    // where mapper is jackson ObjectMapper
    return mapper.readValue(jp, Map.class);
  }
</code>```

This can be used as following:

```<code>while (wrapper.hasNext()) {
    var inv = wrapper.next();
    //processing
}
</code>```

Do not forget to jp.close() after you finish processing.

Body:
Been recently trying to dig into how to stream JSON content via an HTTP endpoint as I don't want to store the whole JSON in memory before sending the response.

However, I have some doubts related on how to do this and if my previous JSON schema has to change in order to cope with streaming and later parsing.

Currently what I have (and would like to still have doing streaming) is the following.

    {
        "content": [ // I don't want to wait for this array to be populated to flush it.
            {
                "key": "value",
                "yet": "another_value"
            }, // read individual nested record, flush it
            {
                "key": "valueagain",
                "yet": "another_value_in_here"
            } // read individual nested record, flush it
        ],
        "random": {
            "more": "fields",
            "in": {
                 "here": "yeah"
            }
        }
    }

My doubt here is, is there a way (using Jackson or any other Java lib) to stream inner parts of a JSON without waiting for closing the value of a given key?

Let's say I want to start streaming

{
    "content": [
         ...

And then all the contents following that...

{
        "key": "value",
        "yet": "another_value"
}

Or the way of doing this is changing the overall result to this.

[
  {
    "key": "value",
    "yet": "another_value"
  },
  {
    "key": "valueagain",
    "yet": "another_value_in_here"
  },
  {
    "more": "fields",
    "in": {
      "here": "yeah"
    }
  }
]

So, basically, having a JsonGenerator, would I be able to flush incomplete arrays such as in my example?

jGenerator.writeStartObject();
jGenerator.writeFieldName("content");
jGenerator.writeStartArray();
jGenerator.flush(); // initial stream, records incoming within next flush. Can this be streamed?

jGenerator.writeStartObject();
jGenerator.writeStringField("key", "value");
jGenerator.writeStringField("yet", "another_value");
jGenerator.writeEndObject();
jGenerator.flush(); // streaming individual JSON object

... so on so forth until array is complete ...

jGenerator.writeEndArray();
jsonGenerator.writeFieldName("random");

Body:
If you can get input stream to your Json without putting whole content in memory. For example you can have it saved on HDD and just get InputStream from File.

With jackson you can have something like this:

  private final JsonParser jp;

  public JsonArrayInputStreamWrapper(InputStream inputStream) throws IOException {
    this.jp = new JsonFactory().createParser(inputStream);
    setUpCursorToContentArray();
  }

  private void setUpCursorToContentArray() throws IOException {
    // validate if json contains "content" key
    do {
      if (jp.nextToken() == null)
        throw new JsonException("Provided input doesn't contain content.");
    } while (!"content".equals(jp.getText()));

    // set up coursor on first array that is found after "content"
    while (jp.nextToken() != JsonToken.START_ARRAY) {
      if (jp.currentToken() == null)
        // throw exception when there weren't any array
        throw new JsonException("Content input is malformed.");
    }
  }

So my idea was to set up my coursor in the place where I'd like to start processing in the constructor of this so called wrapper. This way after successful initialization of object I can use hasNext() and next() for a change.

  @Override
  public boolean hasNext() {
    if(jp.isClosed()) {
      // has to be handled
    }
    return jp.nextToken() == JsonToken.START_OBJECT
  }

  @Override
  public Map next() {
    // where mapper is jackson ObjectMapper
    return mapper.readValue(jp, Map.class);
  }

This can be used as following:

while (wrapper.hasNext()) {
    var inv = wrapper.next();
    //processing
}

Do not forget to jp.close() after you finish processing.


问:
Import Excel with HTML Format to DataTable
I've been searching in the net with no answers
How do you import a .xls file that is made of
,,
, tags to DataTable?

答:
I would use PHP

This should get you started.

ContentLicense: CC BY-SA 3.0


问:
Keep Business Process Display State as collapsed
I am trying to keep the business process flow display state as collapsed.

I am currently making it collapsed at addOnStageChange

```<code>Xrm.Page.ui.process.setDisplayState('collapsed');
</code>```

It works fine on Stage Change for me. But if I click on the same stage twice which means stage is not changing then the BPF gets expanded. I am assuming if it is the default behavior.

How can I prevent it from expanding permanently?

答:
If you are using Unified Interface it will be collapsed by defualt.

But if you are using legacy web client.

Add onload event on your From (for ex.Opportunity entity) and add below lines of code.

```<code>function collapseOpporBusinessProcess(){setTimeout(collapseOpporBusinessProcessDelay,300)}

function collapseOpporBusinessProcessDelay(){Xrm.Page.ui.process!=null&&Xrm.Page.ui.process.setDisplayState(“collapsed”)}
</code>```

Body:
I am trying to keep the business process flow display state as collapsed.

I am currently making it collapsed at addOnStageChange

Xrm.Page.ui.process.setDisplayState('collapsed');

It works fine on Stage Change for me. But if I click on the same stage twice which means stage is not changing then the BPF gets expanded. I am assuming if it is the default behavior.

How can I prevent it from expanding permanently?

Body:
If you are using Unified Interface it will be collapsed by defualt.

But if you are using legacy web client.

Add onload event on your From (for ex.Opportunity entity) and add below lines of code.

function collapseOpporBusinessProcess(){setTimeout(collapseOpporBusinessProcessDelay,300)}

function collapseOpporBusinessProcessDelay(){Xrm.Page.ui.process!=null&&Xrm.Page.ui.process.setDisplayState(“collapsed”)}


问:
Missing category to be shown at bottom
I want category of 'Missing' to be shown at bottom in result after groupby. There can be any character value in column x. See example below.</p>

```<code>library(dplyr)
df <- data.frame(x = c('Ap','LA','MN', 'Missing','ZA'),
                 y = c('PA','NA','DN', 'Missing','ZD'),
                 z = 1:5,
                 stringsAsFactors = F)

df %>% group_by(x) %>% summarise(x1 = sum(z))
</code>```

答:
Soultion using dplyr::arrange:

```<code>df %>% group_by(x) %>%
  summarise(x1 = sum(z)) %>%
  arrange(x == "Missing", x)
</code>```

Returns:

```<code># A tibble: 5 x 2
  x          x1
  <chr>   <int>
1 Ap          1
2 LA          2
3 MN          3
4 ZA          5
5 Missing     4
</code>```

Title: Missing category to be shown at bottom

Body:
I want category of 'Missing' to be shown at bottom in result after groupby. There can be any character value in column x. See example below.

library(dplyr)
df <- data.frame(x = c('Ap','LA','MN', 'Missing','ZA'),
                 y = c('PA','NA','DN', 'Missing','ZD'),
                 z = 1:5,
                 stringsAsFactors = F)

df %>% group_by(x) %>% summarise(x1 = sum(z))

Body:
Soultion using dplyr::arrange:

df %>% group_by(x) %>%
  summarise(x1 = sum(z)) %>%
  arrange(x == "Missing", x)

Returns:

# A tibble: 5 x 2
  x          x1
  <chr>   <int>
1 Ap          1
2 LA          2
3 MN          3
4 ZA          5
5 Missing     4


问:
Image uploaded with Active storage not showing in the view
I am trying to upgrade and a Rails app to RoR6 with ActiveStorage.
In the view, I use an image_tag on the attached image called "whiteboard_background" on @project.

And it shows a broken link in the browser:
Link

Environment: development and files stored locally

Model:

```<code>class Project < ApplicationRecord

  has_one_attached :whiteboard_background
</code>```

View code:

```<code>attachment: <%= @project.whiteboard_background.attached? %>
<p>image:
<%= image_tag @project.whiteboard_background if @project.whiteboard_background.attached? %>
</p>
</code>```

Server:

```<code>Started GET "/projects/6" for 127.0.0.1 at 2020-02-19 20:29:27 +0100
Processing by ProjectsController#show as HTML
  Parameters: {"id"=>"6"}
...
ActiveStorage::Attachment Load (2.8ms)  SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = $1 AND "active_storage_attachments"."record_type" = $2 AND "active_storage_attachments"."name" = $3 LIMIT $4  [["record_id", 6], ["record_type", "Project"], ["name", "whiteboard_background"], ["LIMIT", 1]]
  ↳ app/views/projects/show.html.erb:94
  ActiveStorage::Blob Load (0.6ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", 13], ["LIMIT", 1]]
  ↳ app/views/projects/show.html.erb:96
  Location Load (0.5ms)  SELECT "locations".* FROM "locations" ....
</code>```

I have checked that @project.whiteboard_background.attached? is true and in the console Project.last.whiteboard_background.metadata gives correct image data which indicates that the upload works fine.

The Firefox inspector does show the element with a source path, but says "could not load image". Same behaviour in chrome

If I repeat the process in a blank test app from scratch, it works fine and i can display the image.

Any idea?

答:
The error was due to the following "catch all" at the end of my rails routes:
get "*path", to: redirect('/')

It seems the browser is not able to load the image with the URL given by active storage due to forced redirection to root. This was not an issue using previous upload method (carrierwave)

Removing this line from routes.rb fixed it.

Body:
I am trying to upgrade and a Rails app to RoR6 with ActiveStorage.
In the view, I use an image_tag on the attached image called "whiteboard_background" on @project.

And it shows a broken link in the browser:
Link

Environment: development and files stored locally

Model:

class Project < ApplicationRecord

  has_one_attached :whiteboard_background

View code:

attachment: <%= @project.whiteboard_background.attached? %>

image:
<%= image_tag @project.whiteboard_background if @project.whiteboard_background.attached? %>

Server:

Started GET "/projects/6" for 127.0.0.1 at 2020-02-19 20:29:27 +0100
Processing by ProjectsController#show as HTML
  Parameters: {"id"=>"6"}
...
ActiveStorage::Attachment Load (2.8ms)  SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = $1 AND "active_storage_attachments"."record_type" = $2 AND "active_storage_attachments"."name" = $3 LIMIT $4  [["record_id", 6], ["record_type", "Project"], ["name", "whiteboard_background"], ["LIMIT", 1]]
  ↳ app/views/projects/show.html.erb:94
  ActiveStorage::Blob Load (0.6ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", 13], ["LIMIT", 1]]
  ↳ app/views/projects/show.html.erb:96
  Location Load (0.5ms)  SELECT "locations".* FROM "locations" ....

I have checked that @project.whiteboard_background.attached? is true and in the console Project.last.whiteboard_background.metadata gives correct image data which indicates that the upload works fine.

The Firefox inspector does show the element with a source path, but says "could not load image". Same behaviour in chrome

If I repeat the process in a blank test app from scratch, it works fine and i can display the image.

Any idea?


问:
TextView with spans , how can I know which one is clicked on?
I am using this library, but from the onClick styles that they have, neither handles my needed case.
https://github.com/splitwise/TokenAutoComplete

So I wanted to do my own. So I have a ContactsCompletionView, which is a TextView. and I override the onTouchEvent like this:

```<code>override fun onTouchEvent(event: MotionEvent): Boolean {
    val action = event.actionMasked
    val text = text
    var handled = super.onTouchEvent(event)
    if (isFocused && text != null && action == MotionEvent.ACTION_UP) {
        val offset = getOffsetForPosition(event.x, event.y)
        if (offset != -1) {
            var offseted = text.substring(offset, text.length)
            var indexLeft = offseted.indexOf("(") + 1
            var indexRight = offseted.indexOf(")")
            if (indexLeft > 0 && indexRight > indexLeft)
                Toast.makeText(context, offseted.substring(indexLeft, indexRight), Toast.LENGTH_SHORT).show()
        }
    }
    return handled
}
</code>```

This is what they had, but I cannot use TokenImageSpan because it is a protected class:

```<code>@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
    int action = event.getActionMasked();
    Editable text = getText();
    boolean handled = false;

    if (tokenClickStyle == TokenClickStyle.None) {
        handled = super.onTouchEvent(event);
    }

    if (isFocused() && text != null && lastLayout != null && action == MotionEvent.ACTION_UP) {

        int offset = getOffsetForPosition(event.getX(), event.getY());

        if (offset != -1) {
            TokenImageSpan[] links = text.getSpans(offset, offset, TokenImageSpan.class);

            if (links.length > 0) {
                links[0].onClick();
                handled = true;
            } else {
                //We didn't click on a token, so if any are selected, we should clear that
                clearSelections();
            }
        }
    }

    if (!handled && tokenClickStyle != TokenClickStyle.None) {
        handled = super.onTouchEvent(event);
    }
    return handled;

}
</code>```

My code works, but my issue is that whenever I press an TAG at the end of it. It gets the next object. I assume that this is because I just use:

```<code> val offset = getOffsetForPosition(event.x, event.y)
 if (offset != -1) {
     var offseted = text.substring(offset, text.length)
 }
</code>```

When they use:

```<code>  if (offset != -1) {
      TokenImageSpan[] links = text.getSpans(offset, offset, TokenImageSpan.class);
  }
</code>```

TokenImageSpan extends ImageSpan, so I can use it like that, But I do not know how to take the text from the ImageSpan. Any ideas how I can fix this please?

答:
This is what I used:

```<code>  override fun onTouchEvent(event: MotionEvent): Boolean {
    val action = event.actionMasked
    val text = text
    var handled = super.onTouchEvent(event)
    var offset = getOffsetForPosition(event.getX(), event.getY())
    if (isFocused && text != null && action == MotionEvent.ACTION_UP) {
        var cursor = this@ContactsCompletionView.selectionEnd
        if (cursor < 0)
            cursor = 0
        val links: Array<ViewSpan> = text.getSpans(0, cursor, ViewSpan::class.java)
        if (objects.size > 0 && objects.size >= links.size && links.size > 0 && offset < cursor)
            Snackbar().make(this, objects[links.size - 1].address, com.google.android.material.snackbar.Snackbar.LENGTH_SHORT).show()

    }

    return handled
}
</code>```

The library if ClickStyle is set to NONE, it moves the cursor at the end of the chosen object. So I create a substring of that, check how many spans I have, and then I use that as an index for my objects. in order to show the first one on the left of cursor

Body:
I am using this library, but from the onClick styles that they have, neither handles my needed case.
https://github.com/splitwise/TokenAutoComplete

So I wanted to do my own. So I have a ContactsCompletionView, which is a TextView. and I override the onTouchEvent like this:

override fun onTouchEvent(event: MotionEvent): Boolean {
    val action = event.actionMasked
    val text = text
    var handled = super.onTouchEvent(event)
    if (isFocused && text != null && action == MotionEvent.ACTION_UP) {
        val offset = getOffsetForPosition(event.x, event.y)
        if (offset != -1) {
            var offseted = text.substring(offset, text.length)
            var indexLeft = offseted.indexOf("(") + 1
            var indexRight = offseted.indexOf(")")
            if (indexLeft > 0 && indexRight > indexLeft)
                Toast.makeText(context, offseted.substring(indexLeft, indexRight), Toast.LENGTH_SHORT).show()
        }
    }
    return handled
}

This is what they had, but I cannot use TokenImageSpan because it is a protected class:

@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
    int action = event.getActionMasked();
    Editable text = getText();
    boolean handled = false;

    if (tokenClickStyle == TokenClickStyle.None) {
        handled = super.onTouchEvent(event);
    }

    if (isFocused() && text != null && lastLayout != null && action == MotionEvent.ACTION_UP) {

        int offset = getOffsetForPosition(event.getX(), event.getY());

        if (offset != -1) {
            TokenImageSpan[] links = text.getSpans(offset, offset, TokenImageSpan.class);

            if (links.length > 0) {
                links[0].onClick();
                handled = true;
            } else {
                //We didn't click on a token, so if any are selected, we should clear that
                clearSelections();
            }
        }
    }

    if (!handled && tokenClickStyle != TokenClickStyle.None) {
        handled = super.onTouchEvent(event);
    }
    return handled;

}

My code works, but my issue is that whenever I press an TAG at the end of it. It gets the next object. I assume that this is because I just use:

 val offset = getOffsetForPosition(event.x, event.y)
 if (offset != -1) {
     var offseted = text.substring(offset, text.length)
 }

When they use:

  if (offset != -1) {
      TokenImageSpan[] links = text.getSpans(offset, offset, TokenImageSpan.class);
  }

TokenImageSpan extends ImageSpan, so I can use it like that, But I do not know how to take the text from the ImageSpan. Any ideas how I can fix this please?

Body:
This is what I used:

  override fun onTouchEvent(event: MotionEvent): Boolean {
    val action = event.actionMasked
    val text = text
    var handled = super.onTouchEvent(event)
    var offset = getOffsetForPosition(event.getX(), event.getY())
    if (isFocused && text != null && action == MotionEvent.ACTION_UP) {
        var cursor = this@ContactsCompletionView.selectionEnd
        if (cursor < 0)
            cursor = 0
        val links: Array<ViewSpan> = text.getSpans(0, cursor, ViewSpan::class.java)
        if (objects.size > 0 && objects.size >= links.size && links.size > 0 && offset < cursor)
            Snackbar().make(this, objects[links.size - 1].address, com.google.android.material.snackbar.Snackbar.LENGTH_SHORT).show()

    }

    return handled
}

The library if ClickStyle is set to NONE, it moves the cursor at the end of the chosen object. So I create a substring of that, check how many spans I have, and then I use that as an index for my objects. in order to show the first one on the left of cursor


问:
How to make the link inside Button change color on hover without hovering over link
My link changes color on hovering over it directly but does not change color when I hover over the button and not the link directly

```<code>btn:hover{
color: black;
}
</code>```

This does not work.

```<code>a:hover{
color:black
}
</code>```

This is working currently but does not do the job as needed.

How do I make the button change the color of the link when I hover over it?
As seen in the first image.

答:
btn is wrong try button selector like below.

button:hover{
color: black;
}```

Body:
My link changes color on hovering over it directly but does not change color when I hover over the button and not the link directly

btn:hover{
color: black;
}

This does not work.

a:hover{
color:black
}

This is working currently but does not do the job as needed.

How do I make the button change the color of the link when I hover over it?
As seen in the first image.


问:
Odoo 10 Website_hr_recruitment
enter image description here

```<code>   Hello for all , I have a form and i wish that the field "Nombre d'années d'expérience" will be added in the model of hr.applicant
</code>```

2

```<code>    In the case
    { nom : Koussay
    Prénom Abdouli
    Email : ...
    works correctly , but the hole problem is on the field
    "Nombre d'années d'expérience" }
</code>```

答:
first you have to inherit the recruitment template id " apply "to display your fields</p>

```<code><template id="show_year_number"
            inherit_id="website_hr_recruitment.apply" name="Show year number">
            <xpath expr="//div/div/div[3]"
                position="after">
                <div class="form-group row form-field o_website_form_required_custom">
                            <div class="col-lg-3 col-md-4 text-right">
                                <label class="col-form-label" for="number_year_experience">Your File name</label> <!-- add your field name nembre anne... -->
                            </div>
                            <div class="col-lg-7 col-md-8">
                                <input type="text" class="form-control o_website_form_input" name="your_field_name_here" required=""/> <!-- add your field name nembre anne... -->
                            </div>
                        </div>
            </xpath>
</template>

<function model="ir.model.fields" name="formbuilder_whitelist">
            <value>hr.applicant</value>
            <value eval="[
                'description',
                'email_from',
                'partner_name',
                'partner_phone',
                'job_id',
                'department_id',
                'your_field_name_here',  <!-- add your field name nembre anne... -->
            ]"/>
        </function>
</code>```

Title: Odoo 10 Website_hr_recruitment

Body:
enter image description here

   Hello for all , I have a form and i wish that the field "Nombre d'années d'expérience" will be added in the model of hr.applicant

2

    In the case
    { nom : Koussay
    Prénom Abdouli
    Email : ...
    works correctly , but the hole problem is on the field
    "Nombre d'années d'expérience" }

Body:
first you have to inherit the recruitment template id " apply "to display your fields

<template id="show_year_number"
            inherit_id="website_hr_recruitment.apply" name="Show year number">
            <xpath expr="//div/div/div[3]"
                position="after">
                <div class="form-group row form-field o_website_form_required_custom">
                            <div class="col-lg-3 col-md-4 text-right">
                                <label class="col-form-label" for="number_year_experience">Your File name</label> <!-- add your field name nembre anne... -->
                            </div>
                            <div class="col-lg-7 col-md-8">
                                <input type="text" class="form-control o_website_form_input" name="your_field_name_here" required=""/> <!-- add your field name nembre anne... -->
                            </div>
                        </div>
            </xpath>
</template>

<function model="ir.model.fields" name="formbuilder_whitelist">
            <value>hr.applicant</value>
            <value eval="[
                'description',
                'email_from',
                'partner_name',
                'partner_phone',
                'job_id',
                'department_id',
                'your_field_name_here',  <!-- add your field name nembre anne... -->
            ]"/>
        </function>


问:
Sockets: What is causing read() to return EINVAL?
A socket client program establishes a connection with the server,
writes some bytes and waits for response using the (blocking) read().

But this fails with the error EINVAL ("Invalid argument").
Previous calls to create(), bind() and connect() the socket have been made successfully.

My Question

What's wrong here?

Platform is Linux x64.

答:
The problem was that I passed a size of 1 byte to the read() function.
It seems that this is not supported

(why? what is the minimum size? must it be a multiple of 2/the bitness of the platform?).

Now I am passing 8 and it works.
Thank you all for your comments.


问:
Why is tensorflow model always predicting same class?
my TensorFlow model is always predicting the same class with a confidant of 100%.

First a short description of my setting: Task is to do image classification with 7 classes and reading images from the webcam. For training, validation, and testing of the model, I'm using TensorFlow with data generators.

```<code>model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Conv2D(32,(3,3), activation='elu',input_shape=(image_heigth,image_width,3)))
model.add(tf.keras.layers.Conv2D(64,(3,3), activation='elu'))
model.add(tf.keras.layers.MaxPooling2D((2,2)))
model.add(tf.keras.layers.Conv2D(128,(3,3), activation='elu'))
model.add(tf.keras.layers.MaxPooling2D((2,2)))
model.add(tf.keras.layers.Conv2D(256,(3,3), activation='elu'))
model.add(tf.keras.layers.Conv2D(256,(3,3), activation='elu'))
model.add(tf.keras.layers.MaxPooling2D((2,2)))
model.add(tf.keras.layers.Conv2D(512,(3,3), activation='elu'))
model.add(tf.keras.layers.MaxPooling2D((2,2)))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(512, activation='elu'))
model.add(tf.keras.layers.Dense(7, activation='softmax'))

model.summary()

model.compile(loss='categorical_crossentropy', optimizer=tf.keras.optimizers.RMSprop(lr=1e-4), metrics=['acc'])
</code>```

Just for information this is my model. Training, validation and testing is done with this code:

```<code>train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255, rotation_range=40, shear_range=0.2,zoom_range=0.2, horizontal_flip=True)
validation_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
test_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(train_dir, target_size=(image_heigth,image_width),batch_size=batch_size, class_mode='categorical', shuffle=True)
validation_generator = validation_datagen.flow_from_directory(validation_dir, target_size=(image_heigth,image_width), batch_size=5, class_mode='categorical')

for data_batch, labels_batch in train_generator:
    print('Shape des Datenstapels:', data_batch.shape)
    print('Shape des Klassenbzeichnungsstabels:', labels_batch.shape)
    break

history = model.fit(train_generator,steps_per_epoch=steps_per_epoch, epochs=epochs, validation_data=validation_generator,validation_steps=10, callbacks=callback_list)

# Testing the Model
test_generator = test_datagen.flow_from_directory(test_dir, target_size=(image_heigth,image_width), batch_size=5, class_mode='categorical')
test_loss, test_acc = model.evaluate(test_generator, steps=5)
predictions = model.predict(test_generator)
image_batch, label_batch = next (test_generator)
</code>```

I'm reaching a correct classification rate up to 90%. My loss function is down to something around 0,3.
Debugging the testing and watching the predictions get expected values like [0.08;0.06;0.56;0.04;0.10;0.09;0.07].

In the end, I'm saving my model as an h5 with the TensorFlow method.

In another python program, I'm loading this h5 and want to predict the webcam image. But now the output is always [1.0;0.0;0.0;0.0;0.0;0.0;0.0]. Here is my code how I'm doing this:

```<code> import numpy as np
import cv2
import tensorflow as tf

model = tf.keras.models.load_model('/home/poppe/Dokumente/Models/Proto2.h5')

classes = ['One', 'two', 'three', 'four', 'five', 'six', 'seven']

model.summary()

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
    # Our operations on the frame come here
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    rezised = cv2.resize(frame, (150, 150))
    expandArrayImage = np.expand_dims(rezised, axis=0)

    prediction = model.predict(expandArrayImage)

    print (np.max(prediction))
    print(classes[np.argmax(prediction)])

    # Display the resulting frame
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything is done, release the capture
cap.release()
cv2.destroyAllWindows()
</code>```

As you can see, I'm using OpenCV to read from a webcam.

To solve my problem I have tried the following:
Reduce my model to a minimum --> no effect

Reduce my problem to a binary classification --> no effect (always predicting one of the two classes with 100%)

Load and predict a single image --> no effect

Load and predict a single image directly after the code for testing (don't have to save and load the model) --> no effect, the image was one of my test images...By testing this image was classified correctly, loading it as a single image and use the predict method I've got the same error as bevor.

So because of testing is running as expected, I don't think I've got a problem with my data or model. Is there anything wrong with transforming the webcam image from OpenCV to the TensorFlow model?

Do you have any other ideas I can try to fix my problem?

Many thanks at all! :)

答:
cv2.VideoCapture().read() will return a numpy array with values ranging in (0,255) but your model expects them to be in range (0, 1)

you can pass an image within the expected range like:

```<code>rezised = cv2.resize(frame, (150, 150)) / 255
expandArrayImage = np.expand_dims(rezised, axis=0)
# rest of the code
</code>```

Body:
my TensorFlow model is always predicting the same class with a confidant of 100%.

First a short description of my setting: Task is to do image classification with 7 classes and reading images from the webcam. For training, validation, and testing of the model, I'm using TensorFlow with data generators.

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Conv2D(32,(3,3), activation='elu',input_shape=(image_heigth,image_width,3)))
model.add(tf.keras.layers.Conv2D(64,(3,3), activation='elu'))
model.add(tf.keras.layers.MaxPooling2D((2,2)))
model.add(tf.keras.layers.Conv2D(128,(3,3), activation='elu'))
model.add(tf.keras.layers.MaxPooling2D((2,2)))
model.add(tf.keras.layers.Conv2D(256,(3,3), activation='elu'))
model.add(tf.keras.layers.Conv2D(256,(3,3), activation='elu'))
model.add(tf.keras.layers.MaxPooling2D((2,2)))
model.add(tf.keras.layers.Conv2D(512,(3,3), activation='elu'))
model.add(tf.keras.layers.MaxPooling2D((2,2)))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(512, activation='elu'))
model.add(tf.keras.layers.Dense(7, activation='softmax'))

model.summary()

model.compile(loss='categorical_crossentropy', optimizer=tf.keras.optimizers.RMSprop(lr=1e-4), metrics=['acc'])

Just for information this is my model. Training, validation and testing is done with this code:

train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255, rotation_range=40, shear_range=0.2,zoom_range=0.2, horizontal_flip=True)
validation_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
test_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(train_dir, target_size=(image_heigth,image_width),batch_size=batch_size, class_mode='categorical', shuffle=True)
validation_generator = validation_datagen.flow_from_directory(validation_dir, target_size=(image_heigth,image_width), batch_size=5, class_mode='categorical')

for data_batch, labels_batch in train_generator:
    print('Shape des Datenstapels:', data_batch.shape)
    print('Shape des Klassenbzeichnungsstabels:', labels_batch.shape)
    break

history = model.fit(train_generator,steps_per_epoch=steps_per_epoch, epochs=epochs, validation_data=validation_generator,validation_steps=10, callbacks=callback_list)

# Testing the Model
test_generator = test_datagen.flow_from_directory(test_dir, target_size=(image_heigth,image_width), batch_size=5, class_mode='categorical')
test_loss, test_acc = model.evaluate(test_generator, steps=5)
predictions = model.predict(test_generator)
image_batch, label_batch = next (test_generator)

I'm reaching a correct classification rate up to 90%. My loss function is down to something around 0,3.
Debugging the testing and watching the predictions get expected values like [0.08;0.06;0.56;0.04;0.10;0.09;0.07].

In the end, I'm saving my model as an h5 with the TensorFlow method.

In another python program, I'm loading this h5 and want to predict the webcam image. But now the output is always [1.0;0.0;0.0;0.0;0.0;0.0;0.0]. Here is my code how I'm doing this:

 import numpy as np
import cv2
import tensorflow as tf

model = tf.keras.models.load_model('/home/poppe/Dokumente/Models/Proto2.h5')

classes = ['One', 'two', 'three', 'four', 'five', 'six', 'seven']

model.summary()

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
    # Our operations on the frame come here
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    rezised = cv2.resize(frame, (150, 150))
    expandArrayImage = np.expand_dims(rezised, axis=0)

    prediction = model.predict(expandArrayImage)

    print (np.max(prediction))
    print(classes[np.argmax(prediction)])

    # Display the resulting frame
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything is done, release the capture
cap.release()
cv2.destroyAllWindows()

As you can see, I'm using OpenCV to read from a webcam.

To solve my problem I have tried the following:
Reduce my model to a minimum --> no effect

Reduce my problem to a binary classification --> no effect (always predicting one of the two classes with 100%)

Load and predict a single image --> no effect

Load and predict a single image directly after the code for testing (don't have to save and load the model) --> no effect, the image was one of my test images...By testing this image was classified correctly, loading it as a single image and use the predict method I've got the same error as bevor.

So because of testing is running as expected, I don't think I've got a problem with my data or model. Is there anything wrong with transforming the webcam image from OpenCV to the TensorFlow model?

Do you have any other ideas I can try to fix my problem?

Many thanks at all! :)

Body:
cv2.VideoCapture().read() will return a numpy array with values ranging in (0,255) but your model expects them to be in range (0, 1)

you can pass an image within the expected range like:

rezised = cv2.resize(frame, (150, 150)) / 255
expandArrayImage = np.expand_dims(rezised, axis=0)
# rest of the code


问:
React navigation drawer V5
I'm using react-navigation version 5.
I have tab navigation and drawer navigation together.

I'm trying to add an icon in my header to open/close drawer:

here is my custom right header for toggling the drawer:

```<code>const HeaderRight = ({ navigation }) => {
    return (
      <View style={{flexDirection: 'row'}}>
        <TouchableOpacity
        onPress={ () =>{ navigation.toggleDrawer()}}>  //here is the problem
          <Image source={require('./assets/images/icons/drawer.png')}/>
        </TouchableOpacity>
      </View>
    );}
</code>```

this is my tab navigator:

```<code>const Tab = createBottomTabNavigator();
function AppTab() {
  return (
     <Tab.Navigator>
        <Tab.Screen name="Category" component={Category} />
        <Tab.Screen name="Home" component={Home}/>
      </Tab.Navigator>
   );}
</code>```

drawer navigator:

```<code>    const Drawer = createDrawerNavigator();
    function App() {
      return (
          <Drawer.Navigator>
            <Drawer.Screen name="AppTab" component={AppTab} />
            <Drawer.Screen name="Notifications" component={NotificationsScreen} />
          </Drawer.Navigator>
      );}
</code>```

and my stack navigator to theme mix all:

```<code>const Stack = createStackNavigator();
  export default function MyStack() {
  return (
    <NavigationContainer>
    <Stack.Navigator
    headerMode="screen"
     screenOptions={{
          headerRight: ({ navigation }) => (<HeaderRight navigation={navigation} />
        ),}} >
      <Stack.Screen name="Settings" component={Settings} />
    </Stack.Navigator>
    </NavigationContainer>
  );
}
</code>```

when I press the right header icon

what I'm missing here?
the documents weren't really helpful

note:I have also try using dispatch but it didn't work:

navigation.dispatch(DrawerActions.toggleDrawer())

package.json:

```<code>{
  "name": "test",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-community/async-storage": "^1.8.0",
    "@react-native-community/masked-view": "^0.1.6",
    "@react-navigation/bottom-tabs": "^5.0.5",
    "@react-navigation/drawer": "^5.0.5",
    "@react-navigation/native": "^5.0.5",
    "@react-navigation/stack": "^5.0.5",
    "moment": "^2.24.0",
    "randomcolor": "^0.5.4",
    "react": "16.9.0",
    "react-native": "0.61.5",
    "react-native-base64": "0.0.2",
    "react-native-gesture-handler": "^1.6.0",
    "react-native-image-slider": "^2.0.3",
    "react-native-reanimated": "^1.7.0",
    "react-native-safe-area-context": "^0.7.3",
    "react-native-screens": "^2.0.0-beta.4",
    "react-native-woocommerce-api": "^1.0.12"
  },
  "devDependencies": {
    "@babel/core": "^7.6.2",
    "@babel/runtime": "^7.6.2",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-jest": "^24.9.0",
    "eslint": "^6.5.1",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.56.0",
    "react-test-renderer": "16.9.0"
  },
  "jest": {
    "preset": "react-native"
  }
}
</code>```

答:
Instead of toggleDrawer() use openDrawer()

STEPS

```<code>import { DrawerActions } from '@react-navigation/native';

navigation.dispatch(DrawerActions.openDrawer());
</code>```

If the above function not working try this:

```<code>this.props.navigation.openDrawer()
</code>```

UPDATE CODE

```<code>const HeaderRight = ({ navigation }) => {
  return (
    <View style={{ flexDirection: "row" }}>
      <TouchableOpacity
        onPress={() => {
          navigation.dispatch(DrawerActions.openDrawer());
        }}
      >
        <Image source={require("./assets/images/icons/drawer.png")} />
      </TouchableOpacity>
    </View>
  );
};
</code>```

Make sure you have imported the package before using

Title: React navigation drawer V5

Body:
I'm using react-navigation version 5.
I have tab navigation and drawer navigation together.

I'm trying to add an icon in my header to open/close drawer:

here is my custom right header for toggling the drawer:

const HeaderRight = ({ navigation }) => {
    return (
      <View style={{flexDirection: 'row'}}>
        <TouchableOpacity
        onPress={ () =>{ navigation.toggleDrawer()}}>  //here is the problem
          <Image source={require('./assets/images/icons/drawer.png')}/>
        </TouchableOpacity>
      </View>
    );}

this is my tab navigator:

const Tab = createBottomTabNavigator();
function AppTab() {
  return (
     <Tab.Navigator>
        <Tab.Screen name="Category" component={Category} />
        <Tab.Screen name="Home" component={Home}/>
      </Tab.Navigator>
   );}

drawer navigator:

    const Drawer = createDrawerNavigator();
    function App() {
      return (
          <Drawer.Navigator>
            <Drawer.Screen name="AppTab" component={AppTab} />
            <Drawer.Screen name="Notifications" component={NotificationsScreen} />
          </Drawer.Navigator>
      );}

and my stack navigator to theme mix all:

const Stack = createStackNavigator();
  export default function MyStack() {
  return (
    <NavigationContainer>
    <Stack.Navigator
    headerMode="screen"
     screenOptions={{
          headerRight: ({ navigation }) => (<HeaderRight navigation={navigation} />
        ),}} >
      <Stack.Screen name="Settings" component={Settings} />
    </Stack.Navigator>
    </NavigationContainer>
  );
}

when I press the right header icon

what I'm missing here?
the documents weren't really helpful

note:I have also try using dispatch but it didn't work:

navigation.dispatch(DrawerActions.toggleDrawer())

package.json:

{
  "name": "test",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-community/async-storage": "^1.8.0",
    "@react-native-community/masked-view": "^0.1.6",
    "@react-navigation/bottom-tabs": "^5.0.5",
    "@react-navigation/drawer": "^5.0.5",
    "@react-navigation/native": "^5.0.5",
    "@react-navigation/stack": "^5.0.5",
    "moment": "^2.24.0",
    "randomcolor": "^0.5.4",
    "react": "16.9.0",
    "react-native": "0.61.5",
    "react-native-base64": "0.0.2",
    "react-native-gesture-handler": "^1.6.0",
    "react-native-image-slider": "^2.0.3",
    "react-native-reanimated": "^1.7.0",
    "react-native-safe-area-context": "^0.7.3",
    "react-native-screens": "^2.0.0-beta.4",
    "react-native-woocommerce-api": "^1.0.12"
  },
  "devDependencies": {
    "@babel/core": "^7.6.2",
    "@babel/runtime": "^7.6.2",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-jest": "^24.9.0",
    "eslint": "^6.5.1",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.56.0",
    "react-test-renderer": "16.9.0"
  },
  "jest": {
    "preset": "react-native"
  }
}

Body:
Instead of toggleDrawer() use openDrawer()

STEPS

import { DrawerActions } from '@react-navigation/native';

navigation.dispatch(DrawerActions.openDrawer());

If the above function not working try this:

this.props.navigation.openDrawer()

UPDATE CODE

const HeaderRight = ({ navigation }) => {
  return (
    <View style={{ flexDirection: "row" }}>
      <TouchableOpacity
        onPress={() => {
          navigation.dispatch(DrawerActions.openDrawer());
        }}
      >
        <Image source={require("./assets/images/icons/drawer.png")} />
      </TouchableOpacity>
    </View>
  );
};

Make sure you have imported the package before using


问:
Kendo scrollview(angular) next/prev methods use
I am using kendo scrollview (angular) in my angular project, but I am not able to call next prev method provided by kendo.

Is there anyone who used it, and provide information for the same.

ANy example appreciated.

答:
Use itemChanged event as below

```<code><kendo-scrollview (itemChanged)="onItemChange($event)">

onItemChange(event) {
 console.log('onitemchage', event)
}
</code>```

Result : {index: 1, item: {title: '', url: ''}}

Body:
Use itemChanged event as below

<kendo-scrollview (itemChanged)="onItemChange($event)">

onItemChange(event) {
 console.log('onitemchage', event)
}

Result : {index: 1, item: {title: '', url: ''}}


问:
Error:Execution failed for task 'app:generateDebugBuildConfig'
Error:Execution failed for task 'app:generateDebugBuildConfig'

java.io.FileNotFoundException: C:\Users\bok\Desktop\Zipzap\app\build\generated\source\buildConfig\debug\com\storie\myapp \BuildConfig.java (Le chemin d’accès spécifié est introuvable)

What's the solution ..

I hope to find a solution to this problem

答:
Try to clean project this is working for me

for android

```<code>$ cd android

$ ./gradlew clean

BUILD SUCCESSFUL in 5s
1 actionable task: 1 executed
</code>```

Body:
Try to clean project this is working for me

for android

$ cd android

$ ./gradlew clean

BUILD SUCCESSFUL in 5s
1 actionable task: 1 executed


问:
How to print key and values from the following collection?
I have the following collection that holds a dictionary:

```<code> {'EHAM': [78, [55, 23]], 'EGLL': [67, [46, 21]], 'LOWW': [67, [44, 23]], 'LFPG': [75, [43, 32]]}
</code>```

I'd like to print the collection in the following output data format:

```<code> NAME    #TOTAL     #TK     #LA
 EHAM    78         55      23
 EGLL    67         46      21
 LOWW    67         44      23
 LFPG    75         43      32
</code>```

Right now I'm getting the following ouput:

```<code>#NAME #TOTAL #TK #LA
 EHAM [78, [55, 23]]
 EGLL [67, [46, 21]]
 LOWW [67, [44, 23]]
 LFPG [75, [43, 32]]
</code>```

This is the piece of code I'm using:

```<code>#print(topAirpots_dict)
print("\n#NAME"+ " #TOTAL"+ " #TK"+ " #LA\n")
for k in (top_dict):
    print(k,top_dict[k])
</code>```

答:
Might not be the most performant way but gives the wanted output:

```<code>print("\nNAME"+ " \t#TOTAL"+ " \t#TK"+ " \t#LA\n")
for k in (top_dict):
    first_val = top_dict[k][0]
    sec_val = top_dict[k][1][0]
    third_val = top_dict[k][1][1]
    print(k , " \t" , first_val , " \t" , sec_val , " \t" , third_val)
</code>```

or faster but a bit harder to read:

```<code>print("\nNAME"+ " \t#TOTAL"+ " \t#TK"+ " \t#LA\n")
for k in (top_dict):
    print(k , " \t" , top_dict[k][0], " \t" , top_dict[k][1][0], " \t" , top_dict[k][1][1])
</code>```

Body:
I have the following collection that holds a dictionary:

 {'EHAM': [78, [55, 23]], 'EGLL': [67, [46, 21]], 'LOWW': [67, [44, 23]], 'LFPG': [75, [43, 32]]}

I'd like to print the collection in the following output data format:

 NAME    #TOTAL     #TK     #LA
 EHAM    78         55      23
 EGLL    67         46      21
 LOWW    67         44      23
 LFPG    75         43      32

Right now I'm getting the following ouput:

#NAME #TOTAL #TK #LA
 EHAM [78, [55, 23]]
 EGLL [67, [46, 21]]
 LOWW [67, [44, 23]]
 LFPG [75, [43, 32]]

This is the piece of code I'm using:

#print(topAirpots_dict)
print("\n#NAME"+ " #TOTAL"+ " #TK"+ " #LA\n")
for k in (top_dict):
    print(k,top_dict[k])

Body:
Might not be the most performant way but gives the wanted output:

print("\nNAME"+ " \t#TOTAL"+ " \t#TK"+ " \t#LA\n")
for k in (top_dict):
    first_val = top_dict[k][0]
    sec_val = top_dict[k][1][0]
    third_val = top_dict[k][1][1]
    print(k , " \t" , first_val , " \t" , sec_val , " \t" , third_val)

or faster but a bit harder to read:

print("\nNAME"+ " \t#TOTAL"+ " \t#TK"+ " \t#LA\n")
for k in (top_dict):
    print(k , " \t" , top_dict[k][0], " \t" , top_dict[k][1][0], " \t" , top_dict[k][1][1])


问:
Compile Xamarin iOS
I'm at loss with Xamarin and cross-platform development.
We've been developing an app for Android and iOS and we've been testing Android no problem but we have issues trying to test anything for iOS.
We've created VM of MacOS Catalina (I know I know - legal things with running Mac OSX on non-apple machine), installed Xcode and Visual Studio for Mac but we still cannot run any kind of simulations or compile any sort of apk file to test on a physical phone.
We are not developing this to be published on Apple Store, the client wants an app in a closed environment and only needs some apk file.

So, my very frustrated question is how can we test and compile iOS app?
Is it possible to do so without trying to publish to Apple Store?
Is it enough to get the provisioning license and certificates for out client and to archive the app? (that is the last hurrah that we hope for)

Thank you very much.

答:
To run on a device you need a provisioning certificate linked to the app ID you're developing. This does not mean you HAVE to publish the app to the app store, you can publish Ad Hoc builds and use the app in closed environments, but is limited to 100 devices. Additionally, you can enroll as a developer to the enterprise program and not use the app store at all, but release to an enterprise with no device limits.

Ad Hoc Distribution Authorizes a Limited Set of Devices to Run Your App

iOS developers enrolled in the Standard Program can also
  distribute an app outside of the App Store on up to 100 different
  devices for testing purposes only. To use ad hoc distribution, create
  an archive of your app, or have a teammate send you an iOS App Store
  Package (.ipa) of the archived app.

You distribute your app by providing the .ipa file for users to
  install on their devices. Because you select a valid ad hoc
  provisioning profile to archive the app, users don’t need to install
  the profile on their device, only the .ipa file. Users can use iTunes
  to install the app on their devices. If users want to use Xcode to
  install the app on their device, share the archive as an .xcarchive
  file package.

In-House Distribution Allows Companies to Distribute Apps Internally

iOS developers enrolled in the Enterprise Program can distribute
  in-house without identifying individual devices or using the App
  Store. To distribute your app in-house, create an archive of your app,
  or have a teammate send you an archived app. Distribute your internal
  app using your company’s authorized software distribution mechanism.
  Because the app file can be installed on any iOS device, make sure you
  protect the distribution of this file. Members of your company can use
  iTunes, iPhone Configuration Utility, or Xcode to install the app on
  their devices.

Title: Compile Xamarin iOS


问:
How can I monitor objective-c method return value changes
I'm using Sparkle http://sparkle-project.org/ framework for autoupdates in my application. I have a UI item which enables/disables automatic updates downloads, but I can use neither Interface Builder bindings as stated in documentation for Sparkle, nor KVO, because there is no property for automatic updates download - only getter and setter methods. Can I hook the setter method and have a callback invoked when this option changes through Sparkle's interface interaction.

What can I do in this situation?

Thank you.

答:
Why do you need to monitor these changes? The most application I know check for updates on startup only and not during runtime. So you would check and update or just continue with the application.

If there is no other way a timer (NSTimer) will always work to check things periodically.


问:
How to get the full dates between two dates using javascript / react?
My requirement is to get the number of days between two dates.

For example, the start date is 02/20/2020 to 01/03/2020 I would like to display the results like

Feb 20 Thursday, Feb 21 Friday,....01 Mar Monday.

I went through this scenario in StackOverflow but I didn't get the expected solution for the same.

Could anyone please guide in achieving this scenario using javascript or react?

答:
You may calculate the difference between dates, than make up desired array of dates casted to date string of necessary format:

const d1 = new Date('02/20/2020'),
      d2 = new Date('03/01/2020'),
      diff = (d2-d1)/864e5,
      dateFormat = {weekday:'long',month:'short',day:'numeric'},
      dates = Array.from(
        {length: diff+1},
        (_,i) => {
          const date = new Date()
          date.setDate(d1.getDate()+i)
          const [weekdayStr, dateStr] = date.toLocaleDateString('en-US',dateFormat).split(', ')
          return `${dateStr} ${weekdayStr}`
        }
      )

console.log(dates)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {min-height:100%;}</code>```

Or, as long as we're having fun here :) following is React implementation:

const { render } = ReactDOM,
      { useState } = React

const DatePicker = ({min,max,onPick,role}) => (
  <input
    type="date"
    onChange={onPick}
    {...{min,max}}
  />
)

const ListOfDates = ({startDate,endDate}) => {
    const d1 = new Date(startDate),
          d2 = new Date(endDate),
          diff = (d2-d1)/864e5,
          dateFormat = {weekday:'long',month:'short',day:'numeric'},
          dates = Array.from(
            {length: diff+1},
            (_,i) => {
              const date = new Date()
              date.setDate(d1.getDate()+i)
              const [weekdayStr, dateStr] = date.toLocaleDateString('en-US',dateFormat).split(', ')
              return `${dateStr} ${weekdayStr}`
            }
          )
     return (

          {dates.map((date,key) =>
{date}
)}

     )
}

const App = () => {
  const [start, setStart] = useState(''),
        [end, setEnd] = useState(''),
        onPickStart = ({target:{value}}) => setStart(value),
        onPickEnd = ({target:{value}}) => setEnd(value)
  return (

      <DatePicker max={end} onPick={onPickStart} />
      <DatePicker min={start} onPick={onPickEnd} />
      <ListOfDates startDate={start} endDate={end} />

  )

}

render (
  <App />,
  document.getElementById('root')
)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div></code>```

...and jQuery one:

$(document).ready(() => {
  $('.datepick').on('change', function(){
    $(this).attr('id') == 'startDate' ?
    $('#endDate').attr('min', $(this).val()) :
    $('#startDate').attr('max', $(this).val())
    if($('#startDate').length && $('#endDate').length) {
      const d1 = new Date($('#startDate').val()),
            d2 = new Date($('#endDate').val()),
            diff = (d2-d1)/864e5,
            dateFormat = {weekday:'long',month:'short',day:'numeric'},
            dates = Array.from(
              {length: diff+1},
              (_,i) => {
                const date = new Date()
                date.setDate(d1.getDate()+i)
                const [weekdayStr, dateStr] = date.toLocaleDateString('en-US',dateFormat).split(', ')
                return `${dateStr} ${weekdayStr}`
              }
            ),
            dateListItems = dates.map(d => `<li>${d}</li>`)
      $('#dateList').html(dateListItems)
    }
  })

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Start Date: <input id="startDate" type="date" class="datepick"></input></label>
<label>End Date: <input id="endDate" type="date" class="datepick"></input></label>
<ul id="dateList"></ul></code>```

Body:
You may calculate the difference between dates, than make up desired array of dates casted to date string of necessary format:

const d1 = new Date('02/20/2020'),
      d2 = new Date('03/01/2020'),
      diff = (d2-d1)/864e5,
      dateFormat = {weekday:'long',month:'short',day:'numeric'},
      dates = Array.from(
        {length: diff+1},
        (_,i) => {
          const date = new Date()
          date.setDate(d1.getDate()+i)
          const [weekdayStr, dateStr] = date.toLocaleDateString('en-US',dateFormat).split(', ')
          return `${dateStr} ${weekdayStr}`
        }
      )

console.log(dates)

.as-console-wrapper {min-height:100%;}

Or, as long as we're having fun here :) following is React implementation:

const { render } = ReactDOM,
      { useState } = React

const DatePicker = ({min,max,onPick,role}) => (
  <input
    type="date"
    onChange={onPick}
    {...{min,max}}
  />
)

const ListOfDates = ({startDate,endDate}) => {
    const d1 = new Date(startDate),
          d2 = new Date(endDate),
          diff = (d2-d1)/864e5,
          dateFormat = {weekday:'long',month:'short',day:'numeric'},
          dates = Array.from(
            {length: diff+1},
            (_,i) => {
              const date = new Date()
              date.setDate(d1.getDate()+i)
              const [weekdayStr, dateStr] = date.toLocaleDateString('en-US',dateFormat).split(', ')
              return `${dateStr} ${weekdayStr}`
            }
          )
     return (
        <ul>
          {dates.map((date,key) => <li {...{key}}>{date}</li>)}
        </ul>
     )
}

const App = () => {
  const [start, setStart] = useState(''),
        [end, setEnd] = useState(''),
        onPickStart = ({target:{value}}) => setStart(value),
        onPickEnd = ({target:{value}}) => setEnd(value)
  return (
    <div>
      <DatePicker max={end} onPick={onPickStart} />
      <DatePicker min={start} onPick={onPickEnd} />
      <ListOfDates startDate={start} endDate={end} />
    </div>
  )

}

render (
  <App />,
  document.getElementById('root')
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>

...and jQuery one:

$(document).ready(() => {
  $('.datepick').on('change', function(){
    $(this).attr('id') == 'startDate' ?
    $('#endDate').attr('min', $(this).val()) :
    $('#startDate').attr('max', $(this).val())
    if($('#startDate').length && $('#endDate').length) {
      const d1 = new Date($('#startDate').val()),
            d2 = new Date($('#endDate').val()),
            diff = (d2-d1)/864e5,
            dateFormat = {weekday:'long',month:'short',day:'numeric'},
            dates = Array.from(
              {length: diff+1},
              (_,i) => {
                const date = new Date()
                date.setDate(d1.getDate()+i)
                const [weekdayStr, dateStr] = date.toLocaleDateString('en-US',dateFormat).split(', ')
                return `${dateStr} ${weekdayStr}`
              }
            ),
            dateListItems = dates.map(d => `<li>${d}</li>`)
      $('#dateList').html(dateListItems)
    }
  })

})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Start Date: <input id="startDate" type="date" class="datepick"></input></label>
<label>End Date: <input id="endDate" type="date" class="datepick"></input></label>
<ul id="dateList"></ul>


问:
Beautifulsoup not finding the tag
im working on a project on beautifulsoup

```<code>from bs4 import BeautifulSoup as soup
from requests import get

url = "https://www.yelp.com/search?find_desc=&find_loc=New+York%2C+NY&ns=1"
clnt = get(url)
page=soup(clnt.text,"html.parser")
container = page.findAll("div",{"class":"lemon--div__373c0__1mboc container__373c0__ZB8u4 hoverable__373c0__3CcYQ margin-t3__373c0__1l90z margin-b3__373c0__q1DuY padding-t3__373c0__1gw9E padding-r3__373c0__57InZ padding-b3__373c0__342DA padding-l3__373c0__1scQ0 border--top__373c0__3gXLy border--right__373c0__1n3Iv border--bottom__373c0__3qNtD border--left__373c0__d1B7K border-color--default__373c0__3-ifU"})

container = container[1]
url2= "https://www.yelp.com"+container.a["href"]
clnt2 = get(url2)
page2 = soup(clnt2.text, 'html.parser')

info = page2.find("div",{"class":"lemon--div__373c0__1mboc island__373c0__3fs6U u-padding-t1 u-padding-r1 u-padding-b1 u-padding-l1 border--top__373c0__19Owr border--right__373c0__22AHO border--bottom__373c0__uPbXS border--left__373c0__1SjJs border-color--default__373c0__2oFDT background-color--white__373c0__GVEnp"})

contact=info.div (Example contact variable)
</code>```

In this "info" variable i am getting the div which has all the contact details, I want to grab the Contact number form this div

And as I print this "info" variable it also shows that contact no. is present in the variable including other details but as I traverse through the div's to get the Contact No. I couldn't find it.
I have also tried to get all the child div's and even including the class of the div itself I wasn't able to get that

First url given is this  :https://www.yelp.com/search?find_desc=&find_loc=New+York%2C+NY&ns=1

Second url "url2" is this : https://www.yelp.com/biz/levain-bakery-new-york Which has the Contact details

Any Solutions ???

答:
The following works for me:

```<code>from bs4 import BeautifulSoup as soup
from requests import get

url = "https://www.yelp.com/search?find_desc=&find_loc=New+York%2C+NY&ns=1"
clnt = get(url)
page=soup(clnt.text,"html.parser")
container = page.findAll("div",{"class":"lemon--div__373c0__1mboc container__373c0__ZB8u4 hoverable__373c0__3CcYQ margin-t3__373c0__1l90z margin-b3__373c0__q1DuY padding-t3__373c0__1gw9E padding-r3__373c0__57InZ padding-b3__373c0__342DA padding-l3__373c0__1scQ0 border--top__373c0__3gXLy border--right__373c0__1n3Iv border--bottom__373c0__3qNtD border--left__373c0__d1B7K border-color--default__373c0__3-ifU"})

container = container[1]
url2= "https://www.yelp.com"+container.a["href"]
clnt2 = get(url2)
page2 = soup(clnt2.text, 'html.parser')

info = page2.find("div",{"class":"lemon--div__373c0__1mboc island__373c0__3fs6U u-padding-t1 u-padding-r1 u-padding-b1 u-padding-l1 border--top__373c0__19Owr border--right__373c0__22AHO border--bottom__373c0__uPbXS border--left__373c0__1SjJs border-color--default__373c0__2oFDT background-color--white__373c0__GVEnp"})

p_tags_of_info = info.find_all("p")
print(p_tags_of_info[2].text)
</code>```

I just extracted all the
 tags from the info variable, and then selected the text of the third
 tag.

Title: Beautifulsoup not finding the tag

Body:
im working on a project on beautifulsoup

from bs4 import BeautifulSoup as soup
from requests import get

url = "https://www.yelp.com/search?find_desc=&find_loc=New+York%2C+NY&ns=1"
clnt = get(url)
page=soup(clnt.text,"html.parser")
container = page.findAll("div",{"class":"lemon--div__373c0__1mboc container__373c0__ZB8u4 hoverable__373c0__3CcYQ margin-t3__373c0__1l90z margin-b3__373c0__q1DuY padding-t3__373c0__1gw9E padding-r3__373c0__57InZ padding-b3__373c0__342DA padding-l3__373c0__1scQ0 border--top__373c0__3gXLy border--right__373c0__1n3Iv border--bottom__373c0__3qNtD border--left__373c0__d1B7K border-color--default__373c0__3-ifU"})

container = container[1]
url2= "https://www.yelp.com"+container.a["href"]
clnt2 = get(url2)
page2 = soup(clnt2.text, 'html.parser')

info = page2.find("div",{"class":"lemon--div__373c0__1mboc island__373c0__3fs6U u-padding-t1 u-padding-r1 u-padding-b1 u-padding-l1 border--top__373c0__19Owr border--right__373c0__22AHO border--bottom__373c0__uPbXS border--left__373c0__1SjJs border-color--default__373c0__2oFDT background-color--white__373c0__GVEnp"})

contact=info.div (Example contact variable)

In this "info" variable i am getting the div which has all the contact details, I want to grab the Contact number form this div

And as I print this "info" variable it also shows that contact no. is present in the variable including other details but as I traverse through the div's to get the Contact No. I couldn't find it.
I have also tried to get all the child div's and even including the class of the div itself I wasn't able to get that

First url given is this  :https://www.yelp.com/search?find_desc=&find_loc=New+York%2C+NY&ns=1

Second url "url2" is this : https://www.yelp.com/biz/levain-bakery-new-york Which has the Contact details

Any Solutions ???

Body:
The following works for me:

from bs4 import BeautifulSoup as soup
from requests import get

url = "https://www.yelp.com/search?find_desc=&find_loc=New+York%2C+NY&ns=1"
clnt = get(url)
page=soup(clnt.text,"html.parser")
container = page.findAll("div",{"class":"lemon--div__373c0__1mboc container__373c0__ZB8u4 hoverable__373c0__3CcYQ margin-t3__373c0__1l90z margin-b3__373c0__q1DuY padding-t3__373c0__1gw9E padding-r3__373c0__57InZ padding-b3__373c0__342DA padding-l3__373c0__1scQ0 border--top__373c0__3gXLy border--right__373c0__1n3Iv border--bottom__373c0__3qNtD border--left__373c0__d1B7K border-color--default__373c0__3-ifU"})

container = container[1]
url2= "https://www.yelp.com"+container.a["href"]
clnt2 = get(url2)
page2 = soup(clnt2.text, 'html.parser')

info = page2.find("div",{"class":"lemon--div__373c0__1mboc island__373c0__3fs6U u-padding-t1 u-padding-r1 u-padding-b1 u-padding-l1 border--top__373c0__19Owr border--right__373c0__22AHO border--bottom__373c0__uPbXS border--left__373c0__1SjJs border-color--default__373c0__2oFDT background-color--white__373c0__GVEnp"})

p_tags_of_info = info.find_all("p")
print(p_tags_of_info[2].text)

I just extracted all the <p> tags from the info variable, and then selected the text of the third <p> tag.


问:
table attributes are not correct with bootstrap
I created a table using the bootstrap table , but the fields are not correct
How can i fix them ?
Only the first one is correct

答:
"""<ngb-tab>
      <ng-template ngbTabTitle>
        Jahresplanung
      </ng-template>
      <ng-template ngbTabContent>

                        #

                    AT

                          EPL Pakete pm
                         ...

                            EPL DF
                            ...

                            EPL Stopps pm
                            ...

                            EPL Pakete pd

                            ...

                            EPL Stopps pm

                          ...

                            APL Pakete pm
                            <input size="3">
                            ...

                            APL KDF
                            <input size="3">
                            ...

                            APL Stopps pm
                           ...

                            APL Pakete pd

                            ...

                            APL Stopps pm
                           ...

                            Fahrzeuge
                            ...
                            <input size="3">

                            EPL Pakete pro FZG

                            ...

                            EPL Stopps pro FZG

                            ...

                            APL Pakete pro FZG

                           ...

                            APL Stopps pro FZG

                          ...

      </ng-template>
    </ngb-tab>```

Body:
"""<ngb-tab>
      <ng-template ngbTabTitle>
        <span jhiTranslate="mainPage.yearPlan">Jahresplanung</span>
      </ng-template>
      <ng-template ngbTabContent>
          <table class="table table-striped table-responsive" aria-hidden="true">
              <thead>
                    <tr>
                        <th class="yearPlan">#</th>
                        <th class="yearPlan" jhiTranslate="yearPlan.april"></th>
                        <th class="yearPlan" jhiTranslate="yearPlan.mai"></th>
                        <th class="yearPlan" jhiTranslate="yearPlan.june"></th>
                        <th class="yearPlan" jhiTranslate="yearPlan.july"></th>
                        <th class="yearPlan" jhiTranslate="yearPlan.august"></th>
                        <th class="yearPlan" jhiTranslate="yearPlan.september"></th>
                        <th class="yearPlan" jhiTranslate="yearPlan.october"></th>
                        <th class="yearPlan" jhiTranslate="yearPlan.november"></th>
                        <th class="yearPlan" jhiTranslate="yearPlan.december"></th>
                        <th class="yearPlan" jhiTranslate="yearPlan.january"></th>
                        <th class="yearPlan" jhiTranslate="yearPlan.february"></th>
                        <th class="yearPlan" jhiTranslate="yearPlan.march"></th>
                        <th class="yearPlan" jhiTranslate="yearPlan.average"></th>
                    </tr>
              </thead>
              <tbody>
                <tr>
                    <th class="yearPlan">AT</th>
                </tr>
                <br>
                <tr>
                          <th class="yearPlan">EPL Pakete pm</th>
                         ...
                          <th><p></p></th>
                      </tr>
                      <tr>
                            <th class="yearPlan">EPL DF</th>
                            ...
                            <th><p></p></th>
                        </tr>
                        <tr>
                            <th>EPL Stopps pm</th>
                            ...
                            <th><p></p></th>
                        </tr>
                        <tr>
                            <th>EPL Pakete pd</th>
                            <th><p></p></th>
                            ...
                        </tr>
                        <tr>
                            <th>EPL Stopps pm</th>
                            <th><p></p></th>
                          ...
                        </tr>
                        <tr>
                            <th></th>
                        </tr>
                        <tr>
                            <th>APL Pakete pm</th>
                            <th><input size="3"></th>
                            ...
                            <th><p></p></th>
                        </tr>
                        <tr>
                            <th>APL KDF</th>
                            <th><input size="3"></th>
                            ...
                            <th><p></p></th>
                        </tr>
                        <tr>
                            <th>APL Stopps pm</th>
                           ...
                        </tr>
                        <tr>
                            <th>APL Pakete pd</th>
                            <th><p></p></th>
                            ...
                            <th><p></p></th>
                        </tr>
                        <tr>
                            <th>APL Stopps pm</th>
                           ...
                        </tr>
                        <tr>
                            <th></th>
                        </tr>
                        <tr>
                            <th>Fahrzeuge</th>
                            ...
                            <th><input size="3"></th>
                            <th><p></p></th>
                        </tr>
                        <tr>
                            <th></th>
                        </tr>
                        <tr>
                            <th>EPL Pakete pro FZG</th>
                            <th><p></p></th>
                            ...
                        </tr>
                        <tr>
                            <th>EPL Stopps pro FZG</th>
                            <th><p></p></th>
                            <th><p></p></th>
                            ...
                        </tr>
                        <tr>
                            <th>APL Pakete pro FZG</th>
                            <th><p></p></th>
                           ...
                        </tr>
                        <tr>
                            <th>APL Stopps pro FZG</th>
                            <th><p></p></th>
                            <th><p></p></th>
                          ...
                        </tr>
                        <tr>
                            <th></th>
                        </tr>
                        </tbody>
                </table>
      </ng-template>
    </ngb-tab>