问:
How to check if array contains more than one element?
I would like to ensure that an array contains more then one element and that it is not null nor undefined. With other words: I am looking for an alternative to

```<code>if(array && array.length > 1)
</code>```

that would be better to read.

Lodash provides a method for checking if an array contains at least one element:

```<code>if(_.some(array))
</code>```

Is there a similar method for checking for several elements?

Unfortunately following methods do not exist:

```<code>if(_.several(array))

if(_.many(array))
</code>```

Would I have to write my own extension method or did I just not find the right lodash command, yet?

答:
This is the atLeast() function, which works like _.some(), but accepts a min number. If the callback returns true a number of times that is identical to min, the function will return true.

 // the parameters order is to maintain compatability with lodash. A more functional order would be - cb, min, arr
function atLeast(arr, min, cb) {
  cb = cb || _.identity; // default is like some

  var counter = 0;
  return _.some(arr, function(v) {
    cb(v) && counter++;

    return counter === min;
  });
}

_.mixin({ 'atLeast': atLeast });

var arr1 = [1, 0, null, undefined];
var arr2 = [null, undefined, 0];

var isNotNil = _.negate(_.isNil); // not null or undefined

console.log(_.atLeast(arr1, 2, isNotNil));

console.log(_.atLeast(arr2, 2, isNotNil));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

Body:
I would like to ensure that an array contains more then one element and that it is not null nor undefined. With other words: I am looking for an alternative to

if(array && array.length > 1)

that would be better to read.

Lodash provides a method for checking if an array contains at least one element:

if(_.some(array))

Is there a similar method for checking for several elements?

Unfortunately following methods do not exist:

if(_.several(array))

if(_.many(array))

Would I have to write my own extension method or did I just not find the right lodash command, yet?

Body:
This is the atLeast() function, which works like _.some(), but accepts a min number. If the callback returns true a number of times that is identical to min, the function will return true.

 // the parameters order is to maintain compatability with lodash. A more functional order would be - cb, min, arr
function atLeast(arr, min, cb) {
  cb = cb || _.identity; // default is like some

  var counter = 0;
  return _.some(arr, function(v) {
    cb(v) && counter++;

    return counter === min;
  });
}

_.mixin({ 'atLeast': atLeast });

var arr1 = [1, 0, null, undefined];
var arr2 = [null, undefined, 0];

var isNotNil = _.negate(_.isNil); // not null or undefined

console.log(_.atLeast(arr1, 2, isNotNil));

console.log(_.atLeast(arr2, 2, isNotNil));

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


来源: stackexchange

问:
Vehicles are missing in default CryEngine 5 installation
I installed CryEngine 5 from an official site. Now I want to add a vehicle to a level.

As described in Beginners manual, I need to

open the Create Object tool, go to Entity and expand Vehicles in the list that appears in the bottom of the tool.

However, there is no Vehicles item:

How to add DefaultVehicle into my level?

答:
I guess you are using one of the many templates from the Cryengine launcher. In those templates you have almost nothing, so you would have to implement them by yourself.

Here you can find some useful resource to register a new vehicle entity

Vehicle System overview

Vehicle Setup Tutorial

XML Setup Guide

And here you can find a small guide on vehicle modelling and setup.

But if you want just start using a vehicle without having to implement it from scratch, I suggest you to download and use the CRYENGINE GameSDK Sample Project that comes with some cool stuff, such as different categories of vehicles, particles, objects and an actual player.

Please note that these guides from the official documentation were developed for CryEngine 3.X but they should work also for CryEngine 5.X

I hope I helped you :)

ContentLicense: CC BY-SA 3.0


问:
Custom error message json object with flask-restful
It is easy to propagate error messages with flask-restful to the client with the abort() method, such as

```<code>abort(500, message="Fatal error: Pizza the Hutt was found dead earlier today
in the back seat of his stretched limo. Evidently, the notorious gangster
became locked in his car and ate himself to death.")
</code>```

This will generate the following json output

```<code>{
  "message": "Fatal error: Pizza the Hutt was found dead earlier today
       in the back seat of his stretched limo. Evidently, the notorious gangster
       became locked in his car and ate himself to death.",
  "status": 500
}
</code>```

Is there a way to customise the json output with additional members? For example:

```<code>{
  "sub_code": 42,
  "action": "redirect:#/Outer/Space"
  "message": "You idiots! These are not them! You've captured their stunt doubles!",
  "status": 500
}
</code>```

答:
As @Miguel explains, normally you shouldn't use exceptions, just return some error response. However, sometimes you really need an abort mechanism that raises an exception. This may be useful in filter methods, for example. Note that flask.abort accepts a Response object (check this gist):</p>
```<code>from flask import abort, make_response, jsonify

json = jsonify(message="Message goes here")
response = make_response(json, 400)
abort(response)
</code>```

Body:
It is easy to propagate error messages with flask-restful to the client with the abort() method, such as

abort(500, message="Fatal error: Pizza the Hutt was found dead earlier today
in the back seat of his stretched limo. Evidently, the notorious gangster
became locked in his car and ate himself to death.")

This will generate the following json output

{
  "message": "Fatal error: Pizza the Hutt was found dead earlier today
       in the back seat of his stretched limo. Evidently, the notorious gangster
       became locked in his car and ate himself to death.",
  "status": 500
}

Is there a way to customise the json output with additional members? For example:

{
  "sub_code": 42,
  "action": "redirect:#/Outer/Space"
  "message": "You idiots! These are not them! You've captured their stunt doubles!",
  "status": 500
}

Body:
As @Miguel explains, normally you shouldn't use exceptions, just return some error response. However, sometimes you really need an abort mechanism that raises an exception. This may be useful in filter methods, for example. Note that flask.abort accepts a Response object (check this gist):

from flask import abort, make_response, jsonify

json = jsonify(message="Message goes here")
response = make_response(json, 400)
abort(response)

ContentLicense: CC BY-SA 4.0


问:
When to use Ajax vs Json for Javascript events?
I'm not so familiar with Ajax but I keep hearing Json mentioned as some kind of competing option. Is there a rule for when to use one versus the other?

I'd like to process Javascript events in my app and update the front-end dynamically from the app but I'm not sure whether I need to use Ajax or Json for this.

答:
The above answers are correct, but If you are new to using web technologies, all you need to know is simply
that Ajax is a subset of JavaScript.
It is a technology, a means for you to send only portion of the web page data back to the server to get processed
and get the response back while the user is interacting with other parts of the page.  This way, the
Interaction with the page is consistent and  seemless from the user stand point.   Now, JSON on the other hand is
the how you can format the data (similar to XML) that you are sending back to the server, and getting back.
and it's used primarily with Ajax.  It was developed and used mainly
because it is lightweight and human readable,  which makes it more efficient and user friendly.
Hope that helps a bit.</p>

ContentLicense: CC BY-SA 2.5


问:
How to count function calls using decorators?
I'm refreshing my memory about some python features that I didn't get yet, I'm learning from this python tutorial and there's an example that I don't fully understand. It's about a decorator counting calls to a function, here's the code:

```<code>def call_counter(func):
    def helper(x):
        helper.calls += 1
        return func(x)
    helper.calls = 0
    return helper

@call_counter
def succ(x):
    return x + 1

if __name__ == '__main__':
    print(succ.calls)
    for i in range(10):
        print(succ(i))
    print(succ.calls)
</code>```

What I don't get here is why do we increment the calls of the function wrapper (helper.calls += 1) instead of the function calls itself, and why does it actually working?

答:
What I don't get here is why do we increment the calls of the function wrapper (helper.calls += 1) instead of the function calls itself, and why does it actually working?

I think to make it a generically useful decorator. You could do this

```<code>def succ(x):
    succ.calls += 1
    return x + 1

if __name__ == '__main__':
    succ.calls = 0
    print(succ.calls)
    for i in range(10):
        print(succ(i))
    print(succ.calls)
</code>```

which works just fine, but you would need to put the .calls +=1 in every function you wanted to apply this too, and initialise to 0 before you ran any of them. If you had a whole bunch of functions you wanted to count this is definitely nicer. Plus it initialises them to 0 at definition, which is nice.

As i understand it it works because it replaces the function succ with the helper function from within the decorator (which is redefined every time it decorates a function) so succ = helper and succ.calls = helper.calls. (although of course the name helper is only definied within the namespace of the decorator)

Does that make sense?

Body:
I'm refreshing my memory about some python features that I didn't get yet, I'm learning from this python tutorial and there's an example that I don't fully understand. It's about a decorator counting calls to a function, here's the code:

def call_counter(func):
    def helper(x):
        helper.calls += 1
        return func(x)
    helper.calls = 0
    return helper

@call_counter
def succ(x):
    return x + 1

if __name__ == '__main__':
    print(succ.calls)
    for i in range(10):
        print(succ(i))
    print(succ.calls)

What I don't get here is why do we increment the calls of the function wrapper (helper.calls += 1) instead of the function calls itself, and why does it actually working?

Body:
What I don't get here is why do we increment the calls of the function wrapper (helper.calls += 1) instead of the function calls itself, and why does it actually working?

I think to make it a generically useful decorator. You could do this

def succ(x):
    succ.calls += 1
    return x + 1

if __name__ == '__main__':
    succ.calls = 0
    print(succ.calls)
    for i in range(10):
        print(succ(i))
    print(succ.calls)

which works just fine, but you would need to put the .calls +=1 in every function you wanted to apply this too, and initialise to 0 before you ran any of them. If you had a whole bunch of functions you wanted to count this is definitely nicer. Plus it initialises them to 0 at definition, which is nice.

As i understand it it works because it replaces the function succ with the helper function from within the decorator (which is redefined every time it decorates a function) so succ = helper and succ.calls = helper.calls. (although of course the name helper is only definied within the namespace of the decorator)

Does that make sense?


问:
Why does this sql query not work in pdo?
i'm trying to retrieve info from my database using PDO.

The code i'm using is

```<code>$input = $_GET['input'];

$inputvalue = $_GET['inputvalue'];

$db = DB::get_instance();
$query = $db->prepare('SELECT * FROM hwidex7 WHERE :input=:inputvalue');
$query->bindParam(':inputvalue', $inputvalue);
$query->bindParam(':input', $input);
$query->execute();
</code>```

答:
You can't bind table or column as parameter in PDO

You can build your query as

```<code>$query = $db->prepare("SELECT * FROM hwidex7 WHERE `$input` =:inputvalue");
$query->bindParam(':inputvalue', $inputvalue);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
print_r($result);
</code>```

Body:
i'm trying to retrieve info from my database using PDO.

The code i'm using is

$input = $_GET['input'];

$inputvalue = $_GET['inputvalue'];

$db = DB::get_instance();
$query = $db->prepare('SELECT * FROM hwidex7 WHERE :input=:inputvalue');
$query->bindParam(':inputvalue', $inputvalue);
$query->bindParam(':input', $input);
$query->execute();

Body:
You can't bind table or column as parameter in PDO

You can build your query as

$query = $db->prepare("SELECT * FROM hwidex7 WHERE `$input` =:inputvalue");
$query->bindParam(':inputvalue', $inputvalue);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
print_r($result);


问:
How to limit the upload speed of an application?
I am using QNetworkAccessManager to upload a file (and some data) like this:

```<code>QNetworkRequest request(<some URL>);
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
<multipart is filled with single parts>

networkAccessManager->post(request, multiPart);
</code>```

It works well.
However, users have reported that the upload influences their upload bandwidth. Which... makes sense, of course ;)

