问:
Request failed: unauthorized (401) with Twitter login
I am trying to login with Twitter in my iOS app but I am getting following error:

```<code>CredStore - performQuery - Error copying matching creds.  Error=-25300, query={
class = inet;
"m_Limit" = "m_LimitAll";
ptcl = htps;
"r_Attributes" = 1;
sdmn = "https://api.twitter.com";
srvr = "api.twitter.com";
sync = syna;
}
error: Optional("Request failed: unauthorized (401)")
</code>```

My code for login:

```<code>Twitter.sharedInstance().logIn(completion: { (session, error) in
        if (session != nil) {
            print("signed in as \(session?.userName)");

            let client = TWTRAPIClient(userID: session?.userName)
            client.loadUser(withID: (session?.userID)!, completion: { (user, error) in

                let twitterClient = TWTRAPIClient.withCurrentUser()
                let request = twitterClient.urlRequest(withMethod: "GET",
                                                       url: "https://api.twitter.com/1.1/followers/list.json?cursor=-1&screen_name=dearestpankaj&skip_status=true&include_user_entities=false",
                                                       parameters: ["include_email": "true", "skip_status": "true"],
                                                       error: nil)

                twitterClient.sendTwitterRequest(request) { response, data, connectionError in
                    print(data!)
                    let s :String = String(data: data! as Data, encoding: String.Encoding.utf8)!

                    if let data = s.data(using: String.Encoding.utf8) {
                        do {
                            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
                            print(json!)

                        } catch {
                            print("Something went wrong")
                        }
                    }
                }
            })

        } else {
            print("error: \(error?.localizedDescription)");
        }
    })
</code>```

Yesterday this error was intermittent but today I am continuously getting this error.

答:
You need to change this value: let client = TWTRAPIClient(userID: session?.userName)

with this : let client = TWTRAPIClient(userID: session?.userID)

Body:
I am trying to login with Twitter in my iOS app but I am getting following error:

CredStore - performQuery - Error copying matching creds.  Error=-25300, query={
class = inet;
"m_Limit" = "m_LimitAll";
ptcl = htps;
"r_Attributes" = 1;
sdmn = "https://api.twitter.com";
srvr = "api.twitter.com";
sync = syna;
}
error: Optional("Request failed: unauthorized (401)")

My code for login:

Twitter.sharedInstance().logIn(completion: { (session, error) in
        if (session != nil) {
            print("signed in as \(session?.userName)");

            let client = TWTRAPIClient(userID: session?.userName)
            client.loadUser(withID: (session?.userID)!, completion: { (user, error) in

                let twitterClient = TWTRAPIClient.withCurrentUser()
                let request = twitterClient.urlRequest(withMethod: "GET",
                                                       url: "https://api.twitter.com/1.1/followers/list.json?cursor=-1&screen_name=dearestpankaj&skip_status=true&include_user_entities=false",
                                                       parameters: ["include_email": "true", "skip_status": "true"],
                                                       error: nil)

                twitterClient.sendTwitterRequest(request) { response, data, connectionError in
                    print(data!)
                    let s :String = String(data: data! as Data, encoding: String.Encoding.utf8)!

                    if let data = s.data(using: String.Encoding.utf8) {
                        do {
                            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
                            print(json!)

                        } catch {
                            print("Something went wrong")
                        }
                    }
                }
            })

        } else {
            print("error: \(error?.localizedDescription)");
        }
    })

Yesterday this error was intermittent but today I am continuously getting this error.


来源: stackexchange

问:
REST and spring-mvc
Since REST based controller methods only return objects ( not views ) to the client based on the request, how can I show view to my user ? Or maybe better question what is a good way to combine spring-mvc web app with REST, so my user always get the answer, not in just ( for example ) JSON format, but also with the view ?

So far as I understood, REST based controller would be perfectly fitting to the mobile app ( for example twitter ), where views are handled inside the app and the only thing server has to worry about is to pass the right object to the right request. But what about the web app ?

I might be wrong in several things ( correct me if I am ), since I am trying to understand REST and I am still learning.

答:
To simplify things - you basically have two options:
1) Build Spring MVC application.
2) Build REST backend application.

In case of first option - within your application you will have both backend and frontend (MVC part).

In case of second option you build only backend application and expose it through REST API. In most cases, you will need to build another application - REST client for your application. This is more flexible application because it gives you opportunity to access your backend application from various clients - for example, you can have Android, IOS applications, you can have web application implemented using Angular etc...

Please note, that thins are not so simple, you can within one application have both REST backend and REST client etc... This is just very very simplified in order that you get some general picture. Hope this clarified a little things.

ContentLicense: CC BY-SA 3.0

Title: REST and spring-mvc


问:
Cross-browser method for detecting the scrollTop of the browser window
What is the best cross-browser way to detect the scrollTop of the browser window?  I prefer not to use any pre-built code libraries because this is a very simple script, and I don't need all of that deadweight.</p>

答:
This works well from IE5 to IE11. It also supports all major new browsers.</p>

```<code>var scrollTop = (document.documentElement && document.documentElement.scrollTop) ||
                (document.body.scrollTop) || (document.scrollingElement);
</code>```

OwnerDisplayName: Hot Pastrami

ContentLicense: CC BY-SA 2.5

Body:
This works well from IE5 to IE11. It also supports all major new browsers.

var scrollTop = (document.documentElement && document.documentElement.scrollTop) ||
                (document.body.scrollTop) || (document.scrollingElement);


问:
F# Applying Map.filter on Map derived from list of records
I have these records:

```<code>type Name        = string
type PhoneNumber = int
type Sex         = Male | Female
type YearOfBirth = int
type Interests   = string list
type Client      = {name: Name; phone: PhoneNumber; sex: Sex; birth: YearOfBirth; interests: Interests}

let client1 = {name = "Jon"; phone = 37613498; sex = Male; birth = 1980; interests = ["Cars"; "Boats"; "Airplanes"]}
let client2 = {name = "Jonna"; phone = 31852654; sex = Female; birth = 1970; interests = ["Makeup"; "Sewing"; "Bananas"]}
</code>```

Which I put into a list:

```<code>let file1 = [client1;client2]
</code>```

I then attempt to create a function using Map which should be able to filter file1 and only return the client, which has the same birthday as the one given in the function.

Example:

```<code>requestMap 1980
</code>```

Would return map [("Jon", (37613498, Male, 1980, ["Cars"; "Boats"; "Airplanes"]))] in this case.

I've stumbled into a function, but I've got a bit stuck now.

```<code>let requestMap yob =
    Map.ofList [for f in file1 do yield f.name,(f.phone,f.sex,f.birth,f.interests)] |>
    Map.filter (fun key value -> )
</code>```

I have trouble figuring out how I can get to birth in the current map's value? Because as it is right now, it's hidden inside value which is a PhoneNumber * Sex * YearOfBirth * Interests tuple currently.

Any hints?

答:
To access elements of a tuple, you can use pattern matching:

```<code>Map.filter (fun key (phone, sex, birth, interests) -> birth = yob)
</code>```

Or, if you're not interested in anything except birth year, you can ignore all other fields using underscore:

```<code>Map.filter (fun _ (_, _, birth, _) -> birth = yob)
</code>```

That said, I would recommend filtering first and creating the map after, this would be less expensive:

```<code>let requestMap yob =
    file1
    |> List.filter (fun x -> x.birth = yob)
    |> List.map (fun f -> f.name,(f.phone,f.sex,f.birth,f.interests))
    |> Map.ofList
</code>```

And while we're on the subject: why do you need to create that huge tuple in the first place? Can't you make the original records be values in your map? Like this:

```<code>let requestMap yob =
    file1
    |> List.filter (fun x -> x.birth = yob)
    |> List.map (fun f -> f.name, f)
    |> Map.ofList
</code>```

Body:
I have these records:

type Name        = string
type PhoneNumber = int
type Sex         = Male | Female
type YearOfBirth = int
type Interests   = string list
type Client      = {name: Name; phone: PhoneNumber; sex: Sex; birth: YearOfBirth; interests: Interests}

let client1 = {name = "Jon"; phone = 37613498; sex = Male; birth = 1980; interests = ["Cars"; "Boats"; "Airplanes"]}
let client2 = {name = "Jonna"; phone = 31852654; sex = Female; birth = 1970; interests = ["Makeup"; "Sewing"; "Bananas"]}

Which I put into a list:

let file1 = [client1;client2]

I then attempt to create a function using Map which should be able to filter file1 and only return the client, which has the same birthday as the one given in the function.

Example:

requestMap 1980

Would return map [("Jon", (37613498, Male, 1980, ["Cars"; "Boats"; "Airplanes"]))] in this case.

I've stumbled into a function, but I've got a bit stuck now.

let requestMap yob =
    Map.ofList [for f in file1 do yield f.name,(f.phone,f.sex,f.birth,f.interests)] |>
    Map.filter (fun key value -> )

I have trouble figuring out how I can get to birth in the current map's value? Because as it is right now, it's hidden inside value which is a PhoneNumber * Sex * YearOfBirth * Interests tuple currently.

Any hints?

Body:
To access elements of a tuple, you can use pattern matching:

Map.filter (fun key (phone, sex, birth, interests) -> birth = yob)

Or, if you're not interested in anything except birth year, you can ignore all other fields using underscore:

Map.filter (fun _ (_, _, birth, _) -> birth = yob)

That said, I would recommend filtering first and creating the map after, this would be less expensive:

let requestMap yob =
    file1
    |> List.filter (fun x -> x.birth = yob)
    |> List.map (fun f -> f.name,(f.phone,f.sex,f.birth,f.interests))
    |> Map.ofList

And while we're on the subject: why do you need to create that huge tuple in the first place? Can't you make the original records be values in your map? Like this:

let requestMap yob =
    file1
    |> List.filter (fun x -> x.birth = yob)
    |> List.map (fun f -> f.name, f)
    |> Map.ofList


问:
put numpy array items into "bins"
I have a numpy array with some integers, e.g.,

```<code>a = numpy.array([1, 6, 6, 4, 1, 1, 4])
</code>```

I would now like to put all items into "bins" of equal values such that the bin with label 1 contains all indices of a that have the value 1. For the above example:

```<code>bins = {
    1: [0, 4, 5],
    6: [1, 2],
    4: [3, 6],
    }
</code>```

A combination of unique and wheres does the trick,

```<code>uniques = numpy.unique(a)
bins = {u: numpy.where(a == u)[0] for u in uniques}
</code>```

but this doesn't seem ideal since the number of unique entries may be large.

答:
Here's one approach -

```<code>def groupby_uniqueness_dict(a):
    sidx = a.argsort()
    b = a[sidx]
    cut_idx = np.flatnonzero(b[1:] != b[:-1])+1
    parts = np.split(sidx, cut_idx)
    out = dict(zip(b[np.r_[0,cut_idx]], parts))
    return out
</code>```

More efficient one by avoiding the use of np.split -

```<code>def groupby_uniqueness_dict_v2(a):
    sidx = a.argsort()  # use .tolist() for output dict values as lists
    b = a[sidx]
    cut_idx = np.flatnonzero(b[1:] != b[:-1])+1
    idxs = np.r_[0,cut_idx, len(b)+1]
    out = {b[i]:sidx[i:j] for i,j in zip(idxs[:-1], idxs[1:])}
    return out
</code>```

Sample run -

```<code>In [161]: a
Out[161]: array([1, 6, 6, 4, 1, 1, 4])

In [162]: groupby_uniqueness_dict(a)
Out[162]: {1: array([0, 4, 5]), 4: array([3, 6]), 6: array([1, 2])}
</code>```

Runtime test

Other approach(es) -

```<code>from collections import defaultdict

def defaultdict_app(a): # @Grisha's soln
    d = defaultdict(list)
    for ix, val in enumerate(a):
        d[val].append(ix)
    return d
</code>```

