问:
xlsx package can't be loaded
XLSX package is not loading in WIndows 7 with Rstudio 3.5.3

Error: package or namespace load failed for ‘xlsx’:
 .onLoad failed in loadNamespace() for 'rJava', details:
  call: fun(libname, pkgname)
  error: JAVA_HOME cannot be determined from the Registry

答:
This error is likely resolved by installing a Java version (e.g. 64-bit Java or 32-bit Java) that corresponds to the type of R version that you are using (e.g. 64-bit R or 32-bit R).

```<code># check which version of R you are running
Sys.getenv("R_ARCH")

# check which version of Java is being utilized by R
system("java -version")
</code>```

If you need a different version of Java then you'll need to manually download and install the right version from here. Don't forget to restart R and your browser after you install Java.

Title: xlsx package can't be loaded

Body:
This error is likely resolved by installing a Java version (e.g. 64-bit Java or 32-bit Java) that corresponds to the type of R version that you are using (e.g. 64-bit R or 32-bit R).

# check which version of R you are running
Sys.getenv("R_ARCH")

# check which version of Java is being utilized by R
system("java -version")

If you need a different version of Java then you'll need to manually download and install the right version from here. Don't forget to restart R and your browser after you install Java.


来源: stackexchange

问:
Http GetJsonAsync returns null from server API
I am trying to create an application using Blazor and .NET Core 3 with EF Core 3. I have setup a database model and an API for users (/api/users) and browsing to this in chrome returns all of the entities in the database. My GetJson method in the Razor file returns null however.

Here is my Razor code file:

@page "/"
@using LogicX.Shared
@inject HttpClient Http

Users