Now, I would like to implement something to limit the upload speed of this post request. However, after looking around for a while, I found absolutely nothing to do this in any simple way.

There is setReadBufferSize for the QNetworkReply, but no equivalent for writing. Seems like an obvious mistake not to add that...

I have found this thing: http://doc.qt.io/qt-5/qtnetwork-torrent-example.html

And tried to adjust some of its classes to my needs.
However, it all fails because I just cannot find a way to interrupt the writing of data (to do it slower than it normally would). That example relies on the user writing the writing-code himself - but that isn't possible here since Qt internally does the writing of the data after a post request.

I also tried using the Windows API Traffic Control, but that can just be used to limit a complete network interface or inspect packets, not a specific application. Plus, this has practically no examples, just some ancient code snippets. Not exactly what I want to work with...

Is there any way to achieve an upload throttle at all without having to rewrite Qt sources (which I won't do)?

A way to "globally" limit the upload speed of the application would be acceptable as well, using Windows API code or anything, really, as long as it is possible in code.

Additional info:

Limiting the upload speed of the user's computer is not acceptable. It must be limiting only a specific application. Similar to what you can do with NetLimiter.

答:
While not a 100% solution for this problem (it's not using Qt and not limiting an application's bandwidth in general, so I won't "accept" this), this is the workaround we ended up implementing:

A class that makes use of

libcurl

We are using that class instead of a QNetworkAccessManager wherever we need to have an up/download with a speed limit.

Built libcurl myself with OpenSSL support, and then you can very easily use the CURLOPT_MAX_SEND_SPEED_LARGE parameter to set the upload speed limit.

Body:
I am using QNetworkAccessManager to upload a file (and some data) like this:

QNetworkRequest request(<some URL>);
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
<multipart is filled with single parts>

networkAccessManager->post(request, multiPart);

It works well.
However, users have reported that the upload influences their upload bandwidth. Which... makes sense, of course ;)

Now, I would like to implement something to limit the upload speed of this post request. However, after looking around for a while, I found absolutely nothing to do this in any simple way.

There is setReadBufferSize for the QNetworkReply, but no equivalent for writing. Seems like an obvious mistake not to add that...

I have found this thing: http://doc.qt.io/qt-5/qtnetwork-torrent-example.html

And tried to adjust some of its classes to my needs.
However, it all fails because I just cannot find a way to interrupt the writing of data (to do it slower than it normally would). That example relies on the user writing the writing-code himself - but that isn't possible here since Qt internally does the writing of the data after a post request.

I also tried using the Windows API Traffic Control, but that can just be used to limit a complete network interface or inspect packets, not a specific application. Plus, this has practically no examples, just some ancient code snippets. Not exactly what I want to work with...

Is there any way to achieve an upload throttle at all without having to rewrite Qt sources (which I won't do)?

A way to "globally" limit the upload speed of the application would be acceptable as well, using Windows API code or anything, really, as long as it is possible in code.

Additional info:

Limiting the upload speed of the user's computer is not acceptable. It must be limiting only a specific application. Similar to what you can do with NetLimiter.


问:
ASP.NET Web Api 2 code first JSON array returns null
I need help with my ASP.NET Web Api 2 project, I can make successfully send JSON data, I want to save Invites and the members who are invited.

Post Data Successfully saved on localdb

I used the scaffolding on Visual Studio 2017 and this is my first ever attempt on the .NET enviroment

```<code>{
    "InviteID": 6,
    "Subject": "sddsdsds",
    "DateTime": "54545:55",
    "Members": [
        {
            "MemberID": 8,
            "MemberName": "sdds",
            "IsAdmin": false,
            "MemberNumber": 0,
            "PhoneNumber": null,
            "InviteID": 6
        },
        {
            "MemberID": 9,
            "MemberName": "sdds",
            "IsAdmin": false,
            "MemberNumber": 0,
            "PhoneNumber": null,
            "InviteID": 6
        },
        {
            "MemberID": 10,
            "MemberName": "sdds",
            "IsAdmin": false,
            "MemberNumber": 0,
            "PhoneNumber": null,
            "InviteID": 6
        }
    ]
}
</code>```

But when I try to retrieve the invites, the members array is null:

```<code>[
    {
        "InviteID": 2,
        "Subject": null,
        "DateTime": null,
        "Members": null
    },
    {
        "InviteID": 3,
        "Subject": null,
        "DateTime": null,
        "Members": null
    },
    {
        "InviteID": 4,
        "Subject": "sddsdsds",
        "DateTime": "54545:55",
        "Members": null
    },
    {
        "InviteID": 5,
        "Subject": "sddsdsds",
        "DateTime": "54545:55",
        "Members": null
    },
    {
        "InviteID": 6,
        "Subject": "sddsdsds",
        "DateTime": "54545:55",
        "Members": null
    }
]
</code>```

My Invites model

```<code>public class Invite
{
    public int InviteID { get; set; }
    public string Subject { get; set; }
    public string DateTime { get; set; }
    public virtual List<Member> Members { get; set; }
}
</code>```

My Member model

```<code>public class Member
{
    public int MemberID { get; set; }
    public string MemberName { get; set; }
    public bool IsAdmin { get; set; }
    public int MemberNumber { get; set; }
    public string PhoneNumber { get; set; }
    public int InviteID { get; set; }
    [JsonIgnore]
    public virtual Invite Iinvite { get; set; }
}
</code>```

My controller

```<code>public class InvitesController : ApiController
{
    private InviteContext db = new InviteContext();

    public InvitesController()
    {
        db.Configuration.ProxyCreationEnabled = false;
    }

    // GET: api/Invites
    public IEnumerable<Invite> Getinvites()
    {
        return db.invites.ToList();
    }

    // GET: api/Invites/5
    [ResponseType(typeof(Invite))]
    public IHttpActionResult GetInvite(int id)
    {
        Invite invite = db.invites.Find(id);

        if (invite == null)
        {
            return NotFound();
        }

        return Ok(invite);
    }

    // PUT: api/Invites/5
    [ResponseType(typeof(void))]
    public IHttpActionResult PutInvite(int id, Invite invite)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != invite.InviteID)
        {
            return BadRequest();
        }

        db.Entry(invite).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!InviteExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // POST: api/Invites
    [ResponseType(typeof(Invite))]
    public IHttpActionResult PostInvite(Invite invite)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.invites.Add(invite);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = invite.InviteID }, invite);
    }

    // DELETE: api/Invites/5
    [ResponseType(typeof(Invite))]
    public IHttpActionResult DeleteInvite(int id)
    {
        Invite invite = db.invites.Find(id);

        if (invite == null)
        {
            return NotFound();
        }

        db.invites.Remove(invite);
        db.SaveChanges();

        return Ok(invite);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool InviteExists(int id)
    {
        return db.invites.Count(e => e.InviteID == id) > 0;
    }
}
</code>```

my db context

```<code>public class InviteContext : DbContext
{
    public DbSet<Invite> invites { get; set; }
    public DbSet<Member> members { get; set; }
}
</code>```

edit
** Data received when querying Member table**

```<code>[
    {
        "MemberID": 1,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 2
    },
    {
        "MemberID": 2,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 2
    },
    {
        "MemberID": 3,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 3
    },
    {
        "MemberID": 4,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 4
    },
    {
        "MemberID": 5,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 5
    },
    {
        "MemberID": 6,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 5
    },
    {
        "MemberID": 7,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 5
    },
    {
        "MemberID": 8,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 6
    },
    {
        "MemberID": 9,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 6
    },
    {
        "MemberID": 10,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 6
    }
]
</code>```

答:
You need to set ProxyCreationEnabled to true to load foreign key tables' data.

```<code>public InvitesController()
{
    db.Configuration.ProxyCreationEnabled = true;
}
</code>```

If you are choosing to set ProxyCreationEnabled to false, then you need to write linq query to fetch data

```<code>public IEnumerable<Invite> Getinvites()
{
    return db.invites.Include("Members").ToList();
}
</code>```

Body:
I need help with my ASP.NET Web Api 2 project, I can make successfully send JSON data, I want to save Invites and the members who are invited.

Post Data Successfully saved on localdb

I used the scaffolding on Visual Studio 2017 and this is my first ever attempt on the .NET enviroment

{
    "InviteID": 6,
    "Subject": "sddsdsds",
    "DateTime": "54545:55",
    "Members": [
        {
            "MemberID": 8,
            "MemberName": "sdds",
            "IsAdmin": false,
            "MemberNumber": 0,
            "PhoneNumber": null,
            "InviteID": 6
        },
        {
            "MemberID": 9,
            "MemberName": "sdds",
            "IsAdmin": false,
            "MemberNumber": 0,
            "PhoneNumber": null,
            "InviteID": 6
        },
        {
            "MemberID": 10,
            "MemberName": "sdds",
            "IsAdmin": false,
            "MemberNumber": 0,
            "PhoneNumber": null,
            "InviteID": 6
        }
    ]
}

But when I try to retrieve the invites, the members array is null:

[
    {
        "InviteID": 2,
        "Subject": null,
        "DateTime": null,
        "Members": null
    },
    {
        "InviteID": 3,
        "Subject": null,
        "DateTime": null,
        "Members": null
    },
    {
        "InviteID": 4,
        "Subject": "sddsdsds",
        "DateTime": "54545:55",
        "Members": null
    },
    {
        "InviteID": 5,
        "Subject": "sddsdsds",
        "DateTime": "54545:55",
        "Members": null
    },
    {
        "InviteID": 6,
        "Subject": "sddsdsds",
        "DateTime": "54545:55",
        "Members": null
    }
]

My Invites model

public class Invite
{
    public int InviteID { get; set; }
    public string Subject { get; set; }
    public string DateTime { get; set; }
    public virtual List<Member> Members { get; set; }
}

My Member model

public class Member
{
    public int MemberID { get; set; }
    public string MemberName { get; set; }
    public bool IsAdmin { get; set; }
    public int MemberNumber { get; set; }
    public string PhoneNumber { get; set; }
    public int InviteID { get; set; }
    [JsonIgnore]
    public virtual Invite Iinvite { get; set; }
}

My controller

public class InvitesController : ApiController
{
    private InviteContext db = new InviteContext();

    public InvitesController()
    {
        db.Configuration.ProxyCreationEnabled = false;
    }

    // GET: api/Invites
    public IEnumerable<Invite> Getinvites()
    {
        return db.invites.ToList();
    }

    // GET: api/Invites/5
    [ResponseType(typeof(Invite))]
    public IHttpActionResult GetInvite(int id)
    {
        Invite invite = db.invites.Find(id);

        if (invite == null)
        {
            return NotFound();
        }

        return Ok(invite);
    }

    // PUT: api/Invites/5
    [ResponseType(typeof(void))]
    public IHttpActionResult PutInvite(int id, Invite invite)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != invite.InviteID)
        {
            return BadRequest();
        }

        db.Entry(invite).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!InviteExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // POST: api/Invites
    [ResponseType(typeof(Invite))]
    public IHttpActionResult PostInvite(Invite invite)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.invites.Add(invite);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = invite.InviteID }, invite);
    }

    // DELETE: api/Invites/5
    [ResponseType(typeof(Invite))]
    public IHttpActionResult DeleteInvite(int id)
    {
        Invite invite = db.invites.Find(id);

        if (invite == null)
        {
            return NotFound();
        }

        db.invites.Remove(invite);
        db.SaveChanges();

        return Ok(invite);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool InviteExists(int id)
    {
        return db.invites.Count(e => e.InviteID == id) > 0;
    }
}

