问:
Central Directory Corrupt deploying Python Azure function
I was previously able to deploy an Azure function written in Python using the command func azure functionapp publish <FunctionAppName>  from my project directory, building it remotely.  It worked until lunchtime yesterday.

I now get the following message.

```<code>Creating archive for current directory...
Performing remote build for functions project.
Deleting the old .python_packages directory
Uploading  [######################################################################################]
Remote build in progress, please wait...
Fetching changes.
Cleaning up temp folders from previous zip deployments and extracting pushed zip file /tmp/zipdeploy/c5e66350-4b87-4e72-9900-b2a1ae4521a8.zip (0.00 MB) to /tmp/zipdeploy/extracted
Central Directory corrupt.
Remote build failed!
</code>```

I've tried the following to see if I can resolve it without any success:

Switching my machine off and on.

Deploying an older version of the code in case I've changed anything.

Deploying from the command prompt in visual studio code.

Reinstalling Azure functions core tools.

Deploying from a different machine on a different network (I read that there are sometimes firewall issues with uploading zip files but my IT manager assures me we have no restrictions and these settings have not been changed).  In doing so, I had to install Azure functions core tools from scratch as it had never been installed on that machine before.

Creating a completely new clean functionapp and deploying there.

Creating a brand new minimal Python application in a clean directory and deploying this to the new functionapp.

I get the same message in each case.

I'm stuck here.  Does anyone have any more information about what the error message might mean is going wrong or any ideas?

Other investigations -

I've tried deploying as a different Azure user (same error).

I've checked for any processes using port 9091 (none were found).

I have also tried to build locally using func azure functionapp publish IncidentProcessing4 --build local

I got some different error messages

```<code>Performing local build for functions project.
Directory .python_packages already in sync with requirements.txt. Skipping restoring dependencies...
Uploading package...
Uploading 0 B [###################################################################################]
Attempted to divide by zero.
Retry: 1 of 3
Uploading 0 B [###################################################################################]
Attempted to divide by zero.
Retry: 2 of 3
Uploading 0 B [###################################################################################]
Attempted to divide by zero.
Retry: 3 of 3
Uploading 0 B [###################################################################################]
Attempted to divide by zero.
</code>```

I noticed that in my \users\name\appdata\local\temp directory 2 files had been created by the build, called temp374D.tmp and tmp374E.tmp.  The first of these was 0KB in size and the 2nd 8KB in size.

My suspicion is something is causing the first file to be created and something on the server is attempting and failing to unzip it.

More additional information - "Deploy to Function App" from Visual Studio code deploys, but when the Azure function runs, I get errors about modules referenced by the function not being loaded.    If it's possible to deploy the modules in requirements.txt with the function app that will be a work around.

答:
I think I've fixed it by reverting to an earlier version of Azure Functions Core Tools.  It's deploying with 2.7.1575.

I'll experiment to see if I can find out any more but I've got my function deploying now.

Body:
I was previously able to deploy an Azure function written in Python using the command func azure functionapp publish <FunctionAppName>  from my project directory, building it remotely.  It worked until lunchtime yesterday.

I now get the following message.

