问:
CSS not centering
I have the following html and css.

  .divOuter {
  width: 50%;
  margin: 0 auto;
}

.divInner1,
.divInner2,
.divInner3 {
  border: 1px solid;
  float: left;
  width: 150px;
  height: 150px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="logo">
  <img src="http://i.cubeupload.com/jmdKlW.png"></img>
</div>
<div id="title">
  <h3>Who's watching</h3>
</div>
<div class="divOuter">
  <div class="divInner1">First DIV</div>
  <div class="divInner2">Second DIV</div>
  <div class="divInner3">Third DIV</div>
</div></code>```

I used the outer div to try and center everything inside. but i get the following image:

The squares in the middle are not centered. A working example is on xat.me/madses1996

I would like the squares next to eachtother.

答:
    body{

  background: black;
}

#title h3{
  color: white;
  text-align: center;
}
.divOuter {
      margin: 0 auto;
      width: 100%;
      text-align: center;
      margin: 0 auto;
    }

    .divInner1,
    .divInner2,
    .divInner3 {
          border: 1px solid white;

          width: 150px;
          height: 150px;
          margin-left: 3px;
          margin-right: 3px;
          margin-top: 50px;
          text-align: center;
          display: inline-block;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="logo">
  <img src="http://i.cubeupload.com/jmdKlW.png"></img>
</div>
<div id="title">
  <h3>Who's watching</h3>
</div>
<div class="divOuter">
  <div class="divInner1">First DIV</div>
  <div class="divInner2">Second DIV</div>
  <div class="divInner3">Third DIV</div>
</div></code>```

.divOuter {
  width: 150px;
  margin: 0 auto;
}

.divInner1,
.divInner2,
.divInner3 {
  border: 1px solid;
  float: left;
  width: 100%;
  height: 150px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="logo">
  <img src="http://i.cubeupload.com/jmdKlW.png" />
</div>
<div id="title">
  <h3>Who's watching</h3>
</div>
<div class="divOuter">
  <div class="divInner1">First DIV</div>
  <div class="divInner2">Second DIV</div>
  <div class="divInner3">Third DIV</div>
</div></code>```

Title: CSS not centering

Body:
I have the following html and css.

  .divOuter {
  width: 50%;
  margin: 0 auto;
}

.divInner1,
.divInner2,
.divInner3 {
  border: 1px solid;
  float: left;
  width: 150px;
  height: 150px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;

Who's watching

First DIV

Second DIV

Third DIV

I used the outer div to try and center everything inside. but i get the following image:

The squares in the middle are not centered. A working example is on xat.me/madses1996

I would like the squares next to eachtother.

Body:
    body{

  background: black;
}

#title h3{
  color: white;
  text-align: center;
}
.divOuter {
      margin: 0 auto;
      width: 100%;
      text-align: center;
      margin: 0 auto;
    }

    .divInner1,
    .divInner2,
    .divInner3 {
          border: 1px solid white;

          width: 150px;
          height: 150px;
          margin-left: 3px;
          margin-right: 3px;
          margin-top: 50px;
          text-align: center;
          display: inline-block;

<div id="logo">
  <img src="http://i.cubeupload.com/jmdKlW.png"></img>
</div>
<div id="title">
  <h3>Who's watching</h3>
</div>
<div class="divOuter">
  <div class="divInner1">First DIV</div>
  <div class="divInner2">Second DIV</div>
  <div class="divInner3">Third DIV</div>
</div>

.divOuter {
  width: 150px;
  margin: 0 auto;
}

.divInner1,
.divInner2,
.divInner3 {
  border: 1px solid;
  float: left;
  width: 100%;
  height: 150px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;

<div id="logo">
  <img src="http://i.cubeupload.com/jmdKlW.png" />
</div>
<div id="title">
  <h3>Who's watching</h3>
</div>
<div class="divOuter">
  <div class="divInner1">First DIV</div>
  <div class="divInner2">Second DIV</div>
  <div class="divInner3">Third DIV</div>
</div>


来源: stackexchange

问:
How to build a VS2010 MakeFile project (vcxproj) with TFS Build (No VS 2010)
I have a project that was building fine in VS 2008, and then we installed and started using TFS Build, and then we upgraded to TFS 2010.  Everything was still fine and building correctly (after I implemented our new build process that made everything very nice with a single-click build initiation from any remote Visual Studio 2010 client).  Visual Studio did not need to be installed on the Build Agent.  I'm trying very hard (very hard) not to install Visual Studio on the Build Agent because my understanding is that it's not necessary, and we're not licensed to install it on a non-development machine.

Now I tried upgrading the solution to VS 2010, still targeting .NET 3.5 because it's an assembly targeted for SQL Server CLR procedures, and SQL Server doesn't support .NET 4.0 yet.  But I simply cannot make it build any more under TFS Build.  I can't seem to get a consistent error message from TFS Build and from an MS Build command line, but I think it has something to do with Microsoft.Cpp.Targets not being in C:\Program Files\MSBuild\ because I haven't installed Visual Studio.  I did install the Microsoft Windows SDK 7.1 so that I could run the .NET 4.0 SDK tools like svcutil for some other .NET 4.0 projects, but nothing seems to install what this build wants.  The error TFS build gives me is:

C:\TFSBld[...]\GenerateLanguage\GenerateLanguage.vcxproj(46,3):
  error MSB4019: The imported project
  "C:\Microsoft.Cpp.Default.props" was
  not found. Confirm that the path in
  the  declaration is correct,
  and that the file exists on disk.

And when I click on that error it takes me to this line in the vcxproj file:

```<code>  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
</code>```

All I really need to do in this project is run resgen to generate resources files from resx files, and compile them into sattelite assemblies.  I was using a makefile build to do this, manually running resgen (I think it was because I can't find a way to compile sattelite assemblies as a stand-alone solution any other way), and then compile those into a DLL (I can't remember how that worked now, but I think it was manually running AL.exe to compile DLL files from resources files).  So basically I just need to run command lines to build this project, and I can't seem to find a reasonable way to do it without throwing out the entire project and editing the TFS build script to run a bunch of hard-coded command lines instead.  There's got to be a better way.

I've been at this all day, and tried writing my own .targets file and .xml property sheets to take the place of the standard file, but it's way over my head.  I tried simply deleting the  lines, but then MSBuild complains that there's no "Build" target.  I tried adding a dummy  to the vcxproj file, but then it didn't seem to run the pre- and post-build steps where all the work is done.

答: The Microsoft Windows SDK 7.1 has several installation options.  Having only the ".NET Development" child "Tools" checked is apparently not enough to build vcxproj projects, even if they don't include any C++ code (only pre- and post-build steps).  Adding the "Visual C++ compilers" option and fully selecting the "Intellisense and Reference Assemblies" checkbox installs the necessary files and settings.  I'm not sure if both are necessary, but that combination did work for me.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a project that was building fine in VS 2008, and then we installed and started using TFS Build, and then we upgraded to TFS 2010.  Everything was still fine and building correctly (after I implemented our new build process that made everything very nice with a single-click build initiation from any remote Visual Studio 2010 client).  Visual Studio did not need to be installed on the Build Agent.  I'm trying very hard (very hard) not to install Visual Studio on the Build Agent because my understanding is that it's not necessary, and we're not licensed to install it on a non-development machine.

Now I tried upgrading the solution to VS 2010, still targeting .NET 3.5 because it's an assembly targeted for SQL Server CLR procedures, and SQL Server doesn't support .NET 4.0 yet.  But I simply cannot make it build any more under TFS Build.  I can't seem to get a consistent error message from TFS Build and from an MS Build command line, but I think it has something to do with Microsoft.Cpp.Targets not being in C:\Program Files\MSBuild\ because I haven't installed Visual Studio.  I did install the Microsoft Windows SDK 7.1 so that I could run the .NET 4.0 SDK tools like svcutil for some other .NET 4.0 projects, but nothing seems to install what this build wants.  The error TFS build gives me is:

C:\TFSBld[...]\GenerateLanguage\GenerateLanguage.vcxproj(46,3):
  error MSB4019: The imported project
  "C:\Microsoft.Cpp.Default.props" was
  not found. Confirm that the path in
  the  declaration is correct,
  and that the file exists on disk.

And when I click on that error it takes me to this line in the vcxproj file:

  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />

All I really need to do in this project is run resgen to generate resources files from resx files, and compile them into sattelite assemblies.  I was using a makefile build to do this, manually running resgen (I think it was because I can't find a way to compile sattelite assemblies as a stand-alone solution any other way), and then compile those into a DLL (I can't remember how that worked now, but I think it was manually running AL.exe to compile DLL files from resources files).  So basically I just need to run command lines to build this project, and I can't seem to find a reasonable way to do it without throwing out the entire project and editing the TFS build script to run a bunch of hard-coded command lines instead.  There's got to be a better way.

I've been at this all day, and tried writing my own .targets file and .xml property sheets to take the place of the standard file, but it's way over my head.  I tried simply deleting the  lines, but then MSBuild complains that there's no "Build" target.  I tried adding a dummy  to the vcxproj file, but then it didn't seem to run the pre- and post-build steps where all the work is done.


问:
How to get Number of bits from Hex
For example how do I get 8 from 0x01, or 16 from 0x0001.

I want to know the number of bits a variable has.

```<code>var someNumber = 0x123456;
var len = whatToDoHere(someNumber);
console.log(len); // => 24 for example
</code>```

答:
Here are few alternatives:

f1 = n => (Math.log2(n) & -8) + 8                          // log2 (-Infinity & -8 = 0)

f2 = n => ((n >>= 8) && f2(n)) + 8                         // recursion

f3 = n => n.toString(16).length + 1 << 2 & -8              // string length

for (n of [0, 0xff, 0x100, 0xffff, 0x10000, 0xffffff])
  console.log( f1(n) + '\t' + f2(n) + '\t' + f3(n) + '\t0x' + n.toString(16) )```

ContentLicense: CC BY-SA 3.0

Title: How to get Number of bits from Hex

Body:
For example how do I get 8 from 0x01, or 16 from 0x0001.

I want to know the number of bits a variable has.

var someNumber = 0x123456;
var len = whatToDoHere(someNumber);
console.log(len); // => 24 for example


问:
Return a promise without waiting for a dependant promise in function in nodejs
I am using node 8.x. Hence, I have access to all latest features i.e. async/ await etc.

The scenario is similar to following
(Not correct syntax, just for explanation):

```<code>createUser()
{
    let userAddress = createAddress(); // Aync, returns a promise
    User.create(name: 'foo', address: userAddress); // User creation is dependant on address. Also, User.create returns a promise.
}
</code>```

Basically, User object creation is dependant on the creation of address object. I want the createUser function to execute asynchronously i.e. to return a promise as soon as possible without waiting for address object to be created.

The purpose of this question is not to get things done but to understand what is the best way to solve this kind of issues in async programming.

Few ways that I can think of:
1: Create a new promise object and return right away when entered in createUser function. Resolve it when the user object is created.
2: Make createUser an async function and then return user Promise. Facing issues with this method:

```<code>async function createUser()
{
    address = await createAddress();
    return User.create(name: 'foo', address: userAddress);
}
</code>```

The problem is function waits for the address before returning the control which I don't want. (Or it does not make any diff as the function is async. Performance is a big criterion in my case)

How to deal with this kind of promise dependancy where you want to return promise of parent object but you parent object is dependant on child object's promise.

Thank you.

答:
This is another approach, assuming that createAddress returns a promise (of course)

```<code>function createUser(){
    return createAddress().then(function(address) {
        // the return is to handle latter the user creation
        return User.create(name: 'foo', address: address)
    }, function() {
        throw 'Promise Rejected';
    });
}

createUser().then(function(result) {
    console.log("result => " + result);
    // Do something here with the 'user creation' if you want
}).catch(function(error) {
    console.log("error => " + error);
});

// Do some stuff, while the code above is executed
</code>```

Body:
I am using node 8.x. Hence, I have access to all latest features i.e. async/ await etc.

The scenario is similar to following
(Not correct syntax, just for explanation):

createUser()
{
    let userAddress = createAddress(); // Aync, returns a promise
    User.create(name: 'foo', address: userAddress); // User creation is dependant on address. Also, User.create returns a promise.
}

Basically, User object creation is dependant on the creation of address object. I want the createUser function to execute asynchronously i.e. to return a promise as soon as possible without waiting for address object to be created.

The purpose of this question is not to get things done but to understand what is the best way to solve this kind of issues in async programming.

Few ways that I can think of:
1: Create a new promise object and return right away when entered in createUser function. Resolve it when the user object is created.
2: Make createUser an async function and then return user Promise. Facing issues with this method:

async function createUser()
{
    address = await createAddress();
    return User.create(name: 'foo', address: userAddress);
}

The problem is function waits for the address before returning the control which I don't want. (Or it does not make any diff as the function is async. Performance is a big criterion in my case)

How to deal with this kind of promise dependancy where you want to return promise of parent object but you parent object is dependant on child object's promise.

Thank you.

Body:
This is another approach, assuming that createAddress returns a promise (of course)

function createUser(){
    return createAddress().then(function(address) {
        // the return is to handle latter the user creation
        return User.create(name: 'foo', address: address)
    }, function() {
        throw 'Promise Rejected';
    });
}

createUser().then(function(result) {
    console.log("result => " + result);
    // Do something here with the 'user creation' if you want
}).catch(function(error) {
    console.log("error => " + error);
});

// Do some stuff, while the code above is executed


问:
Allow a user to login/signin between actions
I have a requirement, where we allow a user to access a URL without logging in until a certain point.
For example:

OnlineBooking/Services.  They can select the services, this populates the viewmodel and then brings up a confirm view OnlineBooking/Confirm allowing a user to add an email address etc.  Which then generates a ViewModel.

My question is, how can I check the user exists, if it does.  Redirect to the login view (Account Controller - Login Action), allow them to login, then redirect back to this action without losing the viewmodel in this action?  This may not even be possible, if not how can I achieve this?
Thanks for any advice.

Example:

```<code>     public async Task<IActionResult> Confirm(BookingViewModel bookingViewModel)
    {
        try
        {
            var matchedUser = await _userManager.FindByEmailAsync(bookingViewModel.Email);
            if (matchedUser == null) //User does not have an existing account, so register them.
            {
              //This is fine
            }
            else
            {
              //Need to redirect to login, then back to here without losing the viewmodel
            }
     }
</code>```

答:
My question is, how can I check the user exists, if it does. Redirect to the login view (Account Controller - Login Action), allow them to login, then redirect back to this action without losing the viewmodel in this action

My personal preference would be to not even redirect the user.  If you need them to login, popup a dialog asking them to login.  Once the user is logged in (ajax), enable the button to continue..

Body:
I have a requirement, where we allow a user to access a URL without logging in until a certain point.
For example:

OnlineBooking/Services.  They can select the services, this populates the viewmodel and then brings up a confirm view OnlineBooking/Confirm allowing a user to add an email address etc.  Which then generates a ViewModel.

My question is, how can I check the user exists, if it does.  Redirect to the login view (Account Controller - Login Action), allow them to login, then redirect back to this action without losing the viewmodel in this action?  This may not even be possible, if not how can I achieve this?
Thanks for any advice.

Example:

     public async Task<IActionResult> Confirm(BookingViewModel bookingViewModel)
    {
        try
        {
            var matchedUser = await _userManager.FindByEmailAsync(bookingViewModel.Email);
            if (matchedUser == null) //User does not have an existing account, so register them.
            {
              //This is fine
            }
            else
            {
              //Need to redirect to login, then back to here without losing the viewmodel
            }
     }


问:
Adding Values to a List Separately
I am a beginner to Python and just programming in general so this will probably have a very obvious answer to everyone here.

So - I am currently trying to make hangman however I have run into an issue with the display. I am trying to add underscores to a list, with each underscore being in it's own string. I am doing this with

```<code>targetWord = ["_ " * len(answer)]
</code>```

answer is the word being searched for

targetWord is what the user sees (e.g. app_e)

However instead of adding say, 5 strings with each string containing 1 underscore, 1 string is being added with 5 underscores.

The output is ["_ _ _ _ _ "]

The output should be ["_ ","_ ","_ ","_ ","_ "]

All help is appreciated :)

答:
Here is another way to do it:</p>

```<code>targetWord = 'stackoverflow'

lst = []

for letter in targetWord:
    lst.append('_')

print(lst)

#output

['_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_']
</code>```

Title: Adding Values to a List Separately

Body:
I am a beginner to Python and just programming in general so this will probably have a very obvious answer to everyone here.

So - I am currently trying to make hangman however I have run into an issue with the display. I am trying to add underscores to a list, with each underscore being in it's own string. I am doing this with

targetWord = ["_ " * len(answer)]

answer is the word being searched for

targetWord is what the user sees (e.g. app_e)

However instead of adding say, 5 strings with each string containing 1 underscore, 1 string is being added with 5 underscores.

The output is ["_ _ _ _ _ "]

The output should be ["_ ","_ ","_ ","_ ","_ "]

All help is appreciated :)

Body:
Here is another way to do it:

targetWord = 'stackoverflow'

lst = []

for letter in targetWord:
    lst.append('_')

print(lst)

#output

['_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_']


问:
Can `SendChannel.offer`, `CompletableDeferred.complete`, and similar be called outside coroutines?
CompletableDeferred documentation says

All functions on this interface and on all interfaces derived from it are thread-safe and can be safely invoked from concurrent coroutines without external synchronization.

Is it safe to call these functions outside any coroutine?

For SendChannel<E>, offer and close are not suspend and so they can be called outside coroutines syntactically, but is it actually safe to do so?

If a coroutine is needed, what is the cheapest way to start one: launch(Unconfined)?

答:
It is safe to call offer and close from anywhere. That is what documentation means to say with "are thread-safe" phrase.

One of the reasons these methods are included into channel APIs is to enable integration of coroutines with the regular non-coroutine world that is based on various callbacks and event handlers. You can see the actual example of such integration in this guide on UI programming with coroutines.


问:
iOS 11 iPhone X simulator UITabBar icons and titles being rendered on top covering eachother
Anyone having issue with the iPhone X simulator around the UITabBar component?

Mine seem to be rendering the icons and title on top of each other, I'm not sure if I'm missing anything, I also ran it in the iPhone 8 simulator, and one actual devices where it looks fine just as shown on the story board.

iPhone X:

iPhone 8

答:
Moving the tab bar 1 point away from the bottom worked for me.

Of course you'll get a gap by doing so which you'll have to fill in some way, but the text/icons are now properly positioned.


问:
Split array into chunks - is there faster method?
I'm looking for the quickest method to split an array into chunks of fixed size (last one can be smaller, of course). I've looked throughout the site and didn't find any performance-wise comparisons, so I wrote them, and here are the results:

Time in microseconds, mean/error/stddev

For int[] - 30.02 | 0.1002 | 0.0937

For IEnumerable<int> - 76.67 | 0.2146 | 0.1902

Update: Version below (in @Markus' answer) is 139.5 | 0.6702 | 0.5597

Most popular here on SO and frequently recommended method to use LINQ's  GroupBy with index/chunkSize is a no go - 267 microseconds is way too greater than either of aforementioned implementations.

Is there any faster way to split arrays?

P.S.
This is the code for Array and IEnumerable<T>:

```<code>    /// <summary>
    /// Splits <paramref name="source"/> into chunks of size not greater than <paramref name="chunkMaxSize"/>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="source">Array to be split</param>
    /// <param name="chunkMaxSize">Max size of chunk</param>
    /// <returns><see cref="IEnumerable{T}"/> of <see cref="Array"/> of <typeparam name="T"/></returns>
    public static IEnumerable<T[]> AsChunks<T>(this T[] source, int chunkMaxSize)
    {
        var pos = 0;
        var sourceLength = source.Length;
        do
        {
            var len = Math.Min(pos + chunkMaxSize, sourceLength) - pos;
            if (len == 0)
            {
                yield break;;
            }
            var arr = new T[len];
            Array.Copy(source, pos, arr, 0, len);
            pos += len;
            yield return arr;
        } while (pos < sourceLength);
    }

    /// <summary>
    /// Splits <paramref name="source"/> into chunks of size not greater than <paramref name="chunkMaxSize"/>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="source"><see cref="IEnumerable{T}"/> to be split</param>
    /// <param name="chunkMaxSize">Max size of chunk</param>
    /// <returns><see cref="IEnumerable{T}"/> of <see cref="Array"/> of <typeparam name="T"/></returns>
    public static IEnumerable<T[]> AsChunks<T>(this IEnumerable<T> source, int chunkMaxSize)
    {
        var arr = new T[chunkMaxSize];
        var pos = 0;
        foreach (var item in source)
        {
            arr[pos++] = item;
            if (pos == chunkMaxSize)
            {
                yield return arr;
                arr = new T[chunkMaxSize];
                pos = 0;
            }
        }
        if (pos > 0)
        {
            Array.Resize(ref arr, pos);
            yield return arr;
        }
    }
</code>```

P.P.S Complete solution with BenchmarkDotNet tests is on GitHub.

答:
I used this Code:

Source: http://blogs.msdn.com/b/pfxteam/archive/2012/11/16/plinq-and-int32-maxvalue.aspx

```<code>public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> source, int batchSize) {
    if (batchSize <= 0) {
        throw new ArgumentOutOfRangeException(nameof(batchSize));
    }
    using(var enumerator = source.GetEnumerator()) {
        while (enumerator.MoveNext()) {
            yield return YieldBatchElements(enumerator, batchSize - 1);
        }
    }
}

private static IEnumerable<T> YieldBatchElements<T>(IEnumerator<T> source, int batchSize) {
    yield return source.Current;
    for (var i = 0; i < batchSize && source.MoveNext(); i++) {
        yield return source.Current;
    }
}
</code>```

Body:
I'm looking for the quickest method to split an array into chunks of fixed size (last one can be smaller, of course). I've looked throughout the site and didn't find any performance-wise comparisons, so I wrote them, and here are the results:

Time in microseconds, mean/error/stddev

For int[] - 30.02 | 0.1002 | 0.0937

For IEnumerable<int> - 76.67 | 0.2146 | 0.1902

Update: Version below (in @Markus' answer) is 139.5 | 0.6702 | 0.5597

Most popular here on SO and frequently recommended method to use LINQ's  GroupBy with index/chunkSize is a no go - 267 microseconds is way too greater than either of aforementioned implementations.

Is there any faster way to split arrays?

P.S.
This is the code for Array and IEnumerable<T>:

    ///
    /// Splits <paramref name="source"/> into chunks of size not greater than <paramref name="chunkMaxSize"/>
    ///
    /// <typeparam name="T"></typeparam>
    /// <param name="source">Array to be split</param>
    /// <param name="chunkMaxSize">Max size of chunk</param>
    /// <returns><see cref="IEnumerable{T}"/> of <see cref="Array"/> of <typeparam name="T"/></returns>
    public static IEnumerable<T[]> AsChunks<T>(this T[] source, int chunkMaxSize)
    {
        var pos = 0;
        var sourceLength = source.Length;
        do
        {
            var len = Math.Min(pos + chunkMaxSize, sourceLength) - pos;
            if (len == 0)
            {
                yield break;;
            }
            var arr = new T[len];
            Array.Copy(source, pos, arr, 0, len);
            pos += len;
            yield return arr;
        } while (pos < sourceLength);
    }

    ///
    /// Splits <paramref name="source"/> into chunks of size not greater than <paramref name="chunkMaxSize"/>
    ///
    /// <typeparam name="T"></typeparam>
    /// <param name="source"><see cref="IEnumerable{T}"/> to be split</param>
    /// <param name="chunkMaxSize">Max size of chunk</param>
    /// <returns><see cref="IEnumerable{T}"/> of <see cref="Array"/> of <typeparam name="T"/></returns>
    public static IEnumerable<T[]> AsChunks<T>(this IEnumerable<T> source, int chunkMaxSize)
    {
        var arr = new T[chunkMaxSize];
        var pos = 0;
        foreach (var item in source)
        {
            arr[pos++] = item;
            if (pos == chunkMaxSize)
            {
                yield return arr;
                arr = new T[chunkMaxSize];
                pos = 0;
            }
        }
        if (pos > 0)
        {
            Array.Resize(ref arr, pos);
            yield return arr;
        }
    }

P.P.S Complete solution with BenchmarkDotNet tests is on GitHub.

Body:
I used this Code:

Source: http://blogs.msdn.com/b/pfxteam/archive/2012/11/16/plinq-and-int32-maxvalue.aspx

public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> source, int batchSize) {
    if (batchSize <= 0) {
        throw new ArgumentOutOfRangeException(nameof(batchSize));
    }
    using(var enumerator = source.GetEnumerator()) {
        while (enumerator.MoveNext()) {
            yield return YieldBatchElements(enumerator, batchSize - 1);
        }
    }
}

private static IEnumerable<T> YieldBatchElements<T>(IEnumerator<T> source, int batchSize) {
    yield return source.Current;
    for (var i = 0; i < batchSize && source.MoveNext(); i++) {
        yield return source.Current;
    }
}


问:
Frequency count for Comma delimited categories within a column
I have a data frame in R. the data frame has multiple rows and multiple columns. One of the columns has comma separated values for different vehicle makes such as Toyota, Honda, etc. I want to calculate the frequency of the comma separated values and output the top three values in terms of frequency of occurrence for each row.
Here is the data-set looks like:

```<code>Zip                   Make
12325 Toyota, Honda, Toyota, Mitsubishi, Mercedes
85271 Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan, Nissan
56098 Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet, Honda
</code>```

Here is the output I want

Output appended in the image

Can anyone help with the actual R code based on the example?

答:
You need to tidy the data first before you do any manipulation and summing.

Your Dataset:

```<code>df <- data.frame(Zip =c(12325, 85271, 56098), Make = c("Toyota,Honda,Toyota,Mitsubishi,Mercedes", "Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan,Nissan", "Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet,Honda"))
</code>```

Turn Make into Character so we can split it

```<code>df$Make <- as.character(df$Make)
</code>```

Import libraries

```<code>library(stringr)
library(tidyverse)
</code>```

Split out each column by comma, and create a matrix of different makes, and then turn it into a dataframe. Then name the columns, and assign the zip column from your dataframe to our new cleaner one.

```<code>df2 <- as.data.frame(str_split_fixed(df$Make, ",", max(unlist(lapply(strsplit(df$Make, ","), length)))))

names(df2) <- paste0("car_", 1:ncol(df2))

df2$zip <- df$Zip
</code>```

Inspect:

```<code>> df2
   car_1 car_2  car_3      car_4     car_5  car_6     car_7     car_8  car_9 car_10 car_11   zip
1 Toyota Honda Toyota Mitsubishi  Mercedes                                                 12325
2 Toyota Honda Toyota      Honda    Toyota Toyota     Volvo    Nissan Nissan Nissan Nissan 85271
3 Toyota Honda Toyota Mitsubishi Chevrolet  Acura Chevrolet Chevrolet  Honda               56098
</code>```

Now we want to tidy it up. We can gather the columns to turn it from wide format to long. Then we replace empties with NA, and filter them out. We then remove the car column that we created. After that we'll group by zip and Make and summarise which shows the count of each Make by zip. Lastly we arrange it descending by number.

```<code>df3 <- df2 %>%
  gather(car, Make, -zip) %>%
  replace(. == "", NA) %>%
  filter(!is.na(Make)) %>%
  select(-car) %>%
  group_by(zip, Make) %>%
  summarise(number = n()) %>%
  arrange(zip, desc(number))
</code>```

Last thing we do is we can create a new df called top3, and we can slice it to grab just the first 3 rows from each grouping (of zip and Make). Since we've arranged it descending, we will get the top 3 makes by zip code with this dataframe.

```<code>top3 <- df3 %>%
  slice(1:3)
</code>```

Body:
I have a data frame in R. the data frame has multiple rows and multiple columns. One of the columns has comma separated values for different vehicle makes such as Toyota, Honda, etc. I want to calculate the frequency of the comma separated values and output the top three values in terms of frequency of occurrence for each row.
Here is the data-set looks like:

Zip                   Make
12325 Toyota, Honda, Toyota, Mitsubishi, Mercedes
85271 Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan, Nissan
56098 Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet, Honda

Here is the output I want

Output appended in the image

Can anyone help with the actual R code based on the example?

Body:
You need to tidy the data first before you do any manipulation and summing.

Your Dataset:

df <- data.frame(Zip =c(12325, 85271, 56098), Make = c("Toyota,Honda,Toyota,Mitsubishi,Mercedes", "Toyota,Honda,Toyota,Honda,Toyota,Toyota,Volvo,Nissan,Nissan,Nissan,Nissan", "Toyota,Honda,Toyota,Mitsubishi,Chevrolet,Acura,Chevrolet,Chevrolet,Honda"))

Turn Make into Character so we can split it

df$Make <- as.character(df$Make)

Import libraries

library(stringr)
library(tidyverse)

Split out each column by comma, and create a matrix of different makes, and then turn it into a dataframe. Then name the columns, and assign the zip column from your dataframe to our new cleaner one.

df2 <- as.data.frame(str_split_fixed(df$Make, ",", max(unlist(lapply(strsplit(df$Make, ","), length)))))

names(df2) <- paste0("car_", 1:ncol(df2))

df2$zip <- df$Zip

Inspect:

> df2
   car_1 car_2  car_3      car_4     car_5  car_6     car_7     car_8  car_9 car_10 car_11   zip
1 Toyota Honda Toyota Mitsubishi  Mercedes                                                 12325
2 Toyota Honda Toyota      Honda    Toyota Toyota     Volvo    Nissan Nissan Nissan Nissan 85271
3 Toyota Honda Toyota Mitsubishi Chevrolet  Acura Chevrolet Chevrolet  Honda               56098

Now we want to tidy it up. We can gather the columns to turn it from wide format to long. Then we replace empties with NA, and filter them out. We then remove the car column that we created. After that we'll group by zip and Make and summarise which shows the count of each Make by zip. Lastly we arrange it descending by number.

df3 <- df2 %>%
  gather(car, Make, -zip) %>%
  replace(. == "", NA) %>%
  filter(!is.na(Make)) %>%
  select(-car) %>%
  group_by(zip, Make) %>%
  summarise(number = n()) %>%
  arrange(zip, desc(number))

Last thing we do is we can create a new df called top3, and we can slice it to grab just the first 3 rows from each grouping (of zip and Make). Since we've arranged it descending, we will get the top 3 makes by zip code with this dataframe.

top3 <- df3 %>%
  slice(1:3)


问:
Missing ".NET Framework 4 Client Profile" as target framework in "New Project" window
".NET Framework 4 Client Profile" is missing in the "New Project" window in Visual Studio 2010, so I cannot set it as a target framework.

Any ideas?

答: That's normal. You won't see in this combobox. Depending on the project type you are creating (windows, web, ...) Visual Studio will choose it. Once the project created you can go to the project properties and modify it there:


问:
Android: Getting "Manifest merger failed" error after updating to a new version of gradle
After accepting to update the project to new version of gradle I get this error:

```<code>Error:Execution failed for task ':app:processDebugManifest'.
Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.0-alpha1) from [com.android.support:cardview-v7:26.0.0-alpha1] AndroidManifest.xml:24:9-38
    is also present at [com.android.support:design:25.3.1] AndroidManifest.xml:27:9-31 value=(25.3.1).
    Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:22:5-24:41 to override.
</code>```

How can I solve this problem?
This is my app's build.gradle file:

```<code>android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.sample.bookReader"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }
    ...
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:multidex:+'
    compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
    compile 'com.android.support:cardview-v7:26.0.0-alpha1'
    compile 'com.android.support:design:25+'
    compile 'com.jakewharton:butterknife:8.2.1'
    apt 'com.jakewharton:butterknife-compiler:8.2.1'
    ...
}
</code>```

And this is the project's build.gradle:

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.1'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://www.jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

How do I fix this error while maintaining the changes made by updating the gradle version?

答:
You can find out what library depends on a wrong version of the support library and exclude it like this:

```<code>compile ('com.stripe:stripe-android:5.1.1') {
    exclude group: 'com.android.support'
  }
</code>```

stripe-android in my case.

Body:
After accepting to update the project to new version of gradle I get this error:

Error:Execution failed for task ':app:processDebugManifest'.
Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.0-alpha1) from [com.android.support:cardview-v7:26.0.0-alpha1] AndroidManifest.xml:24:9-38
    is also present at [com.android.support:design:25.3.1] AndroidManifest.xml:27:9-31 value=(25.3.1).
    Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:22:5-24:41 to override.

How can I solve this problem?
This is my app's build.gradle file:

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.sample.bookReader"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }
    ...
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:multidex:+'
    compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
    compile 'com.android.support:cardview-v7:26.0.0-alpha1'
    compile 'com.android.support:design:25+'
    compile 'com.jakewharton:butterknife:8.2.1'
    apt 'com.jakewharton:butterknife-compiler:8.2.1'
    ...
}