my db context

public class InviteContext : DbContext
{
    public DbSet<Invite> invites { get; set; }
    public DbSet<Member> members { get; set; }
}

edit
** Data received when querying Member table**

[
    {
        "MemberID": 1,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 2
    },
    {
        "MemberID": 2,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 2
    },
    {
        "MemberID": 3,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 3
    },
    {
        "MemberID": 4,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 4
    },
    {
        "MemberID": 5,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 5
    },
    {
        "MemberID": 6,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 5
    },
    {
        "MemberID": 7,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 5
    },
    {
        "MemberID": 8,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 6
    },
    {
        "MemberID": 9,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 6
    },
    {
        "MemberID": 10,
        "MemberName": "sdds",
        "IsAdmin": false,
        "MemberNumber": 0,
        "PhoneNumber": null,
        "InviteID": 6
    }
]

Body:
You need to set ProxyCreationEnabled to true to load foreign key tables' data.

public InvitesController()
{
    db.Configuration.ProxyCreationEnabled = true;
}

If you are choosing to set ProxyCreationEnabled to false, then you need to write linq query to fetch data

public IEnumerable<Invite> Getinvites()
{
    return db.invites.Include("Members").ToList();
}


问:
Python script scheduling in airflow
Hi everyone,

I need to schedule my python files(which contains data extraction from sql and some joins) using airflow. I have successfully installed airflow into my linux server and webserver of airflow is available with me. But even after going through documentation I am not clear where exactly I need to write script for scheduling and how will that script be available into airflow webserver so I could see the status

As far as the configuration is concerned I know where the dag folder is located in my home directory and also where example dags are located.

Note: Please dont mark this as duplicate with How to run bash script file in Airflow as I need to run python files lying in some different location.

Please find the configuration in Airflow webserver as :

Below is the screenshot of dag folder in AIRFLOW_HOME dir

Also find the below screenshot for DAG creation screenshot and Missing DAG error

After i select the simple DAG following error of missing DAG is populated

答:
Install airflow using Airflow official documentation. Its good idea to install in python virtual environment.
http://python-guide-pt-br.readthedocs.io/en/latest/dev/virtualenvs/

When we start airflow first time using

airflow webserver -p <port>

It loads examples dags automatically, It can be disable in
$HOME/airflow/airflow.cfg

```<code>`load_examples = False`
</code>```

Create dags folder in $HOME/airflow/, put tutorial.py file in dags folder from https://airflow.incubator.apache.org/tutorial.html

Do some experiments, make changes in tutorial.py. If you are giving schedule_interval as cron syntax, then 'start_date' : datetime(2017, 7, 7)

```<code>'start_date': datetime.now()
</code>```

dag = DAG('tutorial', default_args=default_args,schedule_interval="@once")
     or
dag = DAG('tutorial', default_args=default_args,schedule_interval="* * * * *") # schedule each minute

start airflow: $ airflow webserver -p <port>

start scheduler: $ airflow scheduler

Title: Python script scheduling in airflow

Body:
Install airflow using Airflow official documentation. Its good idea to install in python virtual environment.
http://python-guide-pt-br.readthedocs.io/en/latest/dev/virtualenvs/

When we start airflow first time using

airflow webserver -p <port>

It loads examples dags automatically, It can be disable in
$HOME/airflow/airflow.cfg

`load_examples = False`

Create dags folder in $HOME/airflow/, put tutorial.py file in dags folder from https://airflow.incubator.apache.org/tutorial.html

Do some experiments, make changes in tutorial.py. If you are giving schedule_interval as cron syntax, then 'start_date' : datetime(2017, 7, 7)

'start_date': datetime.now()

dag = DAG('tutorial', default_args=default_args,schedule_interval="@once")
     or
dag = DAG('tutorial', default_args=default_args,schedule_interval="* * * * *") # schedule each minute

start airflow: $ airflow webserver -p <port>

start scheduler: $ airflow scheduler


问:
Collaborative filtering in Python
I work now with the Graphlab. After installing of this program, I could run the algorithms of Collaborative filtering.
Now I try to work with Graphlab in the Python. I have found already this brilliant toolkits. My question is, does anybody know about Collaborative Filtering in the python implementation? I couldn't find this tool & it seems me it doesn't implemented for Python...

Thank you in advance.

答: Apart from above suggestions in Answer section, I will STRONGLY recommend you to do a course on Coursera Here for getting better understanding of ML and Recommendation Systems. For just getting started with Collaborative filtering, you also may refer this simple and easily understandable blog Here and obvious Turi official Website . I hope this helps. </p>

Title: Collaborative filtering in Python


问:
How to calculate time difference between two dates using LocalDateTime in Java 8?
There are numerous answers given but I am unable to find compatible with my situation. I need to find difference of 8 hours in time as well as on date change too. Like if time is greater then 8 hours then do not execute something .

Do we have any method which achieve the same in LocalDateTime in Java-8?

I have tried to use following but unable to achieve the same.

```<code>LocalDateTime fromDateTime = LocalDateTime.of(2017, 07, 07, 07, 00, 55);
LocalDateTime toDateTime = LocalDateTime.now();
LocalDateTime tempDateTime = LocalDateTime.from(fromDateTime);

long years = tempDateTime.until(toDateTime, ChronoUnit.YEARS);
tempDateTime = tempDateTime.plusYears(years);

long months = tempDateTime.until(toDateTime, ChronoUnit.MONTHS);
tempDateTime = tempDateTime.plusMonths(months);

long days = tempDateTime.until(toDateTime, ChronoUnit.DAYS);
tempDateTime = tempDateTime.plusDays(days);

long hours = tempDateTime.until(toDateTime, ChronoUnit.HOURS);
tempDateTime = tempDateTime.plusHours(hours);

long minutes = tempDateTime.until(toDateTime, ChronoUnit.MINUTES);
tempDateTime = tempDateTime.plusMinutes(minutes);

long seconds = tempDateTime.until(toDateTime, ChronoUnit.SECONDS);

System.out.println("" + java.time.Duration.between(tempDateTime, toDateTime).toHours());

System.out.println(years + " years "
        + months + " months "
        + days + " days "
        + hours + " hours "
        + minutes + " minutes "
        + seconds + " seconds.");
</code>```

It is difficult to check on time and date separately.

Initially I coded it like but it does not looks correct:

```<code>return openBrat!=null
        && openBrat.until(LocalDateTime.now(), ChronoUnit.DAYS) == 0 &&
          openBrat.until(LocalDateTime.now(), ChronoUnit.HOURS) >= 8
         && openBrat.until(LocalDateTime.now(), ChronoUnit.Minutes) >= 0;
</code>```

Could anyone please suggest how to subtract like:

```<code>2017 07 06 23:30:00 - 2017 07 07 01:30:00 - Should return 2 hours.
</code>```

答:
The following prints 2, just like you'd expect.

```<code>LocalDateTime ldt1 = LocalDateTime.of(2017, 07, 06, 23, 30, 00);
LocalDateTime ldt2 = LocalDateTime.of(2017, 07, 07, 1, 30, 00);
System.out.println(Duration.between(ldt1, ldt2).toHours());
</code>```