Timings -

Case #1 : Dict values as arrays

```<code>In [226]: a = np.random.randint(0,1000, 10000)

In [227]: %timeit defaultdict_app(a)
     ...: %timeit groupby_uniqueness_dict(a)
     ...: %timeit groupby_uniqueness_dict_v2(a)
100 loops, best of 3: 4.06 ms per loop
100 loops, best of 3: 3.06 ms per loop
100 loops, best of 3: 2.02 ms per loop

In [228]: a = np.random.randint(0,10000, 100000)

In [229]: %timeit defaultdict_app(a)
     ...: %timeit groupby_uniqueness_dict(a)
     ...: %timeit groupby_uniqueness_dict_v2(a)
10 loops, best of 3: 43.5 ms per loop
10 loops, best of 3: 29.1 ms per loop
100 loops, best of 3: 19.9 ms per loop
</code>```

Case #2 : Dict values as lists

```<code>In [238]: a = np.random.randint(0,1000, 10000)

In [239]: %timeit defaultdict_app(a)
     ...: %timeit groupby_uniqueness_dict(a)
     ...: %timeit groupby_uniqueness_dict_v2(a)
100 loops, best of 3: 4.15 ms per loop
100 loops, best of 3: 4.5 ms per loop
100 loops, best of 3: 2.44 ms per loop

In [240]: a = np.random.randint(0,10000, 100000)

In [241]: %timeit defaultdict_app(a)
     ...: %timeit groupby_uniqueness_dict(a)
     ...: %timeit groupby_uniqueness_dict_v2(a)
10 loops, best of 3: 57.5 ms per loop
10 loops, best of 3: 54.6 ms per loop
10 loops, best of 3: 34 ms per loop
</code>```

Title: put numpy array items into "bins"

Body:
I have a numpy array with some integers, e.g.,

a = numpy.array([1, 6, 6, 4, 1, 1, 4])

I would now like to put all items into "bins" of equal values such that the bin with label 1 contains all indices of a that have the value 1. For the above example:

bins = {
    1: [0, 4, 5],
    6: [1, 2],
    4: [3, 6],
    }

A combination of unique and wheres does the trick,

uniques = numpy.unique(a)
bins = {u: numpy.where(a == u)[0] for u in uniques}

but this doesn't seem ideal since the number of unique entries may be large.

Body:
Here's one approach -

def groupby_uniqueness_dict(a):
    sidx = a.argsort()
    b = a[sidx]
    cut_idx = np.flatnonzero(b[1:] != b[:-1])+1
    parts = np.split(sidx, cut_idx)
    out = dict(zip(b[np.r_[0,cut_idx]], parts))
    return out

More efficient one by avoiding the use of np.split -

def groupby_uniqueness_dict_v2(a):
    sidx = a.argsort()  # use .tolist() for output dict values as lists
    b = a[sidx]
    cut_idx = np.flatnonzero(b[1:] != b[:-1])+1
    idxs = np.r_[0,cut_idx, len(b)+1]
    out = {b[i]:sidx[i:j] for i,j in zip(idxs[:-1], idxs[1:])}
    return out

Sample run -

In [161]: a
Out[161]: array([1, 6, 6, 4, 1, 1, 4])

In [162]: groupby_uniqueness_dict(a)
Out[162]: {1: array([0, 4, 5]), 4: array([3, 6]), 6: array([1, 2])}

Runtime test

Other approach(es) -

from collections import defaultdict

def defaultdict_app(a): # @Grisha's soln
    d = defaultdict(list)
    for ix, val in enumerate(a):
        d[val].append(ix)
    return d

Timings -

Case #1 : Dict values as arrays

In [226]: a = np.random.randint(0,1000, 10000)

In [227]: %timeit defaultdict_app(a)
     ...: %timeit groupby_uniqueness_dict(a)
     ...: %timeit groupby_uniqueness_dict_v2(a)
100 loops, best of 3: 4.06 ms per loop
100 loops, best of 3: 3.06 ms per loop
100 loops, best of 3: 2.02 ms per loop

In [228]: a = np.random.randint(0,10000, 100000)

In [229]: %timeit defaultdict_app(a)
     ...: %timeit groupby_uniqueness_dict(a)
     ...: %timeit groupby_uniqueness_dict_v2(a)
10 loops, best of 3: 43.5 ms per loop
10 loops, best of 3: 29.1 ms per loop
100 loops, best of 3: 19.9 ms per loop

Case #2 : Dict values as lists

In [238]: a = np.random.randint(0,1000, 10000)

In [239]: %timeit defaultdict_app(a)
     ...: %timeit groupby_uniqueness_dict(a)
     ...: %timeit groupby_uniqueness_dict_v2(a)
100 loops, best of 3: 4.15 ms per loop
100 loops, best of 3: 4.5 ms per loop
100 loops, best of 3: 2.44 ms per loop

In [240]: a = np.random.randint(0,10000, 100000)

In [241]: %timeit defaultdict_app(a)
     ...: %timeit groupby_uniqueness_dict(a)
     ...: %timeit groupby_uniqueness_dict_v2(a)
10 loops, best of 3: 57.5 ms per loop
10 loops, best of 3: 54.6 ms per loop
10 loops, best of 3: 34 ms per loop


问:
Finding matches in python 3
I have two files with lots of columns and different information about a bunch of objects, that come with object IDs. I need to find matches between the two files, but the object IDs come in two different formats:

12-12-1 in one file will be written as 0012 00012 1 in the other. For instance, in one file I have:

```<code>0001 01531 1
0001 01535 1
0001 01538 1
</code>```

Which corresponds to this in the other:

```<code>1-1531-1
1-1535-1
1-1538-1
</code>```

Something as simple as

```<code>matches = open('matches.dat','w')
for j in range(len(file1)):
    for i in range(len(file2)):
        if file1[j] == file2[i]:
            matches.write('{}/n'.format(file1[j]))
</code>```

doesn't seem to do the trick.

file1 and file2 here are lists that contain all the object IDs from the different files.

What do I add to my code to find the matches?

答:
A few notes:

-You don't close your matches file at the end of your code. Using with will automatically take care of file cleanup.

-Your newline character in the last line of your code isn't escaped properly - it's \n, not /n.

If your numeric formatting is always constant (i.e. the first column is always padded to four values, the second is always padded to 5, and the last is never padded), this should work:

```<code>with open('matches.dat', 'w') as matches:
    for j in range(len(file1)):
        for i in range(len(file2)):
            match_list = file2[i].split('-')
            match_str = '{} {} {}'.format(match_list[0].zfill(4), match_list[1].zfill(5), match_list[2])
            if file1[j] == match_str:
                matches.write('{}\n'.format(file1[j]))
</code>```

Title: Finding matches in python 3

Body:
I have two files with lots of columns and different information about a bunch of objects, that come with object IDs. I need to find matches between the two files, but the object IDs come in two different formats:

12-12-1 in one file will be written as 0012 00012 1 in the other. For instance, in one file I have:

0001 01531 1
0001 01535 1
0001 01538 1

Which corresponds to this in the other:

1-1531-1
1-1535-1
1-1538-1

Something as simple as

matches = open('matches.dat','w')
for j in range(len(file1)):
    for i in range(len(file2)):
        if file1[j] == file2[i]:
            matches.write('{}/n'.format(file1[j]))

doesn't seem to do the trick.

file1 and file2 here are lists that contain all the object IDs from the different files.

What do I add to my code to find the matches?

Body:
A few notes:

-You don't close your matches file at the end of your code. Using with will automatically take care of file cleanup.

-Your newline character in the last line of your code isn't escaped properly - it's \n, not /n.

If your numeric formatting is always constant (i.e. the first column is always padded to four values, the second is always padded to 5, and the last is never padded), this should work:

with open('matches.dat', 'w') as matches:
    for j in range(len(file1)):
        for i in range(len(file2)):
            match_list = file2[i].split('-')
            match_str = '{} {} {}'.format(match_list[0].zfill(4), match_list[1].zfill(5), match_list[2])
            if file1[j] == match_str:
                matches.write('{}\n'.format(file1[j]))


问:
Test a controller in .Net Core always returns false?
I write the following XUnit test to test a .Net Core WebApi controller's action:

```<code>namespace VistaBest.XUnitTest.Api.Test
{
    public class Account_UnitTest
    {
        [Fact]
        public void ValidateUserTest()
        {
            const string username = "admin";
            const string password = "admin";
            var usersBusinessObjectMock = new Mock<IUsersBusinessObject>();
            usersBusinessObjectMock.Setup(service => service.ValidateUser(username, password)).Returns(() => true);
            var controller = new AccountController(usersBusinessObjectMock.Object);
            var actionResult = controller.ValidateUser(new LoginModel
            {
                Username = username,
                Password = password
            });
            var okObjectResult = Assert.IsType<OkObjectResult>(actionResult);
            var result = okObjectResult.Value as bool?;
            Assert.True(result);
        }
    }
}
</code>```

AccountController:

```<code>namespace VistaBest.Api.Controllers
{
    public class AccountController : BaseController
    {
        private readonly IUsersBusinessObject _usersBusinessObject;
        public AccountController(IUsersBusinessObject usersBusinessObject)
        {
            _usersBusinessObject = usersBusinessObject;
        }

        [HttpPost]
        public IActionResult ValidateUser(LoginModel model)
        {
            if(!ModelState.IsValid) return BadRequest(ModelState);
            return Ok(_usersBusinessObject.ValidateUser(model.Username, model.Password.ToMd5Hash()));
        }
    }
}
</code>```

IUsersBusinessObject:

```<code>namespace VistaBest.Data.BusinessObjects
{
    public interface IUsersBusinessObject
    {
        bool ValidateUser(string username, string password);
        UserModel SelectByUsername(string username);
    }

    public class UsersBusinessObject : BaseBusinessObject, IUsersBusinessObject
    {
        public UsersBusinessObject(IDbConnection connection) : base(connection)
        {

        }

        private const string TableName = "Users";

        public bool ValidateUser(string username, string password)
        {
            var query = $"SELECT COUNT(*) FROM [{TableName}] WHERE UserName = @username and Password = @password";
            return DbConnection.QueryFirst<int>(query, new { username, password }) == 1;
        }
}
</code>```

As you see I said usersBusinessObjectMock must return true:

```<code>usersBusinessObjectMock
    .Setup(service => service.ValidateUser(username, password))
    .Returns(() => true);
</code>```

But var result = okObjectResult.Value as bool?; is always false

What's wrong?

答:
This will work and I make some small refactor in your code.</p>

```<code>namespace VistaBest.XUnitTest.Api.Test
{
  public class Account_UnitTest
  {
    private readonly Mock<IUsersBusinessObject> _usersBusinessObjectMock;
    private readonly AccountController _accountController;
    public Account_UnitTest()
    {
       _usersBusinessObjectMock = new Mock<IUsersBusinessObject>();
       _accountController = new AccountController(_usersBusinessObjectMock.Object);
    }

    [Fact]
    public void ValidateUserTest()
    {
        var model = new LoginModel
        {
            Username = "admin",
            Password = "admin"
        };

        _usersBusinessObjectMock.Setup(service => service.ValidateUser(model.Username, model.Password)).Returns(() => true);

        var actual = _accountController.ValidateUser(model) as OkObjectResult;

        actual.Value.ShouldBeEquivalentTo(true);
        // or Assert.True(actual.Value);
    }
  }
}
</code>```

Body:
I write the following XUnit test to test a .Net Core WebApi controller's action:

namespace VistaBest.XUnitTest.Api.Test
{
    public class Account_UnitTest
    {
        [Fact]
        public void ValidateUserTest()
        {
            const string username = "admin";
            const string password = "admin";
            var usersBusinessObjectMock = new Mock<IUsersBusinessObject>();
            usersBusinessObjectMock.Setup(service => service.ValidateUser(username, password)).Returns(() => true);
            var controller = new AccountController(usersBusinessObjectMock.Object);
            var actionResult = controller.ValidateUser(new LoginModel
            {
                Username = username,
                Password = password
            });
            var okObjectResult = Assert.IsType<OkObjectResult>(actionResult);
            var result = okObjectResult.Value as bool?;
            Assert.True(result);
        }
    }
}

AccountController:

namespace VistaBest.Api.Controllers
{
    public class AccountController : BaseController
    {
        private readonly IUsersBusinessObject _usersBusinessObject;
        public AccountController(IUsersBusinessObject usersBusinessObject)
        {
            _usersBusinessObject = usersBusinessObject;
        }

        [HttpPost]
        public IActionResult ValidateUser(LoginModel model)
        {
            if(!ModelState.IsValid) return BadRequest(ModelState);
            return Ok(_usersBusinessObject.ValidateUser(model.Username, model.Password.ToMd5Hash()));
        }
    }
}

IUsersBusinessObject:

namespace VistaBest.Data.BusinessObjects
{
    public interface IUsersBusinessObject
    {
        bool ValidateUser(string username, string password);
        UserModel SelectByUsername(string username);
    }

    public class UsersBusinessObject : BaseBusinessObject, IUsersBusinessObject
    {
        public UsersBusinessObject(IDbConnection connection) : base(connection)
        {

        }

        private const string TableName = "Users";

        public bool ValidateUser(string username, string password)
        {
            var query = $"SELECT COUNT(*) FROM [{TableName}] WHERE UserName = @username and Password = @password";
            return DbConnection.QueryFirst<int>(query, new { username, password }) == 1;
        }
}

As you see I said usersBusinessObjectMock must return true:

usersBusinessObjectMock
    .Setup(service => service.ValidateUser(username, password))
    .Returns(() => true);

But var result = okObjectResult.Value as bool?; is always false

What's wrong?

Body:
This will work and I make some small refactor in your code.

namespace VistaBest.XUnitTest.Api.Test
{
  public class Account_UnitTest
  {
    private readonly Mock<IUsersBusinessObject> _usersBusinessObjectMock;
    private readonly AccountController _accountController;
    public Account_UnitTest()
    {
       _usersBusinessObjectMock = new Mock<IUsersBusinessObject>();
       _accountController = new AccountController(_usersBusinessObjectMock.Object);
    }

    [Fact]
    public void ValidateUserTest()
    {
        var model = new LoginModel
        {
            Username = "admin",
            Password = "admin"
        };

        _usersBusinessObjectMock.Setup(service => service.ValidateUser(model.Username, model.Password)).Returns(() => true);

        var actual = _accountController.ValidateUser(model) as OkObjectResult;

        actual.Value.ShouldBeEquivalentTo(true);
        // or Assert.True(actual.Value);
    }
  }
}


问:
cannot use the part to traverse the element
I have this query:

```<code> Query query = new Query();
 query.addCriteria(where("cakes.color.owner._id").is(new ObjectId(person.getId())));

 Update update = new Update();
 update.set("cakes.color.owner", person);

 mongoOperations.updateMulti(query, update, StockEntity.class);
</code>```

And this the structure of the objects that I use:

```<code>    public class StockEntity {
            private List<Cake> cakes= new ArrayList<>();
    }

    public class Cake implements Serializable {
            private Color color;
    }

    public class Color implements Serializable {
            private Seller owner;
    }
</code>```

The problem is that I get the error:

```<code>Write failed with error code 16837 and error message 'cannot use the part (cakes of cakes.color.owner) to traverse the element({cakes:[{cake:{color:{owner:_id:ObjectId('5a0c1bd15efad44437b2e76d')}}}]} )
</code>```

Why do I have this error? any idea?

Thanks!

答:
There are limitations to the positional operator $ https://docs.mongodb.com/manual/reference/operator/update/positional/
I assume you use mongo version <= 3.4

Try this out: update.set("cakes.$.color.owner", person);

Body:
I have this query:

 Query query = new Query();
 query.addCriteria(where("cakes.color.owner._id").is(new ObjectId(person.getId())));

 Update update = new Update();
 update.set("cakes.color.owner", person);

 mongoOperations.updateMulti(query, update, StockEntity.class);

And this the structure of the objects that I use:

    public class StockEntity {
            private List<Cake> cakes= new ArrayList<>();
    }

    public class Cake implements Serializable {
            private Color color;
    }

    public class Color implements Serializable {
            private Seller owner;
    }

The problem is that I get the error:

Write failed with error code 16837 and error message 'cannot use the part (cakes of cakes.color.owner) to traverse the element({cakes:[{cake:{color:{owner:_id:ObjectId('5a0c1bd15efad44437b2e76d')}}}]} )

Why do I have this error? any idea?

Thanks!


问:
Why image not taking the whole width of the browser on MAC?
I developed a website that contain some images , some of them are main images with about 3000px in width .

I'm using this to make the image fill the whole width and it's working with me during testing but the client said that it's not taking the whole width and sent me screenshots :

```<code>img{
  display:block;
  max-width:100%
  height:auto;
}
</code>```

Here is the demo link of the website:
http://www.zhtml.aba.ae

How to make it work?

He was browsing it from Chrome Browser on MAC

答:
You only defined the maximum width, which is 100% of the page. You should try to replace "max-width" for just "width".</p>

```<code>img{
  display:block;
  width:100%
  height:auto;
}
</code>```

Body:
I developed a website that contain some images , some of them are main images with about 3000px in width .

I'm using this to make the image fill the whole width and it's working with me during testing but the client said that it's not taking the whole width and sent me screenshots :

img{
  display:block;
  max-width:100%
  height:auto;
}

Here is the demo link of the website:
http://www.zhtml.aba.ae

How to make it work?

He was browsing it from Chrome Browser on MAC

Body:
You only defined the maximum width, which is 100% of the page. You should try to replace "max-width" for just "width".

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


问:
Extracting the (i) estimated variance-covariance matrix of random effects and/or (ii) mixed model equation solutions from lme4 as matrices?
As the title says I am trying to extract matrices from an lme4 (or other packages?) object. To make clear what I want precisely I think it is easiest to refer to the SAS documentation: https://support.sas.com/documentation/cdl/en/statug/63033/HTML/default/viewer.htm#statug_mixed_sect022.htm

Variance-covariance matrix of random effects

In SAS notation this matrix is called G and is the variance-covariance matrix of the random effect parameter gamma. By using the option "G" in PROC MIXED and  the Output Delivery System you obtain G as a matrix.

I am aware that it is relatively simple to construct this matrix manually once I have the variance components and dimensions of gamma. I nevertheless expected there to be an even simpler way.

Mixed model equations solution

In SAS notation these are called C.
By using the option "MMEQSOL" in PROC MIXED and  the Output Delivery System you request that a solution to the mixed model equations be produced, as well as the inverted coefficients matrix. It is the latter that I am interested in.

Thanks in advance!

答:
Not a very sensible model (see ?lme4::cake), but reasonable for illustration:

```<code>library(lme4)
fm1 <- lmer(angle ~ temperature +
           (1|recipe)+(1|replicate), cake)
</code>```

The VarCorr() method gives a list of variance-covariance matrices for each term (in this case each one is 1x1), with its own print method:

```<code>v <- VarCorr(fm1)
</code>```

You can combine these into a single matrix by using the bdiag() (block-diagonal) function from Matrix (as.matrix() converts from a sparse matrix to a standard (dense) R matrix object).

```<code>as.matrix(Matrix::bdiag(v))
##          [,1]      [,2]
## [1,] 39.21541 0.0000000
## [2,]  0.00000 0.4949681
</code>```

The C matrix is unfortunately not so easy to get. As discussed in vignette("lmer",package="lme4"), lme4 doesn't use the Henderson-equation formulation. The upper block of C (variance-covariance matrix of fixed effects) is accessible via vcov(), but the variance-covariance matrix of the variances is not so easy: see e.g. here.

Body:
Not a very sensible model (see ?lme4::cake), but reasonable for illustration:

library(lme4)
fm1 <- lmer(angle ~ temperature +
           (1|recipe)+(1|replicate), cake)

The VarCorr() method gives a list of variance-covariance matrices for each term (in this case each one is 1x1), with its own print method:

v <- VarCorr(fm1)

You can combine these into a single matrix by using the bdiag() (block-diagonal) function from Matrix (as.matrix() converts from a sparse matrix to a standard (dense) R matrix object).

as.matrix(Matrix::bdiag(v))
##          [,1]      [,2]
## [1,] 39.21541 0.0000000
## [2,]  0.00000 0.4949681

The C matrix is unfortunately not so easy to get. As discussed in vignette("lmer",package="lme4"), lme4 doesn't use the Henderson-equation formulation. The upper block of C (variance-covariance matrix of fixed effects) is accessible via vcov(), but the variance-covariance matrix of the variances is not so easy: see e.g. here.


问:
Is it possible to use the same session variable on the index and a underpage without cookies?
I try to use the same session variable I created in localhost/project/underpages/page.php in localhost/project/index.php.

But if I check with var_dump it says null so there must be something wrong.

page.php

```<code><?php
    session_start();
    $_SESSION['loggedin'] = true;
    header("Location: ../index.php?logged-in");
?>
</code>```

index.php

```<code>  <?php
        session_start();
        var_dump $_SESSION['loggedin'];
    ?>
</code>```

I thougt now must be written true and not null.

Can someone help me? Thank you

答:
I just try your code and it works fine...
When you go on localhost/project/underpages/page.php
It redirect you to localhost/project/index.php?logged-in
and then I got this statement path/index.php:3:boolean true

I just notice that u use  var_dump $_SESSION['loggedin']; without "()", so you need to use var_dump($_SESSION['loggedin']);, I hope that this will resolve your problem

Body:
I try to use the same session variable I created in localhost/project/underpages/page.php in localhost/project/index.php.

But if I check with var_dump it says null so there must be something wrong.

page.php

<?php
    session_start();
    $_SESSION['loggedin'] = true;
    header("Location: ../index.php?logged-in");
?>

index.php