And this is the project's build.gradle:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.1'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://www.jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

How do I fix this error while maintaining the changes made by updating the gradle version?

Body:
You can find out what library depends on a wrong version of the support library and exclude it like this:

compile ('com.stripe:stripe-android:5.1.1') {
    exclude group: 'com.android.support'
  }

stripe-android in my case.


问:
How to design a parallel code for a Fibonacci algorithm, but without openmp tasks?
I want to write a c++ code for calculating Fibonacci numbers in parallel, with a use of OpenMP tools. I know that, with #pragma omp task, the code will be:

```<code>int fib(int n) {
int i, j;
if (n<2)
    return n;
else {
    #pragma omp task shared(i)
    i=fib(n-1);
    #pragma omp task shared(j)
    j=fib(n-2);
    #pragma omp taskwait
    return i+j;
    }
}
</code>```

Computing this way is not cool, since each thread is waiting for its child threads to complete their work, so the whole process is still a sequential!

I want to write the parallel code, using this equation:

F(n + k) = F(n + 1) * F(k) + F(n) * F(k - 1)

Would anyone help me to do this?

答:
This way is "cool" and works in parallel. Note that taskwait does allow the thread to execute some other task, e.g. a task created by it's own child task. Just to illustrate a possible execution schedule:

```<code>* creating a task , # actually waiting for all child tasks
           ------- time --->
Thread 1   {fib(4): **b      {fib(2): ** {fib(1): ret 1}   # ret 1+0}         # ret 2+1
Thread 2            {fib(3): ** {fib(1): ret 1}                     # ret 1+1}
Thread 3             {fib(2): ** {fib(0): ret 0} ret 1+0}
Thread 4                      {fib(1): ret 1}{fib(0): ret 0}
</code>```