There is nothing wrong with your code. If you don't get the outcome you expect, you may need to check if your expectation is correct.

To do something when the difference is less than 8 hours, you can do something like this:

```<code>LocalDateTime ldt1 = LocalDateTime.of(2017, 07, 06, 23, 30, 00);
LocalDateTime ldt2 = LocalDateTime.of(2017, 07, 07, 1, 30, 00);
Duration d1 = Duration.between(ldt1, ldt2);
Duration d2 = Duration.ofHours(8);

if (d1.compareTo(d2) > 0) {
    System.out.println("do nothing");
} else {
    System.out.println("do something");
}
</code>```

Body:
There are numerous answers given but I am unable to find compatible with my situation. I need to find difference of 8 hours in time as well as on date change too. Like if time is greater then 8 hours then do not execute something .

Do we have any method which achieve the same in LocalDateTime in Java-8?

I have tried to use following but unable to achieve the same.

LocalDateTime fromDateTime = LocalDateTime.of(2017, 07, 07, 07, 00, 55);
LocalDateTime toDateTime = LocalDateTime.now();
LocalDateTime tempDateTime = LocalDateTime.from(fromDateTime);

long years = tempDateTime.until(toDateTime, ChronoUnit.YEARS);
tempDateTime = tempDateTime.plusYears(years);

long months = tempDateTime.until(toDateTime, ChronoUnit.MONTHS);
tempDateTime = tempDateTime.plusMonths(months);

long days = tempDateTime.until(toDateTime, ChronoUnit.DAYS);
tempDateTime = tempDateTime.plusDays(days);

long hours = tempDateTime.until(toDateTime, ChronoUnit.HOURS);
tempDateTime = tempDateTime.plusHours(hours);

long minutes = tempDateTime.until(toDateTime, ChronoUnit.MINUTES);
tempDateTime = tempDateTime.plusMinutes(minutes);

long seconds = tempDateTime.until(toDateTime, ChronoUnit.SECONDS);

System.out.println("" + java.time.Duration.between(tempDateTime, toDateTime).toHours());

System.out.println(years + " years "
        + months + " months "
        + days + " days "
        + hours + " hours "
        + minutes + " minutes "
        + seconds + " seconds.");

It is difficult to check on time and date separately.

Initially I coded it like but it does not looks correct:

return openBrat!=null
        && openBrat.until(LocalDateTime.now(), ChronoUnit.DAYS) == 0 &&
          openBrat.until(LocalDateTime.now(), ChronoUnit.HOURS) >= 8
         && openBrat.until(LocalDateTime.now(), ChronoUnit.Minutes) >= 0;

Could anyone please suggest how to subtract like:

2017 07 06 23:30:00 - 2017 07 07 01:30:00 - Should return 2 hours.

Body:
The following prints 2, just like you'd expect.

LocalDateTime ldt1 = LocalDateTime.of(2017, 07, 06, 23, 30, 00);
LocalDateTime ldt2 = LocalDateTime.of(2017, 07, 07, 1, 30, 00);
System.out.println(Duration.between(ldt1, ldt2).toHours());

There is nothing wrong with your code. If you don't get the outcome you expect, you may need to check if your expectation is correct.

To do something when the difference is less than 8 hours, you can do something like this:

LocalDateTime ldt1 = LocalDateTime.of(2017, 07, 06, 23, 30, 00);
LocalDateTime ldt2 = LocalDateTime.of(2017, 07, 07, 1, 30, 00);
Duration d1 = Duration.between(ldt1, ldt2);
Duration d2 = Duration.ofHours(8);

if (d1.compareTo(d2) > 0) {
    System.out.println("do nothing");
} else {
    System.out.println("do something");
}


问:
MMORPG protocol encryption
Anyone know what the trend is with MMORPG developers encryption their client/server protocols these days?

The pro's and con's are as follows.

Encrypting protocol:

protects trade secrets regarding client/server protocol to a degree?

Botting isn't stopped, it is only changed because people will create bots which read screen states and trigger mouse+keyboard events will then be developed, merely mitigating the development of bots as opposed to stopping them in anyway. Still though bot development is less in supply somewhat, but the demand is still there, they merely get higher bids on rentacoder.com

Regular plain text:

more advanced bots since the developers are able to inject their own datagrams into the client/server protocol. (ie: running through walls, teleporting... which the server side has to now check, which in turn leads to a development contest between out patching exploits via injection (time consuming)

答:
@Samuel & coxymla:

That's not entirely true. If the protocol uses asynchronous encryption where the server's private key is unknown to the client, then the bot cannot decrypt the client's egress. This means that to modify the outgoing data, the bot actually has to hook the game process and intercept the data before it's encrypted.

It's simple enough in theory, but it can be technically challenging. At least you're raising the bar for attackers.

@Zombies:
Beyond initial key exchange, most encryption schemes do not require extra data transfer. Further, while there is extra work to be done when encryption is used, the data transfer will most certainly be limited by the network and not the processor.

Put plainly, encryption does not lead to slower/more data transfer.

Cautionary note: This Wikipedia page contains a story about a common encryption mistake made by the developers of Phantasy Star Online. It's worth a read.

OwnerDisplayName: Zombies

Title: MMORPG protocol encryption

OwnerDisplayName: Eam


问:
C++ How to draw letter same size
I'm working on my edit box that I'm creating.  I need to find a font that draw letter at same size.  I'm using directx</p>

答: I'm guessing that by "find a font that draw letter at same size" you mean a font where all of the letters are the same size. This is called a Monospaced or Fixed Width Font. There should be several on most systems, the one that you should be able to count on always existing on Windows systems is "Courier New".</p>

Title: C++ How to draw letter same size


问:
How would you implement a ROS publisher and subscriber in an existing QT Creator GUI project?
I currently have a piece of simulator GUI written in QT Creator that simulates a robot's movements, that I would like to integrate with ROS such that it can actually control a robot.

How can a ROS publisher and subscriber node be written into the QT Creator project?

Thanks in advance!

答:
Well, you can take a look at the qt_ros package.

Basically, the logic will be having a QThreaded node (private member of the Gui class) running behind the gui. It will be responsible for handling all the ROS logic (subscribe, publish, service server/Client...) and then relaying that data to the parent Qt Gui using appropriate methods.

For inetgrating Qt in a ROS Project, the easiest way would be depending on the qt-build package and in your CMakelists, here is a short setup for making a node with a Gui :

```<code>rosbuild_prepare_qt4(QtCore QtGui QtXml) # Add the appropriate components to the component list here

# Sections

file(GLOB QT_FORMS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ui/*.ui)
file(GLOB QT_RESOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.qrc)
file(GLOB_RECURSE QT_MOC RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}     FOLLOW_SYMLINKS include/*.h include/*.hpp include/msg-pack-include/*.h)

QT4_ADD_RESOURCES(QT_RESOURCES_CPP ${QT_RESOURCES})
QT4_WRAP_UI(QT_FORMS_HPP ${QT_FORMS})
QT4_WRAP_CPP(QT_MOC_HPP ${QT_MOC})

# Sources

file(GLOB_RECURSE QT_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} FOLLOW_SYMLINKS src/*.cpp)

# Binaries

add_executable(qt_gui_node ${QT_MOC_HPP} ${QT_SOURCES} ${QT_RESOURCES_CPP} ${QT_FORMS_HPP})
target_link_libraries(qt_gui_node ${QT_LIBRARIES} ${catkin_LIBRARIES})
</code>```

If you want a cleaner way, you can just copy/paste the qt-ros.cmake.in in a folder named cmake in your project and then include it in your CMakeLists as following :

```<code>include(cmake/qt-ros.cmake.in)
</code>```

Hope that helps, a startup point at least !

Cheers,

Body:
Well, you can take a look at the qt_ros package.

Basically, the logic will be having a QThreaded node (private member of the Gui class) running behind the gui. It will be responsible for handling all the ROS logic (subscribe, publish, service server/Client...) and then relaying that data to the parent Qt Gui using appropriate methods.

For inetgrating Qt in a ROS Project, the easiest way would be depending on the qt-build package and in your CMakelists, here is a short setup for making a node with a Gui :

rosbuild_prepare_qt4(QtCore QtGui QtXml) # Add the appropriate components to the component list here

# Sections

file(GLOB QT_FORMS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ui/*.ui)
file(GLOB QT_RESOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.qrc)
file(GLOB_RECURSE QT_MOC RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}     FOLLOW_SYMLINKS include/*.h include/*.hpp include/msg-pack-include/*.h)

QT4_ADD_RESOURCES(QT_RESOURCES_CPP ${QT_RESOURCES})
QT4_WRAP_UI(QT_FORMS_HPP ${QT_FORMS})
QT4_WRAP_CPP(QT_MOC_HPP ${QT_MOC})

# Sources

file(GLOB_RECURSE QT_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} FOLLOW_SYMLINKS src/*.cpp)

# Binaries

add_executable(qt_gui_node ${QT_MOC_HPP} ${QT_SOURCES} ${QT_RESOURCES_CPP} ${QT_FORMS_HPP})
target_link_libraries(qt_gui_node ${QT_LIBRARIES} ${catkin_LIBRARIES})

If you want a cleaner way, you can just copy/paste the qt-ros.cmake.in in a folder named cmake in your project and then include it in your CMakeLists as following :

include(cmake/qt-ros.cmake.in)

Hope that helps, a startup point at least !

Cheers,


问:
SQL query not returning all days from timestamp
I need to run an sql query grouping each data by date. My column in named created and is a timestamp. The query works fine using YEAR(created), MONTH(created), WEEK(created) and shows all the results, however, with day it shows only a range. How can I solve this?

query with YEAR or MONTH or WEEK(created)

```<code>SELECT created
FROM mimesi_indexer.meta_served_clips
GROUP BY YEAR(created)    //<-- that can be either YEAR, MONTH or WEEK
</code>```

This query returns all data divided into year, months or weeks between 3rd of March 2017 and today

query with DAY(created)

```<code>SELECT created
FROM mimesi_indexer.meta_served_clips
GROUP BY DAY(created)
</code>```

This query, however, returns all data divided days only between 3rd of March 2017 and 31st of March

答: The answer is to use DATE(created) instead of DAY(created). Because Day() returns the day of the month (1-31) not the date.

Body:
I need to run an sql query grouping each data by date. My column in named created and is a timestamp. The query works fine using YEAR(created), MONTH(created), WEEK(created) and shows all the results, however, with day it shows only a range. How can I solve this?

query with YEAR or MONTH or WEEK(created)

SELECT created
FROM mimesi_indexer.meta_served_clips
GROUP BY YEAR(created)    //<-- that can be either YEAR, MONTH or WEEK

This query returns all data divided into year, months or weeks between 3rd of March 2017 and today

query with DAY(created)

SELECT created
FROM mimesi_indexer.meta_served_clips
GROUP BY DAY(created)

This query, however, returns all data divided days only between 3rd of March 2017 and 31st of March


问:
Eclipse indigo randomly shutdowns
I'm using windows 7 64bit and everytime I code (java core only) in Eclipse Indigo, for some reasons, eclipse randomly shutdowns after Ctrl+S, Ctrl+Space or even when F6 or F8 in debugging process. After eclipse shutdowns, the 'javaw.exe' still remains in Task Manager so I have to turn it off manually in order to renew another coding session in eclipse. Any help would be appreciated!

答: I just downloaded the lastest version of Eclipse Indigo from Eclipse's Homepage, and i still haven't seen any crash till now. I think it works!</p>

Title: Eclipse indigo randomly shutdowns


问:
Python Machine Learning Functions
Is there functionality in Machine Learning (using Python) that I could use to feed it a group of inputs, tell it what the end product should be, then have the code figure out what function it should use in order to reach the end product?

Thanks.

答:
question is really vague one.

still as you mentioned machine learning TAG. i take it as machine learning problem. in this case there is no specific model or algorithm available to decide which algorithm/function best suits to your data !!.

it's hit & trial method to decide which model should be best for your data. so you are going to write a wrapper program which going to test your data with all possible model and based on their Accuracy Score your code will decide which model best suits. !!

Title: Python Machine Learning Functions


问:
Text and Images in Column - align image
I have two or more columns with an image + text flow.

Image size could be 50 to 400px, text from 1 line to 2 paragraphs

```<code>+---+
|   | +---+
|   | |   |
+---+ +---+
text  text
text  text
text
text
</code>```

Is it possible using flex to align about the bottom of the images without using js?

* { box-sizing: border-box; }

body { line-height: 1.5; }

.row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap row;
  max-width: 60rem;
  margin-right: auto;
  margin-left: auto;
}

.col {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: 33.33333%;
  padding-right: .5rem;
  padding-left: .5rem;
}

.col-img {
  display: flex;
  flex: 1 0 auto;
  overflow: hidden;
  align-items: flex-end;
}

img {
  width: 100%;
  height: auto;
}

.col-content {
  flex: 1 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col">
    <div class="col-img">
      <img src="//placehold.it/600x200">
    </div>
    <div class="col-content">
      <h1>Title</h1>
      <p>Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa</p>
    </div>
  </div>
  <div class="col">
    <div class="col-img">
      <img src="//placehold.it/600x300">
    </div>
    <div class="col-content">
      <h1>Title</h1>
      <p>Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa</p>
    </div>
  </div>
  <div class="col">
    <div class="col-img">
      <img src="//placehold.it/600x400">
    </div>
    <div class="col-content">
      <h1>Title</h1>
      <p>Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa</p>
      <p>Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa</p>
    </div>
  </div>
</div></code>```

https://jsfiddle.net/87j37r81/

答:
For that to work you need to drop the col rule/markup and use the order property to group them.

And the reason it doesn't work with the col elements is because then the row's can't see each other and won't be able to align vertical.
 (unless you give col-img a fixed height, but I assume you don't want that)

That, together with align-items: flex-end, will give the expected result.

The flex-basis will make them take equal width and break line, and with the order you place the image first.

* {
  box-sizing: border-box;
}

body {
  line-height: 1.5;
}

.row {
  display: flex;
  flex-wrap: wrap;
  max-width: 60rem;
}

.col-img {
  flex-basis: calc(33.33% - 20px);
  margin: 10px;
  display: flex;
  overflow: hidden;
  align-items: flex-end;
  order: -1;
}

.col-img img {
  width: 100%;
  height: auto;
}

.col-content {
  flex-basis: calc(33.33% - 20px);
  margin: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col-img">
    <img src="//placehold.it/600x200">
  </div>
  <div class="col-content">
    <h1>Title</h1>
    <p>Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa</p>
  </div>

  <div class="col-img">
    <img src="//placehold.it/600x300">
  </div>
  <div class="col-content">
    <h1>Title</h1>
    <p>Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa</p>
  </div>

  <div class="col-img">
    <img src="//placehold.it/600x400">
  </div>
  <div class="col-content">
    <h1>Title</h1>
    <p>Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa</p>
    <p>Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa</p>
  </div>
</div></code>```

Title: Text and Images in Column - align image

Body:
I have two or more columns with an image + text flow.

Image size could be 50 to 400px, text from 1 line to 2 paragraphs

+---+
|   | +---+
|   | |   |
+---+ +---+
text  text
text  text
text
text

Is it possible using flex to align about the bottom of the images without using js?

* { box-sizing: border-box; }

body { line-height: 1.5; }

.row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap row;
  max-width: 60rem;
  margin-right: auto;
  margin-left: auto;
}

.col {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: 33.33333%;
  padding-right: .5rem;
  padding-left: .5rem;
}

.col-img {
  display: flex;
  flex: 1 0 auto;
  overflow: hidden;
  align-items: flex-end;
}

img {
  width: 100%;
  height: auto;
}

.col-content {
  flex: 1 0 auto;
}

Title

Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa

Title

Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa

Title

Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa

Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa

https://jsfiddle.net/87j37r81/

Body:
For that to work you need to drop the col rule/markup and use the order property to group them.

And the reason it doesn't work with the col elements is because then the row's can't see each other and won't be able to align vertical.
 (unless you give col-img a fixed height, but I assume you don't want that)

That, together with align-items: flex-end, will give the expected result.

The flex-basis will make them take equal width and break line, and with the order you place the image first.

* {
  box-sizing: border-box;
}

body {
  line-height: 1.5;
}

.row {
  display: flex;
  flex-wrap: wrap;
  max-width: 60rem;
}

.col-img {
  flex-basis: calc(33.33% - 20px);
  margin: 10px;
  display: flex;
  overflow: hidden;
  align-items: flex-end;
  order: -1;
}

.col-img img {
  width: 100%;
  height: auto;
}

.col-content {
  flex-basis: calc(33.33% - 20px);
  margin: 10px;
}

<div class="row">
  <div class="col-img">
    <img src="//placehold.it/600x200">
  </div>
  <div class="col-content">
    <h1>Title</h1>
    <p>Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa</p>
  </div>

  <div class="col-img">
    <img src="//placehold.it/600x300">
  </div>
  <div class="col-content">
    <h1>Title</h1>
    <p>Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa</p>
  </div>

  <div class="col-img">
    <img src="//placehold.it/600x400">
  </div>
  <div class="col-content">
    <h1>Title</h1>
    <p>Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa</p>
    <p>Tousled cronut twee echo park la croix, church-key readymade wayfarers flexitarian mustache ethical semiotics microdosing cliche quinoa</p>
  </div>
</div>


问:
Set DataTemplate control Style code behind
So ia have this ListView with Custom Column Progress-Bar:

```<code>            <ListView Name="lvFiles">
                <ListView.Resources>
                    <DataTemplate x:Key="MyDataTemplate">
                        <Grid Margin="0,0,0,0">
                            <ProgressBar
                                Name="progressBarColumn"
                                Maximum="100"
                                Value="{Binding Progress, UpdateSourceTrigger=PropertyChanged}"
                                Width="{Binding Path=Width, ElementName=ProgressCell}"
                                Margin="0,0,0,0"
                                Style="{StaticResource CustomProgressBar}" />
                            <TextBlock
                                Text="{Binding Path=Value, ElementName=progressBarColumn, StringFormat={}{0:N1}%}"
                                VerticalAlignment="Center"
                                HorizontalAlignment="Center"
                                FontSize="11.5"
                                Foreground="White"
                                Margin="0,-2,0,0"/>
                        </Grid>
                    </DataTemplate>
                    <ControlTemplate x:Key="ProgressBarTemplate">
                        <Label  HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </ControlTemplate>
                    <Style TargetType="{x:Type TextBlock}">
                        <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=Text }"></Setter>
                    </Style>
                </ListView.Resources>
            </ListView>
</code>```

Style

```<code><Style x:Key="CustomProgressBar" TargetType="ProgressBar" >
    <Setter Property="Template" >
        <Setter.Value>
            <ControlTemplate TargetType="ProgressBar">
                <Border BorderBrush="#FF103766" BorderThickness="0" Background="#FF103766" CornerRadius="0" Padding="0">
                    <Grid x:Name="PART_Track">
                        <Rectangle x:Name="PART_Indicator" HorizontalAlignment="Left">
                            <Rectangle.Style>
                                <Style TargetType="Rectangle">
                                    <Setter Property="Fill" Value="Gray"/>
                                    <Style.Triggers>
                                        <DataTrigger Value="100" Binding="{Binding Path=Value, RelativeSource={RelativeSource AncestorType=ProgressBar}}">
                                            <Setter Property="Fill" Value="LightSeaGreen"/>
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </Rectangle.Style>
                        </Rectangle>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

So in case i want to create several Styles and change this Style from code behain, is it possible ?

答:
If you use the DynamicResource markup extension:

```<code>Style="{DynamicResource CustomProgressBar}" />
</code>```

...you could easily switch the resource at runtime:

```<code>lvFiles.Resources["CustomProgressBar"] = Application.Current.Resources["yourOtherStyle"] as Style;
</code>```

What's the difference between StaticResource and DynamicResource in WPF?

Body:
So ia have this ListView with Custom Column Progress-Bar:

            <ListView Name="lvFiles">
                <ListView.Resources>
                    <DataTemplate x:Key="MyDataTemplate">
                        <Grid Margin="0,0,0,0">
                            <ProgressBar
                                Name="progressBarColumn"
                                Maximum="100"
                                Value="{Binding Progress, UpdateSourceTrigger=PropertyChanged}"
                                Width="{Binding Path=Width, ElementName=ProgressCell}"
                                Margin="0,0,0,0"
                                Style="{StaticResource CustomProgressBar}" />
                            <TextBlock
                                Text="{Binding Path=Value, ElementName=progressBarColumn, StringFormat={}{0:N1}%}"
                                VerticalAlignment="Center"
                                HorizontalAlignment="Center"
                                FontSize="11.5"
                                Foreground="White"
                                Margin="0,-2,0,0"/>
                        </Grid>
                    </DataTemplate>
                    <ControlTemplate x:Key="ProgressBarTemplate">

                    </ControlTemplate>

                </ListView.Resources>
            </ListView>

Style

                                </Style>
                            </Rectangle.Style>
                        </Rectangle>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

So in case i want to create several Styles and change this Style from code behain, is it possible ?

Body:
If you use the DynamicResource markup extension:

Style="{DynamicResource CustomProgressBar}" />

...you could easily switch the resource at runtime:

lvFiles.Resources["CustomProgressBar"] = Application.Current.Resources["yourOtherStyle"] as Style;

What's the difference between StaticResource and DynamicResource in WPF?


问:
How to find intersection of sublists of sublists in Python3.0?
Imagine a list like:

```<code>SuperList = [[[1,2,3],[1,2,4]],[[6,3,1],[9,0,4]]]
</code>```

As you can see I have a sublist inside a sublist.
How can I code it find the intersection of those sublists.?
In this case the answer is 1,3 and 4.
My goal is to append all elements that appear at least once in each sublist in a new list(it doesn't matter if it appears in all sublists of one sublist)

I tried with set.intersection, but constantly I get

```<code>'unhashable type: 'list''
</code>```

or while trying to unwind the list I get

```<code>'can't use the starred expression here'!
</code>```

答:
It's not clear from your question what exactly you are trying to do, but if you are trying to test for existence of an element (for example 1) in any of the sublists, you can first flatten the "super list", and than make a set from that list.

We can do it in one go with flatset():

```<code>def flatset(lst):
    try:
        return set(lst)
    except TypeError:
        s = set()
        for item in lst:
            s.update(flatset(item))
        return s
</code>```

For example:

```<code>>>> superlist = [[[1,2,3],[1,2,4]],[[6,3,1],[9,0,4]]]
>>> flatset(superlist)
set([0, 1, 2, 3, 4, 6, 9])
>>> 1 in flatset(superlist)
True
</code>```

Body:
Imagine a list like:

SuperList = [[[1,2,3],[1,2,4]],[[6,3,1],[9,0,4]]]

As you can see I have a sublist inside a sublist.
How can I code it find the intersection of those sublists.?
In this case the answer is 1,3 and 4.
My goal is to append all elements that appear at least once in each sublist in a new list(it doesn't matter if it appears in all sublists of one sublist)

I tried with set.intersection, but constantly I get

'unhashable type: 'list''

or while trying to unwind the list I get

'can't use the starred expression here'!

Body:
It's not clear from your question what exactly you are trying to do, but if you are trying to test for existence of an element (for example 1) in any of the sublists, you can first flatten the "super list", and than make a set from that list.

We can do it in one go with flatset():

def flatset(lst):
    try:
        return set(lst)
    except TypeError:
        s = set()
        for item in lst:
            s.update(flatset(item))
        return s

For example:

>>> superlist = [[[1,2,3],[1,2,4]],[[6,3,1],[9,0,4]]]
>>> flatset(superlist)
set([0, 1, 2, 3, 4, 6, 9])
>>> 1 in flatset(superlist)
True


问:
Configure SSRS for SSL
I have a SSRS instance, running SSRS 2014, and I want configure it for usage over SSL.

The server is available at http://reports.mydomain2.com

I purchased a multi SSL certificate from GoDaddy, on domain www.mydomain.com, and I added reports.mydomain2.com as SAN

I generated the SSL certificate from GoDaddy as for IIS, imported the certificate into Intermediate Certification Authority and in Personal/Certificates

The I started the SSRS config manager, and I'm trying to setup the SSL
I see the certificate, but when I select it and click Apply I get error that SSL certificate cannot be bound

The error shown is

```<code>Microsoft.ReportingServices.WmiProvider.WMIProviderException: An unknown error has occurred in the WMI Provider. Error Code 80070520

 ---> System.Runtime.InteropServices.COMException (0x80070520): A specified logon session does not exist. It may already have been terminated. (Exception from HRESULT: 0x80070520)
   --- End of inner exception stack trace ---
   at Microsoft.ReportingServices.WmiProvider.RSWmiAdmin.ThrowOnError(ManagementBaseObject mo)
   at Microsoft.ReportingServices.WmiProvider.RSWmiAdmin.CreateSSLCertificateBinding(String application, String certificateHash, String ipAddress, Int32 port)
   at ReportServicesConfigUI.WMIProvider.RSReportServerAdmin.CreateSSLCertificateBinding(UrlApplication app, String certificateHash, String ipAddress, Int32 port)
</code>```

I checked the bindings with command

```<code>netsh http show urlacl
</code>```

and I found an entry on port 443

```<code>Reserved URL            : https://+:443/sra_{BA195980-CD49-458b-9E23-C84EE0ADCD75}/
    User: NT SERVICE\SstpSvc
        Listen: Yes
        Delegate: Yes
    User: BUILTIN\Administrators
        Listen: No
        Delegate: No
    User: NT AUTHORITY\SYSTEM
        Listen: Yes
        Delegate: Yes
        SDDL: D:(A;;GA;;;S-1-5-80-3435701886-799518250-3791383489-3228296122-2938884314)(A;;GR;;;BA)(A;;GA;;;SY)
</code>```

I don't know if this makes any difference or not (if the port 443 is already bound, preventing it from binding to SSRS url or not

But another possible problem is might be the fact that SSRS Config manager doesn't allow me to change the url for SSL binding to reports.mydomain2.com. but instead it tried to bind to default domain of the certificate.

Any idea what could be wrong, and how can I solve it?

答:
Error : An SSL binding already exists for the specified IP address and port combination.

Ever encountered above error ? A simple fix is below.

we need to remove the existing binding and in order to achieve that we need to know which certificate is actually binding it;

use the following command in cmd (Command Prompt): netsh http show sslcert;

remove the binding by using the following command: netsh http delete sslcert ipport=0.0.0.0:443;

Once you are done, bind the URL again with the SSL certificate and this time it will go through. Test the URL and it should be working fine.

Title: Configure SSRS for SSL

Body:
I have a SSRS instance, running SSRS 2014, and I want configure it for usage over SSL.

The server is available at http://reports.mydomain2.com

I purchased a multi SSL certificate from GoDaddy, on domain www.mydomain.com, and I added reports.mydomain2.com as SAN

I generated the SSL certificate from GoDaddy as for IIS, imported the certificate into Intermediate Certification Authority and in Personal/Certificates

The I started the SSRS config manager, and I'm trying to setup the SSL
I see the certificate, but when I select it and click Apply I get error that SSL certificate cannot be bound

The error shown is

Microsoft.ReportingServices.WmiProvider.WMIProviderException: An unknown error has occurred in the WMI Provider. Error Code 80070520

 ---> System.Runtime.InteropServices.COMException (0x80070520): A specified logon session does not exist. It may already have been terminated. (Exception from HRESULT: 0x80070520)
   --- End of inner exception stack trace ---
   at Microsoft.ReportingServices.WmiProvider.RSWmiAdmin.ThrowOnError(ManagementBaseObject mo)
   at Microsoft.ReportingServices.WmiProvider.RSWmiAdmin.CreateSSLCertificateBinding(String application, String certificateHash, String ipAddress, Int32 port)
   at ReportServicesConfigUI.WMIProvider.RSReportServerAdmin.CreateSSLCertificateBinding(UrlApplication app, String certificateHash, String ipAddress, Int32 port)

I checked the bindings with command

netsh http show urlacl

and I found an entry on port 443

Reserved URL            : https://+:443/sra_{BA195980-CD49-458b-9E23-C84EE0ADCD75}/
    User: NT SERVICE\SstpSvc
        Listen: Yes
        Delegate: Yes
    User: BUILTIN\Administrators
        Listen: No
        Delegate: No
    User: NT AUTHORITY\SYSTEM
        Listen: Yes
        Delegate: Yes
        SDDL: D:(A;;GA;;;S-1-5-80-3435701886-799518250-3791383489-3228296122-2938884314)(A;;GR;;;BA)(A;;GA;;;SY)

I don't know if this makes any difference or not (if the port 443 is already bound, preventing it from binding to SSRS url or not

But another possible problem is might be the fact that SSRS Config manager doesn't allow me to change the url for SSL binding to reports.mydomain2.com. but instead it tried to bind to default domain of the certificate.

Any idea what could be wrong, and how can I solve it?


问:
Adding items to end of linked list
I'm studying for an exam, and this is a problem from an old test:

We have a singly linked list with a list head with the following declaration:

```<code>class Node {
    Object data;
    Node next;
    Node(Object d,Node n) {
        data = d;
        next = n;
    }
}
</code>```

Write a method void addLast(Node header, Object x) that adds x at the end of the list.

I know that if I actually had something like:

```<code>LinkedList someList = new LinkedList();
</code>```

I could just add items to the end by doing:

```<code>list.addLast(x);
</code>```

But how can I do it here?

答:
The addLast() needs some optimisation as the while loop inside addLast() has O(n) complexity. Below is my implementation of LinkedList. Run the code with ll.addLastx(i) once and run it with ll.addLast(i) again , you can see their is a lot of difference in processing time of addLastx() with addLast().

Node.java

```<code>package in.datastructure.java.LinkedList;

/**
* Created by abhishek.panda on 07/07/17.
*/
public final class Node {
    int data;
    Node next;

    Node (int data){
       this.data = data;
    }
    public String toString(){
      return this.data+"--"+ this.next;
    }
}
</code>```

LinkedList.java

```<code>package in.datastructure.java.LinkedList;
import java.util.ArrayList;
import java.util.Date;

public class LinkedList {

    Node head;
    Node lastx;
    /**
     * @description To append node at end looping all nodes from head
     * @param data
     */
    public void addLast(int data){

        if(head == null){
            head = new Node(data);
            return;
        }
        Node last = head;
        while(last.next != null) {
            last = last.next;
        }
        last.next = new Node(data);
    }

    /**
     * @description This keep track on last node and append to it
     * @param data
     */
    public void addLastx(int data){

        if(head == null){
            head = new Node(data);
            lastx = head;
            return;
        }
        if(lastx.next == null){
            lastx.next = new Node(data);
            lastx = lastx.next;
        }

    }

    public String toString(){
        ArrayList<Integer> arrayList = new ArrayList<Integer>(10);
        Node current = head;
        while(current.next != null) {
            arrayList.add(current.data);
            current = current.next;
        }
        if(current.next == null) {
            arrayList.add(current.data);
        }
        return arrayList.toString();
    }

    public static void main(String[] args) {
        LinkedList ll = new LinkedList();
        /**
         * @description Checking the code optimization of append code
         */
        Date startTime = new Date();
        for (int i = 0 ; i < 100000 ; i++){
            ll.addLastx(i);
        }
        Date endTime = new Date();
        System.out.println("To total processing time : " + (endTime.getTime()-startTime.getTime()));
        System.out.println(ll.toString());
    }

}
</code>```

Title: Adding items to end of linked list

Body:
I'm studying for an exam, and this is a problem from an old test:

We have a singly linked list with a list head with the following declaration:

class Node {
    Object data;
    Node next;
    Node(Object d,Node n) {
        data = d;
        next = n;
    }
}

Write a method void addLast(Node header, Object x) that adds x at the end of the list.

I know that if I actually had something like:

LinkedList someList = new LinkedList();

I could just add items to the end by doing:

list.addLast(x);

But how can I do it here?

Body:
The addLast() needs some optimisation as the while loop inside addLast() has O(n) complexity. Below is my implementation of LinkedList. Run the code with ll.addLastx(i) once and run it with ll.addLast(i) again , you can see their is a lot of difference in processing time of addLastx() with addLast().

Node.java

package in.datastructure.java.LinkedList;

/**
* Created by abhishek.panda on 07/07/17.
*/
public final class Node {
    int data;
    Node next;

    Node (int data){
       this.data = data;
    }
    public String toString(){
      return this.data+"--"+ this.next;
    }
}

LinkedList.java

package in.datastructure.java.LinkedList;
import java.util.ArrayList;
import java.util.Date;

public class LinkedList {

    Node head;
    Node lastx;
    /**
     * @description To append node at end looping all nodes from head
     * @param data
     */
    public void addLast(int data){

        if(head == null){
            head = new Node(data);
            return;
        }
        Node last = head;
        while(last.next != null) {
            last = last.next;
        }
        last.next = new Node(data);
    }

    /**
     * @description This keep track on last node and append to it
     * @param data
     */
    public void addLastx(int data){

        if(head == null){
            head = new Node(data);
            lastx = head;
            return;
        }
        if(lastx.next == null){
            lastx.next = new Node(data);
            lastx = lastx.next;
        }

    }

    public String toString(){
        ArrayList<Integer> arrayList = new ArrayList<Integer>(10);
        Node current = head;
        while(current.next != null) {
            arrayList.add(current.data);
            current = current.next;
        }
        if(current.next == null) {
            arrayList.add(current.data);
        }
        return arrayList.toString();
    }

    public static void main(String[] args) {
        LinkedList ll = new LinkedList();
        /**
         * @description Checking the code optimization of append code
         */
        Date startTime = new Date();
        for (int i = 0 ; i < 100000 ; i++){
            ll.addLastx(i);
        }
        Date endTime = new Date();
        System.out.println("To total processing time : " + (endTime.getTime()-startTime.getTime()));
        System.out.println(ll.toString());
    }

}


问:
React Js pass boolean back to parent state
I have my login on my navbar component but i have something on my main component that i need to update when someone logs in, i can get the login on the navbar to work but the variable isn't being passed back up to the parent my code that calls the navbar looks like this

```<code><LoginBar AuthRes={this.state.AuthResults} IsLoggedIn={this.state.isLoggedIn}/>
</code>```

this is passing the variable IsLoggedIn into my navbar and then in my navbar my code is this

```<code>LoginAuth = (Res) => {
    if (Res.username === this.state.Username && Res.password === this.state.Password) {
        this.setState({
            IsLoggedIn: true,
        }, function(){

        });
        this.hideModal();

    } else {
        console.log("Gets to login auth and false");
    }
}
CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    var self = this;
    this.props.AuthRes.map(function (Res) {
        console.log("ID=" + Res.id);
        console.log("Username=" + Res.username);
        console.log("Password=" + Res.password);
        self.LoginAuth(Res);
    });
}
</code>```

so on clicking login it will ask you for the details it will then use .map to go through all the login details in the file i have, then it passes that into LoginAuth which will check that the input matches the auth file and sets IsLoggedIn to true if it matches how would i push IsLoggedIn back to the parent to change something on there

also how would i break the loop once i found the correct one as if i have an alert saying alert("Incorrect username or password") is does this 3 times if all three values haven't been met

thanks Andy

edit:

When i do  this.props.IsLoggedIn(true) or this.props.isLoggedIn(true) i get the error TypeError: Cannot read property 'props' of undefined so it saying isLoggedIn and IsLoggedIn are undefined yet

state = {
        AuthRes: this.props.AuthRes,
        isOpen: false,
        Username: '',
        Password: '',
        searchResults: [],
        testMode: true,
        isLoggedIn: this.props.IsLoggedIn,
        Auth: '',
    }

答:
What you can do is pass a function from the Parent component to the Child component using props.
Lets say you have this function in your parent component:

```<code>function doSomething(argument){
    console.log(argument);
}
</code>```

Now pass this function to your child component:

```<code><LoginBar AuthRes={this.state.AuthResults} IsLoggedIn={this.state.isLoggedIn} doSomething={this.doSomething}/>
</code>```

Then, in child component, when you get that function, just call it from wherever you need:

```<code>//Some code ...
this.props.doSomething(argument)
//Some code ...
</code>```

For the break question, you can't break map function. What you could do is convert you map function to for loop and use break or use some flag in map to know when to stop execution of the map. Check this out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break

Body:
I have my login on my navbar component but i have something on my main component that i need to update when someone logs in, i can get the login on the navbar to work but the variable isn't being passed back up to the parent my code that calls the navbar looks like this

<LoginBar AuthRes={this.state.AuthResults} IsLoggedIn={this.state.isLoggedIn}/>

this is passing the variable IsLoggedIn into my navbar and then in my navbar my code is this

LoginAuth = (Res) => {
    if (Res.username === this.state.Username && Res.password === this.state.Password) {
        this.setState({
            IsLoggedIn: true,
        }, function(){

        });
        this.hideModal();

    } else {
        console.log("Gets to login auth and false");
    }
}
CheckLoginAuth() {
    console.log("gets to check login auth");
    console.log(this.state.AuthRes);
    console.log("Username=" + this.state.Username);
    console.log("Password=" + this.state.Password);
    var self = this;
    this.props.AuthRes.map(function (Res) {
        console.log("ID=" + Res.id);
        console.log("Username=" + Res.username);
        console.log("Password=" + Res.password);
        self.LoginAuth(Res);
    });
}

so on clicking login it will ask you for the details it will then use .map to go through all the login details in the file i have, then it passes that into LoginAuth which will check that the input matches the auth file and sets IsLoggedIn to true if it matches how would i push IsLoggedIn back to the parent to change something on there

also how would i break the loop once i found the correct one as if i have an alert saying alert("Incorrect username or password") is does this 3 times if all three values haven't been met

thanks Andy

edit:

When i do  this.props.IsLoggedIn(true) or this.props.isLoggedIn(true) i get the error TypeError: Cannot read property 'props' of undefined so it saying isLoggedIn and IsLoggedIn are undefined yet

state = {
        AuthRes: this.props.AuthRes,
        isOpen: false,
        Username: '',
        Password: '',
        searchResults: [],
        testMode: true,
        isLoggedIn: this.props.IsLoggedIn,
        Auth: '',
    }

Body:
What you can do is pass a function from the Parent component to the Child component using props.
Lets say you have this function in your parent component:

function doSomething(argument){
    console.log(argument);
}

Now pass this function to your child component:

<LoginBar AuthRes={this.state.AuthResults} IsLoggedIn={this.state.isLoggedIn} doSomething={this.doSomething}/>

Then, in child component, when you get that function, just call it from wherever you need:

//Some code ...
this.props.doSomething(argument)
//Some code ...

For the break question, you can't break map function. What you could do is convert you map function to for loop and use break or use some flag in map to know when to stop execution of the map. Check this out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break


问:
How to display separators in Android SeekBar?

I have added a SeekBar to one of my fragments. Struggling to add white lines(divider) as shown in above SeekBar. Any clue ? Is there any property I can set for this?

答:
Below is what I have done on a basic level. You will need to make it dynamic to taste:</p>

```<code>public class SegmentedSeekBar extends android.support.v7.widget.AppCompatSeekBar {

    private Paint progressPaint;

    public SegmentedSeekBar(Context context) {
        super(context);
        init();
    }

    public SegmentedSeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public SegmentedSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        progressPaint = new Paint();
        progressPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        progressPaint.setColor(Color.LTGRAY);
        progressPaint.setStrokeWidth(2.0f);
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        int halfHeight = getHeight() / 2;

        int pos;
        float smallH = 10;

        float div = (getWidth() - getPaddingRight() - getPaddingLeft()) / (getMax());

        for (int i = 1; i < getMax(); i++) {
            pos = (int) (div * i) + getPaddingLeft();

            canvas.drawLine(
                    pos + 1.0f,
                    halfHeight - (halfHeight / 2.0f),
                    pos + 1.0f,
                    halfHeight + (halfHeight / 2.0f),
                    progressPaint);
        }

        super.onDraw(canvas);
    }
}
</code>```

Body:
Below is what I have done on a basic level. You will need to make it dynamic to taste:

public class SegmentedSeekBar extends android.support.v7.widget.AppCompatSeekBar {

    private Paint progressPaint;

    public SegmentedSeekBar(Context context) {
        super(context);
        init();
    }

    public SegmentedSeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public SegmentedSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        progressPaint = new Paint();
        progressPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        progressPaint.setColor(Color.LTGRAY);
        progressPaint.setStrokeWidth(2.0f);
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        int halfHeight = getHeight() / 2;

        int pos;
        float smallH = 10;

        float div = (getWidth() - getPaddingRight() - getPaddingLeft()) / (getMax());

        for (int i = 1; i < getMax(); i++) {
            pos = (int) (div * i) + getPaddingLeft();

            canvas.drawLine(
                    pos + 1.0f,
                    halfHeight - (halfHeight / 2.0f),
                    pos + 1.0f,
                    halfHeight + (halfHeight / 2.0f),
                    progressPaint);
        }

        super.onDraw(canvas);
    }
}


问:
App Freezes when Network connection is slow,Because a POST API Call happens on APP launch. Below is my Connection Manager code,Objective-C, iOS
//Below is the code i have used to perform simple httpPOST. But app hangs on App launch on splash screen and crashes . i am doing an API Call on applaunch in Appdelegate</p>

```<code>- (NSDictionary *)postUserRegWithUrl:(NSString *)urlString andParams:(NSString *)paramString{
NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                                                                                NULL,
                                                                                (CFStringRef)paramString,
                                                                                NULL,
                                                                                (CFStringRef)@"+",
                                                                                kCFStringEncodingUTF8 ));