  <?php
        session_start();
        var_dump $_SESSION['loggedin'];
    ?>

I thougt now must be written true and not null.

Can someone help me? Thank you


问:
TypeError: util.promisify is not a function?
I'm trying to promisify zlib.gunzip in my react application:

```<code>const zlib = require('zlib')
const util = require('util')

const gunzipPromisified = util.promisify(zlib.gunzip)
</code>```

But I get this error:

TypeError: util.promisify is not a function

That works fine if I put it in a standalone script file and run it through node.

If I try:

```<code>import zlib from 'zlib'
import util from 'util'

const gunzipPromisified = util.promisify(zlib.gunzip)
</code>```

I get something even fancier:

TypeError: __WEBPACK_IMPORTED_MODULE_8_util___default.a.promisify is not a function

What am I missing?

[Edit] The node.js version installed on my laptop is 8.9.1.

[Edit] As somebody commented, the node.js installed in my local development environment has nothing to do with what the app code has access to in the browser. So now my question is, how do I determine what API I have access to in the browser?

答: Of course everything works fine when I switch to bluebird's Promise.

Body:
I'm trying to promisify zlib.gunzip in my react application:

const zlib = require('zlib')
const util = require('util')

const gunzipPromisified = util.promisify(zlib.gunzip)

But I get this error:

TypeError: util.promisify is not a function

That works fine if I put it in a standalone script file and run it through node.

If I try:

import zlib from 'zlib'
import util from 'util'

const gunzipPromisified = util.promisify(zlib.gunzip)

I get something even fancier:

TypeError: __WEBPACK_IMPORTED_MODULE_8_util___default.a.promisify is not a function

What am I missing?

[Edit] The node.js version installed on my laptop is 8.9.1.

[Edit] As somebody commented, the node.js installed in my local development environment has nothing to do with what the app code has access to in the browser. So now my question is, how do I determine what API I have access to in the browser?


答:
I think it would be better to filter the file1 list before transforming it into a map rather than creating the map and then filtering it.

```<code>let requestMap yob =
let filtered =
    List.filter (fun client ->
      match client with
      | { Client.birth = year } when year = yob -> true
      | _ -> false) file1
Map.ofList [for f in filtered do yield f.name,(f.phone,f.sex,f.birth,f.interests)]
</code>```

Title: F# Applying Map.filter on Map derived from list of records

Body:
I think it would be better to filter the file1 list before transforming it into a map rather than creating the map and then filtering it.

let requestMap yob =
let filtered =
    List.filter (fun client ->
      match client with
      | { Client.birth = year } when year = yob -> true
      | _ -> false) file1
Map.ofList [for f in filtered do yield f.name,(f.phone,f.sex,f.birth,f.interests)]


问:
Request for the detailed description of "Static Initialization Order Fiasco"
I read about the SIOF in the faq-lite and still I really don't understand why the issue happens. I have a static library(.a) and I use that library to use its static const data member object type. Then that static const data member object type I use and assign to a global variable(object). But it seems that global variable is empty when I use that global variable to my main or to any local function. I know obviously that my issue is SIOF but I really don't understand why my static const data member object was not initialized.

It was static library so I guess when we created our static library the static const data member object was compiled and linked to that static library, correct me if I'm wrong..

```<code>//libsource.h
class foo
{
   public:
   ....

   public:
   static const barbar foofaa;
};

//libsource.cpp
const barbar foo::foofaa = barbar();

//main.cpp
#include <libsource.h>

barbar foos= foo::foofaa;

int main()
{
   //can't use foos because its empty
}
</code>```

Please advice. Why that static const data member object was not initialized even if its in the static library?

Many thanks.

答:
The static initialization order fiasco is fairly straightforward:  static objects in a single translation unit are initialized in the order in which they are declared, but there is no guarantee as to the order in which static objects in different translation units are initialized with respect to each other.

So, in your specific example, foos in main.cpp may be initialized before foo::foofaa, which is declared in libsource.cpp.

Body:
I read about the SIOF in the faq-lite and still I really don't understand why the issue happens. I have a static library(.a) and I use that library to use its static const data member object type. Then that static const data member object type I use and assign to a global variable(object). But it seems that global variable is empty when I use that global variable to my main or to any local function. I know obviously that my issue is SIOF but I really don't understand why my static const data member object was not initialized.

It was static library so I guess when we created our static library the static const data member object was compiled and linked to that static library, correct me if I'm wrong..

//libsource.h
class foo
{
   public:
   ....

   public:
   static const barbar foofaa;
};

//libsource.cpp
const barbar foo::foofaa = barbar();

//main.cpp
#include <libsource.h>

barbar foos= foo::foofaa;

int main()
{
   //can't use foos because its empty
}

Please advice. Why that static const data member object was not initialized even if its in the static library?

Many thanks.


答:
One method uses group by with a having clause that counts the times in the time period:

```<code>select tt.[date]
from TestingTable tt
group by tt.[date]
having sum(case when [time] >= @mintime and [time] <= @maxtime then 1 else 0 end) = 0;
</code>```

Title: SQL: Filtering data which has some records outside time interval and nothing inside

Body:
I need return only dates which has some values outside time interval and nothing inside time interval.

create table dbo.TestingTable
(
     [Group] varchar(20)
    ,[Date] int
    ,[Time] time
)

insert into dbo.TestingTable values
('ddo',20171108, '02:00:00.0000000')
,('ddo',20171108, '03:00:00.0000000')
,('ddo',20171108, '05:00:00.0000000')
,('ddo',20171108, '08:00:00.0000000')
,('ddo',20171108, '17:00:00.0000000')
,('ddo',20171108, '19:00:00.0000000')
,('ddo',20171108, '23:00:00.0000000')
,('ddo',20171109, '04:00:00.0000000')
,('ddo',20171109, '06:00:00.0000000')
,('ddo',20171109, '08:00:00.0000000')
,('ddo',20171109, '15:00:00.0000000')
,('ddo',20171109, '21:00:00.0000000')
,('kpo',20171108, '02:00:00.0000000')
,('kpo',20171108, '03:00:00.0000000')
,('kpo',20171108, '05:00:00.0000000')
,('kpo',20171108, '08:00:00.0000000')
,('kpo',20171108, '15:00:00.0000000')
,('kpo',20171108, '19:00:00.0000000')

So desired output for predefined @group, @mintime and @maxtime

declare @group as varchar(20) = 'ddo'
declare @mintime as varchar(20) = '09:00:00.0000000'
declare @maxtime as varchar(20) = '16:00:00.0000000'

should be [Date] column with dates passes condition.

In above case should return just 20171108 [Date], because 20171109 has some value inside interval between @mintime and @maxtime.

Body:
One method uses group by with a having clause that counts the times in the time period:

select tt.[date]
from TestingTable tt
group by tt.[date]
having sum(case when [time] >= @mintime and [time] <= @maxtime then 1 else 0 end) = 0;


问:
Check authenticity of SAML assertion message as SP
We are sharing our SP metadata on public URL which also contains our public key and SSO URL (binding as well). I completely understand that public keys are meant to be freely shared between parties. But I am just trying to understand what if an unauthorised user gets access to our public key (as this is available in publicly available metadata) and knows the URL for our company's SSO (that is also available in our publicly available metadata), would they be able to authenticate themselves? How I can ensure that SAML assertion is coming from authorised source only?</p>

答: The SP should have the metadata of the IdP, which includes its signing certificate(s). A SAML exchange can be secured by two way trust using the metadata of the SP and IdP. The IdP will normally sign the AuthenticationStatement in the SAMLResponse and the SP verifies the signature using the certificate(s) in the IdP metadata. Also the SP usually sends the user to the IdP for authentication so the SP is the one that starts the protocol flow.


问:
Retrieve specific field based on structure of file, awk
MyFile:

```<code>    1       Cufflinks       exon    162752  163607  .       +       .       gene_id "XLOC_000001"; transcript_id "TCONS_00000001"; exon_number "1"; oId "CUFF.1.1"; class_code "u"; tss_id "TSS1";
    1       Cufflinks       exon    177199  177399  .       +       .       gene_id "XLOC_000002"; transcript_id "TCONS_00000002"; exon_number "1"; oId "CUFF.3.1"; class_code "u"; tss_id "TSS2";
    1       Cufflinks       exon    178775  179390  .       +       .       gene_id "XLOC_000003"; transcript_id "TCONS_00000003"; exon_number "1"; gene_name "ENSORLG00000000007"; oId "CUFF.15.1"; nearest_ref "ENSORLT00000000006"; class_code "s"; tss_id "TSS3";
    1       Cufflinks       exon    218671  219224  .       +       .       gene_id "XLOC_000007"; transcript_id "TCONS_00000005"; exon_number "1"; gene_name "slc43a1b"; oId "CUFF.50.1"; nearest_ref "ENSORLT00000000013"; class_code "s"; tss_id "TSS7";
</code>```

Disired output:

```<code>    1       Cufflinks       exon    162752  163607  .       +       .       gene_id "XLOC_000001"; transcript_id "TCONS_00000001"; exon_number "1"; oId "CUFF.1.1"; class_code "u"; tss_id "TSS1";
    1       Cufflinks       exon    177199  177399  .       +       .       gene_id "XLOC_000002"; transcript_id "TCONS_00000002"; exon_number "1"; oId "CUFF.3.1"; class_code "u"; tss_id "TSS2";
    1       Cufflinks       exon    180630  180720  .       +       .       gene_id "XLOC_000003"; transcript_id "ENSORLT00000000006"; exon_number "5"; gene_name "ENSORLG00000000007"; oId "CUFF.15.1"; nearest_ref "ENSORLT00000000006"; class_code "s"; tss_id "TSS3";
    1       Cufflinks       exon    218671  219224  .       +       .       gene_id "XLOC_000007"; transcript_id "ENSORLT00000000013"; exon_number "1"; gene_name "slc43a1b"; oId "CUFF.50.1"; nearest_ref "ENSORLT00000000013"; class_code "s"; tss_id "TSS7";
</code>```

Explanation:

If there is a field nearest_ref, write it in field transcript_id, else, do nothing.

Field nearest_ref:

```<code>nearest_ref "XXXXXXX";
</code>```

Field transcript_id:

```<code>transcript_id "XXXXXXX";
</code>```

I would like a awk solution if possible.

I don't know how to retrive fields based on their name and not on their position :

```<code>awk -v FS=" " 'length($20)>20{$12=$20} 1' MyFile |less
</code>```

Note : File is tab separated, 9th column is space separated.

Edit: Found a way to do it, but it is really bad, I am still interested in a better way to do it:

```<code>awk -v FS=" " -v OFS="\t" 'length($20)>20{$12=$20} 1' MyFile | sed "s/;\t/; /g" | sed 's/\t"/ "/g'
</code>```

答:
Whenever you have name->value pairs, I find it's clearest and easiest to modify in future to first create an array to hold that mapping (n2v[] below) and then just modify the array using the names as indices:

```<code>$ cat tst.awk
BEGIN {
    FS=OFS="\t"
    src = "nearest_ref"
    dst = "transcript_id"
}
{
    n = split($9,f," ")
    delete n2v
    for (i=1; i<=n; i+=2) {
        name  = f[i]
        value = f[i+1]
        n2v[name] = value
    }

    new = ""
    for (i=1; i<=n; i+=2) {
        name  = f[i]
        value = ((name == dst) && (src in n2v) ? n2v[src] : n2v[name])
        new = (i>1 ? new " " : "") name " " value
    }
    $9 = new

    print
}
$
$ awk -f tst.awk file
1       Cufflinks       exon    162752  163607  .       +       .       gene_id "XLOC_000001"; transcript_id "TCONS_00000001"; exon_number "1"; oId "CUFF.1.1"; class_code "u"; tss_id "TSS1";
1       Cufflinks       exon    177199  177399  .       +       .       gene_id "XLOC_000002"; transcript_id "TCONS_00000002"; exon_number "1"; oId "CUFF.3.1"; class_code "u"; tss_id "TSS2";
1       Cufflinks       exon    178775  179390  .       +       .       gene_id "XLOC_000003"; transcript_id "ENSORLT00000000006"; exon_number "1"; gene_name "ENSORLG00000000007"; oId "CUFF.15.1"; nearest_ref "ENSORLT00000000006"; class_code "s"; tss_id "TSS3";
1       Cufflinks       exon    218671  219224  .       +       .       gene_id "XLOC_000007"; transcript_id "ENSORLT00000000013"; exon_number "1"; gene_name "slc43a1b"; oId "CUFF.50.1"; nearest_ref "ENSORLT00000000013"; class_code "s"; tss_id "TSS7";
</code>```

With that you can swap whatever other fields you like, change the order they're output in or do whatever else you like just by accessing the values by their names.

Body:
MyFile:

    1       Cufflinks       exon    162752  163607  .       +       .       gene_id "XLOC_000001"; transcript_id "TCONS_00000001"; exon_number "1"; oId "CUFF.1.1"; class_code "u"; tss_id "TSS1";
    1       Cufflinks       exon    177199  177399  .       +       .       gene_id "XLOC_000002"; transcript_id "TCONS_00000002"; exon_number "1"; oId "CUFF.3.1"; class_code "u"; tss_id "TSS2";
    1       Cufflinks       exon    178775  179390  .       +       .       gene_id "XLOC_000003"; transcript_id "TCONS_00000003"; exon_number "1"; gene_name "ENSORLG00000000007"; oId "CUFF.15.1"; nearest_ref "ENSORLT00000000006"; class_code "s"; tss_id "TSS3";
    1       Cufflinks       exon    218671  219224  .       +       .       gene_id "XLOC_000007"; transcript_id "TCONS_00000005"; exon_number "1"; gene_name "slc43a1b"; oId "CUFF.50.1"; nearest_ref "ENSORLT00000000013"; class_code "s"; tss_id "TSS7";

Disired output:

    1       Cufflinks       exon    162752  163607  .       +       .       gene_id "XLOC_000001"; transcript_id "TCONS_00000001"; exon_number "1"; oId "CUFF.1.1"; class_code "u"; tss_id "TSS1";
    1       Cufflinks       exon    177199  177399  .       +       .       gene_id "XLOC_000002"; transcript_id "TCONS_00000002"; exon_number "1"; oId "CUFF.3.1"; class_code "u"; tss_id "TSS2";
    1       Cufflinks       exon    180630  180720  .       +       .       gene_id "XLOC_000003"; transcript_id "ENSORLT00000000006"; exon_number "5"; gene_name "ENSORLG00000000007"; oId "CUFF.15.1"; nearest_ref "ENSORLT00000000006"; class_code "s"; tss_id "TSS3";
    1       Cufflinks       exon    218671  219224  .       +       .       gene_id "XLOC_000007"; transcript_id "ENSORLT00000000013"; exon_number "1"; gene_name "slc43a1b"; oId "CUFF.50.1"; nearest_ref "ENSORLT00000000013"; class_code "s"; tss_id "TSS7";

Explanation:

If there is a field nearest_ref, write it in field transcript_id, else, do nothing.

Field nearest_ref:

nearest_ref "XXXXXXX";

Field transcript_id:

transcript_id "XXXXXXX";

I would like a awk solution if possible.

I don't know how to retrive fields based on their name and not on their position :

awk -v FS=" " 'length($20)>20{$12=$20} 1' MyFile |less

Note : File is tab separated, 9th column is space separated.

Edit: Found a way to do it, but it is really bad, I am still interested in a better way to do it:

awk -v FS=" " -v OFS="\t" 'length($20)>20{$12=$20} 1' MyFile | sed "s/;\t/; /g" | sed 's/\t"/ "/g'

Body:
Whenever you have name->value pairs, I find it's clearest and easiest to modify in future to first create an array to hold that mapping (n2v[] below) and then just modify the array using the names as indices:

$ cat tst.awk
BEGIN {
    FS=OFS="\t"
    src = "nearest_ref"
    dst = "transcript_id"
}
{
    n = split($9,f," ")
    delete n2v
    for (i=1; i<=n; i+=2) {
        name  = f[i]
        value = f[i+1]
        n2v[name] = value
    }

    new = ""
    for (i=1; i<=n; i+=2) {
        name  = f[i]
        value = ((name == dst) && (src in n2v) ? n2v[src] : n2v[name])
        new = (i>1 ? new " " : "") name " " value
    }
    $9 = new

    print
}
$
$ awk -f tst.awk file
1       Cufflinks       exon    162752  163607  .       +       .       gene_id "XLOC_000001"; transcript_id "TCONS_00000001"; exon_number "1"; oId "CUFF.1.1"; class_code "u"; tss_id "TSS1";
1       Cufflinks       exon    177199  177399  .       +       .       gene_id "XLOC_000002"; transcript_id "TCONS_00000002"; exon_number "1"; oId "CUFF.3.1"; class_code "u"; tss_id "TSS2";
1       Cufflinks       exon    178775  179390  .       +       .       gene_id "XLOC_000003"; transcript_id "ENSORLT00000000006"; exon_number "1"; gene_name "ENSORLG00000000007"; oId "CUFF.15.1"; nearest_ref "ENSORLT00000000006"; class_code "s"; tss_id "TSS3";
1       Cufflinks       exon    218671  219224  .       +       .       gene_id "XLOC_000007"; transcript_id "ENSORLT00000000013"; exon_number "1"; gene_name "slc43a1b"; oId "CUFF.50.1"; nearest_ref "ENSORLT00000000013"; class_code "s"; tss_id "TSS7";

With that you can swap whatever other fields you like, change the order they're output in or do whatever else you like just by accessing the values by their names.


问:
Rails: create a method for a class that needs information from members of its own class?
I was wondering if it's possible to do something like follows:

Let's say I have a Rails model, Foo, with a database attribute value. Foo belongs_to Bar, Bar has_many Foos.

In my model, I'd like to do something like:

```<code>class Foo < ActiveRecord::Base

  belongs_to :bar

  def self.average
    # return the value of all foos here
  end

end
</code>```

Ideally I'd like to have this method return a value that matched the scope from which it was called, so that:

```<code>Foo.average # would return the average value of all foos

@bar = Bar.find(1)
@bar.foos.average # would return the average of all foos where bar_id == 1
</code>```

Can such a thing be done, and if so, how? Thanks!

答:
What you have will work as is, as long as you make sure to call methods on self instead of Foo in the body of the average method. When calling methods on a scope of Foo, self in the body of that method will be assigned to the scope object rather than Foo. Here's a slightly more concrete example:

```<code># app/models/club.rb
class Club < ActiveRecord::Base
  # name:string
  has_many :people
end

# app/models/person.rb
class Person < ActiveRecord::Base
  # club_id:integer, name:string, age:integer
  belongs_to :club

  def self.average_age
    # note that sum and count are being called on self, not Person
    sum('age') / count
  end
end
</code>```

Let's see what happens when we create some clubs and people:

```<code>$ rails console
Loading development environment (Rails 3.0.3)
irb(main):001:0> boys_club = Club.create(:name => 'boys')
irb(main):002:0> girls_club = Club.create(:name => 'girls')
irb(main):003:0> boys_club.people.create(:name => 'bob', :age => 20)
irb(main):004:0> boys_club.people.create(:name => 'joe', :age => 22)
irb(main):005:0> girls_club.people.create(:name => 'betty', :age => 30)
irb(main):006:0> Person.average_age
=> 24
irb(main):007:0> boys_club.people.average_age
=> 21
irb(main):008:0> Person.where("name LIKE 'b%'").average_age
=> 25
</code>```

Body:
I was wondering if it's possible to do something like follows:

Let's say I have a Rails model, Foo, with a database attribute value. Foo belongs_to Bar, Bar has_many Foos.

In my model, I'd like to do something like:

class Foo < ActiveRecord::Base

  belongs_to :bar

  def self.average
    # return the value of all foos here
  end

end

Ideally I'd like to have this method return a value that matched the scope from which it was called, so that:

Foo.average # would return the average value of all foos

@bar = Bar.find(1)
@bar.foos.average # would return the average of all foos where bar_id == 1

Can such a thing be done, and if so, how? Thanks!

Body:
What you have will work as is, as long as you make sure to call methods on self instead of Foo in the body of the average method. When calling methods on a scope of Foo, self in the body of that method will be assigned to the scope object rather than Foo. Here's a slightly more concrete example:

# app/models/club.rb
class Club < ActiveRecord::Base
  # name:string
  has_many :people
end

# app/models/person.rb
class Person < ActiveRecord::Base
  # club_id:integer, name:string, age:integer
  belongs_to :club