Of course this the code is still horribly inefficient compared to iterative computation. Also in actual code using tasking on recursive algorithms, the creation of new tasks should be stopped after a certain recursion depth to manage the task creation overhead.

Body:
I want to write a c++ code for calculating Fibonacci numbers in parallel, with a use of OpenMP tools. I know that, with #pragma omp task, the code will be:

int fib(int n) {
int i, j;
if (n<2)
    return n;
else {
    #pragma omp task shared(i)
    i=fib(n-1);
    #pragma omp task shared(j)
    j=fib(n-2);
    #pragma omp taskwait
    return i+j;
    }
}

Computing this way is not cool, since each thread is waiting for its child threads to complete their work, so the whole process is still a sequential!

I want to write the parallel code, using this equation:

F(n + k) = F(n + 1) * F(k) + F(n) * F(k - 1)

Would anyone help me to do this?

Body:
This way is "cool" and works in parallel. Note that taskwait does allow the thread to execute some other task, e.g. a task created by it's own child task. Just to illustrate a possible execution schedule:

* creating a task , # actually waiting for all child tasks
           ------- time --->
Thread 1   {fib(4): **b      {fib(2): ** {fib(1): ret 1}   # ret 1+0}         # ret 2+1
Thread 2            {fib(3): ** {fib(1): ret 1}                     # ret 1+1}
Thread 3             {fib(2): ** {fib(0): ret 0} ret 1+0}
Thread 4                      {fib(1): ret 1}{fib(0): ret 0}

Of course this the code is still horribly inefficient compared to iterative computation. Also in actual code using tasking on recursive algorithms, the creation of new tasks should be stopped after a certain recursion depth to manage the task creation overhead.


问:
No job functions found. Try making your job classes and methods public
First off, I have looked at the other SO posts with the same error message and none seem to resolve my issue. I have tried many permutations and options. My function builds fine but will not run in the CLI, I get the following cryptic error. The MSFT documentation does not seem to have the answers either.

No job functions found. Try making your job classes and methods public. If you're using binding extensions (e.g. ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. config.UseServiceBus(), config.UseTimers(), etc.).

I am trying to run a timer job and then write a collection of messages to an event hub. What am I missing? I have been fighting this for hours.

Function:

```<code>    [FunctionName("CreateData")]
    public static async Task Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer,
        [EventHub("murraytest", Connection = "evingest")] IAsyncCollector<string> myeventhub,
        TraceWriter log)
    {
        await myeventhub.AddAsync("data1");
        await myeventhub.AddAsync("data2");
        await myeventhub.AddAsync("data3");

        log.Info($"COMPLETED: {DateTime.Now}");
    }
</code>```

local.settings.json:

```<code>{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "Eventhub": "UseDevelopmentStorage=true",
    "AzureWebJobsDashboard": "",
    "evingest": "Endpoint=sb://example.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=LtcqBLT5VWjg0dGMdIvxCcEGs8902010Y6y14iGg="

  }
}
</code>```

Packages

function.json - is missing any eventhub bindings!

```<code>{
  "generatedBy": "Microsoft.NET.Sdk.Functions-1.0.0.0",
  "configurationSource": "attributes",
  "bindings": [
    {
      "type": "timerTrigger",
      "schedule": "0 */5 * * * *",
      "useMonitor": true,
      "runOnStartup": false,
      "name": "myTimer"
    }
  ],
  "disabled": false,
  "scriptFile": "..\\bin\\AzFuncs.dll",
  "entryPoint": "AzFuncs.Function1.Run"
}
</code>```

答:
You should upgrade to the latest Microsoft.NET.Sdk.Functions (1.0.6 as of today) and Microsoft.Azure.WebJobs.Service.Bus (2.1.0-beta4 if running on full framework). You might need to remove the ServiceBus reference first in order to upgrade SDK.

The Microsoft.Azure.Eventhubs package also needs to be removed. All relevant types etc are in Microsoft.Azure.WebJobs.Service.Bus

Also remember to check "Include prerelease" in the package manager in order to find 2.1.0-beta4.

Body:
First off, I have looked at the other SO posts with the same error message and none seem to resolve my issue. I have tried many permutations and options. My function builds fine but will not run in the CLI, I get the following cryptic error. The MSFT documentation does not seem to have the answers either.

No job functions found. Try making your job classes and methods public. If you're using binding extensions (e.g. ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. config.UseServiceBus(), config.UseTimers(), etc.).

I am trying to run a timer job and then write a collection of messages to an event hub. What am I missing? I have been fighting this for hours.

Function:

    [FunctionName("CreateData")]
    public static async Task Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer,
        [EventHub("murraytest", Connection = "evingest")] IAsyncCollector<string> myeventhub,
        TraceWriter log)
    {
        await myeventhub.AddAsync("data1");
        await myeventhub.AddAsync("data2");
        await myeventhub.AddAsync("data3");

        log.Info($"COMPLETED: {DateTime.Now}");
    }

local.settings.json:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "Eventhub": "UseDevelopmentStorage=true",
    "AzureWebJobsDashboard": "",
    "evingest": "Endpoint=sb://example.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=LtcqBLT5VWjg0dGMdIvxCcEGs8902010Y6y14iGg="

  }
}