NSDictionary *responseDictionary;
NSError *err;

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kBaseProdURL,urlString]]];

NSData *data = [encodedString dataUsingEncoding:NSUTF8StringEncoding];
[request setTimeoutInterval:60.0];
 [request setHTTPMethod:@"POST"];
[request setHTTPBody:data];
NSLog(@"the data Details is =%@", request);
NSURLResponse *response;

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];

NSLog(@"got response==%@", resSrt);

if(resSrt.length)
{

    responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&err];

    NSLog(@"Response dictionary formed is =%@", responseDictionary);
} else {

    NSLog(@"failed to connect");

        [self showAlertViewTitle:@"Please try later" withMessage:@"Something went wrong"];

}
return responseDictionary;
</code>```

<p>} </p>

答:
First set the timeoutInterval for your request. if your request takes more time then you have to stop the api call and inform the user with proper error message.

For example:

```<code>NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1200.0];
</code>```

Don't use Synchronised Request. It will block your main thread.

If your network is slow or server is not responding then your app will take more time to load. Which is not good for the user experience.

Remember, your app’s load time is your first chance to impress your users.

Use Asynchronised  Request of the NSURLConnection. Handle the response in the api completion block.

```<code>[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSString *resSrt = [[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];

        NSLog(@"got response==%@", resSrt);

        if(resSrt.length)
        {
            responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&err];

            NSLog(@"Response dictionary formed is =%@", responseDictionary);
        } else {

            NSLog(@"failed to connect");
        }
    }];