  def self.average_age
    # note that sum and count are being called on self, not Person
    sum('age') / count
  end
end

Let's see what happens when we create some clubs and people:

$ rails console
Loading development environment (Rails 3.0.3)
irb(main):001:0> boys_club = Club.create(:name => 'boys')
irb(main):002:0> girls_club = Club.create(:name => 'girls')
irb(main):003:0> boys_club.people.create(:name => 'bob', :age => 20)
irb(main):004:0> boys_club.people.create(:name => 'joe', :age => 22)
irb(main):005:0> girls_club.people.create(:name => 'betty', :age => 30)
irb(main):006:0> Person.average_age
=> 24
irb(main):007:0> boys_club.people.average_age
=> 21
irb(main):008:0> Person.where("name LIKE 'b%'").average_age
=> 25


问:
How to code (first) the following ternary relationship in MVC Entity Framework C# with fluent API?
UPDATE

It seems I did not make my self understood. I might have chosen the problem incorrectly. So I will try with another example which hopefully will illustrate better my problem.

New example: Dog breed - disease - medicine.

Description

A dog breed can be affected by several diseases.

One same disease can affect several dog breeds.

One medicine is effective on one or more disease for a certain dog breed

One medicine is effective for one or more dogs treating a certain disease

Thus, a medicine has a list of pairs  which is necesary and, and though each pair should be unique, there is not a real relation key value because both values can be repeated.

Code

The following code works correctly with EF creating a lookup table between DogBreed and Disease as shown in the image that follows:

```<code>[Table("dog_breed")]
public DogBreed (){
    public int ID { get;set; }
    public string DogBreedName { get;set; }
    public IList<Disease> Diseases { get; set; }
}

[Table("disease")]
public Disease (){
    public int ID { get;set; }
    public string DiseaseName { get;set; }
    public IList<DogBreed> DogBreeds { get; set; }
}
</code>```

The problem

I want to know how to add the entity medicine to my project as follows and get the EF to generate the scheme showed in the next picture.

The code could be something like this:

```<code>[Table("medicine")]
public Medicine (){
    public int ID { get;set; }
    public string MedicineName { get; set; }
    public Lookup<DogBreed,Disease> { get;set; }
}
</code>```

But this does not generate the scheme wanted. How should I proceed?

I'd like to clarify that my doubt is how to make the code automatically generate the structure I want on my data base so I can use entity framework features seamlessly, therefore all solutions implying creating tables on the database manually, or changing the structure (i.e. defining a new class) have already been considered. I'm not looking for proposals on how to bypass the problem.

Old explanation

I have a simple ternary relationship in which three entities relate as I describe below in an example made up for my specific problem. The problem is I do not know how to type the code, to get the tables in my database as I expect them to be.

Entities: Student, Subject, Classroom.

1 Student has several subjects.

1 Subject is attended by several Students.

1 Classroom can hold lessons for several subjects as well as be related to all those students which attend the classes so we would have the following diagram

So this could be easily related in a separate table which would relate the three as follows, where student 1, would take lessons from subject 13, in classroom 2.

This is the behaviour I observe for binary relation when coded the following way:

```<code>[Table("student")]
public class Student
{
[Key]
public int ID {get; set;}
public List<Subject> Subjects;
}

[Table("subject")]
public class Subject
{
[Key]
public int ID {get; set;}
public List<Student> Students;
}
</code>```

In this case, when I run Add-Migration and Update-Database I get a table studentsubject which contains id's for both entities and relates the many to many relationship automatically.

So what would be the way to code the classes if the relationships in as to get that intermediate table with 3 fields, if possible?. Collections, properties, classes dictionaries...?

-The real design for my example is adding to the first listing a the following class:

```<code>[Table("classroom")]
public class Classroom
{
[Key]
public int ID {get; set;}
public KeyValuePair<Student, Subject> StudentSubject;
}
</code>```

Any other configuration of the database gets duplicate data.

A dictionary value does not work (plus, it is not correct as it does not match the real meaning of the entities for there is no real key-value relation in real world between theese three)

In my real problem a student would have a list of subjects, and a subject a list of students. Then separately I would define Classroom and which would be identified by a unique combination of student-subject.

For the time being I will create a class which represents that ternary relationship although I feel this doesn't stick to KISS principle.

I am using Entity Framework 6 on windows and MySql Server.

答:
After searching for a while and waiting for some time I whent back to school and:

By definition, well normalized relationships are binary relationships. Therefore a ternary relationship as described in the example will not work with code first, nevertheless the nature of the relationship makes the  binary relationships that form it (dog breed - medicine, medicine - disease, dog breed - disease) important enough to form entities by their own.

Depending on your problem, you should just choose one to form an entity. So the answer to the question would be...

To take advantage of entity framework and code first, in order to code a ternary relationship you must make the relationship between two of the parts an entity itself.

```<code>[Table("dog_breed")]
public DogBreed (){
    public int ID { get; set; }
    public string DogBreedName { get; set; }
    public List<PairMedicineDisease> PairsMedicineDisease { get; set; }
}

[Table("medicine")]
public Medicine (){
    public int ID { get;set; }
    public string MedicineName { get;set; }
}

[Table("disease")]
public Disease (){
    public int ID { get;set; }
    public string DiseaseName { get;set; }
}

[Table("pair_medicine_disease")]
public PairMedicineDisease (){
    public int ID { get;set; }
    public Disease Disease { get;set; }
    public Medicine Medicine { get;set; }
}
</code>```

Thanks to all who tried to help, specially to @Gert Arnold who pointed me in the right direction.

Body:
UPDATE

It seems I did not make my self understood. I might have chosen the problem incorrectly. So I will try with another example which hopefully will illustrate better my problem.

New example: Dog breed - disease - medicine.

Description

A dog breed can be affected by several diseases.

One same disease can affect several dog breeds.

One medicine is effective on one or more disease for a certain dog breed

One medicine is effective for one or more dogs treating a certain disease

Thus, a medicine has a list of pairs  which is necesary and, and though each pair should be unique, there is not a real relation key value because both values can be repeated.

Code

The following code works correctly with EF creating a lookup table between DogBreed and Disease as shown in the image that follows:

[Table("dog_breed")]
public DogBreed (){
    public int ID { get;set; }
    public string DogBreedName { get;set; }
    public IList<Disease> Diseases { get; set; }
}

[Table("disease")]
public Disease (){
    public int ID { get;set; }
    public string DiseaseName { get;set; }
    public IList<DogBreed> DogBreeds { get; set; }
}

The problem

I want to know how to add the entity medicine to my project as follows and get the EF to generate the scheme showed in the next picture.

The code could be something like this:

[Table("medicine")]
public Medicine (){
    public int ID { get;set; }
    public string MedicineName { get; set; }
    public Lookup<DogBreed,Disease> { get;set; }
}

But this does not generate the scheme wanted. How should I proceed?

I'd like to clarify that my doubt is how to make the code automatically generate the structure I want on my data base so I can use entity framework features seamlessly, therefore all solutions implying creating tables on the database manually, or changing the structure (i.e. defining a new class) have already been considered. I'm not looking for proposals on how to bypass the problem.

Old explanation

I have a simple ternary relationship in which three entities relate as I describe below in an example made up for my specific problem. The problem is I do not know how to type the code, to get the tables in my database as I expect them to be.

Entities: Student, Subject, Classroom.

1 Student has several subjects.

1 Subject is attended by several Students.

1 Classroom can hold lessons for several subjects as well as be related to all those students which attend the classes so we would have the following diagram

So this could be easily related in a separate table which would relate the three as follows, where student 1, would take lessons from subject 13, in classroom 2.

This is the behaviour I observe for binary relation when coded the following way:

[Table("student")]
public class Student
{
[Key]
public int ID {get; set;}
public List<Subject> Subjects;
}

[Table("subject")]
public class Subject
{
[Key]
public int ID {get; set;}
public List<Student> Students;
}

In this case, when I run Add-Migration and Update-Database I get a table studentsubject which contains id's for both entities and relates the many to many relationship automatically.

So what would be the way to code the classes if the relationships in as to get that intermediate table with 3 fields, if possible?. Collections, properties, classes dictionaries...?

-The real design for my example is adding to the first listing a the following class:

[Table("classroom")]
public class Classroom
{
[Key]
public int ID {get; set;}
public KeyValuePair<Student, Subject> StudentSubject;
}

Any other configuration of the database gets duplicate data.

A dictionary value does not work (plus, it is not correct as it does not match the real meaning of the entities for there is no real key-value relation in real world between theese three)

In my real problem a student would have a list of subjects, and a subject a list of students. Then separately I would define Classroom and which would be identified by a unique combination of student-subject.

For the time being I will create a class which represents that ternary relationship although I feel this doesn't stick to KISS principle.

I am using Entity Framework 6 on windows and MySql Server.

Body:
After searching for a while and waiting for some time I whent back to school and:

By definition, well normalized relationships are binary relationships. Therefore a ternary relationship as described in the example will not work with code first, nevertheless the nature of the relationship makes the  binary relationships that form it (dog breed - medicine, medicine - disease, dog breed - disease) important enough to form entities by their own.

Depending on your problem, you should just choose one to form an entity. So the answer to the question would be...

To take advantage of entity framework and code first, in order to code a ternary relationship you must make the relationship between two of the parts an entity itself.

[Table("dog_breed")]
public DogBreed (){
    public int ID { get; set; }
    public string DogBreedName { get; set; }
    public List<PairMedicineDisease> PairsMedicineDisease { get; set; }
}

[Table("medicine")]
public Medicine (){
    public int ID { get;set; }
    public string MedicineName { get;set; }
}

[Table("disease")]
public Disease (){
    public int ID { get;set; }
    public string DiseaseName { get;set; }
}

[Table("pair_medicine_disease")]
public PairMedicineDisease (){
    public int ID { get;set; }
    public Disease Disease { get;set; }
    public Medicine Medicine { get;set; }
}

Thanks to all who tried to help, specially to @Gert Arnold who pointed me in the right direction.


问:
Why does "typedef struct anything_at_all boom;" compile without errors?
Why does

```<code>//The type anything_at_all exists nowhere.
typedef struct anything_at_all lol;
</code>```

compile without errors, whereas

```<code>//The type anything_at_all_2 exists nowhere.
typedef anything_at_all_2 rofl;
</code>```

produces errors?

What's so special about structs? In a way I'm glad it works like this because it allows us to create opaque structs. But it would be nice to understand why it works.

答:
You can declare a struct without defining it.  This is called a forward declaration.  It allows you to do things like this:

```<code>struct s1;

struct s2 {
    int x;
    struct s1 *p;
};

struct s1 {
    int y;
    struct s2 *p;
};
</code>```

Body:
Why does

//The type anything_at_all exists nowhere.
typedef struct anything_at_all lol;

compile without errors, whereas

//The type anything_at_all_2 exists nowhere.
typedef anything_at_all_2 rofl;

produces errors?

What's so special about structs? In a way I'm glad it works like this because it allows us to create opaque structs. But it would be nice to understand why it works.

Body:
You can declare a struct without defining it.  This is called a forward declaration.  It allows you to do things like this:

struct s1;

struct s2 {
    int x;
    struct s1 *p;
};

struct s1 {
    int y;
    struct s2 *p;
};


问:
AutoMapper: Unflattening to constructor
Let's say I have the following classes

```<code>class Foo
{
    public Bar First { get; }

    public Bar Second { get; }

    public Foo(Bar first, Bar second)
    {
        First = first;
        Second = second;
    }
}

class Bar
{
    public string Name { get; set; }
}

class FooDto
{
    public string FirstName { get; set; }

    public string SecondName { get; set; }
}
</code>```

and I want to map FooDto to Foo. I've read about Reverse Mapping and Unflattening so I setup my confoguration like so:

```<code>IMapper mapper = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Foo, FooDto>()
        .ReverseMap();
}).CreateMapper();
</code>```

Unfortunately this fails with

System.ArgumentException : Test.AutoMapper.Foo needs to have a constructor with 0 args or only optional args.

How can I configure AutoMapper to use the Foo constructor without manually mapping all constructor parameters? (In my actual code, the types have more properties)

答:
You have to declare the conversion explicitly, cause the names of the constructor arguments and property names differ. For further informations take a look at the documentation.

Here is a running example:

```<code>public static void Main()
{
    var configuration = new MapperConfiguration(config =>
    {
        config.CreateMap<FooDto, Foo>()
            .ForCtorParam("first", opt => opt.MapFrom(src => src.FirstName))
            .ForCtorParam("second", opt => opt.MapFrom(src => src.SecondName));
        config.CreateMap<string, Bar>().ConvertUsing(value => new Bar() { Name = value });
    });

    var mapper = configuration.CreateMapper();
    var dto = new FooDto() { FirstName = "Hello", SecondName = "World" };

    var foo = mapper.Map<Foo>(dto);

    Console.WriteLine(foo.First.Name);
    Console.WriteLine(foo.Second.Name);
}
</code>```

Title: AutoMapper: Unflattening to constructor

Body:
Let's say I have the following classes

class Foo
{
    public Bar First { get; }

    public Bar Second { get; }

    public Foo(Bar first, Bar second)
    {
        First = first;
        Second = second;
    }
}

class Bar
{
    public string Name { get; set; }
}

class FooDto
{
    public string FirstName { get; set; }

    public string SecondName { get; set; }
}

and I want to map FooDto to Foo. I've read about Reverse Mapping and Unflattening so I setup my confoguration like so:

IMapper mapper = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Foo, FooDto>()
        .ReverseMap();
}).CreateMapper();

Unfortunately this fails with

System.ArgumentException : Test.AutoMapper.Foo needs to have a constructor with 0 args or only optional args.

How can I configure AutoMapper to use the Foo constructor without manually mapping all constructor parameters? (In my actual code, the types have more properties)

Body:
You have to declare the conversion explicitly, cause the names of the constructor arguments and property names differ. For further informations take a look at the documentation.

Here is a running example:

public static void Main()
{
    var configuration = new MapperConfiguration(config =>
    {
        config.CreateMap<FooDto, Foo>()
            .ForCtorParam("first", opt => opt.MapFrom(src => src.FirstName))
            .ForCtorParam("second", opt => opt.MapFrom(src => src.SecondName));
        config.CreateMap<string, Bar>().ConvertUsing(value => new Bar() { Name = value });
    });

    var mapper = configuration.CreateMapper();
    var dto = new FooDto() { FirstName = "Hello", SecondName = "World" };

    var foo = mapper.Map<Foo>(dto);

    Console.WriteLine(foo.First.Name);
    Console.WriteLine(foo.Second.Name);
}


问:
C printf Segmentation fault (core dumped) while mixing with Assembly code
I tried some basic example of mixing C code and x86 Assembly code.
It is simple Find smaller number example.

Here is Assembly code in b.s file (I have to use intel syntax with no prefix and i386 architecture):

```<code>.intel_syntax noprefix
.arch i386

.data
    .globl out_format
    out_format:
        .asciz "min(%i, %i) = %i\n"

.text
    .globl min
    .type min, @function
    min:
        enter 0, 0
        mov ebx, [ebp + 8]
        cmp ebx, [ebp + 12]
        jle 1f
        mov eax, [ebp] + 12
        jmp 2f
        1:
            mov eax, ebx
        2:
            leave
        ret 8

.end
</code>```

Here is the C code in a.c file:

```<code>#include<stdio.h>

extern char out_format;

extern int min(int x, int y);

int main() {
    int x1, x2, r;
    scanf("%i%i", &x1, &x2);
    r = min(x1, x2);
    printf(&out_format, x1, x2, r);

    return 0;
}
</code>```

I compile it with gcc on x64 Arch Linux:

```<code>gcc -m32 -Wall -Werror -g -o p b.s a.c
</code>```

But when I start the executable file p, and insert 2 numbers and hit enter
I get:

```<code>Segmentation fault (core dumped)
</code>```

I researched all previous similar questions, and I tried several things but every time I get the same error.
I also tried to debug it with gdb, and I see that Assembly function min returns the right result, but somehow it always stuck on C printf function.

I tried to not import string out_format from Assembly file, and define it directly in C file (I defined it as simple array of chars, and also as char pointer using malloc and free functions) but it didn't help.