Creating archive for current directory...
Performing remote build for functions project.
Deleting the old .python_packages directory
Uploading  [######################################################################################]
Remote build in progress, please wait...
Fetching changes.
Cleaning up temp folders from previous zip deployments and extracting pushed zip file /tmp/zipdeploy/c5e66350-4b87-4e72-9900-b2a1ae4521a8.zip (0.00 MB) to /tmp/zipdeploy/extracted
Central Directory corrupt.
Remote build failed!

I've tried the following to see if I can resolve it without any success:

Switching my machine off and on.

Deploying an older version of the code in case I've changed anything.

Deploying from the command prompt in visual studio code.

Reinstalling Azure functions core tools.

Deploying from a different machine on a different network (I read that there are sometimes firewall issues with uploading zip files but my IT manager assures me we have no restrictions and these settings have not been changed).  In doing so, I had to install Azure functions core tools from scratch as it had never been installed on that machine before.

Creating a completely new clean functionapp and deploying there.

Creating a brand new minimal Python application in a clean directory and deploying this to the new functionapp.

I get the same message in each case.

I'm stuck here.  Does anyone have any more information about what the error message might mean is going wrong or any ideas?

Other investigations -

I've tried deploying as a different Azure user (same error).

I've checked for any processes using port 9091 (none were found).

I have also tried to build locally using func azure functionapp publish IncidentProcessing4 --build local

I got some different error messages

Performing local build for functions project.
Directory .python_packages already in sync with requirements.txt. Skipping restoring dependencies...
Uploading package...
Uploading 0 B [###################################################################################]
Attempted to divide by zero.
Retry: 1 of 3
Uploading 0 B [###################################################################################]
Attempted to divide by zero.
Retry: 2 of 3
Uploading 0 B [###################################################################################]
Attempted to divide by zero.
Retry: 3 of 3
Uploading 0 B [###################################################################################]
Attempted to divide by zero.

I noticed that in my \users\name\appdata\local\temp directory 2 files had been created by the build, called temp374D.tmp and tmp374E.tmp.  The first of these was 0KB in size and the 2nd 8KB in size.

My suspicion is something is causing the first file to be created and something on the server is attempting and failing to unzip it.

More additional information - "Deploy to Function App" from Visual Studio code deploys, but when the Azure function runs, I get errors about modules referenced by the function not being loaded.    If it's possible to deploy the modules in requirements.txt with the function app that will be a work around.


来源: stackexchange

问:
how to put loading icon before the page loads
I have the following piece of code which is triggered by a button click.

```<code><?php
if(isset($_POST['click']))
            {
      echo "<div class='spinner-grow' role='status'>";
      echo "<span class='sr-only'>Loading...</span>";
      echo "</div>";

       shell_exec("perl myscript1.pl");
       shell_exec("perl myscript2.pl");

    echo "<div class='image'>";
    echo "<img src='figure.png' class='mx-auto d-block' style='width:800px; height:800px;'>";
    echo "</div>";
    }
?>
</code>```

the perl scripts inside that block will generate a image which i will load into page, but those two scripts take around 10s. So I am trying to put a boostrap spinner and have given a fadeout of 9.5s in jquery.

But the spinner and the image together load after 9.5s. The jquery code i am using is below. Kindly help what needs to be done.

```<code>$(function() {
  $(".spinner-grow").fadeOut(9500, function() {
    $(".image").fadeIn(500);
   });
});
</code>```

Thanks,
Karthic

答:
Add a div just after  tag.

   `

$(window).load(function() {
   $(".pre-loader").fadeOut();
    //or your loading icon wrapped in the pre-loader class
    });

ContentLicense: CC BY-SA 4.0

Body:
I have the following piece of code which is triggered by a button click.

<?php
if(isset($_POST['click']))
            {
      echo "
";
      echo "Loading...";
      echo "
";

       shell_exec("perl myscript1.pl");
       shell_exec("perl myscript2.pl");

    echo "
";
    echo "";
    echo "
";
    }
?>

the perl scripts inside that block will generate a image which i will load into page, but those two scripts take around 10s. So I am trying to put a boostrap spinner and have given a fadeout of 9.5s in jquery.

But the spinner and the image together load after 9.5s. The jquery code i am using is below. Kindly help what needs to be done.

$(function() {
  $(".spinner-grow").fadeOut(9500, function() {
    $(".image").fadeIn(500);
   });
});

Thanks,
Karthic

Body:
Add a div just after  tag.

<div class="pre-loader"></div>
   `

$(window).load(function() {
   $(".pre-loader").fadeOut();
    //or your loading icon wrapped in the pre-loader class
    });


问:
Concatenate values returned from an array in Swift
I'm training on Swift, doing some exercises with arrays. I would like to pick up randomly 6 letters in an array containing the 26 letters of the alphabet, then concatenate them to generate a string.

I have no problem picking the values, but when it comes to concatenate them, I get error messages.

Here is my code :

```<code>var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

var a = alphabet.randomElement()
var b = alphabet.randomElement()
var c = alphabet.randomElement()
var d = alphabet.randomElement()
var e = alphabet.randomElement()
var f = alphabet.randomElement()

var password = a + b + c + d + e + f

print(password)
</code>```

What am I doing wrong ?

答:
a, b, c, d, e, f are of type String?. So you need to unwrap them either using if-let or force-unwrapping before, i.e.

Using force-unwrapping,

```<code>let a = alphabet.randomElement()!
let b = alphabet.randomElement()!
let c = alphabet.randomElement()!
let d = alphabet.randomElement()!
let e = alphabet.randomElement()!
let f = alphabet.randomElement()!
</code>```

Using if-let,

```<code>if let a = alphabet.randomElement(), let b = alphabet.randomElement(), let c = alphabet.randomElement(), let d = alphabet.randomElement(), let e = alphabet.randomElement(), let f = alphabet.randomElement() {
    let password = a + b + c + d + e + f
    print(password)
}
</code>```

Using if-let is safer than force-unwrapping.

Note: Use let instead of var when using constant values.

Body:
I'm training on Swift, doing some exercises with arrays. I would like to pick up randomly 6 letters in an array containing the 26 letters of the alphabet, then concatenate them to generate a string.

I have no problem picking the values, but when it comes to concatenate them, I get error messages.

Here is my code :

var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

var a = alphabet.randomElement()
var b = alphabet.randomElement()
var c = alphabet.randomElement()
var d = alphabet.randomElement()
var e = alphabet.randomElement()
var f = alphabet.randomElement()

var password = a + b + c + d + e + f

print(password)

What am I doing wrong ?

Body:
a, b, c, d, e, f are of type String?. So you need to unwrap them either using if-let or force-unwrapping before, i.e.

Using force-unwrapping,

let a = alphabet.randomElement()!
let b = alphabet.randomElement()!
let c = alphabet.randomElement()!
let d = alphabet.randomElement()!
let e = alphabet.randomElement()!
let f = alphabet.randomElement()!

Using if-let,

if let a = alphabet.randomElement(), let b = alphabet.randomElement(), let c = alphabet.randomElement(), let d = alphabet.randomElement(), let e = alphabet.randomElement(), let f = alphabet.randomElement() {
    let password = a + b + c + d + e + f
    print(password)
}

Using if-let is safer than force-unwrapping.

Note: Use let instead of var when using constant values.


问:
how to combine 3 conditions by "OR" in jquery?
Is there anyway to combine 3 conditions by "OR" in jquery? Eg, $(t_obj).keyup(function(e) || $('#sendResp').click(function(e) || $('.emo').click(function(e) {  ? I have tested to combine them but I get error. How to combine them?

答:
Where you are attempting to combine conditions, you are, in fact, interrupting 3 jQuery shorthand calls to bind() on selectors.

If you don't interrupt the code to bind, the anonymous functions you write will be called when those events are raised.

To get the intended functionality, create your function and bind it to the events on those selectors individually as others have detailed in answers to this question.

ContentLicense: CC BY-SA 3.0


问:
C#: asp.net CORE empty Migration
I am trying to add a migration from DatabaseContext
but when I add an migration i generates it empty like this. I had been following this tutorial

```<code>namespace MovieExampleAppDotNetCore.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class ModelMigration : DbMigration
    {
        public override void Up()
        {
        }

        public override void Down()
        {
        }
    }
}
</code>```

these are the models,Migration Configuration, Startup and DatabaseContext

Movie.cs

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace MovieExampleAppDotNetCore.Models
{
    public class Movie
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int MovieId { get; set; }
        public String Name { get; set; }

        [Column(TypeName = "datetime2")]
        public DateTime? DateCreated { get; set; }
    }
}

</code>```

Customer.cs

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace MovieExampleAppDotNetCore.Models
{
    public class Customer
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CustomerId { get; set; }
        public string Name { get; set; }
        public string LastName { get; set; }
        public bool IsCreated { get; set; }
        public int MaxMovies { get; set; }

        [Column(TypeName = "datetime2")]
        public DateTime Created { get; set; }

        [Column(TypeName = "datetime2")]
        public DateTime? LastEdited { get; set; }

    }
}

</code>```

Configuration.cs

```<code>namespace MovieExampleAppDotNetCore.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<MovieExampleApp.Persistention.DatabaseContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }

        protected override void Seed(MovieExampleApp.Persistention.DatabaseContext context)
        {

        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method
        //  to avoid creating duplicate seed data.
    }
}

}
</code>```

DatabaseContext.cs

```<code>using Microsoft.EntityFrameworkCore;
using MovieExampleAppDotNetCore.Models;
using System.Data.Entity;

namespace MovieExampleApp.Persistention
{
    public class DatabaseContext : System.Data.Entity.DbContext
    {
        public DatabaseContext() : base("main")
        {
            //Database.Initialize(true);
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

        public Microsoft.EntityFrameworkCore.DbSet<Movie> Movies { get; set; }
        public Microsoft.EntityFrameworkCore.DbSet<Customer> Customers { get; set; }
    }
}
</code>```

Startup.cs

```<code>using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using MovieExampleApp.Persistention;
using System.Linq;

namespace MovieExampleAppDotNetCore
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddDbContext<DatabaseContext>(
                        options => options.UseSqlServer(Configuration.GetConnectionString("DatabaseContext")));

            services.AddControllersWithViews().AddNewtonsoftJson();

            services.AddControllersWithViews(options =>
            {
                options.InputFormatters.Insert(0, GetJsonPatchInputFormatter());
            });

        }

        private static NewtonsoftJsonPatchInputFormatter GetJsonPatchInputFormatter()
        {
            var builder = new ServiceCollection()
                .AddLogging()
                .AddMvc()
                .AddNewtonsoftJson()
                .Services.BuildServiceProvider();

            return builder
                .GetRequiredService<IOptions<MvcOptions>>()
                .Value
                .InputFormatters
                .OfType<NewtonsoftJsonPatchInputFormatter>()
                .First();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
</code>```

I hope someone can tell what im doing wrong.

答:
You do not need to use as far as I know [DatabaseGenerated(DatabaseGeneratedOption.Identity)] as you use [Key] - this is enough to set Primary Key on property.

Try this way:

First I would remove empty migration by typing in Package-Manger-Console:

Remove-Migration

I also assumed that you do not have any other migrations where you have actually added these models you want to add now.

then:

ApplicationDbContext Class:

```<code>public class ApplicationDbContext : DbContext
{
            public ApplicationDbContext(DbContextOptions<ApplicationDbContext> context) : base(context)
    {
    }

    public DbSet<Movie> Movies { get; set; }
    public DbSet<Customer> Customers { get; set; }
}
</code>```

I assume you got everything in your startup to update database but just to mention:

Startup:

```<code>    public void ConfigureServices(IServiceCollection services)
    {

     //some code...
            services.AddDbContext<ApplicationDbContext>(
            options => options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
    }
</code>```

And of course update your connection string in appsettings.json to reflect connection name:

```<code>  "ConnectionStrings": {
"DevConnection": "Server=SERVER; Database=DB; Trusted_Connection=True; MultipleActiveResultSets=True;",

 }
</code>```

Then type in Package-Manager-Console: add-migration [Migration Name]

Title: C#: asp.net CORE empty Migration

Body:
I am trying to add a migration from DatabaseContext
but when I add an migration i generates it empty like this. I had been following this tutorial

namespace MovieExampleAppDotNetCore.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class ModelMigration : DbMigration
    {
        public override void Up()
        {
        }

        public override void Down()
        {
        }
    }
}

these are the models,Migration Configuration, Startup and DatabaseContext

Movie.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace MovieExampleAppDotNetCore.Models
{
    public class Movie
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int MovieId { get; set; }
        public String Name { get; set; }

        [Column(TypeName = "datetime2")]
        public DateTime? DateCreated { get; set; }
    }
}

Customer.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace MovieExampleAppDotNetCore.Models
{
    public class Customer
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CustomerId { get; set; }
        public string Name { get; set; }
        public string LastName { get; set; }
        public bool IsCreated { get; set; }
        public int MaxMovies { get; set; }

        [Column(TypeName = "datetime2")]
        public DateTime Created { get; set; }

        [Column(TypeName = "datetime2")]
        public DateTime? LastEdited { get; set; }

    }
}

Configuration.cs

namespace MovieExampleAppDotNetCore.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<MovieExampleApp.Persistention.DatabaseContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }

        protected override void Seed(MovieExampleApp.Persistention.DatabaseContext context)
        {

        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method
        //  to avoid creating duplicate seed data.
    }
}

}

DatabaseContext.cs

using Microsoft.EntityFrameworkCore;
using MovieExampleAppDotNetCore.Models;
using System.Data.Entity;

namespace MovieExampleApp.Persistention
{
    public class DatabaseContext : System.Data.Entity.DbContext
    {
        public DatabaseContext() : base("main")
        {
            //Database.Initialize(true);
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

        public Microsoft.EntityFrameworkCore.DbSet<Movie> Movies { get; set; }
        public Microsoft.EntityFrameworkCore.DbSet<Customer> Customers { get; set; }
    }
}

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using MovieExampleApp.Persistention;
using System.Linq;

namespace MovieExampleAppDotNetCore
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddDbContext<DatabaseContext>(
                        options => options.UseSqlServer(Configuration.GetConnectionString("DatabaseContext")));

            services.AddControllersWithViews().AddNewtonsoftJson();

            services.AddControllersWithViews(options =>
            {
                options.InputFormatters.Insert(0, GetJsonPatchInputFormatter());
            });

        }

        private static NewtonsoftJsonPatchInputFormatter GetJsonPatchInputFormatter()
        {
            var builder = new ServiceCollection()
                .AddLogging()
                .AddMvc()
                .AddNewtonsoftJson()
                .Services.BuildServiceProvider();

            return builder
                .GetRequiredService<IOptions<MvcOptions>>()
                .Value
                .InputFormatters
                .OfType<NewtonsoftJsonPatchInputFormatter>()
                .First();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

I hope someone can tell what im doing wrong.

Body:
You do not need to use as far as I know [DatabaseGenerated(DatabaseGeneratedOption.Identity)] as you use [Key] - this is enough to set Primary Key on property.

Try this way:

First I would remove empty migration by typing in Package-Manger-Console:

Remove-Migration

I also assumed that you do not have any other migrations where you have actually added these models you want to add now.

then:

ApplicationDbContext Class:

public class ApplicationDbContext : DbContext
{
            public ApplicationDbContext(DbContextOptions<ApplicationDbContext> context) : base(context)
    {
    }

    public DbSet<Movie> Movies { get; set; }
    public DbSet<Customer> Customers { get; set; }
}

I assume you got everything in your startup to update database but just to mention:

Startup:

    public void ConfigureServices(IServiceCollection services)
    {

     //some code...
            services.AddDbContext<ApplicationDbContext>(
            options => options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
    }

And of course update your connection string in appsettings.json to reflect connection name:

  "ConnectionStrings": {
"DevConnection": "Server=SERVER; Database=DB; Trusted_Connection=True; MultipleActiveResultSets=True;",

 }

Then type in Package-Manager-Console: add-migration [Migration Name]


问:
R scales::label_format is converting my numeric into a float before converting to character
I have a function that is designed to create labels for a graph. I have four data subsets that all come from the same source. My function works on three out of four subsets but is getting messed up on the fourth. I have a whole number (ie 2914). Scales::label_comma() converts the number 2914 to a character that reads "2914.0".

Here is a break down of the table that doesn't work:

```<code>    > str(df_a)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   9 obs. of  12 variables:
 $ year               : num  2017 2017 2017 2017 2018 ...
 $ inpatient_discharge: num  2914 2662 2566 2513 2672 ...
 $ ed_discharges      : num  23225 24117 24565 23001 24005 ...
 $ outpatient_surg    : num  3193 3313 2813 4255 3391 ...
>
</code>```

And when I use label_comma() on the column "inpatient_discharge" which is numeric I get:

```<code>> scales::label_comma()(df_a$inpatient_discharge)
[1] "2,914.0" "2,662.0" "2,566.0" "2,513.0" "2,672.0" "2,478.0" "2,404.0" "2,398.0" "2,504.0"
</code>```

When I use label_comma() on a different column, I get the expected result

```<code>> scales::label_comma()(df_a$ed_discharges)
[1] "23,225" "24,117" "24,565" "23,001" "24,005" "23,416" "23,983" "22,648" "23,390"
</code>```

Furthermore, when I use label_comma() on a different dataframe that has a subset from the same source, I get the expected result

```<code>> scales::label_comma()(df_b$inpatient_discharge)
[1] "7,457" "7,066" "6,918" "6,912" "7,265" "6,918" "6,748" "6,733" "7,064"
</code>```

Is this a bug? I can't find anything on why it would act this way. It even works on those numbers when they are outside of the dataframe

```<code>> test <- as.numeric(2914)
> label_comma()(test)
[1] "2,914"
</code>```

I'm completely lost on this one

答:
Quick fix

You can achieve this by passing the accuracy argument to label_comma.

accuracy = 1 will ensure that no numbers past the decimal point are shown.

Attempt at explanation

There must be something in your series of numbers that is convincing label_comma that it needs to use tenths to distinguish some of the numbers. See the documentation:

accuracy: ... If NULL, the default, uses a heuristic that should ensure breaks have the minimum number of digits needed to show the difference between adjacent values.

This explains why your test example doesn't respond in the same way as your original df: it doesn't trigger the distinguishing heuristic.

Examples of how to do it

Here's a reprex which gives a variety of ways of transforming your series of numbers into comma-formatted strings without the post-decimal point numbers. Obviously you don't need all of them but I was just testing what happens in different situations.

I have only used your first five numbers as visible in your question. In future please try to make reproducible examples - I usually find that this process leads me to the solution to my problem before I even have to ask!

You can insert your fuller number series into the example below, and see what happens.

The first few examples below don't use the accuracy argument; the last couple of examples do. But in all cases there are no post-decimal point numbers.

The final example replaces your original first column with formatted numbers (as strings) - this is how I would prefer to do this operation but you can choose what works for you.

library(scales)
library(tibble)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union

df <- tibble(inpatient_discharge = c(2914, 2662, 2566, 2513, 2672))
str(df)
#> Classes 'tbl_df', 'tbl' and 'data.frame':    5 obs. of  1 variable:
#>  $ inpatient_discharge: num  2914 2662 2566 2513 2672

# add column using label_comma
df["discharge_label_comma"] <- scales::label_comma()(df[[1]])
str(df)
#> Classes 'tbl_df', 'tbl' and 'data.frame':    5 obs. of  2 variables:
#>  $ inpatient_discharge  : num  2914 2662 2566 2513 2672
#>  $ discharge_label_comma: chr  "2,914" "2,662" "2,566" "2,513" ...

# add column using comma alias
df["discharge_comma"] <- scales::comma(df[[1]])
str(df)
#> Classes 'tbl_df', 'tbl' and 'data.frame':    5 obs. of  3 variables:
#>  $ inpatient_discharge  : num  2914 2662 2566 2513 2672
#>  $ discharge_label_comma: chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_comma      : chr  "2,914" "2,662" "2,566" "2,513" ...

# add column using dplyr::mutate
df <- df %>% dplyr::mutate(discharge_comma_mutate = scales::comma(inpatient_discharge))
str(df)
#> Classes 'tbl_df', 'tbl' and 'data.frame':    5 obs. of  4 variables:
#>  $ inpatient_discharge   : num  2914 2662 2566 2513 2672
#>  $ discharge_label_comma : chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_comma       : chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_comma_mutate: chr  "2,914" "2,662" "2,566" "2,513" ...

# add column using accuracy argument
df["discharge_comma_acc"] <- scales::comma(df[[1]], accuracy = 1)
str(df)
#> Classes 'tbl_df', 'tbl' and 'data.frame':    5 obs. of  5 variables:
#>  $ inpatient_discharge   : num  2914 2662 2566 2513 2672
#>  $ discharge_label_comma : chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_comma       : chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_comma_mutate: chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_comma_acc   : chr  "2,914" "2,662" "2,566" "2,513" ...

# convert initial first column using dplyr::mutate_at and accuracy argument
# (alternatively use dplyr::transmute or mutate_all/mutate_if)
df <- df %>% mutate_at(vars(inpatient_discharge), ~ scales::comma(., accuracy = 1))
str(df)
#> Classes 'tbl_df', 'tbl' and 'data.frame':    5 obs. of  5 variables:
#>  $ inpatient_discharge   : chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_label_comma : chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_comma       : chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_comma_mutate: chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_comma_acc   : chr  "2,914" "2,662" "2,566" "2,513" ...
```

Created on 2020-02-20 by the reprex package (v0.3.0)

Body:
I have a function that is designed to create labels for a graph. I have four data subsets that all come from the same source. My function works on three out of four subsets but is getting messed up on the fourth. I have a whole number (ie 2914). Scales::label_comma() converts the number 2914 to a character that reads "2914.0".

Here is a break down of the table that doesn't work:

    > str(df_a)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   9 obs. of  12 variables:
 $ year               : num  2017 2017 2017 2017 2018 ...
 $ inpatient_discharge: num  2914 2662 2566 2513 2672 ...
 $ ed_discharges      : num  23225 24117 24565 23001 24005 ...
 $ outpatient_surg    : num  3193 3313 2813 4255 3391 ...
>

And when I use label_comma() on the column "inpatient_discharge" which is numeric I get:

> scales::label_comma()(df_a$inpatient_discharge)
[1] "2,914.0" "2,662.0" "2,566.0" "2,513.0" "2,672.0" "2,478.0" "2,404.0" "2,398.0" "2,504.0"

When I use label_comma() on a different column, I get the expected result

> scales::label_comma()(df_a$ed_discharges)
[1] "23,225" "24,117" "24,565" "23,001" "24,005" "23,416" "23,983" "22,648" "23,390"

Furthermore, when I use label_comma() on a different dataframe that has a subset from the same source, I get the expected result

> scales::label_comma()(df_b$inpatient_discharge)
[1] "7,457" "7,066" "6,918" "6,912" "7,265" "6,918" "6,748" "6,733" "7,064"

Is this a bug? I can't find anything on why it would act this way. It even works on those numbers when they are outside of the dataframe

> test <- as.numeric(2914)
> label_comma()(test)
[1] "2,914"

I'm completely lost on this one

Body:
Quick fix

You can achieve this by passing the accuracy argument to label_comma.

accuracy = 1 will ensure that no numbers past the decimal point are shown.

Attempt at explanation

There must be something in your series of numbers that is convincing label_comma that it needs to use tenths to distinguish some of the numbers. See the documentation:

accuracy: ... If NULL, the default, uses a heuristic that should ensure breaks have the minimum number of digits needed to show the difference between adjacent values.

This explains why your test example doesn't respond in the same way as your original df: it doesn't trigger the distinguishing heuristic.

Examples of how to do it

Here's a reprex which gives a variety of ways of transforming your series of numbers into comma-formatted strings without the post-decimal point numbers. Obviously you don't need all of them but I was just testing what happens in different situations.

I have only used your first five numbers as visible in your question. In future please try to make reproducible examples - I usually find that this process leads me to the solution to my problem before I even have to ask!

You can insert your fuller number series into the example below, and see what happens.

The first few examples below don't use the accuracy argument; the last couple of examples do. But in all cases there are no post-decimal point numbers.

The final example replaces your original first column with formatted numbers (as strings) - this is how I would prefer to do this operation but you can choose what works for you.

library(scales)
library(tibble)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union

df <- tibble(inpatient_discharge = c(2914, 2662, 2566, 2513, 2672))
str(df)
#> Classes 'tbl_df', 'tbl' and 'data.frame':    5 obs. of  1 variable:
#>  $ inpatient_discharge: num  2914 2662 2566 2513 2672

# add column using label_comma
df["discharge_label_comma"] <- scales::label_comma()(df[[1]])
str(df)
#> Classes 'tbl_df', 'tbl' and 'data.frame':    5 obs. of  2 variables:
#>  $ inpatient_discharge  : num  2914 2662 2566 2513 2672
#>  $ discharge_label_comma: chr  "2,914" "2,662" "2,566" "2,513" ...

# add column using comma alias
df["discharge_comma"] <- scales::comma(df[[1]])
str(df)
#> Classes 'tbl_df', 'tbl' and 'data.frame':    5 obs. of  3 variables:
#>  $ inpatient_discharge  : num  2914 2662 2566 2513 2672
#>  $ discharge_label_comma: chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_comma      : chr  "2,914" "2,662" "2,566" "2,513" ...

# add column using dplyr::mutate
df <- df %>% dplyr::mutate(discharge_comma_mutate = scales::comma(inpatient_discharge))
str(df)
#> Classes 'tbl_df', 'tbl' and 'data.frame':    5 obs. of  4 variables:
#>  $ inpatient_discharge   : num  2914 2662 2566 2513 2672
#>  $ discharge_label_comma : chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_comma       : chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_comma_mutate: chr  "2,914" "2,662" "2,566" "2,513" ...

# add column using accuracy argument
df["discharge_comma_acc"] <- scales::comma(df[[1]], accuracy = 1)
str(df)
#> Classes 'tbl_df', 'tbl' and 'data.frame':    5 obs. of  5 variables:
#>  $ inpatient_discharge   : num  2914 2662 2566 2513 2672
#>  $ discharge_label_comma : chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_comma       : chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_comma_mutate: chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_comma_acc   : chr  "2,914" "2,662" "2,566" "2,513" ...

# convert initial first column using dplyr::mutate_at and accuracy argument
# (alternatively use dplyr::transmute or mutate_all/mutate_if)
df <- df %>% mutate_at(vars(inpatient_discharge), ~ scales::comma(., accuracy = 1))
str(df)
#> Classes 'tbl_df', 'tbl' and 'data.frame':    5 obs. of  5 variables:
#>  $ inpatient_discharge   : chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_label_comma : chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_comma       : chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_comma_mutate: chr  "2,914" "2,662" "2,566" "2,513" ...
#>  $ discharge_comma_acc   : chr  "2,914" "2,662" "2,566" "2,513" ...

Created on 2020-02-20 by the reprex package (v0.3.0)


问:
array synchronization and multithreading
I have a multithreaded application where I'm doing the following:

Thread1: Reads data from a camera and stores it in ArrayFire array (CUDA backend).

Thread2: Use ArrayFire to calculate certain results from the camera's data.

Thread3: Send the results over the network. Calls host function on the array.

The problem that I have is that when I do the last part of sending results over the network I need to copy the data from GPU to CPU using the host function. This causes jitter (varying delay).

When looking at the source code of ArrayFire I notice that host uses CUDA stream synchronization method which (if I understood correctly) forces the only CUDA stream where all the threads are running to finish all the tasks that its doing.

This causes the Thread3 to wait for the Thread2 to finish its ArrayFire calculation (if any occuring at that time) and it causes random jitter in Thread3 where I need to call host in order to copy the array to CPU memory.

Are my assumptions correct, and if so, any suggestions on what to do?

答:
I’ve tried your suggestion. It does not work reliably and there are memory access artifacts.

First the code:

input thread:

```<code>cudaStream_t m_stream;
cudaEvent_t m_streamEvent;

cudaStreamCreateWithFlags(&m_stream, cudaStreamNonBlocking);
cudaEventCreate(&m_streamEvent);

int bytesPerPixel = 2;
int bytes = width * height * bytesPerPixel;

while(!stop)
{
    // Read from file to m_imageData

    // Next buufer is pinned memory allocated with af::pinned
    nextBuffer = getWriteBuffer();

    cudaMemcpyAsync(nextBuffer, m_imageData.data() + m_imageOffset, bytes, cudaMemcpyHostToDevice, m_stream);
    cudaEventRecord(m_streamEvent, m_stream);
    cudaStreamWaitEvent(m_stream, m_streamEvent, 0);

    m_imageOffset =  (m_imageOffset + bytes) % m_imageData.size();
}
</code>```

Processor thread:

```<code>tile x frames (batch) from ring buffer and push the result to a queue
</code>```

Output thread:

```<code>cudaStream_t m_stream;
cudaEvent_t m_streamEvent;

cudaStreamCreateWithFlags(&m_stream, cudaStreamNonBlocking);
cudaEventCreate(&m_streamEvent);

int rgbaBufferSize = width * 4;
auto m_rgbaPinnedBuffer = af::pinned<quint8>(rgbaBufferSize);

while(!stop)
{
    rgba = m_queue.dequeue();
    rgbaAfBuffer = rgba.device<quint8>();
    cudaMemcpyAsync(m_rgbaPinnedBuffer, rgbaAfBuffer, rgbaBufferSize, cudaMemcpyDeviceToHost, m_stream);
    cudaEventRecord(m_streamEvent, m_stream);
    cudaStreamWaitEvent(m_stream, m_streamEvent, 0);
    rgba.unlock();

    // Do something with m_rgbaPinnedBuffer
}
</code>```

When launched with NVidia's profiler, I can see the AF stream, I can see the output thread stream with memcpy outs. I cannot see the input thread stream with memcpy in. I don't know why, although the stream and event creation are reported successful.

When using af::host, there's is no memory access issue, and I can see the cudaMemcpyAsync happening in the default stream. The ouput RGBA looks like this

When using cudaMemcpyAsync I can see the cudaMemcpyAsync in the stream timeline but sometimes memory is repeated. It happens more when I increase the batch size or move other application windows fast stealing GPU time. See the output RGBA

Have you bumped into this kind of issue?

Body:
I’ve tried your suggestion. It does not work reliably and there are memory access artifacts.

First the code:

input thread:

cudaStream_t m_stream;
cudaEvent_t m_streamEvent;

cudaStreamCreateWithFlags(&m_stream, cudaStreamNonBlocking);
cudaEventCreate(&m_streamEvent);

int bytesPerPixel = 2;
int bytes = width * height * bytesPerPixel;

while(!stop)
{
    // Read from file to m_imageData

    // Next buufer is pinned memory allocated with af::pinned
    nextBuffer = getWriteBuffer();

    cudaMemcpyAsync(nextBuffer, m_imageData.data() + m_imageOffset, bytes, cudaMemcpyHostToDevice, m_stream);
    cudaEventRecord(m_streamEvent, m_stream);
    cudaStreamWaitEvent(m_stream, m_streamEvent, 0);

    m_imageOffset =  (m_imageOffset + bytes) % m_imageData.size();
}

Processor thread:

tile x frames (batch) from ring buffer and push the result to a queue

Output thread:

cudaStream_t m_stream;
cudaEvent_t m_streamEvent;

cudaStreamCreateWithFlags(&m_stream, cudaStreamNonBlocking);
cudaEventCreate(&m_streamEvent);

int rgbaBufferSize = width * 4;
auto m_rgbaPinnedBuffer = af::pinned<quint8>(rgbaBufferSize);

while(!stop)
{
    rgba = m_queue.dequeue();
    rgbaAfBuffer = rgba.device<quint8>();
    cudaMemcpyAsync(m_rgbaPinnedBuffer, rgbaAfBuffer, rgbaBufferSize, cudaMemcpyDeviceToHost, m_stream);
    cudaEventRecord(m_streamEvent, m_stream);
    cudaStreamWaitEvent(m_stream, m_streamEvent, 0);
    rgba.unlock();

    // Do something with m_rgbaPinnedBuffer
}

When launched with NVidia's profiler, I can see the AF stream, I can see the output thread stream with memcpy outs. I cannot see the input thread stream with memcpy in. I don't know why, although the stream and event creation are reported successful.

When using af::host, there's is no memory access issue, and I can see the cudaMemcpyAsync happening in the default stream. The ouput RGBA looks like this

When using cudaMemcpyAsync I can see the cudaMemcpyAsync in the stream timeline but sometimes memory is repeated. It happens more when I increase the batch size or move other application windows fast stealing GPU time. See the output RGBA

Have you bumped into this kind of issue?


问:
Scaling SVG dynamically
I am not sure how i can work with SVG backgrounds that scale depending on the screen size (full-width) and depending on how much content we have within the
-tag. I would like to be able to scale to SVG in height, but not in width in that case.

I have been trying to make this work for quite some time now but I don't know how to do it. Could someone help me?

html

```<code><html>
<head>

</head>
<body>
<ul>
  <li>test 1</li>
  <li>test 2</li>
  <li>test 3</li>
</ul>
</body>
</html>
</code>```

css

```<code>ul li {
 height: 6em;
}

li:nth-child(odd) {
    background: url(http://leanimpactaward.ch/img/GRAFIK_Accordeon_V1.svg);
    background-size: 100%;
    background-repeat: no-repeat;
}

li:nth-child(even) {
    background: url(http://leanimpactaward.ch/img/GRAFIK_Accordeon_V2.svg);
    background-size: 100%;
    background-repeat: no-repeat;
}
</code>```

https://jsfiddle.net/3g7n2v5e/3/

答:
You're trying to stretch an svg image, which isn't possible.

Editing your svg file and add preserveAspectRatio="none" to your svg attributes might do the trick. You might also need to remove width and height.

Title: Scaling SVG dynamically

Body:
I am not sure how i can work with SVG backgrounds that scale depending on the screen size (full-width) and depending on how much content we have within the
-tag. I would like to be able to scale to SVG in height, but not in width in that case.

I have been trying to make this work for quite some time now but I don't know how to do it. Could someone help me?

html

test 1

test 2

test 3

css

ul li {
 height: 6em;
}

li:nth-child(odd) {
    background: url(http://leanimpactaward.ch/img/GRAFIK_Accordeon_V1.svg);
    background-size: 100%;
    background-repeat: no-repeat;
}

li:nth-child(even) {
    background: url(http://leanimpactaward.ch/img/GRAFIK_Accordeon_V2.svg);
    background-size: 100%;
    background-repeat: no-repeat;
}

https://jsfiddle.net/3g7n2v5e/3/


问:
How to make a reverse Foreign Key in multiple tables with annotate
I have 3 models connected to one by a Foreign Key:

```<code>class A(models.Model):
    name = models.CharField(max_length=20)

class B(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)
    amount_b = models.FloatField()

class C(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)
    amount_c = models.FloatField()

class D(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)
    amount_d = models.FloatField()
</code>```

And I want to make a JOIN query based on the foreign keys using Django ORM to get the sum of each amount.

In SQL I would make something like:

```<code>SELECT
  a.name,
  b_sum,
  c_sum,
  d_sum
FROM A AS a
  LEFT JOIN (SELECT b.a, sum(amount_b) as b_sum
              from B as b
              group by b.a) as AB AB.a = a.id
  LEFT JOIN (SELECT c.a, sum(amount_c) as c_sum
              from C as c
              group by a) AS AC ON AC.a = a.id
  LEFT JOIN (SELECT d.a, sum(amount_d) as d_sum
              from D as d
              group by a) AS AD ON AD.a = a.id
WHERE a.name LIKE 'init%'
</code>```

But I didn't find something like that on django ORM.

答:
You can do this

```<code>q = A.objects.annotate(
    b_sum=Subquery(
        B.objects.filter(a=OuterRef('pk'))
                 .values('a')
                 .annotate(b_sum=Sum('amount_b'))
                 .values('b_sum')
    ),
    c_sum=Subquery(
        C.objects.filter(a=OuterRef('pk'))
                 .values('a')
                 .annotate(c_sum=Sum('amount_c'))
                 .values('c_sum')
    ),
    d_sum=Subquery(
        D.objects.filter(a=OuterRef('pk'))
                 .values('a')
                 .annotate(d_sum=Sum('amount_d'))
                 .values('d_sum')
    )
)
</code>```

It seems pretty complex query and also does not translate to same sql you mentioned in question, but it does the job.

Here is sql it generates.

```<code>SELECT "A"."id",
       "A"."name",
       (SELECT SUM(U0."amount_b") AS "b_sum" FROM "B" U0 WHERE U0."a_id" = ("A"."id") GROUP BY U0."a_id") AS "b_sum",
       (SELECT SUM(U0."amount_c") AS "c_sum" FROM "C" U0 WHERE U0."a_id" = ("A"."id") GROUP BY U0."a_id") AS "c_sum",
       (SELECT SUM(U0."amount_d") AS "d_sum" FROM "D" U0 WHERE U0."a_id" = ("A"."id") GROUP BY U0."a_id") AS "d_sum"
FROM "A"
</code>```

Body:
I have 3 models connected to one by a Foreign Key:

class A(models.Model):
    name = models.CharField(max_length=20)

class B(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)
    amount_b = models.FloatField()

class C(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)
    amount_c = models.FloatField()

class D(models.Model):
    a = models.ForeignKey(A, on_delete=models.CASCADE)
    amount_d = models.FloatField()

And I want to make a JOIN query based on the foreign keys using Django ORM to get the sum of each amount.

In SQL I would make something like:

SELECT
  a.name,
  b_sum,
  c_sum,
  d_sum
FROM A AS a
  LEFT JOIN (SELECT b.a, sum(amount_b) as b_sum
              from B as b
              group by b.a) as AB AB.a = a.id
  LEFT JOIN (SELECT c.a, sum(amount_c) as c_sum
              from C as c
              group by a) AS AC ON AC.a = a.id
  LEFT JOIN (SELECT d.a, sum(amount_d) as d_sum
              from D as d
              group by a) AS AD ON AD.a = a.id
WHERE a.name LIKE 'init%'

But I didn't find something like that on django ORM.

Body:
You can do this

q = A.objects.annotate(
    b_sum=Subquery(
        B.objects.filter(a=OuterRef('pk'))
                 .values('a')
                 .annotate(b_sum=Sum('amount_b'))
                 .values('b_sum')
    ),
    c_sum=Subquery(
        C.objects.filter(a=OuterRef('pk'))
                 .values('a')
                 .annotate(c_sum=Sum('amount_c'))
                 .values('c_sum')
    ),
    d_sum=Subquery(
        D.objects.filter(a=OuterRef('pk'))
                 .values('a')
                 .annotate(d_sum=Sum('amount_d'))
                 .values('d_sum')
    )
)

It seems pretty complex query and also does not translate to same sql you mentioned in question, but it does the job.

Here is sql it generates.

SELECT "A"."id",
       "A"."name",
       (SELECT SUM(U0."amount_b") AS "b_sum" FROM "B" U0 WHERE U0."a_id" = ("A"."id") GROUP BY U0."a_id") AS "b_sum",
       (SELECT SUM(U0."amount_c") AS "c_sum" FROM "C" U0 WHERE U0."a_id" = ("A"."id") GROUP BY U0."a_id") AS "c_sum",
       (SELECT SUM(U0."amount_d") AS "d_sum" FROM "D" U0 WHERE U0."a_id" = ("A"."id") GROUP BY U0."a_id") AS "d_sum"
FROM "A"


问:
Is there a list of JSON parse error codes?
I'm trying to provide a good experience to users that are using JSON and the parser is on the backend (Ruby).

Most of the time, when you get a badly formatted JSON payload the error is of the format XXX unexpected token at '<entire payload here>'. That's not very user-friendly nor practical.

My question is: Is there a list of the XXX error codes that could help create better error messages that could be understood by beginners and not-really-tech-people?

Thanks!

答:
You can find a list in the documentation for the module.

Think this covers it:

```<code>JSON::JSONError
JSON::GeneratorError
JSON::GenericObject
# The base exception for JSON errors.
JSON::MissingUnicodeSupport
# This exception is raised if the required unicode support is missing on the system. Usually this means that the iconv library is not installed.
JSON::NestingError
# This exception is raised if the nesting of parsed data structures is too deep.
JSON::ParserError
# This exception is raised if a parser error occurs.
JSON::UnparserError
# This exception is raised if a generator or unparser error occurs.
</code>```

JSON::JSONError is the parent class, so you can rescue from that and provide per-error-class messages as needed.

I feel it's worth noting that in my experience the vast majority of errors relating to JSON are of the class JSON::ParserError. Another common issue worth considering is getting ArgumentError if nil is passed as an argument.

As an example of how this could be used, you could work with something like the following:

```<code>begin
  JSON.parse(your_json)
rescue JSON::JSONError, ArgumentError => e
  { error: I18n.t(e.to_s) } # <- or whatever you want to do per error
end
</code>```

Hope that helps - let me know how you get on :)

Body:
You can find a list in the documentation for the module.

Think this covers it:

JSON::JSONError
JSON::GeneratorError
JSON::GenericObject
# The base exception for JSON errors.
JSON::MissingUnicodeSupport
# This exception is raised if the required unicode support is missing on the system. Usually this means that the iconv library is not installed.
JSON::NestingError
# This exception is raised if the nesting of parsed data structures is too deep.
JSON::ParserError
# This exception is raised if a parser error occurs.
JSON::UnparserError
# This exception is raised if a generator or unparser error occurs.

JSON::JSONError is the parent class, so you can rescue from that and provide per-error-class messages as needed.

I feel it's worth noting that in my experience the vast majority of errors relating to JSON are of the class JSON::ParserError. Another common issue worth considering is getting ArgumentError if nil is passed as an argument.

As an example of how this could be used, you could work with something like the following:

begin
  JSON.parse(your_json)
rescue JSON::JSONError, ArgumentError => e
  { error: I18n.t(e.to_s) } # <- or whatever you want to do per error
end

Hope that helps - let me know how you get on :)


问:
While building web crawler using scrapy , twisted failed to establish internet connection
I am trying to build a web crawler using scrapy . Code of my crawler is as below:

```<code>import scrapy

class SpiSpider(scrapy.Spider):

    name = 'spi'
    start_urls = ['http://www.quotes.toscrape.com/']

    def parse(self, response):
        titles = response.css('title:text').extract()
        yield('at:',titles)
</code>```

when I tried to run it , following errors occured :

```<code>2020-02-20 16:10:30 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
2020-02-20 16:10:32 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying <GET http://www.quotes.toscrape.com/robots.txt> (failed 1 times): [<twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed cleanly.>]
2020-02-20 16:10:32 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying <GET http://www.quotes.toscrape.com/robots.txt> (failed 2 times): [<twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed cleanly.>]
2020-02-20 16:10:33 [scrapy.downloadermiddlewares.retry] DEBUG: Gave up retrying <GET http://www.quotes.toscrape.com/robots.txt> (failed 3 times): [<twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed cleanly.>]
2020-02-20 16:10:33 [scrapy.downloadermiddlewares.robotstxt] ERROR: Error downloading <GET http://www.quotes.toscrape.com/robots.txt>: [<twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed cleanly.>]
Traceback (most recent call last):
  File "c:\users\adi\appdata\local\programs\python\python37-32\lib\site-packages\scrapy\core\downloader\middleware.py", line 44, in process_request
    defer.returnValue((yield download_func(request=request, spider=spider)))
twisted.web._newclient.ResponseNeverReceived: [<twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed
cleanly.>]
2020-02-20 16:10:34 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying <GET http://www.quotes.toscrape.com/> (failed 1 times): [<twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed cleanly.>]
2020-02-20 16:10:35 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying <GET http://www.quotes.toscrape.com/> (failed 2 times): [<twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed cleanly.>]
2020-02-20 16:10:36 [scrapy.downloadermiddlewares.retry] DEBUG: Gave up retrying <GET http://www.quotes.toscrape.com/> (failed 3 times): [<twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed cleanly.>]
2020-02-20 16:10:36 [scrapy.core.scraper] ERROR: Error downloading <GET http://www.quotes.toscrape.com/>
Traceback (most recent call last):
  File "c:\users\adi\appdata\local\programs\python\python37-32\lib\site-packages\scrapy\core\downloader\middleware.py", line 44, in process_request
    defer.returnValue((yield download_func(request=request, spider=spider)))
twisted.web._newclient.ResponseNeverReceived: [<twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed
cleanly.>]
</code>```

I have tried changing my USER AGENT and try to apply proxy but no it didn't solve my problem.

答:
Ok, so the problem it is pretty simple and the solution is even easier.

http://www.quotes.toscrape.com/ does not exists, the url you want is http://quotes.toscrape.com/

Now you will have other problems like the pseudoclass :text does not exists, but that is just changing the code to fit the html

Body:
I am trying to build a web crawler using scrapy . Code of my crawler is as below:

import scrapy

class SpiSpider(scrapy.Spider):

    name = 'spi'
    start_urls = ['http://www.quotes.toscrape.com/']

    def parse(self, response):
        titles = response.css('title:text').extract()
        yield('at:',titles)

when I tried to run it , following errors occured :

2020-02-20 16:10:30 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
2020-02-20 16:10:32 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying <GET http://www.quotes.toscrape.com/robots.txt> (failed 1 times): [<twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed cleanly.>]
2020-02-20 16:10:32 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying <GET http://www.quotes.toscrape.com/robots.txt> (failed 2 times): [<twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed cleanly.>]
2020-02-20 16:10:33 [scrapy.downloadermiddlewares.retry] DEBUG: Gave up retrying <GET http://www.quotes.toscrape.com/robots.txt> (failed 3 times): [<twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed cleanly.>]
2020-02-20 16:10:33 [scrapy.downloadermiddlewares.robotstxt] ERROR: Error downloading <GET http://www.quotes.toscrape.com/robots.txt>: [<twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed cleanly.>]
Traceback (most recent call last):
  File "c:\users\adi\appdata\local\programs\python\python37-32\lib\site-packages\scrapy\core\downloader\middleware.py", line 44, in process_request
    defer.returnValue((yield download_func(request=request, spider=spider)))
twisted.web._newclient.ResponseNeverReceived: [<twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed
cleanly.>]
2020-02-20 16:10:34 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying <GET http://www.quotes.toscrape.com/> (failed 1 times): [<twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed cleanly.>]
2020-02-20 16:10:35 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying <GET http://www.quotes.toscrape.com/> (failed 2 times): [<twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed cleanly.>]
2020-02-20 16:10:36 [scrapy.downloadermiddlewares.retry] DEBUG: Gave up retrying <GET http://www.quotes.toscrape.com/> (failed 3 times): [<twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed cleanly.>]
2020-02-20 16:10:36 [scrapy.core.scraper] ERROR: Error downloading <GET http://www.quotes.toscrape.com/>
Traceback (most recent call last):
  File "c:\users\adi\appdata\local\programs\python\python37-32\lib\site-packages\scrapy\core\downloader\middleware.py", line 44, in process_request
    defer.returnValue((yield download_func(request=request, spider=spider)))
twisted.web._newclient.ResponseNeverReceived: [<twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed
cleanly.>]

I have tried changing my USER AGENT and try to apply proxy but no it didn't solve my problem.


问:
I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular
I'm using Angular 4 HttpClient to send requests to external service. It is a very standard setup:

```<code>this.httpClient.get(url).subscribe(response => {
  //do something with response
}, err => {
  console.log(err.message);
}, () => {
  console.log('completed');
}
</code>```

The problem is, when the request fails I see a generic
Http failure response for (unknown url): 0 Unknown Error message in console. Meanwhile, when I inspect the failed request in chrome I can see the response status is 422, and in the "preview" tab I see the actual message desribing failure cause.

How do I access the actual response message I can see in chrome dev tools?

Here's a screenshot demonstrating the problem:

答:
If this is a node service, try the steps outlined here

Basically, it's a Cross-Origin Resource Sharing (CORS) error.  More information about such errors here.

Once I updated my node service with the following lines it worked:

```<code>let express = require("express");
let app = express();

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });
</code>```

Body:
I'm using Angular 4 HttpClient to send requests to external service. It is a very standard setup:

this.httpClient.get(url).subscribe(response => {
  //do something with response
}, err => {
  console.log(err.message);
}, () => {
  console.log('completed');
}

The problem is, when the request fails I see a generic
Http failure response for (unknown url): 0 Unknown Error message in console. Meanwhile, when I inspect the failed request in chrome I can see the response status is 422, and in the "preview" tab I see the actual message desribing failure cause.

How do I access the actual response message I can see in chrome dev tools?

Here's a screenshot demonstrating the problem:

Body:
If this is a node service, try the steps outlined here

Basically, it's a Cross-Origin Resource Sharing (CORS) error.  More information about such errors here.

Once I updated my node service with the following lines it worked:

let express = require("express");
let app = express();

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });


问:
Problems with setting up Android Studio with Flutter on Mac
I made my project on Windows computer, now I'm trying to export to ios on friend's Mac. I've been following this tutorial from part 1 all the way to part 5. How to Install and Setup Flutter for App Development on Mac - Part 1. In other words, Xcode is installed, Android Studio with Flutter and dart plugin installed as well. Android Studio recognizes both simulator and plugged iPhone. When I open the project in Android Studio it looks like this:

Note: Both flutter folder and the project folder are located in "exportalex"

答:
Please try to use terminal and hit this: flutter pub get

You need to load all the dependency before run app.
If still you are facing same issue, please run: flutter doctor

Then share screenshot of result.


问:
.htaccess redirect domains containing dots
I'm using some .htaccess code I found on StackOverflow to redirect non-www domains to their www counterparts:

```<code><IfModule mod_rewrite.c>
    RewriteEngine on

    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
    RewriteCond %{HTTP_HOST} (.+)$ [NC]
    RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.+)$ index.php/$1
</IfModule>
</code>```

The problem is that this also works for domains on our local development server, and redirects http://test/ to http://www.test/. This is not useful, as the domain www.test does not exist on our development server. This means that the .htaccess file used for the site in development needs to be modified when the site goes live.

Is there a simple way to add a line to check that the domain name already has at least one dot? If it contains one dot, continue to add the www.. If it doesn't, stop.

答:
You can add another RewriteCond before your RewriteRule to exclude your testserver:

```<code>RewriteCond %{HTTP_HOST} !^test$
</code>```

I think that an explicit exclusion is better than this dot-count thing.

Edit: Here is the dot-based version:

```<code>RewriteCond %{HTTP_HOST} !\.
</code>```

Body:
I'm using some .htaccess code I found on StackOverflow to redirect non-www domains to their www counterparts:

<IfModule mod_rewrite.c>
    RewriteEngine on

    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
    RewriteCond %{HTTP_HOST} (.+)$ [NC]
    RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.+)$ index.php/$1
</IfModule>

The problem is that this also works for domains on our local development server, and redirects http://test/ to http://www.test/. This is not useful, as the domain www.test does not exist on our development server. This means that the .htaccess file used for the site in development needs to be modified when the site goes live.

Is there a simple way to add a line to check that the domain name already has at least one dot? If it contains one dot, continue to add the www.. If it doesn't, stop.

Body:
You can add another RewriteCond before your RewriteRule to exclude your testserver:

RewriteCond %{HTTP_HOST} !^test$

I think that an explicit exclusion is better than this dot-count thing.

Edit: Here is the dot-based version:

RewriteCond %{HTTP_HOST} !\.


问:
FutureBuilder load API data only once
I've called post type api to load data asynchronously on ListView using FutureBuilder but it called only once, I want to display infinite data loading on my ListView.

Is their I missing to add some properties of FutureBuilder or ListView.

Can anyone help me solved this issue, I'm new to flutter.

I'm using stateful widget to achieve this functionality.

Please refer below code,

```<code>import 'package:flutter/material.dart';
import 'package:testlistviewlazyload/Utils.dart';
import 'package:testlistviewlazyload/ServiceManager.dart';
import 'package:testlistviewlazyload/Constant.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';

class ClassHome extends StatefulWidget {
  @override
  stateClassHome createState() => stateClassHome();
}

class stateClassHome extends State<ClassHome> {

  bool isLoading = false;

  List<dynamic> arrayFoodList = List<dynamic>();

  @override
  void initState() {
    super.initState();
  }

  Future<List<dynamic>> funcLoadMore() async{

      var dicArguments = {'restaurant_id': '3',
        'menu_id': '0',
        'offset': '0'
      };

     final dictResponse = await ServiceManager().callWebservice(
          enumMethodType.POST, ConstantApi.keyRestaurantMenuFoodList,
          dicArguments, {
        'Authorization':
        await Utils().funcGetSession(ConstantSession.keyAuthToken)
      }, 'tagRestaurantMenuFoodList');

      if (dictResponse['error'] == false) {
        if (dictResponse['mainResponse']['error'] == false) {

          return dictResponse['mainResponse']['data']['food_items']
          as List<dynamic>;

        } else {

          Utils()
              .funcDisplayAlertView(
              '', "${dictResponse['message']}", context);

        }
      } else {
        Utils().funcDisplayAlertView(
            '', "${dictResponse['message']}", context);
      }

  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
        appBar: AppBar(title: Text('hello')),
        body: Container(
          color: Colors.pink[50],

          child: Column(

            children: <Widget>[

              Expanded(

                child: FutureBuilder<List<dynamic>>(
                     future: funcLoadMore(), // a previously-obtained Future<String> or null
                   builder: (BuildContext context, AsyncSnapshot<List<dynamic>> snapshot) {

                     List<dynamic> arrayTest = snapshot.data ?? [];

                      return Scrollbar(

                          child: ListView.builder(

                            itemCount: arrayTest.length,

                            itemBuilder: (BuildContext context, int index) {
                              return ListTile(
                                title: Text(arrayTest[index]['name']),
                              );
                            },

                          )
                      );
                     },
                ),

              ),

              Container(
                height: isLoading ? 50.0 : 0,
                color: Colors.white,
                child: Center(
                  child: new CircularProgressIndicator(),
                ),
              ),

            ],

          ),

        )

    );
  }
}
</code>```

答:
You can use a Stream instead of Future. This is an generic example, with a cache and a scrollController which fetches the next items when user is at the bottom page :

```<code>class _PageState extends State<Page> {
  int _count = 10;
  int _limit = 0;

  bool isLoading = false;

  List<Item> _cachedItems = List.from([]);

  StreamController<List<Item>> _streamController =
      StreamController<List<Item>>();
  StreamSink<List<Item>> get itemsSink => _streamController.sink;
  Stream<List<Item>> get itemsStream => _streamController.stream;

  ScrollController _scrollController = ScrollController();

  Future<void> _addItems() async {
    final params = {'count': '$_count', 'limit': '$_limit'};
    try {
      isLoading = true;
      // Fetch newItems with http
      isLoading = false;
      _cachedItems.addAll(newItems);
      itemsSink.add(_cachedItems);
      _limit += 10;
    } catch (e) {
      itemsSink.addError(e);
    }
  }

  _scrollListener() {
    if (_scrollController.offset >=
            _scrollController.position.maxScrollExtent &&
        !_scrollController.position.outOfRange &&
        !isLoading) {
      _addItems();
    }
  }

  @override
  void initState() {
    _scrollController.addListener(_scrollListener);
    super.initState();
  }

  @override
  void didChangeDependencies() {
    if (_cachedItems.isEmpty) _addItems();
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    _streamController.close();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<List<Item>>(
        stream: itemsStream,
        builder: (context, snapshot) {
            ListView(
               controller: _scrollController,
               /// Build here your ListView
            ),
        }
      ),
    );
  }
}
</code>```

Title: FutureBuilder load API data only once

Body:
I've called post type api to load data asynchronously on ListView using FutureBuilder but it called only once, I want to display infinite data loading on my ListView.

Is their I missing to add some properties of FutureBuilder or ListView.

Can anyone help me solved this issue, I'm new to flutter.

I'm using stateful widget to achieve this functionality.

Please refer below code,

import 'package:flutter/material.dart';
import 'package:testlistviewlazyload/Utils.dart';
import 'package:testlistviewlazyload/ServiceManager.dart';
import 'package:testlistviewlazyload/Constant.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';

class ClassHome extends StatefulWidget {
  @override
  stateClassHome createState() => stateClassHome();
}

class stateClassHome extends State<ClassHome> {

  bool isLoading = false;

  List<dynamic> arrayFoodList = List<dynamic>();

  @override
  void initState() {
    super.initState();
  }

  Future<List<dynamic>> funcLoadMore() async{

      var dicArguments = {'restaurant_id': '3',
        'menu_id': '0',
        'offset': '0'
      };

     final dictResponse = await ServiceManager().callWebservice(
          enumMethodType.POST, ConstantApi.keyRestaurantMenuFoodList,
          dicArguments, {
        'Authorization':
        await Utils().funcGetSession(ConstantSession.keyAuthToken)
      }, 'tagRestaurantMenuFoodList');

      if (dictResponse['error'] == false) {
        if (dictResponse['mainResponse']['error'] == false) {

          return dictResponse['mainResponse']['data']['food_items']
          as List<dynamic>;

        } else {

          Utils()
              .funcDisplayAlertView(
              '', "${dictResponse['message']}", context);

        }
      } else {
        Utils().funcDisplayAlertView(
            '', "${dictResponse['message']}", context);
      }

  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
        appBar: AppBar(title: Text('hello')),
        body: Container(
          color: Colors.pink[50],

          child: Column(

            children: <Widget>[

              Expanded(

                child: FutureBuilder<List<dynamic>>(
                     future: funcLoadMore(), // a previously-obtained Future<String> or null
                   builder: (BuildContext context, AsyncSnapshot<List<dynamic>> snapshot) {

                     List<dynamic> arrayTest = snapshot.data ?? [];

                      return Scrollbar(

                          child: ListView.builder(

                            itemCount: arrayTest.length,

                            itemBuilder: (BuildContext context, int index) {
                              return ListTile(
                                title: Text(arrayTest[index]['name']),
                              );
                            },

                          )
                      );
                     },
                ),

              ),

              Container(
                height: isLoading ? 50.0 : 0,
                color: Colors.white,
                child: Center(
                  child: new CircularProgressIndicator(),
                ),
              ),

            ],

          ),

        )

    );
  }
}

Body:
You can use a Stream instead of Future. This is an generic example, with a cache and a scrollController which fetches the next items when user is at the bottom page :

class _PageState extends State<Page> {
  int _count = 10;
  int _limit = 0;

  bool isLoading = false;

  List<Item> _cachedItems = List.from([]);

  StreamController<List<Item>> _streamController =
      StreamController<List<Item>>();
  StreamSink<List<Item>> get itemsSink => _streamController.sink;
  Stream<List<Item>> get itemsStream => _streamController.stream;

  ScrollController _scrollController = ScrollController();

  Future<void> _addItems() async {
    final params = {'count': '$_count', 'limit': '$_limit'};
    try {
      isLoading = true;
      // Fetch newItems with http
      isLoading = false;
      _cachedItems.addAll(newItems);
      itemsSink.add(_cachedItems);
      _limit += 10;
    } catch (e) {
      itemsSink.addError(e);
    }
  }

  _scrollListener() {
    if (_scrollController.offset >=
            _scrollController.position.maxScrollExtent &&
        !_scrollController.position.outOfRange &&
        !isLoading) {
      _addItems();
    }
  }

  @override
  void initState() {
    _scrollController.addListener(_scrollListener);
    super.initState();
  }

  @override
  void didChangeDependencies() {
    if (_cachedItems.isEmpty) _addItems();
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    _streamController.close();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<List<Item>>(
        stream: itemsStream,
        builder: (context, snapshot) {
            ListView(
               controller: _scrollController,
               /// Build here your ListView
            ),
        }
      ),
    );
  }
}


问:
View not updating when form data changes
I have a StackBlitz demo here which shows the issue: https://stackblitz.com/edit/demo-nested-forms

If you wait 2 seconds, the form gets populated by an observable, and you can see the form data as JSON below the coloured blocks. If you change the text in either of the inputs and click off them, you can see the form data gets updated.

If you then click the "Get new form data" button, it calls the same observable to return the initial object again. This time, although the form data gets correctly "reset" the view is not updated.

Any ideas why the view is now out of sync?

答:
You're not applying the formControlName to the control itself, you're setting the value of the text area via the [value] attribute. So it updates first time, but then never receives the updates via the form.

The fix is to pass the form control name into the child and apply it to the control. If you're doing this, you also need to apply the [formGroup] directive in the same component as the form control name, so you'll need to pass that in too.

Original version

child.html

```<code><div>
  <textarea [value]="value">
  </textarea>
</div>
</code>```

parent.html

```<code><div [formGroup]="form">
  <child formControlName="details" [value]="value">
  </child>
</div>
</code>```

Updated version

child.html

```<code><div [formGroup]"myFormGroup">
  <textarea [formControlName]="myFormControlName">
  </textarea>
</div>
</code>```

child.ts

```<code>@Input() myFormControlName: string;
@Input() myFormGroup: FormGroup;
</code>```

parent.html

```<code><div>
  <child [myFormGroup]="form" myFormControlName="details">
  </child>
</div>
</code>```

I've used input property names that are disambiguated from the form directive names. Obviously you would want to use slightly more sensible names.

Forked stackblitz: https://stackblitz.com/edit/demo-nested-forms-wplzbq

I have broken the change handling in the process of forking your stackblitz. But the most important thing is that the values are being updated.

Body:
You're not applying the formControlName to the control itself, you're setting the value of the text area via the [value] attribute. So it updates first time, but then never receives the updates via the form.

The fix is to pass the form control name into the child and apply it to the control. If you're doing this, you also need to apply the [formGroup] directive in the same component as the form control name, so you'll need to pass that in too.

Original version

child.html

<div>
  <textarea [value]="value">
  </textarea>
</div>

parent.html

<div [formGroup]="form">
  <child formControlName="details" [value]="value">
  </child>
</div>

Updated version

child.html

<div [formGroup]"myFormGroup">
  <textarea [formControlName]="myFormControlName">
  </textarea>
</div>

child.ts

@Input() myFormControlName: string;
@Input() myFormGroup: FormGroup;

parent.html

<div>
  <child [myFormGroup]="form" myFormControlName="details">
  </child>
</div>

I've used input property names that are disambiguated from the form directive names. Obviously you would want to use slightly more sensible names.

Forked stackblitz: https://stackblitz.com/edit/demo-nested-forms-wplzbq

I have broken the change handling in the process of forking your stackblitz. But the most important thing is that the values are being updated.


问:
How do I adjust a string's field length with print formatting?
I'm a beginner and I saw this example I didn't understand in a Udemy Python course:

"Within the curly braces you can assign field lengths, left/right alignments, rounding parameters and more."

```<code>print('{0:8} | {1:9}'.format('Fruit', 'Quantity'))
print('{0:8} | {1:9}'.format('Apples', 3.))
print('{0:8} | {1:9}'.format('Oranges', 10))

Fruit    | Quantity
Apples   |       3.0
Oranges  |        10
</code>```

I didn't understand what I was looking at, so I tried playing with the first line like so to figure out the rules:

```<code>print('{0:25} | {1:9}'.format('Fruit', 'Quantity'))

Fruit                     | Quantity
</code>```

Next I tried this:

```<code>print('{0:8} | {1:25}'.format('Fruit', 'Quantity'))

Fruit    | Quantity
</code>```

You can't see it but if you highlight the space after Quantity, I seem to have created a length equal to 25 spaces including the word.

Unexpectedly, reducing the number does not delete letters from the words Fruit or Quantity:

```<code>print('{0:4} | {1:4}'.format('Fruit', 'Quantity'))

Fruit | Quantity
</code>```

The next line seems to have different rules affecting the float 3.0 than the string 'Quantity':

```<code>print('{0:8} | {1:9}'.format('Fruit', 'Quantity'))
print('{0:8} | {1:25}'.format('Apples', 3.))

Fruit    | Quantity
Apples   |                       3.0
</code>```

Next I tried reducing the field's length for the float.

```<code>print('{0:8} | {1:9}'.format('Fruit', 'Quantity'))
print('{0:8} | {1:1}'.format('Apples', 3.))

Fruit    | Quantity
Apples   | 3.0
</code>```

Adjusting this number puts spaces before floats/integers, but adds space to the end of a string if possible. Looking at the 10 in the third line, it seems that the integer appears at the end of the defined number of spaces. That's my guess for what the rules are.

Is there an explanation anywhere online for this technique? There was no further explanation in the course and I didn't know what to search for specifically on Google.

Thanks to anyone who took the time to read all this!

答:
You got it right. As a general rule strings get aligned to the left, numbers to the right. If the number of characters needed to represent a field exceed the allowed space, it will take the additional space.

You can adjust the alignment of each field using '<' or '>'. For more details check this

Body:
I'm a beginner and I saw this example I didn't understand in a Udemy Python course:

"Within the curly braces you can assign field lengths, left/right alignments, rounding parameters and more."

print('{0:8} | {1:9}'.format('Fruit', 'Quantity'))
print('{0:8} | {1:9}'.format('Apples', 3.))
print('{0:8} | {1:9}'.format('Oranges', 10))

Fruit    | Quantity
Apples   |       3.0
Oranges  |        10

I didn't understand what I was looking at, so I tried playing with the first line like so to figure out the rules:

print('{0:25} | {1:9}'.format('Fruit', 'Quantity'))

Fruit                     | Quantity

Next I tried this:

print('{0:8} | {1:25}'.format('Fruit', 'Quantity'))

Fruit    | Quantity

You can't see it but if you highlight the space after Quantity, I seem to have created a length equal to 25 spaces including the word.

Unexpectedly, reducing the number does not delete letters from the words Fruit or Quantity:

print('{0:4} | {1:4}'.format('Fruit', 'Quantity'))

Fruit | Quantity

The next line seems to have different rules affecting the float 3.0 than the string 'Quantity':

print('{0:8} | {1:9}'.format('Fruit', 'Quantity'))
print('{0:8} | {1:25}'.format('Apples', 3.))

Fruit    | Quantity
Apples   |                       3.0

Next I tried reducing the field's length for the float.

print('{0:8} | {1:9}'.format('Fruit', 'Quantity'))
print('{0:8} | {1:1}'.format('Apples', 3.))

Fruit    | Quantity
Apples   | 3.0

Adjusting this number puts spaces before floats/integers, but adds space to the end of a string if possible. Looking at the 10 in the third line, it seems that the integer appears at the end of the defined number of spaces. That's my guess for what the rules are.

Is there an explanation anywhere online for this technique? There was no further explanation in the course and I didn't know what to search for specifically on Google.

Thanks to anyone who took the time to read all this!


问:
Javascript Accordian
I have a simple accordion working, except for one thing. I would like to be able to re-click the same accordion item again, and be able to set height to '0'.

Currently, the open accordion item closes when I click a different accordion item, which is exactly what I want to do — but I also want the ability to re-click the open accordion item and have that one close, when clicked. See working example below:

https://codepen.io/celli/pen/BaNLJWb

```<code>// set heights to 0
gsap.set('.content', {
  height: 0
});

// click function
$('.accordianItem').click(function() {

  if ($('.accordianItem').hasClass('on')) {
    gsap.to($('.content'), {
      duration: .25,
      height: 0
    });
    $('.accordianItem').removeClass('on');
  }

  gsap.to($(this).children('.content'), {
    duration: .25,
    height: "auto"
  });
  $(this).addClass('on');
});
</code>```

What code can I add to add this extra functionality?

答:
You can do this much more simply than how you're currently doing it:

```<code>// Create the animation that you need
const tl = gsap.timeline({paused: true});
tl.to('.content', {duration: 0.25, height:0});

// Set the timeline to its end state
tl.progress(1);

// Toggle the timeline's direction
$('.accordianItem').click(function() {
    tl.reversed() ? tl.play() : tl.reverse();
});

</code>```

Demo

I highly recommend checking out the GreenSock forums. They're super useful and you can get quick help from people who are experts in GSAP and web animation :)

Title: Javascript Accordian

Body:
I have a simple accordion working, except for one thing. I would like to be able to re-click the same accordion item again, and be able to set height to '0'.

Currently, the open accordion item closes when I click a different accordion item, which is exactly what I want to do — but I also want the ability to re-click the open accordion item and have that one close, when clicked. See working example below:

https://codepen.io/celli/pen/BaNLJWb

// set heights to 0
gsap.set('.content', {
  height: 0
});

// click function
$('.accordianItem').click(function() {

  if ($('.accordianItem').hasClass('on')) {
    gsap.to($('.content'), {
      duration: .25,
      height: 0
    });
    $('.accordianItem').removeClass('on');
  }

  gsap.to($(this).children('.content'), {
    duration: .25,
    height: "auto"
  });
  $(this).addClass('on');
});

What code can I add to add this extra functionality?

Body:
You can do this much more simply than how you're currently doing it:

// Create the animation that you need
const tl = gsap.timeline({paused: true});
tl.to('.content', {duration: 0.25, height:0});

// Set the timeline to its end state
tl.progress(1);

// Toggle the timeline's direction
$('.accordianItem').click(function() {
    tl.reversed() ? tl.play() : tl.reverse();
});

Demo

I highly recommend checking out the GreenSock forums. They're super useful and you can get quick help from people who are experts in GSAP and web animation :)


问:
Vuetify VTooltip trigger only on activator click
I wanted to trigger Vuetify tooltip VTooltip only when the activator is clicked rather than hovered. I tried to bind it with a variable but still triggered on hover.

 methods: {

  doCopy(){
     // copy logic
     this.showCopied = true;
     setTimeout(() => {
        this.showCopied = false
      }, 1000)

  }
 }

```

<pre class="lang-html prettyprint-override"><code>
 <VTooltip v-model="showCopied">
    <template #activator="{ on }">
      <VBtn  v-on="on" @click="doCopy"> COPY </VBtn>
    </template>
 </VTooltip>

</code>```

答:
It turns out I have to disable the default event handler of the activator.
Simply removing default event object (on) binding solves the issue.

<VTooltip v-model="showCopied">
    <template #activator={}>
      <VBtn  @click="doCopy"> COPY </VBtn>
    </template>
 </VTooltip>

```

[UPDATED] based on @Kael Watts-Deuchar answer
NB: the v-model biding is mandatory

Body:
I wanted to trigger Vuetify tooltip VTooltip only when the activator is clicked rather than hovered. I tried to bind it with a variable but still triggered on hover.

 methods: {

  doCopy(){
     // copy logic
     this.showCopied = true;
     setTimeout(() => {
        this.showCopied = false
      }, 1000)

  }
 }

 <VTooltip v-model="showCopied">
    <template #activator="{ on }">
      <VBtn  v-on="on" @click="doCopy"> COPY </VBtn>
    </template>
 </VTooltip>

Body:
It turns out I have to disable the default event handler of the activator.
Simply removing default event object (on) binding solves the issue.

<VTooltip v-model="showCopied">
    <template #activator={}>
      <VBtn  @click="doCopy"> COPY </VBtn>
    </template>
 </VTooltip>

[UPDATED] based on @Kael Watts-Deuchar answer
NB: the v-model biding is mandatory


问:
C++: create a pointer in a program and access that location in another program
So, is it possible to create a pointer in C++ like this, and print it out:

```<code>#include <iostream>
int main() {
    int* ptr = new int;
    (*ptr) = 3;
    std::cout << ptr << '\n';
}
</code>```

And then run it, copy the value of ptr, and in another program, while this is running, do this:

```<code>#include <iostream>
#include <cstring>
int main() {
    long long pointer;
    std::cin >> pointer;
    int* ptr = nullptr;
    std::memcpy(&ptr, &pointer, sizeof(pointer));
    std::cout << *ptr << '\n';
}
</code>```

And get 3 printed out? Is it possible, or if not, then exactly why?

答:
It is not possible in standard C++. Standard C++ does not have a concept of programs. There is only one program as far as the language is concerned - the one that is being translated at the moment.

Outside of the C++ standard, multi-tasking operating systems do exist, where it is possible to run multiple processes simultaneously (you are probably using one right now). Such operating systems use virtual memory, and one process cannot directly access virtual memory of another process.

It is technically possible though for example using process_vm_readv system call (Linux specific), if you have sufficient permissions. Before using such trick, you must somehow communicate th process id and virtual address that you want to read, which are not known until the first program runs.

Although it may be possible, this is probably not something that you need to do, unless you are implementing a debugger or similar tool perhaps. If you want this simply so that the processes can communicate, there are other ways. No C++-standard ways, because C++ doesn't know of processes, but for example POSIX standard specifies many ways for processes to communicate: shared memory, files, network sockets etc.

Body:
So, is it possible to create a pointer in C++ like this, and print it out:

#include <iostream>
int main() {
    int* ptr = new int;
    (*ptr) = 3;
    std::cout << ptr << '\n';
}

And then run it, copy the value of ptr, and in another program, while this is running, do this:

#include <iostream>
#include <cstring>
int main() {
    long long pointer;
    std::cin >> pointer;
    int* ptr = nullptr;
    std::memcpy(&ptr, &pointer, sizeof(pointer));
    std::cout << *ptr << '\n';
}

And get 3 printed out? Is it possible, or if not, then exactly why?


问:
How to use progress bar in wpf without multithreading?
Help please.

I want to see the progress bar change with the IsIndeterminate= true property while reading from the database.

I know that I can use Task and BackgroundWorker to create another thread. But for me, it is very important that I do not leave the method in which the long-term operation takes place until it is finished. What can be done in this case?

P.S. Sorry for my English :)

答:
After awaiting a Task, execution returns to the method where you started the Task. This is perhaps all you need, as the method isn't actually "left".

Here is a sample Button Click event handler that disables itself before awaiting an awaitable method call (e.g. some long running operation), and that enables itself again when the call has completed:

```<code>private async void Button_Click(object sender, RoutedEventArgs e)
{
    var button = (Button)sender;
    button.IsEnabled = false;

    await SomethingAsync();

    button.IsEnabled = true;
}

private Task SomethingAsync()
{
    // ...
}
</code>```

Body:
After awaiting a Task, execution returns to the method where you started the Task. This is perhaps all you need, as the method isn't actually "left".

Here is a sample Button Click event handler that disables itself before awaiting an awaitable method call (e.g. some long running operation), and that enables itself again when the call has completed:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    var button = (Button)sender;
    button.IsEnabled = false;

    await SomethingAsync();

    button.IsEnabled = true;
}