Packages

function.json - is missing any eventhub bindings!

{
  "generatedBy": "Microsoft.NET.Sdk.Functions-1.0.0.0",
  "configurationSource": "attributes",
  "bindings": [
    {
      "type": "timerTrigger",
      "schedule": "0 */5 * * * *",
      "useMonitor": true,
      "runOnStartup": false,
      "name": "myTimer"
    }
  ],
  "disabled": false,
  "scriptFile": "..\\bin\\AzFuncs.dll",
  "entryPoint": "AzFuncs.Function1.Run"
}

ContentLicense: CC BY-SA 4.0


问:
how can I turn off screen in android programmatically
I want to turn off the screen. So I tried to do it with PowerManager class but it didn't turn off screen.</p>

```<code>PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
</code>```

答:
It's not clear from the question if you've tried this, but you might need to make sure that you have the  in your manifest:

Any application using a WakeLock must request the android.permission.WAKE_LOCK permission in an  element of the application's manifest.

Another area that you might look is logcat to see if there is any stack traces or errors being logged, which could provide more context for people to help out.

Body:
I want to turn off the screen. So I tried to do it with PowerManager class but it didn't turn off screen.

PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();


问:
Gmail API PHP - Request Entity Too Large Error 413
I need help understanding Gmails API and how I can fix my script below. I have gone through every post on Stack and all the documentation on Gmail to try and figure out how to send an email using the api with attachments over 5 Mb.