Otherwise the program doesn't give such error if I intialize variable r with some integer instead with result of Assembly function min. But it doesn't have any sense to me as I already checked it with gdb and the Assembly function correctly intialize the variable r with correct smaller number.

Please, can anyone help me with this?

Thanks in advance

答:
At the end I just want to leave the code that works.

File b.s:

```<code>.intel_syntax noprefix
.arch i386

.data
    .globl out_format
    out_format:
        .asciz "min(%i, %i) = %i\n"

.text
    .globl min
    .type min, @function
    min:
        enter 0, 0
        push ebx
        mov ebx, [ebp + 8]
        cmp ebx, [ebp + 12]
        jle 1f
        mov eax, [ebp] + 12
        jmp 2f
        1:
            mov eax, ebx
        2:
            pop ebx
            leave
        ret 8

.end
</code>```

File a.c:

```<code>#include<stdio.h>

extern char out_format;

extern int __attribute__((stdcall)) min(int x, int y);

int main() {
    int x1, x2, r;
    scanf("%i%i", &x1, &x2);
    r = min(x1, x2);
    printf(&out_format, x1, x2, r);

    return 0;
}
</code>```

Thanks everyone for their help.

Body:
I tried some basic example of mixing C code and x86 Assembly code.
It is simple Find smaller number example.

Here is Assembly code in b.s file (I have to use intel syntax with no prefix and i386 architecture):

.intel_syntax noprefix
.arch i386

.data
    .globl out_format
    out_format:
        .asciz "min(%i, %i) = %i\n"

.text
    .globl min
    .type min, @function
    min:
        enter 0, 0
        mov ebx, [ebp + 8]
        cmp ebx, [ebp + 12]
        jle 1f
        mov eax, [ebp] + 12
        jmp 2f
        1:
            mov eax, ebx
        2:
            leave
        ret 8

.end

Here is the C code in a.c file:

#include<stdio.h>

extern char out_format;

extern int min(int x, int y);

int main() {
    int x1, x2, r;
    scanf("%i%i", &x1, &x2);
    r = min(x1, x2);
    printf(&out_format, x1, x2, r);

    return 0;
}

I compile it with gcc on x64 Arch Linux:

gcc -m32 -Wall -Werror -g -o p b.s a.c

But when I start the executable file p, and insert 2 numbers and hit enter
I get:

Segmentation fault (core dumped)

I researched all previous similar questions, and I tried several things but every time I get the same error.
I also tried to debug it with gdb, and I see that Assembly function min returns the right result, but somehow it always stuck on C printf function.

I tried to not import string out_format from Assembly file, and define it directly in C file (I defined it as simple array of chars, and also as char pointer using malloc and free functions) but it didn't help.

Otherwise the program doesn't give such error if I intialize variable r with some integer instead with result of Assembly function min. But it doesn't have any sense to me as I already checked it with gdb and the Assembly function correctly intialize the variable r with correct smaller number.

Please, can anyone help me with this?

Thanks in advance

Body:
At the end I just want to leave the code that works.

File b.s:

.intel_syntax noprefix
.arch i386

.data
    .globl out_format
    out_format:
        .asciz "min(%i, %i) = %i\n"

.text
    .globl min
    .type min, @function
    min:
        enter 0, 0
        push ebx
        mov ebx, [ebp + 8]
        cmp ebx, [ebp + 12]
        jle 1f
        mov eax, [ebp] + 12
        jmp 2f
        1:
            mov eax, ebx
        2:
            pop ebx
            leave
        ret 8

.end

File a.c:

#include<stdio.h>

extern char out_format;

extern int __attribute__((stdcall)) min(int x, int y);

int main() {
    int x1, x2, r;
    scanf("%i%i", &x1, &x2);
    r = min(x1, x2);
    printf(&out_format, x1, x2, r);

    return 0;
}

Thanks everyone for their help.


问:
Animation in react-dnd
In this Angular example, if you drag an apple to the orange section and drop it there, then there is an animation which slowly returns the apple to the spot it came from. This visually communicates that dragging an apple to the orange section is not valid. The Angular drag and drop library used is from codef0rmer.

How would I create a similar animation in react-dnd or another react drag and drop package?

Here is a React drag and drop example with some animation. Can I do something like this with react-dnd, or another widely used package?

The rest is the Angular sample code which is also in plnkr Angular example.

index.html:

```<code><!DOCTYPE html>
<html ng-app="drag-and-drop">

<head lang="en">
  <meta charset="utf-8">
  <title>Drag & Drop: Multiple listsr</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/ui-lightness/jquery-ui.min.css" rel="stylesheet" type="text/css" />
  <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.1/css/bootstrap.min.css" rel="stylesheet">
  <script src="angular-dragdrop.min.js"></script>
  <script src="app.js"></script>
  <style>
    .thumbnail {
      height: 280px !important;
    }

    .btn-droppable {
      width: 180px;
      height: 30px;
      padding-left: 4px;
    }

    .btn-draggable {
      width: 160px;
    }
  </style>
</head>
<body>
  <div ng-controller="oneCtrl">
    <!-- Drag Apple -->
    <div>
      <div class="btn"
        ng-repeat="item in applesin"
        data-drag=true
        data-jqyoui-options="{revert: 'invalid'}"
        ng-model="applesin"
        jqyoui-draggable="{index: {{$index}}, placeholder:'keep', animate:true}"
      >
        {{item.title}}
      </div>
    </div>

    <!-- Drop Apple -->
    <div>
      <div class="thumbnail"
        data-drop="true"
        ng-model="applesout"
        data-jqyoui-options="appleOptions"
        data-jqyoui-droppable="{onDrop: 'appleOnDrop'}"
      >
        <div
          ng-hide=applesout.title
          ng-model="applesout"
        >
          Drop an apple here
        </div>
        <div
          class="btn"
          ng-hide=!applesout.title
          ng-model="applesout"
        >
          {{applesout.title}}
        </div>
      </div>
    </div>
    <!-- Drag Orange -->
    <div>
      <div class="btn"
        ng-model="orangesin"
        ng-repeat="item in orangesin"
        data-drag="true"
        data-jqyoui-options="{
          revert: 'invalid',
          scroll: 'true',
          containment: 'body',
          helper: 'clone',
          appendTo: 'body'
        }"
        jqyoui-draggable="{index: {{$index}}, placeholder:'keep', animate:true}"
      >
        {{item.title}}
      </div>
    </div>
    <!-- Drop Orange-->
    <div>
      <div class="thumbnail"
        data-drop="true"
        ng-model="orangesout"
        data-jqyoui-options="validateDropOranges"
        jqyoui-droppable="{multiple:false}">
        <div
          ng-hide=orangesout.title
          ng-model="orangesout"
        >
          Drop an orange here
        </div>
        <div
          class="btn"
          ng-hide=!orangesout.title
          ng-model="orangesout"
        >
          {{orangesout.title}}
        </div>
      </div>
    </div>
  </div>
</body>
</html>
</code>```

And app.js:

```<code>varApp = angular.module('drag-and-drop', ['ngDragDrop']);

App.controller('oneCtrl',function($scope, $timeout) {

  $scope.applesin = [
    { 'title': 'Apple 1'},
    { 'title': 'Apple 2'},
    { 'title': 'Apple 3'},
    { 'title': 'Apple 4'}
  ];

  $scope.applesout = {};

  $scope.orangesin = [
    { 'title': 'Orange 1'},
    { 'title': 'Orange 2'},
    { 'title': 'Orange 3'},
    { 'title': 'Orange 4'}
  ];

  $scope.orangesout = {};

  $scope.appleOnDrop = function(e, obj) {
console.log("on drop apple ");
console.log("$(e.target).scope(): ");
console.log($(e.target).scope());
    var dest = $(e.target).scope().this;
console.log("$(obj.draggable).scope(): ");
console.log($(obj.draggable).scope());
    var src = $(obj.draggable).scope().x;
  };

  // Limit apples to apples, oranges to oranges
  $scope.appleOptions = {
    accept: function(dragEl) {
console.log("validate apple");
      if (dragEl[0].innerHTML.indexOf("Apple") > -1) {
        return true;
      } else {
        return false;
      }
    }
  };

  $scope.validateDropOranges = {
    accept: function(dragEl) {
console.log("validate orange");
      if (dragEl[0].innerHTML.indexOf("Orange") > -1) {
        return true;
      } else {
        return false;
      }
    }
  };
});
</code>```