private Task SomethingAsync()
{
    // ...
}


问:
What should I return instead of null?
I've heard that it is bad practice to return null.

What are the alternatives to returning null in this case?

```<code>    public RollingStock getHeadPoint() {
        if (!train.isEmpty()) {
            return train.get(0);
        } else {
            return null;
        }
    }
</code>```

答:
IMHO, the best option is to return an Optional<RollingStock>, like the foillowing:

```<code>public Optional<RollingStock> getHeadPoint() {
    if (!train.isEmpty()) {
        // or even Optional.ofNullable, if you are not sure
        // whether train.get(0) is null or not
        return Optional.of(train.get(0));
    } else {
        return Optional.empty();
    }
}
</code>```

Assuming train is a collection, as an alternative to manual wrapping the value into an Optional you could use Stream API:

```<code>public Optional<RollingStock> getHeadPoint() {
    return train.stream()
                .findFirst();
}
</code>```

In some cases using inline train.stream().findFirst() may be more preferable than wrapping it into a separate method.

Once you already modified your method getHeadPoint to return Optional<RollingStock> you can use it as follows:

```<code>// ...
RollingStock headPoint = getHeadPoint().orElse(yourDefaultRollingStock);
// or
RollingStock headPoint = getHeadPoint().orElseGet(aMethodGettingYourDefaultRollingStock());
// or
RollingStock headPoint = getHeadPoint().orElseThrow(() -> new Exception("The train is empty!"));
// or
getHeadPoint().ifPresent(headPoint -> doSomethingWithHeadPoint(headPoint));
</code>```