Here is my script. This works fine if the attachments are less than 5Mb. The instant it goes over, I get the 413 error.

Request Entity Too Large Error 413

```<code>    # set up the google client...
    $client = new Google_Client();
    $client->setApplicationName("My App");
    $client->setAuthConfig($array['credentials']);

    # create new gmail service...
    $gmail = new \Google_Service_Gmail($client);

    # set the content...
    $strRawMessage = "";
    $boundary = uniqid(rand(), true);
    $subjectCharset = $charset = 'utf-8';
    $strMailContent = 'Test Message Body...';
    $strMailContent = quoted_printable_encode( $strMailContent );
    $strSubject = 'Test Message Subject...';

    # set up who the message is being sent to...
    $to[] = $this->encodeRecipients('You' . " <you@gmail.com>");
    $strRawMessage .= "To: " . implode(", ", $to) . "\r\n";

    # set the subject...
    $strRawMessage .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($strSubject) . "?=\r\n";
    $strRawMessage .= 'MIME-Version: 1.0' . "\r\n";
    $strRawMessage .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "\r\n";

    # set the body...
    $strRawMessage .= "\r\n--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
    $strRawMessage .= $strMailContent . "\r\n";

    # loop over the attachments...
    $attachments[] = [
        'url'=>'https://s3-us-west-2.amazonaws.com/xyz/bugfiles/Pizigani_1367_Chart_10MB.jpg',
        'name'=>'Pizigani_1367_Chart_10MB.jpg',
        'size'=>'10Mb'
    ];
    foreach($attachments as $attachment){

        # get the file info...
        $url = $attachment['url'];
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_exec($ch);
        $mimeType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
        $fileSize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
        $path = parse_url($url, PHP_URL_PATH);
        $filename = substr($path, strrpos($path, '/') + 1); # $attachment['name'];

        # add it as an attachment to the email...
        $strRawMessage .= "\r\n--{$boundary}\r\n";
        $strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $filename .'";' . "\r\n";
        $strRawMessage .= 'Content-Description: ' . $filename . ';' . "\r\n";
        $strRawMessage .= 'Content-Disposition: attachment; filename="' . $attachment['name'] . '-' . $filename . '"; size=' . $fileSize. ';' . "\r\n";
        $strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
        $strRawMessage .= chunk_split(base64_encode(file_get_contents($url)), 76, "\n") . "\r\n";
        $strRawMessage .= '--' . $boundary . "\r\n";
    }

    try {

        # Prepare the message in message/rfc822
        $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
        $msg = new \Google_Service_Gmail_Message();
        $msg->setRaw($mime);

        # send the message...
        $message = $gmail->users_messages->send("me", $msg);

        echo '```';
        print_r($message);
        echo '```';
        die;

    } catch (\Exception $e) {
        echo '```';
        print_r($e->getMessage());
        echo '```';
        die;
    }
</code>```

What I do not understand is that in Gmails docs it says to use this url when uploading attachments.

```<code> POST https://www.googleapis.com/upload/gmail/v1/users/userId/messages/send?uploadType=multipart
</code>```

Or it says to use this URL to be more reliable...

```<code> POST https://www.googleapis.com/upload/gmail/v1/users/userId/messages/send?uploadType=resumable
</code>```

What I dont see is where I would even use that URL at all. No where in the classes (Google_Client, Google_Service_Gmail, Google_Service_Gmail_Message) is that option even available to use.

答: Google API is strict for some things. The limit for the method you're using (users/SendMessage) which is the right one, is limited to 35MB as per documentation. Actually posting with MIME TYPE multipart, in certain cases (almost all) extends the file size to the double. For example, if you upload a file of 20MB, it can end up to be almost 40MB so Google returns that error because in the end they're getting a file bigger than the file size limit. </p>

Body:
I need help understanding Gmails API and how I can fix my script below. I have gone through every post on Stack and all the documentation on Gmail to try and figure out how to send an email using the api with attachments over 5 Mb.

Here is my script. This works fine if the attachments are less than 5Mb. The instant it goes over, I get the 413 error.

Request Entity Too Large Error 413

    # set up the google client...
    $client = new Google_Client();
    $client->setApplicationName("My App");
    $client->setAuthConfig($array['credentials']);

    # create new gmail service...
    $gmail = new \Google_Service_Gmail($client);

    # set the content...
    $strRawMessage = "";
    $boundary = uniqid(rand(), true);
    $subjectCharset = $charset = 'utf-8';
    $strMailContent = 'Test Message Body...';
    $strMailContent = quoted_printable_encode( $strMailContent );
    $strSubject = 'Test Message Subject...';

    # set up who the message is being sent to...
    $to[] = $this->encodeRecipients('You' . " <you@gmail.com>");
    $strRawMessage .= "To: " . implode(", ", $to) . "\r\n";

    # set the subject...
    $strRawMessage .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($strSubject) . "?=\r\n";
    $strRawMessage .= 'MIME-Version: 1.0' . "\r\n";
    $strRawMessage .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "\r\n";

    # set the body...
    $strRawMessage .= "\r\n--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
    $strRawMessage .= $strMailContent . "\r\n";

    # loop over the attachments...
    $attachments[] = [
        'url'=>'https://s3-us-west-2.amazonaws.com/xyz/bugfiles/Pizigani_1367_Chart_10MB.jpg',
        'name'=>'Pizigani_1367_Chart_10MB.jpg',
        'size'=>'10Mb'
    ];
    foreach($attachments as $attachment){

        # get the file info...
        $url = $attachment['url'];
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_exec($ch);
        $mimeType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
        $fileSize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
        $path = parse_url($url, PHP_URL_PATH);
        $filename = substr($path, strrpos($path, '/') + 1); # $attachment['name'];

        # add it as an attachment to the email...
        $strRawMessage .= "\r\n--{$boundary}\r\n";
        $strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $filename .'";' . "\r\n";
        $strRawMessage .= 'Content-Description: ' . $filename . ';' . "\r\n";
        $strRawMessage .= 'Content-Disposition: attachment; filename="' . $attachment['name'] . '-' . $filename . '"; size=' . $fileSize. ';' . "\r\n";
        $strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
        $strRawMessage .= chunk_split(base64_encode(file_get_contents($url)), 76, "\n") . "\r\n";
        $strRawMessage .= '--' . $boundary . "\r\n";
    }

    try {

        # Prepare the message in message/rfc822
        $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
        $msg = new \Google_Service_Gmail_Message();
        $msg->setRaw($mime);

        # send the message...
        $message = $gmail->users_messages->send("me", $msg);

        echo '
';
        print_r($message);
        echo '
';
        die;

    } catch (\Exception $e) {
        echo '
';
        print_r($e->getMessage());
        echo '
';
        die;
    }

What I do not understand is that in Gmails docs it says to use this url when uploading attachments.

 POST https://www.googleapis.com/upload/gmail/v1/users/userId/messages/send?uploadType=multipart

Or it says to use this URL to be more reliable...

 POST https://www.googleapis.com/upload/gmail/v1/users/userId/messages/send?uploadType=resumable

What I dont see is where I would even use that URL at all. No where in the classes (Google_Client, Google_Service_Gmail, Google_Service_Gmail_Message) is that option even available to use.


问:
Correct practices for where to put images and static files in an ASP.NET MVC application?
There is a directory in the standard ASP.NET template "Content" where most people seem to be putting in images and css files etc.

For instance stackoverflow's logo:

(source: stackoverflow.com)

actually is refered to with a server path containing 'content' in the URL (just do View Source for any SO page and you'll see this). So they obviously are storing images in "content/images/...".

```<code>src="/Content/Img/stackoverflow-logo-250.png"
</code>```

Edit: Sometime in the last 10 years they changed the path - but this is what it used to be.

I dont particularly like this. My HTML ends up with /content all over it, and its slightly harder to migrate existing pages that just have /image. Fortunately my stylesheet doesnt end up with content all over it, as long as I save it in content\site.css.

An alternative is to put an images directory in the root, but then you get images at the same level as Controllers and Views which is pretty horrible.

I'd wondered about trying to add a redirection rule like this :

```<code>routes.RedirectRoute(
   "images rule",
   "Images/{*}",
   "Content/Images/{1}");    // this is NOT valid code - I made it up