</code>```

Change queue:[NSOperationQueue mainQueue] parameter based on your need.

queue ->  An NSOperationQueue upon which    the handler block will
                   be dispatched.

Body:
//Below is the code i have used to perform simple httpPOST. But app hangs on App launch on splash screen and crashes . i am doing an API Call on applaunch in Appdelegate

- (NSDictionary *)postUserRegWithUrl:(NSString *)urlString andParams:(NSString *)paramString{
NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                                                                                NULL,
                                                                                (CFStringRef)paramString,
                                                                                NULL,
                                                                                (CFStringRef)@"+",
                                                                                kCFStringEncodingUTF8 ));
NSDictionary *responseDictionary;
NSError *err;

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kBaseProdURL,urlString]]];

NSData *data = [encodedString dataUsingEncoding:NSUTF8StringEncoding];
[request setTimeoutInterval:60.0];
 [request setHTTPMethod:@"POST"];
[request setHTTPBody:data];
NSLog(@"the data Details is =%@", request);
NSURLResponse *response;

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];

NSLog(@"got response==%@", resSrt);

if(resSrt.length)
{

    responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&err];

    NSLog(@"Response dictionary formed is =%@", responseDictionary);
} else {

    NSLog(@"failed to connect");

        [self showAlertViewTitle:@"Please try later" withMessage:@"Something went wrong"];

}
return responseDictionary;

}

Body:
First set the timeoutInterval for your request. if your request takes more time then you have to stop the api call and inform the user with proper error message.

For example:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1200.0];

Don't use Synchronised Request. It will block your main thread.

If your network is slow or server is not responding then your app will take more time to load. Which is not good for the user experience.

Remember, your app’s load time is your first chance to impress your users.

Use Asynchronised  Request of the NSURLConnection. Handle the response in the api completion block.

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSString *resSrt = [[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];

        NSLog(@"got response==%@", resSrt);

        if(resSrt.length)
        {
            responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&err];

            NSLog(@"Response dictionary formed is =%@", responseDictionary);
        } else {

            NSLog(@"failed to connect");
        }
    }];

Change queue:[NSOperationQueue mainQueue] parameter based on your need.

queue ->  An NSOperationQueue upon which    the handler block will
                   be dispatched.


问:
How to style hint for EditText with inputType set to textPassword in Android
Style of text for hint changes when I set inputType=textPassword in my EditText. Please see this image:

Both EditTexts have same XML but the upper has inputType set to textPassword.

How do I make them look the same?

答:
In the EditText inputType set to textPassword the font will change
use TextInputLayout for the EditText Password field

Try this code:

```<code><android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:hintEnabled="false"
        app:passwordToggleEnabled="true">

        <EditText
            android:id="@+id/input_password"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="@color/white"
            android:drawableLeft="@drawable/ic_password"
            android:drawableStart="@drawable/ic_password"
            android:hint="@string/password"
            android:imeOptions="actionDone"
            android:inputType="textPassword"
            android:textColor="@color/floating_text_color_accent"
            android:textSize="@dimen/text_size_small" />
    </android.support.design.widget.TextInputLayout>