答:
Yes, you can use React DnD (https://github.com/react-dnd/react-dnd) for the actual drag and drop functionality and React Flip Move (https://github.com/joshwcomeau/react-flip-move) or React Motion (https://github.com/chenglou/react-motion) for animating the DOM changes.

They all have enough simple examples/tutorials to get you going..

Title: Animation in react-dnd

Body:
In this Angular example, if you drag an apple to the orange section and drop it there, then there is an animation which slowly returns the apple to the spot it came from. This visually communicates that dragging an apple to the orange section is not valid. The Angular drag and drop library used is from codef0rmer.

How would I create a similar animation in react-dnd or another react drag and drop package?

Here is a React drag and drop example with some animation. Can I do something like this with react-dnd, or another widely used package?

The rest is the Angular sample code which is also in plnkr Angular example.

index.html:

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Drag & Drop: Multiple listsr</title>

  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/ui-lightness/jquery-ui.min.css" rel="stylesheet" type="text/css" />
  <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.1/css/bootstrap.min.css" rel="stylesheet">

        {{item.title}}

          Drop an apple here

          {{applesout.title}}

        {{item.title}}

          Drop an orange here

          {{orangesout.title}}

And app.js:

varApp = angular.module('drag-and-drop', ['ngDragDrop']);

App.controller('oneCtrl',function($scope, $timeout) {

  $scope.applesin = [
    { 'title': 'Apple 1'},
    { 'title': 'Apple 2'},
    { 'title': 'Apple 3'},
    { 'title': 'Apple 4'}
  ];

  $scope.applesout = {};

  $scope.orangesin = [
    { 'title': 'Orange 1'},
    { 'title': 'Orange 2'},
    { 'title': 'Orange 3'},
    { 'title': 'Orange 4'}
  ];

  $scope.orangesout = {};

  $scope.appleOnDrop = function(e, obj) {
console.log("on drop apple ");
console.log("$(e.target).scope(): ");
console.log($(e.target).scope());
    var dest = $(e.target).scope().this;
console.log("$(obj.draggable).scope(): ");
console.log($(obj.draggable).scope());
    var src = $(obj.draggable).scope().x;
  };

  // Limit apples to apples, oranges to oranges
  $scope.appleOptions = {
    accept: function(dragEl) {
console.log("validate apple");
      if (dragEl[0].innerHTML.indexOf("Apple") > -1) {
        return true;
      } else {
        return false;
      }
    }
  };

  $scope.validateDropOranges = {
    accept: function(dragEl) {
console.log("validate orange");
      if (dragEl[0].innerHTML.indexOf("Orange") > -1) {
        return true;
      } else {
        return false;
      }
    }
  };
});


问:
how to copy many directories to many destinations? (massive copy)
I need to copy 3 folders to many destination (600+), I need to parallelize it.

For intance

```<code>C:\Data1   →    D:\Data1
C:\Data1   →    D:\Data2
C:\Data1   →    D:\Data3
D:\Data1   →    \\\VM1\c$\Data1
D:\Data2   →    \\\VM1\c$\Data2
D:\Data3   →    \\\VM1\c$\Data3
…
</code>```

I constructed an object for it

```<code>[pscustomobject][ordered]@{
    Source = 'C:\Data1'
    Dest = 'D:\Data1'
},
[pscustomobject][ordered]@{
    Source = 'C:\Data1'
    Dest = 'D:\Data2'
},
[pscustomobject][ordered]@{
    Source = 'C:\Data1'
    Dest = 'D:\Data3'
},
…
</code>```

答:
I call a Robocopy-Job for each couple but i limit the nomber of Process and number of RoboCopy-Thread.

```<code>function Copy-AsParallelJod {
    param (
        [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory = $true, Position = 0)]
            [ValidateScript({ $_ | Test-Path })]
                [string]$Source,
        [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory = $true, Position = 1)]
            [Alias('Dest')]
                [string]$Destination,
        $MaxRunningJob = 4,
        $MaxThreadByJob = 8
    )
    begin {
        $Start = Get-Date
        write-host (get-date $Start -format 'yyyy/MM/dd HH:mm:ss') -Width 150 -back DarkGreen
         # get-job | Remove-Job -Force
    }
    process {
        while ((Get-Job -State Running  | ?{$_.Name -like "Copy_*"}).count -ge $MaxRunningJob) {

            # Start-Sleep -Seconds 3
            wait-Job -Name 'Copy_*' -Any | Receive-Job  -AutoRemoveJob -Wait
        }
        $WorkName = (($Destination.split('\'))[-2..-1]) -join(' ')

        Write-host 'Copy-Job',' : ',$Source.padleft(55),'  To  ',$Destination.padright(55),'  @ ',(get-date -format 'yyyy/MM/dd HH:mm:ss') red

        Start-Job -ScriptBlock {
            param($Source, $Dest, $log="/LOG+:C:\MAJ\Robocopy.log.txt", $MaxThread)
            $Start = Get-Date
            New-Item -Path $dest -type Directory -Force | Out-Null
            [System.Threading.Thread]::CurrentThread.Priority = 'Lowest'
            $PathIdentity = ($Dest.split('\')[-2..-1]) -join('\')

            Robocopy $Source $Dest /E $log /TEE /MT:$MaxThread /S /DCOPY:DA /COPY:DAT /R:3 /W:2 | Out-Null
            Start-Sleep -Seconds 1

            $Time =  (Get-Date) - $start
            $Time = "$($time.Hours)h $("$($time.Minutes)".padleft(2,'0'))m $("$($time.Seconds)".padleft(2,'0'))s"
        } -ArgumentList $Source,$Destination,"/LOG+:$(split-path $Destination)\RoboCopy($(get-date -format 'yyyy.MM.dd HH.mm'))-$WorkName.log.txt",$MaxThreadByJob -name Copy_$WorkName | Out-Null
        Start-Sleep -Milliseconds 500
    }
    end {
        Get-Job -Name 'Copy_*' | Receive-Job -AutoRemoveJob -Wait
        $Time =  (Get-Date) - $start
        $Time = "$($time.Hours)h $("$($time.Minutes)".padleft(2,'0'))m $("$($time.Seconds)".padleft(2,'0'))s"
        write-host "$(get-date -format 'yyyy/MM/dd HH:mm:ss') [$Time]" -Width 150 -back DarkGreen
    }
}
</code>```

and i call it like that

```<code>[pscustomobject][ordered]@{
    Source = 'C:\Data1'
    Dest = 'D:\Data1'
},
[pscustomobject][ordered]@{
    Source = 'C:\Data1'
    Dest = 'D:\Data2'
},
[pscustomobject][ordered]@{
    Source = 'C:\Data1'
    Dest = 'D:\Data3'
} | Copy-AsParallelJod -MaxRunningJob 4 -MaxThreadByJob 8
</code>```

Body:
I need to copy 3 folders to many destination (600+), I need to parallelize it.

For intance

C:\Data1   →    D:\Data1
C:\Data1   →    D:\Data2
C:\Data1   →    D:\Data3
D:\Data1   →    \\\VM1\c$\Data1
D:\Data2   →    \\\VM1\c$\Data2
D:\Data3   →    \\\VM1\c$\Data3
…

I constructed an object for it

[pscustomobject][ordered]@{
    Source = 'C:\Data1'
    Dest = 'D:\Data1'
},
[pscustomobject][ordered]@{
    Source = 'C:\Data1'
    Dest = 'D:\Data2'
},
[pscustomobject][ordered]@{
    Source = 'C:\Data1'
    Dest = 'D:\Data3'
},
…

Body:
I call a Robocopy-Job for each couple but i limit the nomber of Process and number of RoboCopy-Thread.

function Copy-AsParallelJod {
    param (
        [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory = $true, Position = 0)]
            [ValidateScript({ $_ | Test-Path })]
                [string]$Source,
        [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory = $true, Position = 1)]
            [Alias('Dest')]
                [string]$Destination,
        $MaxRunningJob = 4,
        $MaxThreadByJob = 8
    )
    begin {
        $Start = Get-Date
        write-host (get-date $Start -format 'yyyy/MM/dd HH:mm:ss') -Width 150 -back DarkGreen
         # get-job | Remove-Job -Force
    }
    process {
        while ((Get-Job -State Running  | ?{$_.Name -like "Copy_*"}).count -ge $MaxRunningJob) {

            # Start-Sleep -Seconds 3
            wait-Job -Name 'Copy_*' -Any | Receive-Job  -AutoRemoveJob -Wait
        }
        $WorkName = (($Destination.split('\'))[-2..-1]) -join(' ')

        Write-host 'Copy-Job',' : ',$Source.padleft(55),'  To  ',$Destination.padright(55),'  @ ',(get-date -format 'yyyy/MM/dd HH:mm:ss') red

        Start-Job -ScriptBlock {
            param($Source, $Dest, $log="/LOG+:C:\MAJ\Robocopy.log.txt", $MaxThread)
            $Start = Get-Date
            New-Item -Path $dest -type Directory -Force | Out-Null
            [System.Threading.Thread]::CurrentThread.Priority = 'Lowest'
            $PathIdentity = ($Dest.split('\')[-2..-1]) -join('\')

            Robocopy $Source $Dest /E $log /TEE /MT:$MaxThread /S /DCOPY:DA /COPY:DAT /R:3 /W:2 | Out-Null
            Start-Sleep -Seconds 1

            $Time =  (Get-Date) - $start
            $Time = "$($time.Hours)h $("$($time.Minutes)".padleft(2,'0'))m $("$($time.Seconds)".padleft(2,'0'))s"
        } -ArgumentList $Source,$Destination,"/LOG+:$(split-path $Destination)\RoboCopy($(get-date -format 'yyyy.MM.dd HH.mm'))-$WorkName.log.txt",$MaxThreadByJob -name Copy_$WorkName | Out-Null
        Start-Sleep -Milliseconds 500
    }
    end {
        Get-Job -Name 'Copy_*' | Receive-Job -AutoRemoveJob -Wait
        $Time =  (Get-Date) - $start
        $Time = "$($time.Hours)h $("$($time.Minutes)".padleft(2,'0'))m $("$($time.Seconds)".padleft(2,'0'))s"
        write-host "$(get-date -format 'yyyy/MM/dd HH:mm:ss') [$Time]" -Width 150 -back DarkGreen
    }
}

and i call it like that

[pscustomobject][ordered]@{
    Source = 'C:\Data1'
    Dest = 'D:\Data1'
},
[pscustomobject][ordered]@{
    Source = 'C:\Data1'
    Dest = 'D:\Data2'
},
[pscustomobject][ordered]@{
    Source = 'C:\Data1'
    Dest = 'D:\Data3'
} | Copy-AsParallelJod -MaxRunningJob 4 -MaxThreadByJob 8


问:
How do I grab user info from Microsoft Graph for authenticated user using Azure mobile app backend?
Using the backend of my app, I am attempting to capture information from Microsoft Graph for a user that has been authenticated and then add that user to a database. The authentication appears to be working correctly, but the user is never added to the database. I am really stuck on this. I've studied the online documentation extensively, but have been unable to find a solution. If I could just tell if the user properties were getting populated, I could figure out what's going on, but I've been unable to do that since the code runs on the server. (I've attempted to remote debug, but have been unable to successfully set a breakpoint.) Can anyone tell me what I'm doing wrong in the code below?

class MicrosoftAccountInfo
{
    public string id { get; set; }
    public string displayName { get; set; }
    public string mail { get; set; }
}

[MobileAppController]
public class MicrosoftAccountController : ApiController
{
    MicrosoftAccountCredentials credentials;
    string msRequestUrl;
    MyAppContext context;
    EntityDomainManager<User> domainManager;

    // GET api/<controller>
    public async Task<User> Get()
    {
        if (credentials == null)
        {
            credentials = await this.User.GetAppServiceIdentityAsync<MicrosoftAccountCredentials>(this.Request);
        }

        msRequestUrl = "https://graph.microsoft.com/v1.0/me/?$select=id,displayName,mail";

        var client = new System.Net.Http.HttpClient();
        var headerValue = "Bearer" + credentials.AccessToken;
        client.DefaultRequestHeaders.Add("Authorization", headerValue);
        var resp = await client.GetAsync(msRequestUrl);
        resp.EnsureSuccessStatusCode();
        var msInfo = await resp.Content.ReadAsStringAsync();

        MicrosoftAccountInfo info = JsonConvert.DeserializeObject<MicrosoftAccountInfo>(msInfo);
        context = new MyAppContext();
        domainManager = new EntityDomainManager<User>(context, Request);
        var user = context.Users.FirstOrDefault(u => u.Email == info.mail);
        if (user == null)
        {
            user = new DataObjects.User { Email = info.mail, UserName = info.displayName, ProviderId = info.id };
            await domainManager.InsertAsync(user);
        }
        else if (string.IsNullOrEmpty(user.ProviderId))
        {
            user.UserName = info.displayName;
            user.ProviderId = info.id;
            await context.SaveChangesAsync();
        }
        return user;
    }
}
```

答:
As to why this is failing, it is difficult to determine without an actual error message. There are simply to many variables/potential failure points involved to say for sure.

That said, you can reduce the number of potential failure points by using the Microsoft Graph .NET Client Library. There is also a NuGet package available: Install-Package Microsoft.Graph.

This library will handle composing the Microsoft Graph and deserializing the response into an object. Along with removing a risk factor, it will greatly simplify your code:

Microsoft.Graph.GraphServiceClient graphClient =
    new Microsoft.Graph.GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) =>
    {
        requestMessage.Headers.Authorization =
            new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", "{your-access-token}");
        return Task.FromResult(0);
    }));

Microsoft.Graph.User user = await graphClient.Me.Request().GetAsync();
```

I would also suggest implementing a monitoring solution that can trap exceptions on the server. This will help with debugging. If you're running on Azure, I strongly recommend using Application Insights. Aside from being free to get started, it is effectively a "click once, get monitoring" solution. It will handle wiring up the server and provide reporting for any exceptions it runs into.

Note that you can also use App Insights with your own servers or apps hosted on other services (i.e. AWS, RackSpace), there may however be some manual configuration required.

Body:
As to why this is failing, it is difficult to determine without an actual error message. There are simply to many variables/potential failure points involved to say for sure.

That said, you can reduce the number of potential failure points by using the Microsoft Graph .NET Client Library. There is also a NuGet package available: Install-Package Microsoft.Graph.

This library will handle composing the Microsoft Graph and deserializing the response into an object. Along with removing a risk factor, it will greatly simplify your code:

Microsoft.Graph.GraphServiceClient graphClient =
    new Microsoft.Graph.GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) =>
    {
        requestMessage.Headers.Authorization =
            new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", "{your-access-token}");
        return Task.FromResult(0);
    }));

Microsoft.Graph.User user = await graphClient.Me.Request().GetAsync();

I would also suggest implementing a monitoring solution that can trap exceptions on the server. This will help with debugging. If you're running on Azure, I strongly recommend using Application Insights. Aside from being free to get started, it is effectively a "click once, get monitoring" solution. It will handle wiring up the server and provide reporting for any exceptions it runs into.

Note that you can also use App Insights with your own servers or apps hosted on other services (i.e. AWS, RackSpace), there may however be some manual configuration required.