Title: What should I return instead of null?

Body:
I've heard that it is bad practice to return null.

What are the alternatives to returning null in this case?

    public RollingStock getHeadPoint() {
        if (!train.isEmpty()) {
            return train.get(0);
        } else {
            return null;
        }
    }

Body:
IMHO, the best option is to return an Optional<RollingStock>, like the foillowing:

public Optional<RollingStock> getHeadPoint() {
    if (!train.isEmpty()) {
        // or even Optional.ofNullable, if you are not sure
        // whether train.get(0) is null or not
        return Optional.of(train.get(0));
    } else {
        return Optional.empty();
    }
}

Assuming train is a collection, as an alternative to manual wrapping the value into an Optional you could use Stream API:

public Optional<RollingStock> getHeadPoint() {
    return train.stream()
                .findFirst();
}

In some cases using inline train.stream().findFirst() may be more preferable than wrapping it into a separate method.

Once you already modified your method getHeadPoint to return Optional<RollingStock> you can use it as follows:

// ...
RollingStock headPoint = getHeadPoint().orElse(yourDefaultRollingStock);
// or
RollingStock headPoint = getHeadPoint().orElseGet(aMethodGettingYourDefaultRollingStock());
// or
RollingStock headPoint = getHeadPoint().orElseThrow(() -> new Exception("The train is empty!"));
// or
getHeadPoint().ifPresent(headPoint -> doSomethingWithHeadPoint(headPoint));