</code>```

Body:
In the EditText inputType set to textPassword the font will change
use TextInputLayout for the EditText Password field

Try this code:

<android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:hintEnabled="false"
        app:passwordToggleEnabled="true">

        <EditText
            android:id="@+id/input_password"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="@color/white"
            android:drawableLeft="@drawable/ic_password"
            android:drawableStart="@drawable/ic_password"
            android:hint="@string/password"
            android:imeOptions="actionDone"
            android:inputType="textPassword"
            android:textColor="@color/floating_text_color_accent"
            android:textSize="@dimen/text_size_small" />
    </android.support.design.widget.TextInputLayout>


问:
C# probe for and capture Javascript Alert() and Confirm()
So I've been doing some research for a while and I'm at a dead end. I'm doing some IE automation. In C#/.NET, how do I probe for and consume a javascript alert() or confirm() so I can do things like grab its text and click the OK\Cancel buttons?

Update:

I need to reiterate: I need to be able to pull and verify the text from an alert() or confirm() as well as send it an OK or Cancel click. An example of such a test would be to make sure that, when I click on delete, the confirm() doesn't say "Are you sure you'd like to go to Mexico?" or anything else except the proper message.

Just in case, let me reiterate: For the purposes of this test, I have zero control over the source of the website in question.

Lastly, I'm using SHDocVw.InternetExplorer.

答:
I think what you are looking for is the IDocHostshowUI COM interface.  If I read the documentation correctly and my assumptions are correct ShowMessage function will be called when an alert() or confirm() is called in JavaScript.

I've not done this myself so I am only guessing.  Here are some examples of someone showing an example of using that interface (and many others) in C#.  WebBrowserSample2 sounds like what you are looking for.


问:
Loading UIViewController inside an UIScrollView Swift3
I have 2 UIViewControllers.
One UIViewController has a view with many buttons and is +2000 points high.
Another UIViewController has a UIScrollView.

This is my code:

```<code>import UIKit

 class ViewController: UIViewController {

@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    scrollView.contentSize = CGSize(width: 375, height: 2884)

    DispatchQueue.main.async {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let thumb_vc = storyboard.instantiateViewController(withIdentifier: "thumb") as! ThumbsViewController
        //self.present(vc, animated: true, completion: nil)

    self.addChildViewController(thumb_vc)
    self.scrollView.addSubview(thumb_vc.view)
   }
 }
</code>```

and although the thumbs UIViewController get loaded to UIScrollView, the size is wrong and does not scroll.

Any help appreciated

答:
Why are you giving static height to ScrollView when you can easily embed View in scroll view using Autolayout.
You can refer this link,
https://www.natashatherobot.com/ios-autolayout-scrollview/</p>

Body:
I have 2 UIViewControllers.
One UIViewController has a view with many buttons and is +2000 points high.
Another UIViewController has a UIScrollView.

This is my code:

import UIKit

 class ViewController: UIViewController {

@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    scrollView.contentSize = CGSize(width: 375, height: 2884)

    DispatchQueue.main.async {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let thumb_vc = storyboard.instantiateViewController(withIdentifier: "thumb") as! ThumbsViewController
        //self.present(vc, animated: true, completion: nil)

    self.addChildViewController(thumb_vc)
    self.scrollView.addSubview(thumb_vc.view)
   }
 }

and although the thumbs UIViewController get loaded to UIScrollView, the size is wrong and does not scroll.

Any help appreciated


问:
Kaa Changing sampling period
I was trying the kaa tutorial "Your first kaa application" and in the step "Change sampling period",
the highlighted output is supposed to happen

But it does not, despite the other values still appear.

答:
Press Active not just save
or is there ant more </p>

Title: Kaa Changing sampling period