</code>```

But that code doesnt work because I just made it up. I could use a third party redirection/rewriting plug-in but I want to keep everything 'pure' within the MVC model.

What has anyone else found in this area? Or is everyone just happy with an extra ("/content".length) bytes in their source for every image they serve.

答: It's usually better to put images under a different sub domain.  The reason for this is browsers limit the number of connections per URL.  So if you use http://static.mysiste.com now the browser can open more concurrent connections due to it being in a different URL.</p>

OwnerDisplayName: Simon

Body:
There is a directory in the standard ASP.NET template "Content" where most people seem to be putting in images and css files etc.

For instance stackoverflow's logo:

(source: stackoverflow.com)

actually is refered to with a server path containing 'content' in the URL (just do View Source for any SO page and you'll see this). So they obviously are storing images in "content/images/...".

src="/Content/Img/stackoverflow-logo-250.png"

Edit: Sometime in the last 10 years they changed the path - but this is what it used to be.

I dont particularly like this. My HTML ends up with /content all over it, and its slightly harder to migrate existing pages that just have /image. Fortunately my stylesheet doesnt end up with content all over it, as long as I save it in content\site.css.

An alternative is to put an images directory in the root, but then you get images at the same level as Controllers and Views which is pretty horrible.

I'd wondered about trying to add a redirection rule like this :

routes.RedirectRoute(
   "images rule",
   "Images/{*}",
   "Content/Images/{1}");    // this is NOT valid code - I made it up

But that code doesnt work because I just made it up. I could use a third party redirection/rewriting plug-in but I want to keep everything 'pure' within the MVC model.

What has anyone else found in this area? Or is everyone just happy with an extra ("/content".length) bytes in their source for every image they serve.

OwnerDisplayName: Chad Moran


问:
Using for loop and if statement side by side C++
Can someone explain this syntax of using for and if side by side?    </p>

```<code>int min_dist = huge;
int v = -1;

for (int i = 0; i < N; ++i) if (!done[i]) {
    if (d[i] >= min_dist) continue;
    min_dist = d[i];
    v = i;
}
</code>```

答:
The right way to write this code is like this:

```<code>for (int i  0; i < N; ++i)
    if (!done[i] && d[i] < min_dist) {
        min_dist = d[i];
        v = i;
    }
</code>```

Putting the if on the same line as the for just confuses things. As is having two if statements instead of one.

Body:
Can someone explain this syntax of using for and if side by side?

int min_dist = huge;
int v = -1;

for (int i = 0; i < N; ++i) if (!done[i]) {
    if (d[i] >= min_dist) continue;
    min_dist = d[i];
    v = i;
}

Body:
The right way to write this code is like this:

for (int i  0; i < N; ++i)
    if (!done[i] && d[i] < min_dist) {
        min_dist = d[i];
        v = i;
    }

Putting the if on the same line as the for just confuses things. As is having two if statements instead of one.


问:
HTML5 Gallery remove download button and playbutton overlay?
I have a client using html5 gallery (https://html5box.com/html5gallery/install.php) for video gallery. I know how to remove the download button when it comes to regular html5 video using controlsList="nodownload" on video element and using css to create a play button overlay.How would i achive this when I use the html5 gallery

I tried a bunch of attributes listed in the how to link and non seems to be working, like 'data-showplaybutton' etc. this is my current code now.and what i see on the inspector

```<code><script src="/html5gallery/html5gallery.js"></script>