@functions{
    User[] _users;
    protected override async Task OnInitAsync()
    {
        var users = await Http.GetJsonAsync<User[]>("/api/users");
        _users = users;
    }
}
@foreach (var usr in _users)
{
    @usr.Username
}```
</div>
</div>
</p>

<p>The GetJsonAsync method seems to return null, in spite of records being in the database and in spite of the fact i am able to view the entities in Json format by browsing to /api/users. Is my implementation of this correct and does anyone know how to potentially fix this issue?</p>

<p>Edit: Server Side Code:</p>

```[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class UsersController : Controller
{
    private readonly LogicXDbContext _context;

    public UsersController(LogicXDbContext context)
    {
        _context = context;
    }

    // GET: api/Users
    [HttpGet]
    public async Task<ActionResult<IEnumerable<User>>> GetUsers()
    {
        return await _context.Users.ToListAsync();
    }

    // GET: api/Users/5
    [HttpGet("{id}")]
    public async Task<ActionResult<User>> GetUser(int id)
    {
        var user = await _context.Users.FindAsync(id);

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

        return user;
    }

    // PUT: api/Users/5
    [HttpPut("{id}")]
    public async Task<IActionResult> PutUser(int id, User user)
    {
        if (id != user.Id)
        {
            return BadRequest();
        }

        _context.Entry(user).State = EntityState.Modified;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!UserExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return NoContent();
    }

    // POST: api/Users
    [HttpPost]
    public async Task<ActionResult<User>> PostUser(User user)
    {
        _context.Users.Add(user);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetUser", new { id = user.Id }, user);
    }

    // DELETE: api/Users/5
    [HttpDelete("{id}")]
    public async Task<ActionResult<User>> DeleteUser(int id)
    {
        var user = await _context.Users.FindAsync(id);
        if (user == null)
        {
            return NotFound();
        }

        _context.Users.Remove(user);
        await _context.SaveChangesAsync();

        return user;
    }

    private bool UserExists(int id)
    {
        return _context.Users.Any(e => e.Id == id);
    }
}
```

}

答:
Having a forward slash in front of the url is bugged right now, so no requests will go through.
Use api/Users/GetUsers in your client instead.

Set the Return type on the API to Task<ActionResult<List<User>>> and change the receiving type to List<User> instead of User[].

Doing this will ensure that the sending and receiving types don't mismatch.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create an application using Blazor and .NET Core 3 with EF Core 3. I have setup a database model and an API for users (/api/users) and browsing to this in chrome returns all of the entities in the database. My GetJson method in the Razor file returns null however.

Here is my Razor code file:

@page "/"
@using LogicX.Shared
@inject HttpClient Http

Users

@functions{
    User[] _users;
    protected override async Task OnInitAsync()
    {
        var users = await Http.GetJsonAsync<User[]>("/api/users");
        _users = users;
    }
}
@foreach (var usr in _users)
{
    @usr.Username
}

The GetJsonAsync method seems to return null, in spite of records being in the database and in spite of the fact i am able to view the entities in Json format by browsing to /api/users. Is my implementation of this correct and does anyone know how to potentially fix this issue?

Edit: Server Side Code:

[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class UsersController : Controller
{
    private readonly LogicXDbContext _context;

    public UsersController(LogicXDbContext context)
    {
        _context = context;
    }

    // GET: api/Users
    [HttpGet]
    public async Task<ActionResult<IEnumerable<User>>> GetUsers()
    {
        return await _context.Users.ToListAsync();
    }

    // GET: api/Users/5
    [HttpGet("{id}")]
    public async Task<ActionResult<User>> GetUser(int id)
    {
        var user = await _context.Users.FindAsync(id);

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

        return user;
    }

    // PUT: api/Users/5
    [HttpPut("{id}")]
    public async Task<IActionResult> PutUser(int id, User user)
    {
        if (id != user.Id)
        {
            return BadRequest();
        }

        _context.Entry(user).State = EntityState.Modified;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!UserExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return NoContent();
    }

    // POST: api/Users
    [HttpPost]
    public async Task<ActionResult<User>> PostUser(User user)
    {
        _context.Users.Add(user);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetUser", new { id = user.Id }, user);
    }

    // DELETE: api/Users/5
    [HttpDelete("{id}")]
    public async Task<ActionResult<User>> DeleteUser(int id)
    {
        var user = await _context.Users.FindAsync(id);
        if (user == null)
        {
            return NotFound();
        }

        _context.Users.Remove(user);
        await _context.SaveChangesAsync();

        return user;
    }

    private bool UserExists(int id)
    {
        return _context.Users.Any(e => e.Id == id);
    }
}

}


问:
Function pipeline support, can't bind argument to parameter
I created following simple funcion, where the parameter supports input from pipeline:

```<code>    function Write-Log {
        [CmdletBinding()]
        param (
            # Lines to log
            [Parameter(Mandatory , ValueFromPipeline )]
            [string[]]
            $PipeLineLoglines
        )

        process {
            Write-Host $_
        }
    }
</code>```

If I call the function via e.g. :

```<code>    "test1", "test2" | Write-Log
</code>```

It works as expected, but if I'm forwarding an empty string down the pipeline I get the folowing error:

```<code>C:\> "test1", "", "test2" | Write-Log
test1
Write-Log : Cannot bind argument to parameter 'PipeLineLoglines' because it is an empty string.
At line:1 char:24
+ "test1", "", "test2" | Write-Log
+                        ~~~~~~~~~
    + CategoryInfo          : InvalidData: (:String) [Write-Log], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Write-Log

test2
</code>```

I'm using PowerShell.Core:

```<code>C:\> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      6.2.0
PSEdition                      Core
GitCommitId                    6.2.0
OS                             Microsoft Windows 10.0.17763
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0
</code>```

Can someone explain why an empty string causes this error?

Thx

答:
It's because the parameter is Mandatory, and it's considered that an empty string did not satisfy that condition. Given that there are specific validation attributes to test for that, I don't like this behavior, but that's the way it is.

There is an attribute that can help you though, [AllowEmptyString()]:

 function Write-Log {
        [CmdletBinding()]
        param (
            # Lines to log
            [Parameter(Mandatory , ValueFromPipeline )]
            [AllowEmptyString()]
            [string[]]
            $PipeLineLoglines
        )

        process {
            Write-Host $_
        }
    }
```

Body:
I created following simple funcion, where the parameter supports input from pipeline:

    function Write-Log {
        [CmdletBinding()]
        param (
            # Lines to log
            [Parameter(Mandatory , ValueFromPipeline )]
            [string[]]
            $PipeLineLoglines
        )

        process {
            Write-Host $_
        }
    }

If I call the function via e.g. :

    "test1", "test2" | Write-Log

It works as expected, but if I'm forwarding an empty string down the pipeline I get the folowing error:

C:\> "test1", "", "test2" | Write-Log
test1
Write-Log : Cannot bind argument to parameter 'PipeLineLoglines' because it is an empty string.
At line:1 char:24
+ "test1", "", "test2" | Write-Log
+                        ~~~~~~~~~
    + CategoryInfo          : InvalidData: (:String) [Write-Log], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Write-Log

test2

I'm using PowerShell.Core:

C:\> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      6.2.0
PSEdition                      Core
GitCommitId                    6.2.0
OS                             Microsoft Windows 10.0.17763
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Can someone explain why an empty string causes this error?

Thx


问:
AntiForgeryToken Expiration Blank Page
I'm using IdentityServer4 with ASP.NET Core 2.2. On the Post Login method I have applied the ValidateAntiForgeryToken. Generally after 20 minutes to 2 hours of sitting on the login page and then attempting to login it produces a blank page.

If you look at Postman Console you get a 400 Bad Request message. I then set the Cookie Expiration on the AntiForgery options to 90 days. I was able to allow the page to sit for up to 6 hours and still login. However, after around 8 hours (overnight), I received the blank page again after attempting to login.

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login
</code>```

```<code>services.AddAntiforgery(options =>
{
    options.Cookie.Expiration = TimeSpan.FromDays(90);
});
</code>```

I expect to be able to sit on the login page for 90 days which is the duration of the cookie but that doesn't work. How do I get the cookie for the AntiforgeryToken to last the entire 90 days or whatever time I set it to and not timeout or expire? Is there a way to catch this error and redirect the user back to the login method?

答:
Update '2021

Since ASP.Net Core 3.0 MS decided to make ValidateAntiforgeryTokenAuthorizationFilter internal. Now we have to copy-paste their code, to be able to derive. But most likely we don't need to. To just change the resulting behavior all we need is to test the context for the IAntiforgeryValidationFailedResult and proceed accordantly, as described in this example.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Core.Infrastructure;
using Microsoft.AspNetCore.Mvc.Filters;

namespace BasicWebSite.Filters
{
    public class RedirectAntiforgeryValidationFailedResultFilter : IAlwaysRunResultFilter
    {
        public void OnResultExecuting(ResultExecutingContext context)
        {
            if (context.Result is IAntiforgeryValidationFailedResult result)
            {
                context.Result =
                    new RedirectResult("http://example.com/antiforgery-redirect");
            }
        }

        public void OnResultExecuted(ResultExecutedContext context)
        { }
    }
}
```
<p>Then within the controller:</p>
<pre class="lang-cs prettyprint-override"><code>// POST: /Antiforgery/LoginWithRedirectResultFilter
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[TypeFilter(typeof(RedirectAntiforgeryValidationFailedResultFilter))]
public string LoginWithRedirectResultFilter(LoginViewModel model)
{
    return "Ok";
}
</code>```

The original answer covering .net core 2.2

Yet another implementation using the default one including all prechecks, logging etc. And it's still an AuthorizationFilter, so that prevents any further action execution. The only difference is that it triggers HttpGet to the same url instead of the default 400 response, a kind of the Post/Redirect/Get pattern implementation.

public class AnotherAntiForgeryTokenAttribute : TypeFilterAttribute
{
    public AnotherAntiForgeryTokenAttribute() : base(typeof(AnotherAntiforgeryFilter))
    {
    }
}

public class AnotherAntiforgeryFilter:ValidateAntiforgeryTokenAuthorizationFilter,
    IAsyncAuthorizationFilter
{
    public AnotherAntiforgeryFilter(IAntiforgery a, ILoggerFactory l) : base(a, l)
    {
    }

    async Task IAsyncAuthorizationFilter.OnAuthorizationAsync(
        AuthorizationFilterContext ctx)
    {
        await base.OnAuthorizationAsync(ctx);

        if (ctx.Result is IAntiforgeryValidationFailedResult)
        {
            // the next four rows are optional, just illustrating a way
            // to save some sensitive data such as initial query
            // the form has to support that
            var request = ctx.HttpContext.Request;
            var url = request.Path.ToUriComponent();
            if (request.Form?["ReturnUrl"].Count > 0)
                url = $"{url}?ReturnUrl={Uri.EscapeDataString(request.Form?["ReturnUrl"])}";

            // and the following is the only real customization
            ctx.Result = new LocalRedirectResult(url);
        }
    }
}
```

Title: AntiForgeryToken Expiration Blank Page

Body:
I'm using IdentityServer4 with ASP.NET Core 2.2. On the Post Login method I have applied the ValidateAntiForgeryToken. Generally after 20 minutes to 2 hours of sitting on the login page and then attempting to login it produces a blank page.

If you look at Postman Console you get a 400 Bad Request message. I then set the Cookie Expiration on the AntiForgery options to 90 days. I was able to allow the page to sit for up to 6 hours and still login. However, after around 8 hours (overnight), I received the blank page again after attempting to login.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login

services.AddAntiforgery(options =>
{
    options.Cookie.Expiration = TimeSpan.FromDays(90);
});

I expect to be able to sit on the login page for 90 days which is the duration of the cookie but that doesn't work. How do I get the cookie for the AntiforgeryToken to last the entire 90 days or whatever time I set it to and not timeout or expire? Is there a way to catch this error and redirect the user back to the login method?

Body:
Update '2021

Since ASP.Net Core 3.0 MS decided to make ValidateAntiforgeryTokenAuthorizationFilter internal. Now we have to copy-paste their code, to be able to derive. But most likely we don't need to. To just change the resulting behavior all we need is to test the context for the IAntiforgeryValidationFailedResult and proceed accordantly, as described in this example.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Core.Infrastructure;
using Microsoft.AspNetCore.Mvc.Filters;

namespace BasicWebSite.Filters
{
    public class RedirectAntiforgeryValidationFailedResultFilter : IAlwaysRunResultFilter
    {
        public void OnResultExecuting(ResultExecutingContext context)
        {
            if (context.Result is IAntiforgeryValidationFailedResult result)
            {
                context.Result =
                    new RedirectResult("http://example.com/antiforgery-redirect");
            }
        }

        public void OnResultExecuted(ResultExecutedContext context)
        { }
    }
}

Then within the controller:

// POST: /Antiforgery/LoginWithRedirectResultFilter
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
[TypeFilter(typeof(RedirectAntiforgeryValidationFailedResultFilter))]
public string LoginWithRedirectResultFilter(LoginViewModel model)
{
    return "Ok";
}

The original answer covering .net core 2.2

Yet another implementation using the default one including all prechecks, logging etc. And it's still an AuthorizationFilter, so that prevents any further action execution. The only difference is that it triggers HttpGet to the same url instead of the default 400 response, a kind of the Post/Redirect/Get pattern implementation.

public class AnotherAntiForgeryTokenAttribute : TypeFilterAttribute
{
    public AnotherAntiForgeryTokenAttribute() : base(typeof(AnotherAntiforgeryFilter))
    {
    }
}

public class AnotherAntiforgeryFilter:ValidateAntiforgeryTokenAuthorizationFilter,
    IAsyncAuthorizationFilter
{
    public AnotherAntiforgeryFilter(IAntiforgery a, ILoggerFactory l) : base(a, l)
    {
    }

    async Task IAsyncAuthorizationFilter.OnAuthorizationAsync(
        AuthorizationFilterContext ctx)
    {
        await base.OnAuthorizationAsync(ctx);

        if (ctx.Result is IAntiforgeryValidationFailedResult)
        {
            // the next four rows are optional, just illustrating a way
            // to save some sensitive data such as initial query
            // the form has to support that
            var request = ctx.HttpContext.Request;
            var url = request.Path.ToUriComponent();
            if (request.Form?["ReturnUrl"].Count > 0)
                url = $"{url}?ReturnUrl={Uri.EscapeDataString(request.Form?["ReturnUrl"])}";

            // and the following is the only real customization
            ctx.Result = new LocalRedirectResult(url);
        }
    }
}


问:
R Tidy solution to select from group_by output based on a column's data availability
I have following R dplyr dataframe in df_pub (Science/Nature Publication Data)

Please note that there are same PMID (or paper) with contributing authors in each row (Authors info is not shown here).

I need to select and store publications (PMID) which has no email attached to it and store the last observation of it in data-frame.

Actually I want to remove all PMIDs having any email in any observation. I need to collect the Publications (PMIDs) which does not have an attached email, and then find the last author or last observation (usually she/he/xe are the group leader or PI, we'll contact them manually and request them to update their email).

So for the example above, the expected output will not contain PMID 22522932 because it has an email attached. For other PMIDs only the last row of each such PMID will be stored.

I started with this but then lost

```<code>df_pub %>%
  group_by(pmid) %>%
  filter(is.na(email)) # This does not do the expected
</code>```

答:
If I understand correctly, this will do what you want:</p>

```<code>df_pub %>%
  group_by(pmid) %>%
  filter(!any(!is.na(email)),
         row_number() == n())
</code>```

Body:
I have following R dplyr dataframe in df_pub (Science/Nature Publication Data)

Please note that there are same PMID (or paper) with contributing authors in each row (Authors info is not shown here).

I need to select and store publications (PMID) which has no email attached to it and store the last observation of it in data-frame.

Actually I want to remove all PMIDs having any email in any observation. I need to collect the Publications (PMIDs) which does not have an attached email, and then find the last author or last observation (usually she/he/xe are the group leader or PI, we'll contact them manually and request them to update their email).

So for the example above, the expected output will not contain PMID 22522932 because it has an email attached. For other PMIDs only the last row of each such PMID will be stored.

I started with this but then lost

df_pub %>%
  group_by(pmid) %>%
  filter(is.na(email)) # This does not do the expected

Body:
If I understand correctly, this will do what you want:

df_pub %>%
  group_by(pmid) %>%
  filter(!any(!is.na(email)),
         row_number() == n())


问:
Initialize an std::array algorithmically at compile time
Consider:

```<code>static constexpr unsigned num_points{ 7810 };
std::array< double, num_points > axis;

for (int i = 0; i < num_points; ++i)
{
    axis[i] = 180 + 0.1 * i;
}
</code>```

axis is a class-wide constant. I want to avoid initializing it like any other global variable. Can it be done at compile time?

This is the final class in its entirety:

```<code>// https://www.nist.gov/pml/atomic-spectroscopy-compendium-basic-ideas-notation-data-and-formulas/atomic-spectroscopy
// https://www.nist.gov/pml/atomic-spectra-database
struct Spectrum
{
    static constexpr unsigned _num_points{ 7810 };
    using Axis = std::array< double, _num_points >;

    static constexpr Axis _x{ [] ()            // wavelength, nm
        {
            Axis a {};
            for( unsigned i = 0; i < _num_points; ++i )
            {
                a[ i ] = 180 + 0.1 * i;
            }
            return a;
        } () };
    Axis _y {};                                // radiance, W·sr−1·m−2
};
</code>```

The mixing of code and variables is unsightly, but at least the formula is right in front of the reader's eyes. Any other solution involved a lot of typing in order to get the in-class defined constant and type.

Or if I change my heart, I can simply return the lambda at runtime.

答:
Here is the full compileable code:</p>

```<code>#include <array>

template<int num_points>
static constexpr std::array<double, num_points> init_axis() {
    std::array<double, num_points> a{};
    for(int i = 0; i < num_points; ++i)
    {
        a[i] = 180 + 0.1 * i;
    }
    return a;
};

struct Z {
    static constexpr int num_points = 10;
    static constexpr auto axis = init_axis<num_points>();
};
</code>```

Body:
Consider:

static constexpr unsigned num_points{ 7810 };
std::array< double, num_points > axis;

for (int i = 0; i < num_points; ++i)
{
    axis[i] = 180 + 0.1 * i;
}

axis is a class-wide constant. I want to avoid initializing it like any other global variable. Can it be done at compile time?

This is the final class in its entirety:

// https://www.nist.gov/pml/atomic-spectroscopy-compendium-basic-ideas-notation-data-and-formulas/atomic-spectroscopy
// https://www.nist.gov/pml/atomic-spectra-database
struct Spectrum
{
    static constexpr unsigned _num_points{ 7810 };
    using Axis = std::array< double, _num_points >;

    static constexpr Axis _x{ [] ()            // wavelength, nm
        {
            Axis a {};
            for( unsigned i = 0; i < _num_points; ++i )
            {
                a[ i ] = 180 + 0.1 * i;
            }
            return a;
        } () };
    Axis _y {};                                // radiance, W·sr−1·m−2
};

The mixing of code and variables is unsightly, but at least the formula is right in front of the reader's eyes. Any other solution involved a lot of typing in order to get the in-class defined constant and type.

Or if I change my heart, I can simply return the lambda at runtime.

Body:
Here is the full compileable code:

#include <array>

template<int num_points>
static constexpr std::array<double, num_points> init_axis() {
    std::array<double, num_points> a{};
    for(int i = 0; i < num_points; ++i)
    {
        a[i] = 180 + 0.1 * i;
    }
    return a;
};

struct Z {
    static constexpr int num_points = 10;
    static constexpr auto axis = init_axis<num_points>();
};


问:
How to segue from UIPageViewController to a UINavigationController for iOS app onboarding
I am creating an iOS app with an "onboarding" tutorial to be shown the first time a user uses the app. I have the tutorial set up as a UIPageViewController with a button to finish the tutorial. When this is pressed, I'd like to switch to my main navigation controller that handles the rest of the app. So far I have not found a good way to do this. Any suggestions?</p>

答: I've always coded these 'first time used' view controllers to be launched from the main navigation controller, which is designated as the start-up view controller.  When the main controller is being created, it checks for a flag to see if it is the first time, and if so, then segue to the first time used view controller. This happens so fast, usually, that you don't ever see the main controller first.  At the end of the first time use logic, clicking the done button just returns to its parent navigation controller, which then sets the first time flag to false.</p>


问:
Enrich-my-library by extending TraversableLike with own methods
I tried to extend TraversableLike with my own methods, but I failed.

First, see what I wanna achieve:

```<code>class RichList[A](steps: List[A]) {
  def step(f: (A, A) => A): List[A] = {
    def loop(ret: List[A], steps: List[A]): List[A] = steps match {
      case _ :: Nil => ret.reverse.tail
      case _ => loop(f(steps.tail.head, steps.head) :: ret, steps.tail)
    }
    loop(List(steps.head), steps)
  }
}
implicit def listToRichList[A](l: List[A]) = new RichList(l)

val f = (n: Int) => n * (2*n - 1)
val fs = (1 to 10) map f
fs.toList step (_ - _)
</code>```

This code works fine and it calculates me the differences between the list elements. But I wanna have such a code that works with Seq, Set etc. and not only with List.

I tried this:

```<code>class RichT[A, CC[X] <: TraversableLike[X, CC[X]]](steps: CC[A]) {
  def step(f: (A, A) => A): CC[A] = {
    def loop(ret: CC[A], steps: CC[A]): CC[A] =
      if (steps.size > 1) loop(ret ++ f(steps.tail.head, steps.head), steps.tail)
      else ret.tail
    loop(CC(steps.head), steps)
  }
}
implicit def tToRichT[A, CC[X] <: TraversableLike[X, CC[X]]](t: CC[A]) = new RichT(t)
</code>```

There are several errors. Either the implicit conversion nor the ++-method work. Also, I don't know how to create a new type CC - see the call of the loop.

答:
Based on Rex' comment I have written following code:

```<code>class RichIter[A, C[A] <: Iterable[A]](ca: C[A]) {
  import scala.collection.generic.CanBuildFrom
  def step(f: (A, A) => A)(implicit cbfc: CanBuildFrom[C[A], A, C[A]]): C[A] = {
    val iter = ca.iterator
    val as = cbfc()

    if (iter.hasNext) {
      var olda = iter.next
      as += olda
      while (iter.hasNext) {
        val a = iter.next
        as += f(a, olda)
        olda = a
      }
    }
    as.result
  }
}
implicit def iterToRichIter[A, C[A] <: Iterable[A]](ca: C[A]) = new RichIter[A, C](ca)

val f = (n: Int) => n * (2*n - 1)
val fs = (1 to 10) map f
fs step (_ - _)
</code>```

This works as expected.

ContentLicense: CC BY-SA 3.0

Body:
I tried to extend TraversableLike with my own methods, but I failed.

First, see what I wanna achieve:

class RichList[A](steps: List[A]) {
  def step(f: (A, A) => A): List[A] = {
    def loop(ret: List[A], steps: List[A]): List[A] = steps match {
      case _ :: Nil => ret.reverse.tail
      case _ => loop(f(steps.tail.head, steps.head) :: ret, steps.tail)
    }
    loop(List(steps.head), steps)
  }
}
implicit def listToRichList[A](l: List[A]) = new RichList(l)

val f = (n: Int) => n * (2*n - 1)
val fs = (1 to 10) map f
fs.toList step (_ - _)

This code works fine and it calculates me the differences between the list elements. But I wanna have such a code that works with Seq, Set etc. and not only with List.

I tried this:

class RichT[A, CC[X] <: TraversableLike[X, CC[X]]](steps: CC[A]) {
  def step(f: (A, A) => A): CC[A] = {
    def loop(ret: CC[A], steps: CC[A]): CC[A] =
      if (steps.size > 1) loop(ret ++ f(steps.tail.head, steps.head), steps.tail)
      else ret.tail
    loop(CC(steps.head), steps)
  }
}
implicit def tToRichT[A, CC[X] <: TraversableLike[X, CC[X]]](t: CC[A]) = new RichT(t)

There are several errors. Either the implicit conversion nor the ++-method work. Also, I don't know how to create a new type CC - see the call of the loop.

Body:
Based on Rex' comment I have written following code:

class RichIter[A, C[A] <: Iterable[A]](ca: C[A]) {
  import scala.collection.generic.CanBuildFrom
  def step(f: (A, A) => A)(implicit cbfc: CanBuildFrom[C[A], A, C[A]]): C[A] = {
    val iter = ca.iterator
    val as = cbfc()

    if (iter.hasNext) {
      var olda = iter.next
      as += olda
      while (iter.hasNext) {
        val a = iter.next
        as += f(a, olda)
        olda = a
      }
    }
    as.result
  }
}
implicit def iterToRichIter[A, C[A] <: Iterable[A]](ca: C[A]) = new RichIter[A, C](ca)

val f = (n: Int) => n * (2*n - 1)
val fs = (1 to 10) map f
fs step (_ - _)

This works as expected.


问:
Pass percentiles to pandas agg function
I want to pass the numpy percentile() function through pandas' agg() function as I do below with various other numpy statistics functions.

Right now I have a dataframe that looks like this:

```<code>AGGREGATE   MY_COLUMN
A           10
A           12
B           5
B           9
A           84
B           22
</code>```

And my code looks like this:

```<code>grouped = dataframe.groupby('AGGREGATE')
column = grouped['MY_COLUMN']
column.agg([np.sum, np.mean, np.std, np.median, np.var, np.min, np.max])
</code>```

The above code works, but I want to do something like

```<code>column.agg([np.sum, np.mean, np.percentile(50), np.percentile(95)])
</code>```

I.e., specify various percentiles to return from agg().

How should this be done?

答:
For situations where all you need is a subset of the describe (typically the most common needed statistics) you can just index the returned pandas series without needing any extra functions.

For example, I commonly find myself just needing to present the 25th, median, 75th and count. This can be done in just one line like so:

```<code>columns.agg('describe')[['25%', '50%', '75%', 'count']]
</code>```

For specifying your own set of percentiles, the chosen answer is a good choice, but for simple use case, there is no need for extra functions.

Title: Pass percentiles to pandas agg function

Body:
I want to pass the numpy percentile() function through pandas' agg() function as I do below with various other numpy statistics functions.

Right now I have a dataframe that looks like this:

AGGREGATE   MY_COLUMN
A           10
A           12
B           5
B           9
A           84
B           22

And my code looks like this:

grouped = dataframe.groupby('AGGREGATE')
column = grouped['MY_COLUMN']
column.agg([np.sum, np.mean, np.std, np.median, np.var, np.min, np.max])

The above code works, but I want to do something like

column.agg([np.sum, np.mean, np.percentile(50), np.percentile(95)])

I.e., specify various percentiles to return from agg().

How should this be done?

Body:
For situations where all you need is a subset of the describe (typically the most common needed statistics) you can just index the returned pandas series without needing any extra functions.

For example, I commonly find myself just needing to present the 25th, median, 75th and count. This can be done in just one line like so:

columns.agg('describe')[['25%', '50%', '75%', 'count']]

For specifying your own set of percentiles, the chosen answer is a good choice, but for simple use case, there is no need for extra functions.


问:
read rectangular data blocks with separate tags as new columns
I feel my situation is a typical use case in experiments where the data are logged as text file for human understanding, but not for machine consumption.     Tags are interspersed with the actual data to describe the data that follows.  For data analysis, the tags need to integrated with the data rows to be useful. Below is a made-up example.

```<code>TAG1, t1_1

DATA_A, 5, 3, 4, 8
DATA_A, 3, 4, 5, 7

TAG1, t1_2
TAG2, t2_1

DATA_B, 1, 2, 3, 4, 5

DATA_A, 1, 2, 3, 4
</code>```

The desired parse results should be two data frames. One for DATA_A,

```<code>X1, X2, X3, X4, TAG1, TAG2
5, 3, 4, 8, t1_1, NA
3, 4, 5, 7, t1_1, NA
1, 2, 3, 4, t1_2, t2_1
</code>```

and one for DATA_B

```<code>X1, X2, X3, X4, X5, TAG1, TAG2
1, 2, 3, 4, 5, t1_2, t2_1
</code>```

The current method (implemented in Python) check the file line by line. If it starts with "T", then the corresponding tag variable is updated; if it starts with "DATA", then the tag values are appended to the end of the "DATA" line, and the now completed line is appended to the corresponding CSV file.  In the end, the CSV files are read into data frames for data analysis.

I wonder if this data import can be done faster in one step.  What I have in mind is

library(tidyverse)

text_frame <- read_lines(clipboard(), skip_empty_rows = TRUE) %>%
  enframe(name = NULL, value = "line")

text_frame %>%
  separate(line, into = c("ID", "value"), extra = "merge", sep = ", ")

```
<p>which produces</p>
```# A tibble: 7 x 2
  ID     value
  <chr>  <chr>
1 TAG1   t1_1
2 DATA_A 5, 3, 4, 8
3 DATA_A 3, 4, 5, 7
4 TAG1   t1_2
5 TAG2   t2_1
6 DATA_B 1, 2, 3, 4, 5
7 DATA_A 1, 2, 3, 4
```

The next step is to create new column "TAG1" and "TAG2" with the value added to the row. This is where I got stuck. It is like gather for individual rows.  How could I do it?   Is the general approach reasonable?  Any suggestions?

Fast/memory efficient solutions are welcome since the I need to deal with hundreds of ~10MB text files (they do have the same structure).

答:
Using the input data

```<code>text <- '
TAG1, t1_1

DATA_A, 5, 3, 4, 8
DATA_A, 3, 4, 5, 7

TAG1, t1_2
TAG2, t2_1

DATA_B, 1, 2, 3, 4, 5

DATA_A, 1, 2, 3, 4
'
</code>```

You can get the tags from the second column of the imported data V2 by selecting the elements of V2 where the first column V1 is TAG[1|2], and do this for each group. Groups are identified by a variable starting at 0 and incrementing by 1 after each occurrence of [V1 contains TAG then V1 doesn't contain TAG].

Then with tags as their own columns you can remove the TAG rows, and split the data according to whether the first column contains 'B'

```<code>library(data.table)

df <- fread(text, fill = T, blank.lines.skip = T)

df[, `:=`(TAG1 = V2[V1 == 'TAG1'],
          TAG2 = V2[V1 == 'TAG2']),
   by = .(g = (rleid(grepl('TAG', V1)) - 1) %/% 2)]

df <- df[-grep('TAG', V1)]

split(df, df[, grepl('B', V1)])

# $`FALSE`
#        V1 V2 V3 V4 V5 V6 TAG1 TAG2
# 1: DATA_A  5  3  4  8 NA t1_1 <NA>
# 2: DATA_A  3  4  5  7 NA t1_1 <NA>
# 3: DATA_A  1  2  3  4 NA t1_2 t2_1
#
# $`TRUE`
#        V1 V2 V3 V4 V5 V6 TAG1 TAG2
# 1: DATA_B  1  2  3  4  5 t1_2 t2_1
</code>```

If you don't always 2 tags and may have more or less, you can replace the step after fread above with

```<code>n_tags <- df[, as.numeric(gsub('[^0-9]', '', max(grep('TAG', V1, value = T))))]
df[, g := (rleid(grepl('TAG', V1)) - 1) %/% 2]
for(i in seq_len(n_tags))
  df[, paste0('TAG', i) := V2[V1 == paste0('TAG', i)], g]
</code>```

Body:
I feel my situation is a typical use case in experiments where the data are logged as text file for human understanding, but not for machine consumption.     Tags are interspersed with the actual data to describe the data that follows.  For data analysis, the tags need to integrated with the data rows to be useful. Below is a made-up example.

TAG1, t1_1

DATA_A, 5, 3, 4, 8
DATA_A, 3, 4, 5, 7

TAG1, t1_2
TAG2, t2_1

DATA_B, 1, 2, 3, 4, 5

DATA_A, 1, 2, 3, 4

The desired parse results should be two data frames. One for DATA_A,

X1, X2, X3, X4, TAG1, TAG2
5, 3, 4, 8, t1_1, NA
3, 4, 5, 7, t1_1, NA
1, 2, 3, 4, t1_2, t2_1

and one for DATA_B

X1, X2, X3, X4, X5, TAG1, TAG2
1, 2, 3, 4, 5, t1_2, t2_1

The current method (implemented in Python) check the file line by line. If it starts with "T", then the corresponding tag variable is updated; if it starts with "DATA", then the tag values are appended to the end of the "DATA" line, and the now completed line is appended to the corresponding CSV file.  In the end, the CSV files are read into data frames for data analysis.

I wonder if this data import can be done faster in one step.  What I have in mind is

library(tidyverse)

text_frame <- read_lines(clipboard(), skip_empty_rows = TRUE) %>%
  enframe(name = NULL, value = "line")

text_frame %>%
  separate(line, into = c("ID", "value"), extra = "merge", sep = ", ")

which produces

# A tibble: 7 x 2
  ID     value
  <chr>  <chr>
1 TAG1   t1_1
2 DATA_A 5, 3, 4, 8
3 DATA_A 3, 4, 5, 7
4 TAG1   t1_2
5 TAG2   t2_1
6 DATA_B 1, 2, 3, 4, 5
7 DATA_A 1, 2, 3, 4

The next step is to create new column "TAG1" and "TAG2" with the value added to the row. This is where I got stuck. It is like gather for individual rows.  How could I do it?   Is the general approach reasonable?  Any suggestions?

Fast/memory efficient solutions are welcome since the I need to deal with hundreds of ~10MB text files (they do have the same structure).

Body:
Using the input data

text <- '
TAG1, t1_1

DATA_A, 5, 3, 4, 8
DATA_A, 3, 4, 5, 7

TAG1, t1_2
TAG2, t2_1

DATA_B, 1, 2, 3, 4, 5

DATA_A, 1, 2, 3, 4
'

You can get the tags from the second column of the imported data V2 by selecting the elements of V2 where the first column V1 is TAG[1|2], and do this for each group. Groups are identified by a variable starting at 0 and incrementing by 1 after each occurrence of [V1 contains TAG then V1 doesn't contain TAG].

Then with tags as their own columns you can remove the TAG rows, and split the data according to whether the first column contains 'B'

library(data.table)

df <- fread(text, fill = T, blank.lines.skip = T)

df[, `:=`(TAG1 = V2[V1 == 'TAG1'],
          TAG2 = V2[V1 == 'TAG2']),
   by = .(g = (rleid(grepl('TAG', V1)) - 1) %/% 2)]

df <- df[-grep('TAG', V1)]

split(df, df[, grepl('B', V1)])

# $`FALSE`
#        V1 V2 V3 V4 V5 V6 TAG1 TAG2
# 1: DATA_A  5  3  4  8 NA t1_1 <NA>
# 2: DATA_A  3  4  5  7 NA t1_1 <NA>
# 3: DATA_A  1  2  3  4 NA t1_2 t2_1
#
# $`TRUE`
#        V1 V2 V3 V4 V5 V6 TAG1 TAG2
# 1: DATA_B  1  2  3  4  5 t1_2 t2_1

If you don't always 2 tags and may have more or less, you can replace the step after fread above with

n_tags <- df[, as.numeric(gsub('[^0-9]', '', max(grep('TAG', V1, value = T))))]
df[, g := (rleid(grepl('TAG', V1)) - 1) %/% 2]
for(i in seq_len(n_tags))
  df[, paste0('TAG', i) := V2[V1 == paste0('TAG', i)], g]


问:
Year over Year Inflation Calculation for particular data model
I know that this might be a duplicate question but I have failed to find a solution to my problem after about 5 hours of searching. Sorry in advance if it is.

The data
I have three tables that are in the DIrectQuery Storage Mode. One is called LINE_ITEM it has a one to many relationship with another table INVOICE. The INVOICE table has a one to many relationship with another table CONTRACT. Each CONTRACT has one INVOICE per year. Each INVOICE has one or more line items, all of which have a N_PAID_AMOUNT.

Goal
I'm looking to calculate the percent increase in the amount paid each INVOICE year.

Limitations
This same pbix file will be used to do many other things and needs to be very responsive. I do not want to manipulate the queries or relationships in any way if possible for the sake of both speed and simplicity. I would like to solve this with a measured or calculated column.

Where I'm stuck at
I have a formula, which I am using in a measure

```<code>Previous Paid Amount = CALCULATE(SUM(LINE_ITEM[N_PAID_AMOUNT]), YEAR(INVOICE[DT_START]) = YEAR(INVOICE[DT_START])-1)
</code>```

It throws an error "Cannot find name '[DT_START]'." only for the second occurance in the filter expression. If I replace the formula with,

```<code>Previous Paid Amount = CALCULATE(SUM(LINE_ITEM[N_PAID_AMOUNT]), YEAR(INVOICE[DT_START]) = NOW())
</code>```

It does not throw errors but obviously does not help me calculate what I need.

Other things I've tried
I have tried using the EARLIER DAX function, I have tried changing the data to import mode, I have tried numerous other formulas and functions. I have tried all kinds of quick measures including the one that is supposed to do this exact calculation and none have been successful.

Let me know if there's any other information I can share to help you answer my question.

答:
```<code>Paid Amount LY =
CALCULATE(
    INVOICE[Paid Amount],
    FILTER(
        ALLSELECTED('INVOICE'[Year]),
        ISONORAFTER('INVOICE'[Year], MAX('INVOICE'[Year])-1, DESC)
    )
) -
CALCULATE(
    INVOICE[Paid Amount],
    FILTER(
        ALLSELECTED('INVOICE'[Year]),
        ISONORAFTER('INVOICE'[Year], MAX('INVOICE'[Year])-2, DESC)
    )
)
</code>```

This formula solved my problem. However it is horrendous. If anyone has insight on how I could do this better please let me know.

Body:
I know that this might be a duplicate question but I have failed to find a solution to my problem after about 5 hours of searching. Sorry in advance if it is.

The data
I have three tables that are in the DIrectQuery Storage Mode. One is called LINE_ITEM it has a one to many relationship with another table INVOICE. The INVOICE table has a one to many relationship with another table CONTRACT. Each CONTRACT has one INVOICE per year. Each INVOICE has one or more line items, all of which have a N_PAID_AMOUNT.

Goal
I'm looking to calculate the percent increase in the amount paid each INVOICE year.

Limitations
This same pbix file will be used to do many other things and needs to be very responsive. I do not want to manipulate the queries or relationships in any way if possible for the sake of both speed and simplicity. I would like to solve this with a measured or calculated column.

Where I'm stuck at
I have a formula, which I am using in a measure

Previous Paid Amount = CALCULATE(SUM(LINE_ITEM[N_PAID_AMOUNT]), YEAR(INVOICE[DT_START]) = YEAR(INVOICE[DT_START])-1)

It throws an error "Cannot find name '[DT_START]'." only for the second occurance in the filter expression. If I replace the formula with,

Previous Paid Amount = CALCULATE(SUM(LINE_ITEM[N_PAID_AMOUNT]), YEAR(INVOICE[DT_START]) = NOW())

It does not throw errors but obviously does not help me calculate what I need.

Other things I've tried
I have tried using the EARLIER DAX function, I have tried changing the data to import mode, I have tried numerous other formulas and functions. I have tried all kinds of quick measures including the one that is supposed to do this exact calculation and none have been successful.

Let me know if there's any other information I can share to help you answer my question.

Body:
Paid Amount LY =
CALCULATE(
    INVOICE[Paid Amount],
    FILTER(
        ALLSELECTED('INVOICE'[Year]),
        ISONORAFTER('INVOICE'[Year], MAX('INVOICE'[Year])-1, DESC)
    )
) -
CALCULATE(
    INVOICE[Paid Amount],
    FILTER(
        ALLSELECTED('INVOICE'[Year]),
        ISONORAFTER('INVOICE'[Year], MAX('INVOICE'[Year])-2, DESC)
    )
)

This formula solved my problem. However it is horrendous. If anyone has insight on how I could do this better please let me know.


问:
ggplot2 alternatives to fill in barplots, occurence of factor in multiple rows
I'm pretty new to R and I have a problem with plotting a barplot out of my data which looks like this:

```<code>condition answer
2    H
1    H
8    H
5    W
4    M
7    H
9    H
10   H
6    H
3    W
</code>```

The data consists of 100 rows with the conditions 1 to 10, each randomly generated 10 times (10 times condition 1, 10 times condition 8,...). Each of the conditions  also has a answer which could be H for Hit, M for Miss or W for wrong.

I want to plot the number of Hits for each condition in a barplot (for example 8 Hits out of 10 for condition 1,...) for that I tried to do the following in ggplot2

```<code>ggplot(data=test, aes(x=test$condition, fill=answer=="H"))+
  geom_bar()+labs(x="Conditions", y="Hitrate")+
  coord_cartesian(xlim = c(1:10), ylim = c(0:10))+
  scale_x_continuous(breaks=seq(1,10,1))
</code>```

And it looked like this:

This actually exactly what I need except for the red color which covers everything. You can see that conditions 3 to 5 have no blue bar, because there are no hits for these conditions.

Is there any way to get rid of this red color and to maybe count the amount of hits for the different conditions? -> I tried the count function of dplyr but it only showed me the amount of H when there where some for this particular condition. 3-5 where just "ignored" by count, there wasn't even a 0 in the output.-> but I'd still need those numbers for the plot

I'm sorry for this particular long post but I'm really at the end of knowledge considering this. I'd be open for suggestions or alternatives! Thanks in advance!

答:
This is a situation where a little preprocessing goes a long way. I made sample data that would recreate the issue, i.e. has cases where there won't be any "H"s.

Instead of relying on ggplot to aggregate data in the way you want it, use proper tools. Since you mention dplyr::count, I use dplyr functions.

The preprocessing task is to count observations with answer "H", including cases where the count is 0. To make sure all combinations are retained, convert condition to a factor and set .drop = F in count, which is in turn passed to group_by.

library(dplyr)
library(ggplot2)

set.seed(529)
test <- data.frame(condition = rep(1:10, times = 10),
                   answer = c(sample(c("H", "M", "W"), 50, replace = T),
                              sample(c("M", "W"), 50, replace = T)))

hit_counts <- test %>%
  mutate(condition = as.factor(condition)) %>%
  filter(answer == "H") %>%
  count(condition, .drop = F)

hit_counts
#> # A tibble: 10 x 2
#>    condition     n
#>    <fct>     <int>
#>  1 1             0
#>  2 2             1
#>  3 3             4
#>  4 4             2
#>  5 5             3
#>  6 6             0
#>  7 7             3
#>  8 8             2
#>  9 9             1
#> 10 10            1
```

<p>Then just plot that. <code>geom_col</code> is the version of <code>geom_bar</code> for where you have your y-values already, instead of having <code>ggplot</code> tally them up for you.</p>

<pre class="lang-r prettyprint-override"><code>ggplot(hit_counts, aes(x = condition, y = n)) +
  geom_col()
</code>```

Body:
I'm pretty new to R and I have a problem with plotting a barplot out of my data which looks like this:

condition answer
2    H
1    H
8    H
5    W
4    M
7    H
9    H
10   H
6    H
3    W

The data consists of 100 rows with the conditions 1 to 10, each randomly generated 10 times (10 times condition 1, 10 times condition 8,...). Each of the conditions  also has a answer which could be H for Hit, M for Miss or W for wrong.

I want to plot the number of Hits for each condition in a barplot (for example 8 Hits out of 10 for condition 1,...) for that I tried to do the following in ggplot2

ggplot(data=test, aes(x=test$condition, fill=answer=="H"))+
  geom_bar()+labs(x="Conditions", y="Hitrate")+
  coord_cartesian(xlim = c(1:10), ylim = c(0:10))+
  scale_x_continuous(breaks=seq(1,10,1))

And it looked like this:

This actually exactly what I need except for the red color which covers everything. You can see that conditions 3 to 5 have no blue bar, because there are no hits for these conditions.

Is there any way to get rid of this red color and to maybe count the amount of hits for the different conditions? -> I tried the count function of dplyr but it only showed me the amount of H when there where some for this particular condition. 3-5 where just "ignored" by count, there wasn't even a 0 in the output.-> but I'd still need those numbers for the plot

I'm sorry for this particular long post but I'm really at the end of knowledge considering this. I'd be open for suggestions or alternatives! Thanks in advance!

Body:
This is a situation where a little preprocessing goes a long way. I made sample data that would recreate the issue, i.e. has cases where there won't be any "H"s.

Instead of relying on ggplot to aggregate data in the way you want it, use proper tools. Since you mention dplyr::count, I use dplyr functions.

The preprocessing task is to count observations with answer "H", including cases where the count is 0. To make sure all combinations are retained, convert condition to a factor and set .drop = F in count, which is in turn passed to group_by.

library(dplyr)
library(ggplot2)

set.seed(529)
test <- data.frame(condition = rep(1:10, times = 10),
                   answer = c(sample(c("H", "M", "W"), 50, replace = T),
                              sample(c("M", "W"), 50, replace = T)))

hit_counts <- test %>%
  mutate(condition = as.factor(condition)) %>%
  filter(answer == "H") %>%
  count(condition, .drop = F)

hit_counts
#> # A tibble: 10 x 2
#>    condition     n
#>    <fct>     <int>
#>  1 1             0
#>  2 2             1
#>  3 3             4
#>  4 4             2
#>  5 5             3
#>  6 6             0
#>  7 7             3
#>  8 8             2
#>  9 9             1
#> 10 10            1

Then just plot that. geom_col is the version of geom_bar for where you have your y-values already, instead of having ggplot tally them up for you.

ggplot(hit_counts, aes(x = condition, y = n)) +
  geom_col()


问:
Are there any conventions for how to order Java annotations?
For projects heavily used of Java annotations, is there any suggestion on the annotation order? So as to uniform the code style in the team.</p>

答:
If you must impose an order, alphabetical?

Without some sort of knowledge about the annotations you are using, it's hard to suggest a rational ordering.  Perhaps a better ordering would suit you and your team better; and if so, if you document what's the agreed order, the only thing left is to verify it follows the team agreed ordering.

After talking to your whole team, you might find you don't need to order them after all.


问:
collapsing optgroups that contain all unchecked options in boostrap-multiselect
I am using boostrap-multiselect for my application. The select box contains three optgroups. Whenever I click on some checkbox in it, I want to collapse the optgroups once I switch to another optgroup.

Here is the sample code

```<code><select multiple="multiple" id="food_type">
    <optgroup label="Breakfast">
        <option value="Burger">Burger</option>
        <option value="Fries">Fries</option>
    </optgroup>
    <optgroup label="Lunch">
        <option value="Pizza">Pizza</option>
        <option value="Thali">Thali</option>
    </optgroup>
    <optgroup label="Desserts">
        <option value="Icecreame">Icecreame</option>
        <option value="Fruit Salad">Fruit Salad</option>
    </optgroup>
</select>

$("#food_type").multiselect({
    numberDisplayed: 1,
    buttonText: function (options, select){
        return "Food Types";
    },
    enableCollapsibleOptGroups: true,
    collapseOptGroupsByDefault: true
});
</code>```

By default all optgroups are collapsed. I want to toggle the collapse-expand of optgroups once I switched to another optgroup for selection.

I couldn't find default functionality provided in documentation of bootstrap-mulitselect. Can anyone please help me?

Thanks in advance.

答:
By default all optgroups are collapsed. I want to toggle the collapse-expand of optgroups once I switched to another optgroup for selection.

You can attach the click event handler to each multiselect-group elements. Inside this you can toggle the visibility of the others optgroups.

$("#food_type").multiselect({
    numberDisplayed: 1,
    buttonText: function (options, select) {
        return "Food Types";
    },
    enableCollapsibleOptGroups: true,
    collapseOptGroupsByDefault: true
}).data('multiselect').$ul.find('.multiselect-group').on('click', function(e) {
    $(this).siblings('.multiselect-group').nextUntil('.multiselect-group')
            .addClass('multiselect-collapsible-hidden').hide();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css">
<script src="https://rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js"></script>

<div class="container">
    <div class="row">
        <select multiple="multiple" id="food_type">
            <optgroup label="Breakfast">
                <option value="Burger">Burger</option>
                <option value="Fries">Fries</option>
            </optgroup>
            <optgroup label="Lunch">
                <option value="Pizza">Pizza</option>
                <option value="Thali">Thali</option>
            </optgroup>
            <optgroup label="Desserts">
                <option value="Icecreame">Icecreame</option>
                <option value="Fruit Salad">Fruit Salad</option>
            </optgroup>
        </select>
    </div>
</div></code>```

Instead, if you need to toggle all the optgroups containing all unchecked options you can test it inside the click event handler:

$("#food_type").multiselect({
numberDisplayed: 1,
buttonText: function (options, select) {
return "Food Types";
},
enableCollapsibleOptGroups: true,
collapseOptGroupsByDefault: true
}).data('multiselect').$ul.find('.multiselect-group').on('click', function (e) {
  $(this).siblings('.multiselect-group').each(function(idx, ele) {
      var eles = $(ele).nextUntil('.multiselect-group');
      if (eles.find(':checked').length == 0) {
          eles.addClass('multiselect-collapsible-hidden').hide();
      }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet"
    href="https://rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css">
<script src="https://rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js"></script>

<div class="container">
    <div class="row">
        <select multiple="multiple" id="food_type">
            <optgroup label="Breakfast">
                <option value="Burger">Burger</option>
                <option value="Fries">Fries</option>
            </optgroup>
            <optgroup label="Lunch">
                <option value="Pizza">Pizza</option>
                <option value="Thali">Thali</option>
            </optgroup>
            <optgroup label="Desserts">
                <option value="Icecreame">Icecreame</option>
                <option value="Fruit Salad">Fruit Salad</option>
            </optgroup>
        </select>
    </div>
</div></code>```

Body:
I am using boostrap-multiselect for my application. The select box contains three optgroups. Whenever I click on some checkbox in it, I want to collapse the optgroups once I switch to another optgroup.

Here is the sample code

<select multiple="multiple" id="food_type">
    <optgroup label="Breakfast">
        <option value="Burger">Burger</option>
        <option value="Fries">Fries</option>
    </optgroup>
    <optgroup label="Lunch">
        <option value="Pizza">Pizza</option>
        <option value="Thali">Thali</option>
    </optgroup>
    <optgroup label="Desserts">
        <option value="Icecreame">Icecreame</option>
        <option value="Fruit Salad">Fruit Salad</option>
    </optgroup>
</select>

$("#food_type").multiselect({
    numberDisplayed: 1,
    buttonText: function (options, select){
        return "Food Types";
    },
    enableCollapsibleOptGroups: true,
    collapseOptGroupsByDefault: true
});

By default all optgroups are collapsed. I want to toggle the collapse-expand of optgroups once I switched to another optgroup for selection.

I couldn't find default functionality provided in documentation of bootstrap-mulitselect. Can anyone please help me?

Thanks in advance.

Body:
By default all optgroups are collapsed. I want to toggle the collapse-expand of optgroups once I switched to another optgroup for selection.

You can attach the click event handler to each multiselect-group elements. Inside this you can toggle the visibility of the others optgroups.

$("#food_type").multiselect({
    numberDisplayed: 1,
    buttonText: function (options, select) {
        return "Food Types";
    },
    enableCollapsibleOptGroups: true,
    collapseOptGroupsByDefault: true
}).data('multiselect').$ul.find('.multiselect-group').on('click', function(e) {
    $(this).siblings('.multiselect-group').nextUntil('.multiselect-group')
            .addClass('multiselect-collapsible-hidden').hide();
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css">
<script src="https://rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js"></script>

<div class="container">
    <div class="row">
        <select multiple="multiple" id="food_type">
            <optgroup label="Breakfast">
                <option value="Burger">Burger</option>
                <option value="Fries">Fries</option>
            </optgroup>
            <optgroup label="Lunch">
                <option value="Pizza">Pizza</option>
                <option value="Thali">Thali</option>
            </optgroup>
            <optgroup label="Desserts">
                <option value="Icecreame">Icecreame</option>
                <option value="Fruit Salad">Fruit Salad</option>
            </optgroup>
        </select>
    </div>
</div>

Instead, if you need to toggle all the optgroups containing all unchecked options you can test it inside the click event handler:

$("#food_type").multiselect({
numberDisplayed: 1,
buttonText: function (options, select) {
return "Food Types";
},
enableCollapsibleOptGroups: true,
collapseOptGroupsByDefault: true
}).data('multiselect').$ul.find('.multiselect-group').on('click', function (e) {
  $(this).siblings('.multiselect-group').each(function(idx, ele) {
      var eles = $(ele).nextUntil('.multiselect-group');
      if (eles.find(':checked').length == 0) {
          eles.addClass('multiselect-collapsible-hidden').hide();
      }
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet"
    href="https://rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css">
<script src="https://rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js"></script>

<div class="container">
    <div class="row">
        <select multiple="multiple" id="food_type">
            <optgroup label="Breakfast">
                <option value="Burger">Burger</option>
                <option value="Fries">Fries</option>
            </optgroup>
            <optgroup label="Lunch">
                <option value="Pizza">Pizza</option>
                <option value="Thali">Thali</option>
            </optgroup>
            <optgroup label="Desserts">
                <option value="Icecreame">Icecreame</option>
                <option value="Fruit Salad">Fruit Salad</option>
            </optgroup>
        </select>
    </div>
</div>


问:
Google Task API No More Shows Tasks created via API on Calendar
When creating tasks via API those tasks do not appear in calendar, but are only visible in sidebar section of tabs.

Just few days ago all seems to be working correctly, so this could be some bug or their sudenn change. How to find that? How to notify google api of the issue?

答:
Closing as the issue is already been filled.
https://issuetracker.google.com/issues/133809207</p>


问:
Replace multiple commas with a single one - linux command
This is an output from my google csv contacts (which contains more than 1000 contacts):

```<code>A-Tech Computers Hardware,A-Tech Computers,,Hardware,,,,,,,,,,,,,,,,,,,,Low,,,* My Contacts,,,,,,,,,Home,+38733236313,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
</code>```

I need a linux cli command to replace the duplicate commas, with single commas, so i get this:

```<code>A-Tech Computers Hardware,A-Tech Computers,Hardware,Low,* My Contacts,Home,+38733236313,
</code>```

What I usually do in notepad++ is Replace ",," with "," six times.

I tried with:

```<code>cat googlecontacts.txt | sed -e 's/,,/,/g' -e 's/,,/,/g' -e 's/,,/,/g'  -e 's/,,/,/g' -e 's/,,/,/g' -e 's/,,/,/g' > google.txt
</code>```

But it doesn't work...
However, when I try it on smaller files (two lines) it works... :(

Help please!

答:
Thanks @potong, your solution worked for one of my requirement. I had to replace the | symbol in the first line of my file and used this solution with small change.

```<code>sed -i "1s/|'*//g" ${filename}
</code>```

I was unable to add comments so thought of posting it as an answer. Please excuse

Body:
This is an output from my google csv contacts (which contains more than 1000 contacts):

A-Tech Computers Hardware,A-Tech Computers,,Hardware,,,,,,,,,,,,,,,,,,,,Low,,,* My Contacts,,,,,,,,,Home,+38733236313,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

I need a linux cli command to replace the duplicate commas, with single commas, so i get this:

A-Tech Computers Hardware,A-Tech Computers,Hardware,Low,* My Contacts,Home,+38733236313,

What I usually do in notepad++ is Replace ",," with "," six times.

I tried with:

cat googlecontacts.txt | sed -e 's/,,/,/g' -e 's/,,/,/g' -e 's/,,/,/g'  -e 's/,,/,/g' -e 's/,,/,/g' -e 's/,,/,/g' > google.txt

But it doesn't work...
However, when I try it on smaller files (two lines) it works... :(

Help please!

Body:
Thanks @potong, your solution worked for one of my requirement. I had to replace the | symbol in the first line of my file and used this solution with small change.

sed -i "1s/|'*//g" ${filename}

I was unable to add comments so thought of posting it as an answer. Please excuse


问:
How to extract item from nested list - Rest Assured
I've got this  json object

```<code>{
   "type" : "employee",
   "columns" :
      [
         {
            "id" : 1,
            "human" :
               [
                  {
                     "name" : "ANA",
                     "age" : "23"
                  },
                  {
                     "name" : "IULIA",
                     "age" : "22"
                  }
               ]
         },
         {
            "id" : 2,
            "human" :
               [
                  {
                     "name" : "ADI",
                     "age" : "21"
                  },
                  {
                     "name" : "GELU",
                     "age" : "18"
                  }
               ]
         }
      ]
}
</code>```

and I need to extract the first name from each human list.
I've tried  .body("columns.human.name[0]", everyItem(containsString("A"))) but it doesn't work. Any ideas?

答:
Using JsonPath you can get all columns and all humans.

Each of JSON Object is represented as HashMap<>. If it contains only fields it's HashMap<String, String> but if contains arrays or nested JSON Objects then it is HashMap<String, Object> where Object is either another JSON Object or array.

Given the above you can use following code to get all columns and name of first human in each column:

```<code>JsonPath path = response.jsonPath();
List<HashMap<String, Object>> columns = path.getList("columns");
for (HashMap<String, Object> singleColumn : columns) {
    List<HashMap<String, Object>> humans = (List<HashMap<String, Object>>) singleColumn.get("human");
    System.out.println(humans.get(0).get("name"));
}
</code>```

The above code will print ANA and ADI in the console.
You can store the results in List<String> for further processing

Body:
I've got this  json object

{
   "type" : "employee",
   "columns" :
      [
         {
            "id" : 1,
            "human" :
               [
                  {
                     "name" : "ANA",
                     "age" : "23"
                  },
                  {
                     "name" : "IULIA",
                     "age" : "22"
                  }
               ]
         },
         {
            "id" : 2,
            "human" :
               [
                  {
                     "name" : "ADI",
                     "age" : "21"
                  },
                  {
                     "name" : "GELU",
                     "age" : "18"
                  }
               ]
         }
      ]
}

and I need to extract the first name from each human list.
I've tried  .body("columns.human.name[0]", everyItem(containsString("A"))) but it doesn't work. Any ideas?

Body:
Using JsonPath you can get all columns and all humans.

Each of JSON Object is represented as HashMap<>. If it contains only fields it's HashMap<String, String> but if contains arrays or nested JSON Objects then it is HashMap<String, Object> where Object is either another JSON Object or array.

Given the above you can use following code to get all columns and name of first human in each column:

JsonPath path = response.jsonPath();
List<HashMap<String, Object>> columns = path.getList("columns");
for (HashMap<String, Object> singleColumn : columns) {
    List<HashMap<String, Object>> humans = (List<HashMap<String, Object>>) singleColumn.get("human");
    System.out.println(humans.get(0).get("name"));
}

The above code will print ANA and ADI in the console.
You can store the results in List<String> for further processing


问:
java bit manipulation
```<code>byte x = -1;
for(int i = 0; i < 8; i++)
{
    x = (byte) (x >>> 1);
    System.out.println("X: " + x);
}
</code>```

As I understand it, java stores data in two's-complement, meaning -1 = 11111111 (according to wikipedia).

Also, from the java docs:
"The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension. "

Which means that >>> would shift a 0 to the left most bit every time.  So I expect this code to be

iteration: bit representation of x

0: 11111111

1: 01111111

2: 00111111

3: 00011111

...so on

However, my output is always X: -1, meaning (I guess) that >>> is putting the sign bit in the left most position.  So I then try >>, and same result.

What's going on?  I would expect my output to be: X: -1, x: 127, x: 63, etc.

答:
Remember that:

operands of bitwise operations are always promoted to at least an int!

casts always involve sign extension.

So when you do (x >>> n), even though you defined x as a byte, for the purposes of the shift, it will be first converted to an int. If the byte being converted is negative, then all of the "extra bits" (so, the leftmost 24 bits of the resulting int) added to make it up to an int will be set to 1. Or put another way, if the original byte was -1, the thing you're actually shifting is -1 as an int, i.e. 32-bit number with all 32 bits set to 1. Shifting this right by 1-8 places will still result in the bottom 8 bits all set to 1, hence when you cast back to a byte, you end up with a byte with all 8 bits set to 1, or in other words, a byte value of -1.

OwnerDisplayName: jbu

Title: java bit manipulation

Body:
byte x = -1;
for(int i = 0; i < 8; i++)
{
    x = (byte) (x >>> 1);
    System.out.println("X: " + x);
}

As I understand it, java stores data in two's-complement, meaning -1 = 11111111 (according to wikipedia).

Also, from the java docs:
"The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension. "

Which means that >>> would shift a 0 to the left most bit every time.  So I expect this code to be

iteration: bit representation of x

0: 11111111

1: 01111111

2: 00111111

3: 00011111

...so on

However, my output is always X: -1, meaning (I guess) that >>> is putting the sign bit in the left most position.  So I then try >>, and same result.

What's going on?  I would expect my output to be: X: -1, x: 127, x: 63, etc.

OwnerDisplayName: Neil Coffey

ContentLicense: CC BY-SA 2.5


问:
tabs/indents blocking code on windows server
I have the following code and it's working great on my local xampp and test linux webhosting:

```<code><?php
// include config file
include('config.php');

// get page intel
$_PAGE = switchPage($_GET);

// require language file
require_once("languages/".$_PAGE['language'].".lang.php");

// include header file
include('includes/header.inc.php');
?>

            <section id="main" class="clearfix">

                <?php
                // include correct page
                include($_PAGE['include_path']);
                ?>

            </section>

<?php
// include footer file
include('includes/footer.inc.php');
?>
</code>```

My client has a windows server with PHP 5.2.6 installed. The hosting company claims that tabs/indents like used in the following snipet out of the code does not work on a windows php hosting.

```<code>            <?php
            // include correct page
            include($_PAGE['include_path']);
            ?>
</code>```

So they claim my code is not valid PHP code.. Can someone advice please? I don't want to rewrite my code just because of all the indents I use to keep my code clean and readable ..

答:
So they claim my code is not valid PHP code.. Can someone advice please?

On one hand, they're full of it.  It's valid code.

On the other hand, that code could be problematic -- if that was the opening <?php tag at the beginning of a file.  This is the #2 cause of the infamous "cannot send headers, headers already sent" error that PHP can generate.  Each PHP file should not have any whitespace before the opening PHP tag.

That tag is in the middle of the document and thus is not a problem.

Body:
I have the following code and it's working great on my local xampp and test linux webhosting:

<?php
// include config file
include('config.php');

// get page intel
$_PAGE = switchPage($_GET);

// require language file
require_once("languages/".$_PAGE['language'].".lang.php");

// include header file
include('includes/header.inc.php');
?>

                <?php
                // include correct page
                include($_PAGE['include_path']);
                ?>

<?php
// include footer file
include('includes/footer.inc.php');
?>

My client has a windows server with PHP 5.2.6 installed. The hosting company claims that tabs/indents like used in the following snipet out of the code does not work on a windows php hosting.

            <?php
            // include correct page
            include($_PAGE['include_path']);
            ?>

So they claim my code is not valid PHP code.. Can someone advice please? I don't want to rewrite my code just because of all the indents I use to keep my code clean and readable ..


问:
I've to create a deepArray2String method that expects a 2D int array 'x' and returns its string representation
Create a deepArray2String method that expects a 2D int array 'a1' and returns its string representation, which can be written to the console.

I've tried some logics but i'm getting this error:

tester.java:18: error: incompatible types: StringBuffer cannot be converted to String
   return result;
           ^

```<code>public String deepArray2String(int[][] a1){

    StringBuffer result = new StringBuffer();
    for (int i = 0; i < a1.length; i++) {
        for (int j = 0; j < a1[i].length; j++) {
            result.append("[" + a1[i][j] + "]");
            if (j == a1.length && i != a1.length-1) {
                result.append(",");
            }
        }
    }
    return result;
}
</code>```

System.out.println (deepArray2String (new int [] [] {{1}, {2}, {4}}));

Output should be [1], [2], [4]]

System.out.println (deepArray2String (new int [] [] {{1}, {2, 3}}));

Output should be [[1], [2, 3]]

System.out.println (deepArray2String (new int [] [] {}));

Output should be []

System.out.println (deepArray2String (new int [] [] {{5, 3}, {1}, {-1, 1}}));

Output should be [[5, 3], [1], [-1, 1]]

答:
Your method's signature says that it returns a String, but you're trying to return a StringBuffer.  Make that last line:</p>

```<code>return result.toString();
</code>```

Body:
Create a deepArray2String method that expects a 2D int array 'a1' and returns its string representation, which can be written to the console.

I've tried some logics but i'm getting this error:

tester.java:18: error: incompatible types: StringBuffer cannot be converted to String
   return result;
           ^

public String deepArray2String(int[][] a1){

    StringBuffer result = new StringBuffer();
    for (int i = 0; i < a1.length; i++) {
        for (int j = 0; j < a1[i].length; j++) {
            result.append("[" + a1[i][j] + "]");
            if (j == a1.length && i != a1.length-1) {
                result.append(",");
            }
        }
    }
    return result;
}

System.out.println (deepArray2String (new int [] [] {{1}, {2}, {4}}));

Output should be [1], [2], [4]]

System.out.println (deepArray2String (new int [] [] {{1}, {2, 3}}));

Output should be [[1], [2, 3]]

System.out.println (deepArray2String (new int [] [] {}));

Output should be []

System.out.println (deepArray2String (new int [] [] {{5, 3}, {1}, {-1, 1}}));

Output should be [[5, 3], [1], [-1, 1]]

Body:
Your method's signature says that it returns a String, but you're trying to return a StringBuffer.  Make that last line:

return result.toString();


问:
Incompatible Dims with GlobalAveragePooling2D()
I'm trying to run a few different models, which ran fine until I added a GlobalAveragePooling2D() which now throws the following error:

```<code>ValueError: Input 0 is incompatible with layer flatten_105: expected min_ndim=3, found ndim=2
</code>```

I feel it has something to do with a GlobalAveragePooling2D() layer not being compatible with a flatten() layer and my understand is lacking, but I'm not sure.

My code is below.  Could anyone enlighten me on what they think is going on?  It ran fine without the GlobalAveragePooling2D layer.  I was  hoping to experiment with it though.

```<code>dense_layers = [1,2,3]
layer_sizes = [32, 64, 128]
con_layers = [1,2,3]
con_layer_sizes = [32, 64, 128, 512]

for dense_layer in dense_layers:
    for layer_size in layer_sizes:
        for conv_layer in con_layers:
            for con_layer_size in con_layer_sizes:

                img_size = 125

                batch_size = 16

                K.input_shape = (img_size, img_size)

                NAME = "{}-conv-{}-con_layer_sizes-{}-nodes-{}-dense-{}".format(conv_layer, con_layer_size, layer_size, dense_layer, int(time.time()))
                print(NAME)
                tensorboard = TensorBoard(log_dir= 'logs/{}'.format(NAME))
                mcp = ModelCheckpoint(filepath='C:\\Users\\jordan.howell\\models\\'+NAME+'_model.h5',monitor="val_loss"
                                      , save_best_only=True, save_weights_only=False)
                reduce_learning_rate = ReduceLROnPlateau(monitor='val_loss', factor=0.3,patience=2,cooldown=2
                                                         , min_lr=0.00001, verbose=1)

                #start model build
                model = Sequential()
                model.add(Conv2D(con_layer_size, (3, 3), activation="relu", padding = 'same', input_shape=input_shape))
                model.add(MaxPooling2D(pool_size = (2, 2)))
                model.add(BatchNormalization())
                model.add(Dropout(0.15))

                for l in range(conv_layer-1):
                    #Convolution
                    model.add(Conv2D(con_layer_size, (3, 3), activation="relu", padding = 'same'))
                    model.add(MaxPooling2D(pool_size = (2, 2)))
                    model.add(BatchNormalization())
                    model.add(Dropout(0.15))

                model.add(GlobalAveragePooling2D())
                # Flatten the layer
                model.add(Flatten())

                for l in range(dense_layer):
                    model.add(Dense(layer_size, activation = 'relu'))

                model.add(Dense(activation = 'sigmoid', units = 1))

                model.compile(loss ='binary_crossentropy', optimizer = 'adam'
                              , metrics=[km.binary_precision(), km.binary_recall()])

                #generators = Generators(TRAIN_DATA_DIR, VALIDATION_DATA_DIR, TEST_DATA_DIR)
                #train_generator = generators.train_generator(150, batch_size=32)
                #validation_generator = generators.validation_generator(150, batch_size=16)

                model.fit_generator(train_generator, steps_per_epoch=5216  // batch_size
                                    ,validation_data=validation_generator, validation_steps=1
                                    , epochs = 50, callbacks = [reduce_learning_rate, tensorboard, mcp])
</code>```

答: From Keras docs, GlobalAveragePooling2D input shape is 4D tensor, output shape is 2D tensor. In this case, Flatten is redundant.

Body:
I'm trying to run a few different models, which ran fine until I added a GlobalAveragePooling2D() which now throws the following error:

ValueError: Input 0 is incompatible with layer flatten_105: expected min_ndim=3, found ndim=2

I feel it has something to do with a GlobalAveragePooling2D() layer not being compatible with a flatten() layer and my understand is lacking, but I'm not sure.

My code is below.  Could anyone enlighten me on what they think is going on?  It ran fine without the GlobalAveragePooling2D layer.  I was  hoping to experiment with it though.

dense_layers = [1,2,3]
layer_sizes = [32, 64, 128]
con_layers = [1,2,3]
con_layer_sizes = [32, 64, 128, 512]

for dense_layer in dense_layers:
    for layer_size in layer_sizes:
        for conv_layer in con_layers:
            for con_layer_size in con_layer_sizes:

                img_size = 125

                batch_size = 16

                K.input_shape = (img_size, img_size)

                NAME = "{}-conv-{}-con_layer_sizes-{}-nodes-{}-dense-{}".format(conv_layer, con_layer_size, layer_size, dense_layer, int(time.time()))
                print(NAME)
                tensorboard = TensorBoard(log_dir= 'logs/{}'.format(NAME))
                mcp = ModelCheckpoint(filepath='C:\\Users\\jordan.howell\\models\\'+NAME+'_model.h5',monitor="val_loss"
                                      , save_best_only=True, save_weights_only=False)
                reduce_learning_rate = ReduceLROnPlateau(monitor='val_loss', factor=0.3,patience=2,cooldown=2
                                                         , min_lr=0.00001, verbose=1)

                #start model build
                model = Sequential()
                model.add(Conv2D(con_layer_size, (3, 3), activation="relu", padding = 'same', input_shape=input_shape))
                model.add(MaxPooling2D(pool_size = (2, 2)))
                model.add(BatchNormalization())
                model.add(Dropout(0.15))

                for l in range(conv_layer-1):
                    #Convolution
                    model.add(Conv2D(con_layer_size, (3, 3), activation="relu", padding = 'same'))
                    model.add(MaxPooling2D(pool_size = (2, 2)))
                    model.add(BatchNormalization())
                    model.add(Dropout(0.15))

                model.add(GlobalAveragePooling2D())
                # Flatten the layer
                model.add(Flatten())

                for l in range(dense_layer):
                    model.add(Dense(layer_size, activation = 'relu'))

                model.add(Dense(activation = 'sigmoid', units = 1))

                model.compile(loss ='binary_crossentropy', optimizer = 'adam'
                              , metrics=[km.binary_precision(), km.binary_recall()])

                #generators = Generators(TRAIN_DATA_DIR, VALIDATION_DATA_DIR, TEST_DATA_DIR)
                #train_generator = generators.train_generator(150, batch_size=32)
                #validation_generator = generators.validation_generator(150, batch_size=16)

                model.fit_generator(train_generator, steps_per_epoch=5216  // batch_size
                                    ,validation_data=validation_generator, validation_steps=1
                                    , epochs = 50, callbacks = [reduce_learning_rate, tensorboard, mcp])


问:
.findAll() finds nothing from webpage
In order to pull out reviews from google store, I am trying to learn the library beautiful soup. I wrote a code that should get me all reviews (including the star rating, date and name of reviewer) but the output is just an empty list. The problem is probably something very basic that I am just too inexperienced to know of.

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup as soup
my_url = 'https://play.google.com/store/apps/details?id=com.playstudios.popslots&showAllReviews=true'
uclient = urlopen(my_url)
page_html = uclient.read()
uclient.close()
page_soup = soup(page_html, "html.parser")
reviews = page_soup.findAll("div",{"class":'d15Mdf bAhLNe'})
len(reviews)
</code>```

The output is 0.

What should I do in order to fix this?

答:
Because the class you're looking for is not there.

curl 'https://play.google.com/store/apps/details?id=com.playstudios.popslots&showAllReviews=true' | grep 'd15Mdf bAhLNe'
```

Almost entire  is produced by JavaScript running in the browser, including, I suppose all the interesting bits you're looking for.

If you want to try and scrape such a page, look for scrapers that actually run JavaScript (usually in Chrome running in headless mode).

Title: .findAll() finds nothing from webpage

Body:
In order to pull out reviews from google store, I am trying to learn the library beautiful soup. I wrote a code that should get me all reviews (including the star rating, date and name of reviewer) but the output is just an empty list. The problem is probably something very basic that I am just too inexperienced to know of.

from urllib.request import urlopen
from bs4 import BeautifulSoup as soup
my_url = 'https://play.google.com/store/apps/details?id=com.playstudios.popslots&showAllReviews=true'
uclient = urlopen(my_url)
page_html = uclient.read()
uclient.close()
page_soup = soup(page_html, "html.parser")
reviews = page_soup.findAll("div",{"class":'d15Mdf bAhLNe'})
len(reviews)

The output is 0.

What should I do in order to fix this?

Body:
Because the class you're looking for is not there.

curl 'https://play.google.com/store/apps/details?id=com.playstudios.popslots&showAllReviews=true' | grep 'd15Mdf bAhLNe'

Almost entire <body> is produced by JavaScript running in the browser, including, I suppose all the interesting bits you're looking for.

If you want to try and scrape such a page, look for scrapers that actually run JavaScript (usually in Chrome running in headless mode).


问:
Structural Typing Fails with Unions?
I don't quite understand why the following does not compile:

```<code>interface IPreciousMetal {
    type: "Silver" | "Gold"
}

interface ICryptoCurrency {
    type: "Bitcoin" | "Litecoin"
}

type Asset = ICryptoCurrency | IPreciousMetal;

function process(assetType: Asset["type"]) {
    const asset = { type: assetType };
    processImpl(asset); // Error
}

function processImpl(asset: Asset) {
    console.log(asset.type);
}
</code>```

An argument passed for the parameter assetType must be typed such that it is compatible with the Asset type. However, when an object is created with with said parameter value, the compiler complains.

答: What version of typescript are you on? Typescript 3.5 introduced smarter union type checking which should solve your issue. I don't think typescript playground is using that version yet.</p>

Title: Structural Typing Fails with Unions?

Body:
I don't quite understand why the following <a href="https://www.typescriptlang.org/play/index.html#src=interface%20IPreciousMetal%20%7B%0D%0A%20%20%20%20type%3A%20%22Silver%22%20%7C%20%22Gold%22%0D%0A%7D%0D%0A%0D%0Ainterface%20ICryptoCurrency%20%7B%0D%0A%20%20%20%20type%3A%20%22Bitcoin%22%20%7C%20%22Litecoin%22%0D%0A%7D%0D%0A%0D%0Atype%20Asset%20%3D%20ICryptoCurrency%20%7C%20IPreciousMetal%3B%0D%0A%0D%0Afunction%20process(assetType%3A%20Asset%5B%22type%22%5D)%20%7B%0D%0A%20%20%20%20const%20asset%20%3D%20%7B%20type%3A%20assetType%20%7D%3B%0D%0A%20%20%20%20processImpl(asset)%3B%20%2F%2F%20Error%0D%0A%7D%0D%0A%0D%0Afunction%20processImpl(asset%3A%20Asset)%20%7B%0D%0A%20%20%20%20console.log(asset.type)%3B%0D%0A%7D%0D%0A" rel="nofollow noreferrer">does not compile:

interface IPreciousMetal {
    type: "Silver" | "Gold"
}

interface ICryptoCurrency {
    type: "Bitcoin" | "Litecoin"
}

type Asset = ICryptoCurrency | IPreciousMetal;

function process(assetType: Asset["type"]) {
    const asset = { type: assetType };
    processImpl(asset); // Error
}

function processImpl(asset: Asset) {
    console.log(asset.type);
}

An argument passed for the parameter assetType must be typed such that it is compatible with the Asset type. However, when an object is created with with said parameter value, the compiler complains.


问:
Passing Observable to another component in Angular
I have two components details and details-view.

In the details I have to pass obserwable by @Input() into second component.

Details Component

```<code> res$: (id: number, type: string) => Observable<DetailsResponse[]>;
 constructor(private service: Service) {
  this.res$ = service.getData;
 }
</code>```

Service

```<code> getData(id: number, type: string): Observable<DetailsResponse[]>{
   const params = new HttpParams().append('typename', type);
   return this.http.get<any>('api/id', {params: params});
 }
</code>```

Detalis-View HTML

<dwtalis-view [resources$]="res$"></dwtalis-view>

Detalis-Viev TS Component

```<code>@Input()
resouces$: Observable<DetailsResponse[]>
</code>```

My question is how to subscribe and get the data from resources$ observable in the detalis view component. Subscribing this object retunrs error "resources$ is not a finction can not subscribe"

答:
The typing doesn't match. res$ is a function (id: number, type: string) => Observable<DetailsResponse[]>, but resouces$ is an observable Observable<DetailsResponse[]>;

Based on your comments, you need to pass a function because the arguments aren't available in the parent component. So, you need to accept a function as @Input and then execute it in the child component.

Child Component

```<code>@Input()
resouces$: (id: number, type: string) => Observable<DetailsResponse[]>;

// Use ngOnInit since @Input properties are populated at this time
ngOnInit() {
    // Example arguments
    this.resouces$(this.id, this.type).subscribe(results => {
        // Do whatever you need to do with the results
        console.log(results);
    })
}
</code>```

Body:
I have two components details and details-view.

In the details I have to pass obserwable by @Input() into second component.

Details Component

 res$: (id: number, type: string) => Observable<DetailsResponse[]>;
 constructor(private service: Service) {
  this.res$ = service.getData;
 }

Service

 getData(id: number, type: string): Observable<DetailsResponse[]>{
   const params = new HttpParams().append('typename', type);
   return this.http.get<any>('api/id', {params: params});
 }

Detalis-View HTML

<dwtalis-view [resources$]="res$"></dwtalis-view>

Detalis-Viev TS Component

@Input()
resouces$: Observable<DetailsResponse[]>

My question is how to subscribe and get the data from resources$ observable in the detalis view component. Subscribing this object retunrs error "resources$ is not a finction can not subscribe"

Body:
The typing doesn't match. res$ is a function (id: number, type: string) => Observable<DetailsResponse[]>, but resouces$ is an observable Observable<DetailsResponse[]>;

Based on your comments, you need to pass a function because the arguments aren't available in the parent component. So, you need to accept a function as @Input and then execute it in the child component.

Child Component

@Input()
resouces$: (id: number, type: string) => Observable<DetailsResponse[]>;

// Use ngOnInit since @Input properties are populated at this time
ngOnInit() {
    // Example arguments
    this.resouces$(this.id, this.type).subscribe(results => {
        // Do whatever you need to do with the results
        console.log(results);
    })
}


问:
How to change activity in android?

I am making simple game. I have 3 activities. First activity is main menu (FirstActivity class).

First activity has following code:

```<code>Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
</code>```

It calls second activity where, second activity has following code:

```<code>setContentView(new MovementView(this));
</code>```

MovementView class extends SurfaceView. MovementView class is where I write all game code.

So I want to make when lives == 0, it changes to ThirdActivity. How do I do that?

I have tried putting code similar to FirstActivity's class but it doesn't seems to work.

If I put

 ((Activity)getContext()).finish();

it just jumps back to FirstActivity, but that's not what I need, I need it to go to ThirdActivity class.

答:
Since you start Activity2 with ..ForResult(), you could also set the 2nd Activity's result (with setResult(GAME_OVER) before you finish it) so that Activity1 starts Activity3 in onActivityResult() if it makes sense that Activity2 is not there anymore when Activity3 was shown...

RE: @Yoni Samlan, well if I put

```<code>Intent i = new Intent(this, ThirdActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
</code>```

It shows The constructor Intent(MovementView, Class) is undefined for first line, and The method startActivityForResult(Intent, int) is undefined for the type MovementView for the second line.

You should pass your Activity as first argument and not the view, and call Activity.startActivityForResult()...
So pass your Activity to your view and use it there as described.

Title: How to change activity in android?

Body:
I am making simple game. I have 3 activities. First activity is main menu (FirstActivity class).

First activity has following code:

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);

It calls second activity where, second activity has following code:

setContentView(new MovementView(this));

MovementView class extends SurfaceView. MovementView class is where I write all game code.

So I want to make when lives == 0, it changes to ThirdActivity. How do I do that?

I have tried putting code similar to FirstActivity's class but it doesn't seems to work.

If I put

 ((Activity)getContext()).finish();

it just jumps back to FirstActivity, but that's not what I need, I need it to go to ThirdActivity class.

Body:
Since you start Activity2 with ..ForResult(), you could also set the 2nd Activity's result (with setResult(GAME_OVER) before you finish it) so that Activity1 starts Activity3 in onActivityResult() if it makes sense that Activity2 is not there anymore when Activity3 was shown...

RE: @Yoni Samlan, well if I put

Intent i = new Intent(this, ThirdActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);

It shows The constructor Intent(MovementView, Class) is undefined for first line, and The method startActivityForResult(Intent, int) is undefined for the type MovementView for the second line.

You should pass your Activity as first argument and not the view, and call Activity.startActivityForResult()...
So pass your Activity to your view and use it there as described.


问:
OpenCV4 Imshow function opens an empty gray box
When I run the provided code, a imshow() opens a window but it is just an empty gray window. The code executes successfully (doesn't trigger the !image.data check.) The imwrite() function does successfully write the image to a file so I don't think it is a problem with reading the image.

I also tried opening a named window first, and then calling imshow to that window, but that also didn't help.

It seems like there are a few other people having this issue on this site. I browsed the answers and tried the solutions but nothing worked. Also I could not find anyone using opencv 4.0 with c++.

#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <string>

using namespace std;
using namespace cv;

int main() {
    Mat image;
    image = imread("./887.jpg");
    if (!image.data)
    {
        cout << "Could not open or find the image" << std::endl;
        return -1;
    }

    imwrite("test.jpg", image);
    waitKey(1);
    imshow("Display window", image);                   // Show our image inside it.
    waitKey(0);

    return 0;
}
```

I expect the image to show up in a window titled "Display window", the window does show up but it is just an empty gray box.

答:
Specify absolute path to the image and check if it is working correctly.

If you are running your application from Visual Studio, you need to specify current working directory to be the same as location of the image.

You can also check with ifstream if file exists with

```<code>inputStream.open("887.jpg");
if (inputStream.fail()) {
    // bad file path
}
</code>```

just to confirm that current working directory is properly set.

Body:
When I run the provided code, a imshow() opens a window but it is just an empty gray window. The code executes successfully (doesn't trigger the !image.data check.) The imwrite() function does successfully write the image to a file so I don't think it is a problem with reading the image.

I also tried opening a named window first, and then calling imshow to that window, but that also didn't help.

It seems like there are a few other people having this issue on this site. I browsed the answers and tried the solutions but nothing worked. Also I could not find anyone using opencv 4.0 with c++.

#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <string>

using namespace std;
using namespace cv;

int main() {
    Mat image;
    image = imread("./887.jpg");
    if (!image.data)
    {
        cout << "Could not open or find the image" << std::endl;
        return -1;
    }

    imwrite("test.jpg", image);
    waitKey(1);
    imshow("Display window", image);                   // Show our image inside it.
    waitKey(0);

    return 0;
}

I expect the image to show up in a window titled "Display window", the window does show up but it is just an empty gray box.

Body:
Specify absolute path to the image and check if it is working correctly.

If you are running your application from Visual Studio, you need to specify current working directory to be the same as location of the image.

You can also check with ifstream if file exists with

inputStream.open("887.jpg");
if (inputStream.fail()) {
    // bad file path
}

just to confirm that current working directory is properly set.