<style type="text/css">
div.guide {margin:12px 24px;}
div.guide span {color:#ff0000; font:italic 14px Arial, Helvetica, sans-
serif;}
div.guide p {color:#000000; font:14px Arial, Helvetica, sans-serif;}
div.guide pre {color:#990000;}
div.guide p.title {color:#df501f; font:18px Arial, Helvetica, sans-serif;}
</style>

 <div style="display:none; margin:0 auto;" class="html5gallery" data-
 width="600" data-height="340" data-skin="gallery" data-
 nativehtml5controls="true" data-onvideoend="onVideoEnd">
</code>```

答: I  removed the "data-nativehtml5controls="true" attribute from the native code. which removed the download button and added a play button overlay before video plays</p>


问:
When should we call multiprocessing.Pool.join?
I am using 'multiprocess.Pool.imap_unordered' as following

```<code>from multiprocessing import Pool
pool = Pool()
for mapped_result in pool.imap_unordered(mapping_func, args_iter):
    do some additional processing on mapped_result
</code>```

Do I need to call pool.close or pool.join after the for loop?

答:
I had the same memory issue as Memory usage keep growing with Python's multiprocessing.pool when I didn't use pool.close() and pool.join() when using pool.map() with a function that calculated Levenshtein distance. The function worked fine, but wasn't garbage collected properly on a Win7 64 machine, and the memory usage kept growing out of control every time the  function was called until it took the whole operating system down. Here's the code that fixed the leak:

```<code>stringList = []
for possible_string in stringArray:
    stringList.append((searchString,possible_string))

pool = Pool(5)
results = pool.map(myLevenshteinFunction, stringList)
pool.close()
pool.join()
</code>```

After closing and joining the pool the memory leak went away.

Body:
I am using 'multiprocess.Pool.imap_unordered' as following

from multiprocessing import Pool
pool = Pool()
for mapped_result in pool.imap_unordered(mapping_func, args_iter):
    do some additional processing on mapped_result

Do I need to call pool.close or pool.join after the for loop?

Body:
I had the same memory issue as Memory usage keep growing with Python's multiprocessing.pool when I didn't use pool.close() and pool.join() when using pool.map() with a function that calculated Levenshtein distance. The function worked fine, but wasn't garbage collected properly on a Win7 64 machine, and the memory usage kept growing out of control every time the  function was called until it took the whole operating system down. Here's the code that fixed the leak:

stringList = []
for possible_string in stringArray:
    stringList.append((searchString,possible_string))

pool = Pool(5)
results = pool.map(myLevenshteinFunction, stringList)
pool.close()
pool.join()

After closing and joining the pool the memory leak went away.


问:
Disabling tab focus on form elements
I have several divs within the same form. What I am trying to do is to disable the Tab key in one of the divs in the form without disabling the tab in the other divs in the same form.

Example Form:

div1 - disable Tab

div2 - Tab works

div3 - Tab works

答:
My case may not be typical but what I wanted to do was to have certain columns in a TABLE completely "inert": impossible to tab into them, and impossible to select anything in them.  I had found class "unselectable" from other SO answers:

```<code>.unselectable {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
</code>```

This actually prevents the user using the mouse to put the focus in the TD ... but I couldn't find a way on SO to prevent tabbing into cells. The TDs in my TABLE actually each has a DIV as their sole child, and using console.log I found that in fact the DIVs would get the focus (without the focus first being obtained by the TDs).

My solution involves keeping track of the "previously focused" element (anywhere on the page):

```<code>window.currFocus = document;
//Catch any bubbling focusin events (focus does not bubble)
$(window).on('focusin', function () {
  window.prevFocus = window.currFocus;
  window.currFocus = document.activeElement;
});
</code>```

I can't really see how you'd get by without a mechanism of this kind... jolly useful for all sorts of purposes ... and of course it'd be simple to transform it into a stack of recently focused elements, if you wanted that...

The simplest answer is then just to do this (to the sole DIV child in every newly created TD):

```<code>...
jqNewCellDiv[ 0 ].classList.add( 'unselectable' );
jqNewCellDiv.focus( function() {
    window.prevFocus.focus();
});
</code>```

So far so good. It should be clear that this would work if you just have a TD (with no DIV child).
Slight issue: this just stops tabbing dead in its tracks. Clearly if the table has any more cells on that row or rows below the most obvious action you'd want is to making tabbing tab to the next non-unselectable cell ... either on the same row or, if there are other rows, on the row below. If it's the very end of the table it gets a bit more tricky: i.e. where should tabbing go then. But all good clean fun.

Title: Disabling tab focus on form elements

Body:
My case may not be typical but what I wanted to do was to have certain columns in a TABLE completely "inert": impossible to tab into them, and impossible to select anything in them.  I had found class "unselectable" from other SO answers:

.unselectable {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

This actually prevents the user using the mouse to put the focus in the TD ... but I couldn't find a way on SO to prevent tabbing into cells. The TDs in my TABLE actually each has a DIV as their sole child, and using console.log I found that in fact the DIVs would get the focus (without the focus first being obtained by the TDs).

My solution involves keeping track of the "previously focused" element (anywhere on the page):

window.currFocus = document;
//Catch any bubbling focusin events (focus does not bubble)
$(window).on('focusin', function () {
  window.prevFocus = window.currFocus;
  window.currFocus = document.activeElement;
});

I can't really see how you'd get by without a mechanism of this kind... jolly useful for all sorts of purposes ... and of course it'd be simple to transform it into a stack of recently focused elements, if you wanted that...

The simplest answer is then just to do this (to the sole DIV child in every newly created TD):

...
jqNewCellDiv[ 0 ].classList.add( 'unselectable' );
jqNewCellDiv.focus( function() {
    window.prevFocus.focus();
});

So far so good. It should be clear that this would work if you just have a TD (with no DIV child).
Slight issue: this just stops tabbing dead in its tracks. Clearly if the table has any more cells on that row or rows below the most obvious action you'd want is to making tabbing tab to the next non-unselectable cell ... either on the same row or, if there are other rows, on the row below. If it's the very end of the table it gets a bit more tricky: i.e. where should tabbing go then. But all good clean fun.


问:
Java remote debugging - how can I keep debugger listening?
I'm using IntelliJ IDEA to remote debug a Java CLI program with the debugger listening for connections.

This works fine for the first invocation, but the debugger stops listening after the CLI program disconnects. I want the debugger to keep listening since multiple CLI invocations will be made (in sequence, not in parallel) and only one of these will trigger the breakpoint I've set.

Here's my client debug config:

```<code>-agentlib:jdwp=transport=dt_socket,server=n,address=5005,suspend=y
</code>```

Is it possible to keep the debugger listening?

答:
Try with suspend=n:

```<code>-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
</code>```

On my local app (tomcat web app), even though I run on JDK8, I still use the older way of doing it and it works fine (another thing you could try):

```<code>-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005
</code>```

Body:
I'm using IntelliJ IDEA to remote debug a Java CLI program with the debugger listening for connections.

This works fine for the first invocation, but the debugger stops listening after the CLI program disconnects. I want the debugger to keep listening since multiple CLI invocations will be made (in sequence, not in parallel) and only one of these will trigger the breakpoint I've set.

Here's my client debug config:

-agentlib:jdwp=transport=dt_socket,server=n,address=5005,suspend=y

Is it possible to keep the debugger listening?

Body:
Try with suspend=n:

-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005

On my local app (tomcat web app), even though I run on JDK8, I still use the older way of doing it and it works fine (another thing you could try):

-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005


问:
Plotting Weeks with Bokeh Datetime Axis
I am trying to make a bar chart from Bokeh with a Datetime x-axis. I am using several time resolutions, and I can get all of them to work except for the weeks. I have a pandas dataframe that looks like this (I added the 'Week' column for reference, it shouldn't stay)

```<code>Timestamp   ResultID
2017-12-03  106
2017-11-26  381
2017-11-19  406
2017-11-12  662
2017-11-05  656
2017-10-29  638
2017-10-22  429
2017-10-15  784
</code>```

Output with date

You can see that the labels are misaligned and sometimes missing. It looks like Bokeh is always displaying the first day of the month regardless of if it is the first day of the week or not. this then shifts the other labels out of position. I can't seem to find any documentation that would help to do this. I also can't use a categorical axis because the way that I am setting ranges to only show the 7 most recent bins will break. I've also tried changing the format of the labels to show the calendar week labels but no luck there either. Any ideas on how to get the labels to match with the appropriate columns?

```<code>

    bintime = 'W'
    bins = {'h' : '%Y-%m-%d %H:%M', 'D' : '%F', 'W' : '%F', 'M' : '%Y-%m'}
    widths = {'h' : 3600000, 'D' : 86400000, 'W' : 604800000, 'M' : 2419200000}
    pad = 0.9

    source = ColumnDataSource(df)

    now = np.datetime64(datetime.datetime.now())

    if bintime == 'M':
        padspace = now + np.timedelta64(1*30, 'D')
        dispdelta = now - np.timedelta64(7*30, 'D')
    else:
        padspace = now
        dispdelta = now - np.timedelta64(7, bintime)

    ranges = ['hours', 'days', 'months']

    #xrange = df.DT.tolist()
    xrange = (dispdelta, padspace)

    output = figure(plot_height=300, width=800, title="MPL Output", x_range=xrange, tools ='xpan,reset,xzoom_in,xzoom_out')
    output.vbar(x='Timestamp', top='ResultID', width=widths[bintime]*pad, source=source)
    output.xaxis.formatter=DatetimeTickFormatter(hours=bins[bintime], days=bins[bintime], months=bins[bintime])
    show(output)

</code>```

答:
SO I figured it out, posting in case someone else has a similar problem.

You need to modify the ticker method on the xaxis. When a your x_axis_type is a datetime, Bokeh automatically uses the DatetimeTicker method. This finds the type that best fits the data range, which in this case is a DaysTicker that adds ticks on the 1st, 8th, 15th, and 22nd of the month. This would be fine for a line or other area graph, but to get it to line up with the weeks you need to force the ticks to line up with the bars. You can do this by:

```<code>tickers = pd.to_datetime(df.index.values).astype(int) / 10**6
</code>```

or taking your datetime field and converting it to a ms epoch integer (the 10**6 is because a numpy datetime is in nanoseconds), and then adding
   output.xaxis.ticker = FixedTicker(ticks = tickers)

This forces the ticks to align with the centers of the bars. This way, however you resample your dataframe, the labels will match automatically.

Title: Plotting Weeks with Bokeh Datetime Axis

Body:
I am trying to make a bar chart from Bokeh with a Datetime x-axis. I am using several time resolutions, and I can get all of them to work except for the weeks. I have a pandas dataframe that looks like this (I added the 'Week' column for reference, it shouldn't stay)

Timestamp   ResultID
2017-12-03  106
2017-11-26  381
2017-11-19  406
2017-11-12  662
2017-11-05  656
2017-10-29  638
2017-10-22  429
2017-10-15  784

Output with date

You can see that the labels are misaligned and sometimes missing. It looks like Bokeh is always displaying the first day of the month regardless of if it is the first day of the week or not. this then shifts the other labels out of position. I can't seem to find any documentation that would help to do this. I also can't use a categorical axis because the way that I am setting ranges to only show the 7 most recent bins will break. I've also tried changing the format of the labels to show the calendar week labels but no luck there either. Any ideas on how to get the labels to match with the appropriate columns?

    bintime = 'W'
    bins = {'h' : '%Y-%m-%d %H:%M', 'D' : '%F', 'W' : '%F', 'M' : '%Y-%m'}
    widths = {'h' : 3600000, 'D' : 86400000, 'W' : 604800000, 'M' : 2419200000}
    pad = 0.9

    source = ColumnDataSource(df)

    now = np.datetime64(datetime.datetime.now())

    if bintime == 'M':
        padspace = now + np.timedelta64(1*30, 'D')
        dispdelta = now - np.timedelta64(7*30, 'D')
    else:
        padspace = now
        dispdelta = now - np.timedelta64(7, bintime)

    ranges = ['hours', 'days', 'months']

    #xrange = df.DT.tolist()
    xrange = (dispdelta, padspace)

    output = figure(plot_height=300, width=800, title="MPL Output", x_range=xrange, tools ='xpan,reset,xzoom_in,xzoom_out')
    output.vbar(x='Timestamp', top='ResultID', width=widths[bintime]*pad, source=source)
    output.xaxis.formatter=DatetimeTickFormatter(hours=bins[bintime], days=bins[bintime], months=bins[bintime])
    show(output)

Body:
SO I figured it out, posting in case someone else has a similar problem.

You need to modify the ticker method on the xaxis. When a your x_axis_type is a datetime, Bokeh automatically uses the DatetimeTicker method. This finds the type that best fits the data range, which in this case is a DaysTicker that adds ticks on the 1st, 8th, 15th, and 22nd of the month. This would be fine for a line or other area graph, but to get it to line up with the weeks you need to force the ticks to line up with the bars. You can do this by:

tickers = pd.to_datetime(df.index.values).astype(int) / 10**6

or taking your datetime field and converting it to a ms epoch integer (the 10**6 is because a numpy datetime is in nanoseconds), and then adding
   output.xaxis.ticker = FixedTicker(ticks = tickers)

This forces the ticks to align with the centers of the bars. This way, however you resample your dataframe, the labels will match automatically.


问:
uibarbuttonitem tintColor
I have 2 buttons on a UIToolbar, I'd like one to be tinted green and the other red. Can I do this using the TintColor feature. Or do I have to use images?</p>

答:
EDIT: I misread. If you want to tint the buttons individually, your only option is going to be images and custom views.

I would warn you though, this is a blatant violation of the HIG. I don't think it'll be liked by the review team.

Title: uibarbuttonitem tintColor


问:
How can I select for the latest row based on two different attributes?
I need to select the latest activity code (A, V, W, J) for the following transactions (109, 154, 982, 745)   for my employees.  I need to know what my employee last transaction was (from the list) that had one of those activity codes.  There are 2 tables involved with a join on the employee ID.
Table 1:

```<code>|Emp_id  |  STUFF
|  1     |  stuff
|  2     |  stuff
|  3     |  stuff
</code>```

Table 2:

```<code>|Emp_id   |  date      | act_code   |  trans
|   1     |  1/1/17    |   A        |    109
|   1     |  3/4/12    |   X        |    203
|   1     |  2/14/09   |   A        |    154
|   2     |  1/1/17    |   A        |    110
|   2     |  6/6/13    |   V        |    109
|   3     |  12/13/16  |   J        |    982
|   3     |  11/23/14  |   W        |    745
|   4     |  12/13/16  |   X        |    154
|   4     |  11/23/14  |   W        |    745
</code>```

What I’d like to return is:

```<code>|Emp_id  |  STUFF  |  date      | act_code   |  trans
|  1     |  stuff  |  1/1/17    |   A        |    109
|  3     |  stuff  |  12/13/16  |   J        |    982
</code>```

Emp 2 would not be selected because the latest trans is not one of the correct values.  Emp 4 would not be selected because the latest act_code is not one of the correct values.  Anyone have an idea as to how to go about this?  Thanks in advance.

答:
Use first_value to get the latest values of act_code,trans and then check if they are in the specified list.

```<code>select * from (
select distinct t1.emp_id,t1.stuff,
max(t2.date) over(partition by t2.emp_id) as latest_date,
first_value(t2.act_code) over(partition by t2.emp_id order by t2.date desc) as latest_act_code,
first_value(t2.trans) over(partition by t2.emp_id order by t2.date desc) as latest_trans
from tbl1 t1
join tbl2 t2 on t1.emp_id=t2.emp_id
) t
where latest_act_code in ('A','V','W','J') and latest_trans in (109, 154, 982, 745)
</code>```

Body:
I need to select the latest activity code (A, V, W, J) for the following transactions (109, 154, 982, 745)   for my employees.  I need to know what my employee last transaction was (from the list) that had one of those activity codes.  There are 2 tables involved with a join on the employee ID.
Table 1:

|Emp_id  |  STUFF
|  1     |  stuff
|  2     |  stuff
|  3     |  stuff

Table 2:

|Emp_id   |  date      | act_code   |  trans
|   1     |  1/1/17    |   A        |    109
|   1     |  3/4/12    |   X        |    203
|   1     |  2/14/09   |   A        |    154
|   2     |  1/1/17    |   A        |    110
|   2     |  6/6/13    |   V        |    109
|   3     |  12/13/16  |   J        |    982
|   3     |  11/23/14  |   W        |    745
|   4     |  12/13/16  |   X        |    154
|   4     |  11/23/14  |   W        |    745

What I’d like to return is:

|Emp_id  |  STUFF  |  date      | act_code   |  trans
|  1     |  stuff  |  1/1/17    |   A        |    109
|  3     |  stuff  |  12/13/16  |   J        |    982

Emp 2 would not be selected because the latest trans is not one of the correct values.  Emp 4 would not be selected because the latest act_code is not one of the correct values.  Anyone have an idea as to how to go about this?  Thanks in advance.

Body:
Use first_value to get the latest values of act_code,trans and then check if they are in the specified list.

select * from (
select distinct t1.emp_id,t1.stuff,
max(t2.date) over(partition by t2.emp_id) as latest_date,
first_value(t2.act_code) over(partition by t2.emp_id order by t2.date desc) as latest_act_code,
first_value(t2.trans) over(partition by t2.emp_id order by t2.date desc) as latest_trans
from tbl1 t1
join tbl2 t2 on t1.emp_id=t2.emp_id
) t
where latest_act_code in ('A','V','W','J') and latest_trans in (109, 154, 982, 745)


问:
jQuery: Result of script gets deleted after execution - removeData() running on the background?
I have a modal window used to update or add a new object Store.

This modal has a cascading dropdownlist for two properties: Department and District.

How should it work:

We first identify if we are in the situation of creating or updating a Store.

In case is a new Store the modal opens and using jQuery we present a default value for the District dropdownlists (since no Department has been chosen yet).

```<code>    <script type="text/javascript">

        var wasclicked = 0;
        var $this = this;

        $(document).ready(function () {

            document.getElementById("modalbutton").onclick = function () {
                //is AddNew Store button is hitted, this var = 1
                wasclicked = 1;
            };

            $('#modal-action-store').on('hidden.bs.modal', function () {
                //global.wasclicked = 0;
                wasclicked = 0;
                $(this).removeData('bs.modal');
            });

            $('#modal-action-store').on('shown.bs.modal', function (e) {
                console.log($('#DistrictID').length);
                //if wasclicked equals 1 that means we are in the AddNew Store scenario.
                if (wasclicked == 1) {
                    //a default value is sent to District dropdownlist
                    var items = "<option value='0'>-- Seleccione Distrito --</option>";
                    $('#DistrictID').html(items);
                };

            });
        });

</script>
</code>```

However, at this moment, after the default value is added, after a fraction of a second, the value gets deleted.

What I've tried

I've noticed that when I remove this line of code:

```<code>$(this).removeData('bs.modal');
</code>```

From the previous script, it works ok, but I need that code in order to clear the data from the modal if I need to use the modal to edit another Store.

Plus, when I debug the project the debugger did not stop at the breakpoint of that line, so I'm not sure why it's somehow executing in the background? Is it because it's wrapped inside the function document.ready()?

I've been struggling with this for days. I thank for any helpful comment.

Aditional info:

Online version of the project:

There is an online version for this for debugging:

http://plataformafantasypark.azurewebsites.net/

user: adelgado password: $Adelgado33

Under the menu 'Tiendas' -> 'Registro'

Button that calls the modal:

```<code><div class="btn-group" id="modalbutton">
    <a id="createEditStoreModal" data-toggle="modal" asp-action="Create"
         data-target="#modal-action-store" class="btn btn-primary">
            <i class="glyphicon glyphicon-plus"></i>  NEW STORE
        </a>
</div>
</code>```

The Modal:

```<code>@model Application.Models.ApplicationviewModels.StoreIndexData
@using Application.Models

<form asp-action="Create" role="form">
        @await Html.PartialAsync("_ModalHeader", new ModalHeader
    { Heading = String.Format("Actualización de Modelo: Tiendas") })

        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="modal-body form-horizontal">
            <div class="form-group">
                <label asp-for="DepartmentID" class="col-md-2 control-label"></label>
                <div class="col-md-10">
                    <select asp-for="DepartmentID" class="form-control"
                            asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-2 control-label">Distrito</label>
                <div class="col-md-10">
                    <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                            asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
                </div>
            </div>
            {... more elements}
       </div>
</form>
</code>```

答:
Why not do something like(?):</p>

```<code>$("#modalbutton").on('click', function () {
       //is AddNew Store button is hitted, this var = 1

       wasclicked = 1;
 });
</code>```

Body:
I have a modal window used to update or add a new object Store.

This modal has a cascading dropdownlist for two properties: Department and District.

How should it work:

We first identify if we are in the situation of creating or updating a Store.

In case is a new Store the modal opens and using jQuery we present a default value for the District dropdownlists (since no Department has been chosen yet).

However, at this moment, after the default value is added, after a fraction of a second, the value gets deleted.

What I've tried

I've noticed that when I remove this line of code:

$(this).removeData('bs.modal');

From the previous script, it works ok, but I need that code in order to clear the data from the modal if I need to use the modal to edit another Store.

Plus, when I debug the project the debugger did not stop at the breakpoint of that line, so I'm not sure why it's somehow executing in the background? Is it because it's wrapped inside the function document.ready()?

I've been struggling with this for days. I thank for any helpful comment.

Aditional info:

Online version of the project:

There is an online version for this for debugging:

http://plataformafantasypark.azurewebsites.net/

user: adelgado password: $Adelgado33

Under the menu 'Tiendas' -> 'Registro'

Button that calls the modal:

              NEW STORE

The Modal:

@model Application.Models.ApplicationviewModels.StoreIndexData
@using Application.Models

<form asp-action="Create" role="form">
        @await Html.PartialAsync("_ModalHeader", new ModalHeader
    { Heading = String.Format("Actualización de Modelo: Tiendas") })

                    <select asp-for="DepartmentID" class="form-control"
                            asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>

                Distrito

                    <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                            asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>

            {... more elements}

</form>

Body:
Why not do something like(?):

$("#modalbutton").on('click', function () {
       //is AddNew Store button is hitted, this var = 1

       wasclicked = 1;
 });


问:
How do I stream a file over 5gb into s3 using AWS CLI?
I know I can use transfer manager in java, but I use bash + AWS CLI most the time, and a common task is uploading large files to s3 streaming.

```<code>dd if=/dev/zero of=/dev/stdout bs=1 count=0 seek=6G | aws s3 cp - s3://mybucket/myfile
</code>```

How do I get the equivalent of the above to work by using AWS CLI only? Currently it would file as file is over 5gb.

答:
Use this argument:

--expected-size (string)

This argument specifies the expected size of a stream in terms of bytes. Note that this argument is needed only when a stream is being uploaded to s3 and the size is larger than 5GB. Failure to include this argument under these conditions may result in a failed upload due to too many parts in upload.

http://docs.aws.amazon.com/cli/latest/reference/s3/cp.html

Body:
I know I can use transfer manager in java, but I use bash + AWS CLI most the time, and a common task is uploading large files to s3 streaming.

dd if=/dev/zero of=/dev/stdout bs=1 count=0 seek=6G | aws s3 cp - s3://mybucket/myfile

How do I get the equivalent of the above to work by using AWS CLI only? Currently it would file as file is over 5gb.


问:
Given an array of scores, return true if each score is equal or lesser than the one before. The array will be length 2 or more
What is the problem to my code? I have tried to do this peoblem, but I don't find a good solution. Please help me, if you can!?</p>

```<code>public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    int[] scores = new int[n];
    int c = 0;

    for(int i = 0; i < scores.length; i++){
        scores[i] = scan.nextInt();
    }

    for(int j = scores.length-1; j >= 0; j--){
        boolean b = scores[j] <= scores[j-1] ? true : false;
        if(b == false){
            c++;
        }
    }
    if(c > 0){
        System.out.print(false);
    }
</code>```

答:
Your code could work when adding an if statement to check if j > 0 so you won't get an exception when checking the 0 index with -1 index

```<code> for(int j = scores.length-1; j >= 0; j--){
      if(j > 0) {
          boolean b = scores[j] <= scores[j-1] ? true : false;
          if(b == false){
           c++;
          }
       }
   }
</code>```

Body:
What is the problem to my code? I have tried to do this peoblem, but I don't find a good solution. Please help me, if you can!?

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    int[] scores = new int[n];
    int c = 0;

    for(int i = 0; i < scores.length; i++){
        scores[i] = scan.nextInt();
    }

    for(int j = scores.length-1; j >= 0; j--){
        boolean b = scores[j] <= scores[j-1] ? true : false;
        if(b == false){
            c++;
        }
    }
    if(c > 0){
        System.out.print(false);
    }

Body:
Your code could work when adding an if statement to check if j > 0 so you won't get an exception when checking the 0 index with -1 index

 for(int j = scores.length-1; j >= 0; j--){
      if(j > 0) {
          boolean b = scores[j] <= scores[j-1] ? true : false;
          if(b == false){
           c++;
          }
       }
   }