问:
Why is my R script using all the computer's memory?
I wrote a simple script which opens each .docx document from my folders and looks for certain words. If any of the words exist, it extracts an ID number and then moves on to the next document. The problem is that after ~1500 documents, it consumes all the computer's memory and R gets stuck and aborts. I don't know why it happens - my script should not be using so much memory. Any suggestion would be appreciated!</p>

```<code>rm(list=ls()) #clean environment
library(qdapTools)
setwd("C:/DocxArchive/ParentFolder")
results <- 0 #store results here
years_list <- c("2010","2011","2012","2013","2014","2015","2016","2017","2018","2019","2020")

for (year_index in 1:11) {
  parent_dir <- years_list[year_index]
  file_list <- list.files(path = parent_dir, recursive = TRUE) #get list of file names
  items_to_delete <- grep('~',file_list) #find temporary files - name begins with '~'
  file_list <- file_list[-items_to_delete] #delete temporary files from file list
  length_of_file_list <- length(file_list)
  file_num <- 1 #initialize file number index
  while(file_num <= length_of_file_list){
    DOCX <- read_docx(file=file.path(parent_dir, file_list[file_num]))
      index_of_HITEC1 <- grepl("HI TEC", DOCX, fixed=FALSE, ignore.case=TRUE)
      index_of_HITEC2 <- grepl("HITEC", DOCX, fixed=FALSE, ignore.case=TRUE)
      index_of_HITEC3 <- grepl("HI-TEC", DOCX, fixed=FALSE, ignore.case=TRUE)
      HITEC1_num <- which.max(index_of_HITEC1) #line in document where word exists
      HITEC2_num <- which.max(index_of_HITEC2) #line in document where word exists
      HITEC3_num <- which.max(index_of_HITEC3) #line in document where word exists
      HITEC_sum <- HITEC1_num+HITEC2_num+HITEC3_num
      if (HITEC_sum > 3){
        index_of_person_ID <- grepl("ID:", DOCX, fixed=TRUE) #find lines where ID exist
        text <- DOCX[index_of_person_ID==TRUE] #keep only lines where ID exist
        text <- gsub("[^0-9]","",text) #delete everything except numbers
        results <- c(results,text)
      } #end of if loop
      file_num <- file_num+1
   } #end of while loop
} #end of for loop
</code>```

答:
We made our way into the second Circle, here live the gluttons.

It might help you to read a bit of R inferno. Aside from a possible memory leak arising from read_docx, the line that jumps out to me as problematic is:

results <- c(results, text)
```

There are some details in R Inferno Ch. 2, but basically when you do this, you incur a full copy of results from its old place in memory to a new one, and this happens in every single loop iteration. This means that most of the time you will be using almost double the memory you need to, and possibly much more, since R's garbage collector generally only frees memory when it is requested.

You could improve this code by using a programming different pattern to save the results or, if you are feeling very lazy, by calling gc() periodically (say, every 10th iteration of the loop).

Body:
I wrote a simple script which opens each .docx document from my folders and looks for certain words. If any of the words exist, it extracts an ID number and then moves on to the next document. The problem is that after ~1500 documents, it consumes all the computer's memory and R gets stuck and aborts. I don't know why it happens - my script should not be using so much memory. Any suggestion would be appreciated!

rm(list=ls()) #clean environment
library(qdapTools)
setwd("C:/DocxArchive/ParentFolder")
results <- 0 #store results here
years_list <- c("2010","2011","2012","2013","2014","2015","2016","2017","2018","2019","2020")

for (year_index in 1:11) {
  parent_dir <- years_list[year_index]
  file_list <- list.files(path = parent_dir, recursive = TRUE) #get list of file names
  items_to_delete <- grep('~',file_list) #find temporary files - name begins with '~'
  file_list <- file_list[-items_to_delete] #delete temporary files from file list
  length_of_file_list <- length(file_list)
  file_num <- 1 #initialize file number index
  while(file_num <= length_of_file_list){
    DOCX <- read_docx(file=file.path(parent_dir, file_list[file_num]))
      index_of_HITEC1 <- grepl("HI TEC", DOCX, fixed=FALSE, ignore.case=TRUE)
      index_of_HITEC2 <- grepl("HITEC", DOCX, fixed=FALSE, ignore.case=TRUE)
      index_of_HITEC3 <- grepl("HI-TEC", DOCX, fixed=FALSE, ignore.case=TRUE)
      HITEC1_num <- which.max(index_of_HITEC1) #line in document where word exists
      HITEC2_num <- which.max(index_of_HITEC2) #line in document where word exists
      HITEC3_num <- which.max(index_of_HITEC3) #line in document where word exists
      HITEC_sum <- HITEC1_num+HITEC2_num+HITEC3_num
      if (HITEC_sum > 3){
        index_of_person_ID <- grepl("ID:", DOCX, fixed=TRUE) #find lines where ID exist
        text <- DOCX[index_of_person_ID==TRUE] #keep only lines where ID exist
        text <- gsub("[^0-9]","",text) #delete everything except numbers
        results <- c(results,text)
      } #end of if loop
      file_num <- file_num+1
   } #end of while loop
} #end of for loop

Body:
We made our way into the second Circle, here live the gluttons.

It might help you to read a bit of R inferno. Aside from a possible memory leak arising from read_docx, the line that jumps out to me as problematic is:

results <- c(results, text)

There are some details in R Inferno Ch. 2, but basically when you do this, you incur a full copy of results from its old place in memory to a new one, and this happens in every single loop iteration. This means that most of the time you will be using almost double the memory you need to, and possibly much more, since R's garbage collector generally only frees memory when it is requested.

You could improve this code by using a programming different pattern to save the results or, if you are feeling very lazy, by calling gc() periodically (say, every 10th iteration of the loop).


来源: stackexchange

问:
How to convert each value of a dataframe column by an identifying integer
I have the following dataframe :

```<code>import pandas as pd
df = pd.DataFrame(dict(NoMatter=list(range(6)), Value=['a','b',7,7,'b','b']))
print(df)
   NoMatter Value
0         0     a
1         1     b
2         2     7
3         3     7
4         4     b
5         5     b
</code>```

I would like to modify the Value column such as it contains a different integer by old values. Here, I would like therefore 1 instead of each a, 2 instead of each b and 3 instead of each 7.

Expected result :

```<code>   NoMatter  Value
0         0      1
1         1      2
2         2      3
3         3      3
4         4      2
5         5      2
</code>```

How please could I do ?

答:
Use factorize:

```<code>df['Value'] = pd.factorize(df['Value'])[0] + 1
print (df)
   NoMatter  Value
0         0      1
1         1      2
2         2      3
3         3      3
4         4      2
5         5      2
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following dataframe :

import pandas as pd
df = pd.DataFrame(dict(NoMatter=list(range(6)), Value=['a','b',7,7,'b','b']))
print(df)
   NoMatter Value
0         0     a
1         1     b
2         2     7
3         3     7
4         4     b
5         5     b

I would like to modify the Value column such as it contains a different integer by old values. Here, I would like therefore 1 instead of each a, 2 instead of each b and 3 instead of each 7.

Expected result :

   NoMatter  Value
0         0      1
1         1      2
2         2      3
3         3      3
4         4      2
5         5      2

How please could I do ?

Body:
Use factorize:

df['Value'] = pd.factorize(df['Value'])[0] + 1
print (df)
   NoMatter  Value
0         0      1
1         1      2
2         2      3
3         3      3
4         4      2
5         5      2


问:
Problem with the Microsoft .AspNetCore 3.1 package in a .Net Standard 2.1 project
I have a problem, I have a visual studio solution with different projects with a microservices architecture, and there is a project with common functionalities for all microservices, in that project I have startup methods in order not to repeat code in the different microservices. the problem is that in the Api project of the microservice I have in the startup the method app.UseEndpoints and when I try to transfer this code to the common project that is in .NET Standard 2.1 it does not let me install the updated version of the nuget package: Microsoft.AspNetCore.Routing Version 2.2.2 date: 12/09/2019 instead the Api project pulls the version of .NET Core 3.1.1

Project API-REST Microservice:

```<code>assembled Microsoft.AspNetCore.Routing, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
</code>```

When I install that nuget package into the net Standard 2.1 project the assembly is as follows:

```<code>assembled Microsoft.AspNetCore, Version=2.2.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
</code>```

Could I introduce some functionality from the Microsoft.AspNetCore 3.1.0 package into a net Standard 2.1 project?

答:
Nope. AspNetCore contains more functionality than NetStandard and so you are not linking in the "right" direction.

The proper way is to have a n aspnetcore 3.1 common package that contains (only) those elements that netstandard can not handle.

Body:
I have a problem, I have a visual studio solution with different projects with a microservices architecture, and there is a project with common functionalities for all microservices, in that project I have startup methods in order not to repeat code in the different microservices. the problem is that in the Api project of the microservice I have in the startup the method app.UseEndpoints and when I try to transfer this code to the common project that is in .NET Standard 2.1 it does not let me install the updated version of the nuget package: Microsoft.AspNetCore.Routing Version 2.2.2 date: 12/09/2019 instead the Api project pulls the version of .NET Core 3.1.1

Project API-REST Microservice:

assembled Microsoft.AspNetCore.Routing, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60

When I install that nuget package into the net Standard 2.1 project the assembly is as follows:

assembled Microsoft.AspNetCore, Version=2.2.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60

Could I introduce some functionality from the Microsoft.AspNetCore 3.1.0 package into a net Standard 2.1 project?


问:
Jquery Format HTML Table in a Given Format
Am trying to display query contents in HTMl using following jquery

```<code>    $tableSearch = $('#table-search');
    $tableSearch.html('<tr><th>Name</th><tr><th>Hours</tr></th><tr><th>MB</th></tr>');
    result.forEach(function(row) {
     $('#table-search tr').append('<td>'+ row.Date +'</td>'+'<td>'+ row.Hours+'</td>'+'<td>'+ row.MB+'</td>');
        });
</code>```

But it gives the result like below

Actually I want the result like this

How to format those values like above.

答:
First, you need to define class or id on
 tag of table header row, And then append the data as class/id wise row.

```<code>$tableSearch = $('#table-search');
    $tableSearch.html('<tr class="tr1"><th>Name</th><tr class="tr2"><th>Hours</tr></th><tr class="tr3"><th>MB</th></tr>');
    result.forEach(function(row) {
    $('#table-search .tr1').append('<td>'+ row.Date +'</td>');
     $('#table-search .tr2').append('<td>'+ row.Hours+'</td>');
     $('#table-search .tr3').append('<td>'+ row.MB+'</td>');
   });
</code>```

Body:
Am trying to display query contents in HTMl using following jquery

    $tableSearch = $('#table-search');
    $tableSearch.html('
Name
Hours

MB
');
    result.forEach(function(row) {
     $('#table-search tr').append(''+ row.Date +'	'+''+ row.Hours+'	'+''+ row.MB+'	');
        });

But it gives the result like below

Actually I want the result like this

How to format those values like above.

Body:
First, you need to define class or id on <tr> tag of table header row, And then append the data as class/id wise row.

$tableSearch = $('#table-search');
    $tableSearch.html('<tr class="tr1"><th>Name</th><tr class="tr2"><th>Hours</tr></th><tr class="tr3"><th>MB</th></tr>');
    result.forEach(function(row) {
    $('#table-search .tr1').append('<td>'+ row.Date +'</td>');
     $('#table-search .tr2').append('<td>'+ row.Hours+'</td>');
     $('#table-search .tr3').append('<td>'+ row.MB+'</td>');
   });


问:
Calling 'BuildServiceProvider' from application code results in copy of Singleton warning. How do I avoid this?
I just pasted the 4 lines at the end from another project and it works but I get a warning.. I clearly do not understand DI well enough ... What does it want me to change ? </p>

```<code>  public void ConfigureServices(IServiceCollection services)
        {
            if (HostingEnvironment.EnvironmentName == "Local")
            {
                services.AddHealthChecksUI()
               .AddHealthChecks()
               .AddCheck<TestWebApiControllerHealthCheck>("HomePageHealthCheck")
               .AddCheck<DatabaseHealthCheck>("DatabaseHealthCheck");
            }

        services.Configure<PwdrsSettings>(Configuration.GetSection("MySettings"));
        services.AddDbContext<PwdrsContext>(o => o.UseSqlServer(Configuration.GetConnectionString("PwdrsConnectionRoot")));

        services.AddMvc(o =>
        {
            o.Filters.Add<CustomExceptionFilter>();
        });

        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy", b => b
                .SetIsOriginAllowed((host) => true)
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });

        services.AddSwaggerDocument();
        services.AddHttpContextAccessor();

        services.AddAutoMapper(typeof(ObjectMapperProfile));
        services.AddTransient<IEmailSender, EmailSender>();
        services.AddScoped(typeof(IAppLogger<>), typeof(LoggerAdapter<>));
        services.AddScoped(typeof(IAsyncRepository<>), typeof(Repository<>));
        services.AddScoped<IRfReportTypeRepository, RfReportTypeRepository>();
        services.AddScoped<IRfReportRepository, RfReportRepository>();
        services.AddScoped<IRfReportLookupsService, RfReportLookupsService>();
        services.AddScoped<IRfReportService, RfReportService>();

        services.Configure<RAFLogging>(Configuration.GetSection("RAFLogging"));
        ServiceProvider serviceProvider = services.BuildServiceProvider(); //WARNING IS HERE
        IOptions<RAFLogging> RAFLogger = serviceProvider.GetRequiredService<IOptions<RAFLogging>>();
        RegisterSerilogLogger logger = new RegisterSerilogLogger(RAFLogger);
    }
</code>```

答:
The ONLY purpose of calling 'BuildServiceProvider' is to get a service provider instance,

To remove this call and still be able to use IServiceProvider, change Configure method to get it as parameter:

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider provider)
</code>```

Body:
I just pasted the 4 lines at the end from another project and it works but I get a warning.. I clearly do not understand DI well enough ... What does it want me to change ?

  public void ConfigureServices(IServiceCollection services)
        {
            if (HostingEnvironment.EnvironmentName == "Local")
            {
                services.AddHealthChecksUI()
               .AddHealthChecks()
               .AddCheck<TestWebApiControllerHealthCheck>("HomePageHealthCheck")
               .AddCheck<DatabaseHealthCheck>("DatabaseHealthCheck");
            }

        services.Configure<PwdrsSettings>(Configuration.GetSection("MySettings"));
        services.AddDbContext<PwdrsContext>(o => o.UseSqlServer(Configuration.GetConnectionString("PwdrsConnectionRoot")));

        services.AddMvc(o =>
        {
            o.Filters.Add<CustomExceptionFilter>();
        });

        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy", b => b
                .SetIsOriginAllowed((host) => true)
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });

        services.AddSwaggerDocument();
        services.AddHttpContextAccessor();

        services.AddAutoMapper(typeof(ObjectMapperProfile));
        services.AddTransient<IEmailSender, EmailSender>();
        services.AddScoped(typeof(IAppLogger<>), typeof(LoggerAdapter<>));
        services.AddScoped(typeof(IAsyncRepository<>), typeof(Repository<>));
        services.AddScoped<IRfReportTypeRepository, RfReportTypeRepository>();
        services.AddScoped<IRfReportRepository, RfReportRepository>();
        services.AddScoped<IRfReportLookupsService, RfReportLookupsService>();
        services.AddScoped<IRfReportService, RfReportService>();

        services.Configure<RAFLogging>(Configuration.GetSection("RAFLogging"));
        ServiceProvider serviceProvider = services.BuildServiceProvider(); //WARNING IS HERE
        IOptions<RAFLogging> RAFLogger = serviceProvider.GetRequiredService<IOptions<RAFLogging>>();
        RegisterSerilogLogger logger = new RegisterSerilogLogger(RAFLogger);
    }

Body:
The ONLY purpose of calling 'BuildServiceProvider' is to get a service provider instance,

To remove this call and still be able to use IServiceProvider, change Configure method to get it as parameter:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider provider)


问:
Hero section with CSS slideshow, positioning for heading and normal flow?
I'm trying to create a Hero/Jumbotron with a slideshow using CSS animations. However, what I've got so far disrupts the normal flow.

Anything I add after the slideshow is located on top/under, and removing the position: absolute  of the .pic-wrapper section makes it so that the .pic-wrapper takes up the entire body.

What I need is for the hero section to have a title centered and then for the rest of the site to follow as normally. Any help?

HTML

```<code><section class="pic-wrapper">
    <h1>Slideshow Heading, should be on top of slideshow</h1>
    <figure class="pic-1" style="background-image: url(https://images.pexels.com/photos/258109/pexels-photo-258109.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)"></figure>
    <figure class="pic-2" style="background-image: url(https://images.pexels.com/photos/206359/pexels-photo-206359.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)"></figure>
    <figure class="pic-3" style="background-image: url(https://images.pexels.com/photos/210186/pexels-photo-210186.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)"></figure>
    <figure class="pic-4" style="background-image: url(https://images.pexels.com/photos/1166209/pexels-photo-1166209.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)"></figure>
</section>
<section>
<h2>New Section, this currently ends up under the slideshow</h2>
</section>
</code>```

CSS

```<code>.pic-wrapper {
        position: absolute;
        width: 100%;
        min-height: 50vh;
        /* overflow: hidden; */
        }

        figure {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0;

        /*animation*/
        animation: slideShow 24s linear infinite 0s;
        -o-animation: slideShow 24s linear infinite 0s;
        -moz-animation: slideShow 24s linear infinite 0s;
        -webkit-animation: slideShow 24s linear infinite 0s;
        }

        .pic-1 {
        opacity: 1;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
        background-position-y: 50%;
        }

        .pic-2 {
        animation-delay: 6s;
        -o-animation-delay: 6s;
        -moz--animation-delay: 6s;
        -webkit-animation-delay: 6s;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
        background-position-y: 50%;
        }

        .pic-3 {
        animation-delay: 12s;
        -o-animation-delay: 12s;
        -moz--animation-delay: 12s;
        -webkit-animation-delay: 12s;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
        background-position-y: 50%;
        }

        .pic-4 {
        animation-delay: 18s;
        -o-animation-delay: 18s;
        -moz--animation-delay: 18s;
        -webkit-animation-delay: 18s;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
        background-position-y: 50%;
        }
        /* keyframes*/

        @keyframes
        slideShow {  0% {
        opacity: 0;
        transform:scale(1);
        -ms-transform:scale(1);
        }
        5% {
        opacity: 1
        }
        25% {
        opacity: 1;
        }
        30% {
        opacity: 0;
        transform:scale(1.1);
        -ms-transform:scale(1.1);
        }
        100% {
        opacity: 0;
        transform:scale(1);
        -ms-transformm:scale(1);
        }
        }
        @-o-keyframes
        slideShow {  0% {
        opacity: 0;
        -o-transform:scale(1);
        }
        5% {
        opacity: 1
        }
        25% {
        opacity: 1;
        }
        30% {
        opacity: 0;
        -o-transform:scale(1.1);
        }
        100% {
        opacity: 0;
        -o-transformm:scale(1);
        }
        }
        @-moz-keyframes
        slideShow {  0% {
        opacity: 0;
        -moz-transform:scale(1);
        }
        5% {
        opacity: 1
        }
        25% {
        opacity: 1;
        }
        30% {
        opacity: 0;
        -moz-transform:scale(1.1);
        }
        100% {
        opacity: 0;
        -moz-transformm:scale(1);
        }
        }
        @-webkit-keyframes
        slideShow {  0% {
        opacity: 0;
        -webkit-transform:scale(1);
        }
        5% {
        opacity: 1
        }
        25% {
        opacity: 1;
        }
        30% {
        opacity: 0;
        -webkit-transform:scale(1.1);
        }
        100% {
        opacity: 0;
        -webkit-transformm:scale(1);
        }
        }
</code>```

Codepen link

答:
z-index is your friend. As:
You can polish it by adding a wrapper, text center, etc...

#head {
     min-height: 50vh;
     overflow: hidden;
     position: relative;
}
.pic-wrapper {
     position: absolute;
     width: 100%;
     min-height: 50vh;
     overflow: hidden;
}
/* added this */
 #hero {
     z-index: 20;
     position: absolute;
     width: 100%;
     padding: 2vw;
     text-align: center;
     text-size: 200%
}
figure {
    /* and this */
     z-index: 1;
     position: absolute;
     top: 0;
     left: 0;
     width: 100%;
     height: 100%;
     opacity: 0;
    /*animation*/
     animation: slideShow 24s linear infinite 0s;
     -o-animation: slideShow 24s linear infinite 0s;
     -moz-animation: slideShow 24s linear infinite 0s;
     -webkit-animation: slideShow 24s linear infinite 0s;
}
 .pic-1 {
     opacity: 1;
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover;
     background-position-y: 50%;
}
 .pic-2 {
     animation-delay: 6s;
     -o-animation-delay: 6s;
     -moz--animation-delay: 6s;
     -webkit-animation-delay: 6s;
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover;
     background-position-y: 50%;
}
 .pic-3 {
     animation-delay: 12s;
     -o-animation-delay: 12s;
     -moz--animation-delay: 12s;
     -webkit-animation-delay: 12s;
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover;
     background-position-y: 50%;
}
 .pic-4 {
     animation-delay: 18s;
     -o-animation-delay: 18s;
     -moz--animation-delay: 18s;
     -webkit-animation-delay: 18s;
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover;
     background-position-y: 50%;
}
/* keyframes*/
 @keyframes slideShow {
     0% {
         opacity: 0;
         transform:scale(1);
         -ms-transform:scale(1);
    }
     5% {
         opacity: 1
    }
     25% {
         opacity: 1;
    }
     30% {
         opacity: 0;
         transform:scale(1.1);
         -ms-transform:scale(1.1);
    }
     100% {
         opacity: 0;
         transform:scale(1);
         -ms-transformm:scale(1);
    }
}
 @-o-keyframes slideShow {
     0% {
         opacity: 0;
         -o-transform:scale(1);
    }
     5% {
         opacity: 1
    }
     25% {
         opacity: 1;
    }
     30% {
         opacity: 0;
         -o-transform:scale(1.1);
    }
     100% {
         opacity: 0;
         -o-transformm:scale(1);
    }
}
 @-moz-keyframes slideShow {
     0% {
         opacity: 0;
         -moz-transform:scale(1);
    }
     5% {
         opacity: 1
    }
     25% {
         opacity: 1;
    }
     30% {
         opacity: 0;
         -moz-transform:scale(1.1);
    }
     100% {
         opacity: 0;
         -moz-transformm:scale(1);
    }
}
 @-webkit-keyframes slideShow {
     0% {
         opacity: 0;
         -webkit-transform:scale(1);
    }
     5% {
         opacity: 1
    }
     25% {
         opacity: 1;
    }
     30% {
         opacity: 0;
         -webkit-transform:scale(1.1);
    }
     100% {
         opacity: 0;
         -webkit-transformm:scale(1);
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="head">
    <div class="pic-wrapper">
        <div id="hero">
            <h1>Slideshow Heading</h1></div>
        <figure class="pic-1" style="background-image: url(https://images.pexels.com/photos/258109/pexels-photo-258109.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)"></figure>
        <figure class="pic-2" style="background-image: url(https://images.pexels.com/photos/206359/pexels-photo-206359.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)"></figure>
        <figure class="pic-3" style="background-image: url(https://images.pexels.com/photos/210186/pexels-photo-210186.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)"></figure>
        <figure class="pic-4" style="background-image: url(https://images.pexels.com/photos/1166209/pexels-photo-1166209.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)"></figure>
    </div>
</section>

<section>
    <h2>New Section</2>
</section></code>```

Body:
I'm trying to create a Hero/Jumbotron with a slideshow using CSS animations. However, what I've got so far disrupts the normal flow.

Anything I add after the slideshow is located on top/under, and removing the position: absolute  of the .pic-wrapper section makes it so that the .pic-wrapper takes up the entire body.

What I need is for the hero section to have a title centered and then for the rest of the site to follow as normally. Any help?

HTML

Slideshow Heading, should be on top of slideshow

New Section, this currently ends up under the slideshow

CSS

.pic-wrapper {
        position: absolute;
        width: 100%;
        min-height: 50vh;
        /* overflow: hidden; */
        }

        figure {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0;

        /*animation*/
        animation: slideShow 24s linear infinite 0s;
        -o-animation: slideShow 24s linear infinite 0s;
        -moz-animation: slideShow 24s linear infinite 0s;
        -webkit-animation: slideShow 24s linear infinite 0s;
        }

        .pic-1 {
        opacity: 1;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
        background-position-y: 50%;
        }

        .pic-2 {
        animation-delay: 6s;
        -o-animation-delay: 6s;
        -moz--animation-delay: 6s;
        -webkit-animation-delay: 6s;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
        background-position-y: 50%;
        }

        .pic-3 {
        animation-delay: 12s;
        -o-animation-delay: 12s;
        -moz--animation-delay: 12s;
        -webkit-animation-delay: 12s;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
        background-position-y: 50%;
        }

        .pic-4 {
        animation-delay: 18s;
        -o-animation-delay: 18s;
        -moz--animation-delay: 18s;
        -webkit-animation-delay: 18s;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
        background-position-y: 50%;
        }
        /* keyframes*/

        @keyframes
        slideShow {  0% {
        opacity: 0;
        transform:scale(1);
        -ms-transform:scale(1);
        }
        5% {
        opacity: 1
        }
        25% {
        opacity: 1;
        }
        30% {
        opacity: 0;
        transform:scale(1.1);
        -ms-transform:scale(1.1);
        }
        100% {
        opacity: 0;
        transform:scale(1);
        -ms-transformm:scale(1);
        }
        }
        @-o-keyframes
        slideShow {  0% {
        opacity: 0;
        -o-transform:scale(1);
        }
        5% {
        opacity: 1
        }
        25% {
        opacity: 1;
        }
        30% {
        opacity: 0;
        -o-transform:scale(1.1);
        }
        100% {
        opacity: 0;
        -o-transformm:scale(1);
        }
        }
        @-moz-keyframes
        slideShow {  0% {
        opacity: 0;
        -moz-transform:scale(1);
        }
        5% {
        opacity: 1
        }
        25% {
        opacity: 1;
        }
        30% {
        opacity: 0;
        -moz-transform:scale(1.1);
        }
        100% {
        opacity: 0;
        -moz-transformm:scale(1);
        }
        }
        @-webkit-keyframes
        slideShow {  0% {
        opacity: 0;
        -webkit-transform:scale(1);
        }
        5% {
        opacity: 1
        }
        25% {
        opacity: 1;
        }
        30% {
        opacity: 0;
        -webkit-transform:scale(1.1);
        }
        100% {
        opacity: 0;
        -webkit-transformm:scale(1);
        }
        }

Codepen link

Body:
z-index is your friend. As:
You can polish it by adding a wrapper, text center, etc...

#head {
     min-height: 50vh;
     overflow: hidden;
     position: relative;
}
.pic-wrapper {
     position: absolute;
     width: 100%;
     min-height: 50vh;
     overflow: hidden;
}
/* added this */
 #hero {
     z-index: 20;
     position: absolute;
     width: 100%;
     padding: 2vw;
     text-align: center;
     text-size: 200%
}
figure {
    /* and this */
     z-index: 1;
     position: absolute;
     top: 0;
     left: 0;
     width: 100%;
     height: 100%;
     opacity: 0;
    /*animation*/
     animation: slideShow 24s linear infinite 0s;
     -o-animation: slideShow 24s linear infinite 0s;
     -moz-animation: slideShow 24s linear infinite 0s;
     -webkit-animation: slideShow 24s linear infinite 0s;
}
 .pic-1 {
     opacity: 1;
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover;
     background-position-y: 50%;
}
 .pic-2 {
     animation-delay: 6s;
     -o-animation-delay: 6s;
     -moz--animation-delay: 6s;
     -webkit-animation-delay: 6s;
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover;
     background-position-y: 50%;
}
 .pic-3 {
     animation-delay: 12s;
     -o-animation-delay: 12s;
     -moz--animation-delay: 12s;
     -webkit-animation-delay: 12s;
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover;
     background-position-y: 50%;
}
 .pic-4 {
     animation-delay: 18s;
     -o-animation-delay: 18s;
     -moz--animation-delay: 18s;
     -webkit-animation-delay: 18s;
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover;
     background-position-y: 50%;
}
/* keyframes*/
 @keyframes slideShow {
     0% {
         opacity: 0;
         transform:scale(1);
         -ms-transform:scale(1);
    }
     5% {
         opacity: 1
    }
     25% {
         opacity: 1;
    }
     30% {
         opacity: 0;
         transform:scale(1.1);
         -ms-transform:scale(1.1);
    }
     100% {
         opacity: 0;
         transform:scale(1);
         -ms-transformm:scale(1);
    }
}
 @-o-keyframes slideShow {
     0% {
         opacity: 0;
         -o-transform:scale(1);
    }
     5% {
         opacity: 1
    }
     25% {
         opacity: 1;
    }
     30% {
         opacity: 0;
         -o-transform:scale(1.1);
    }
     100% {
         opacity: 0;
         -o-transformm:scale(1);
    }
}
 @-moz-keyframes slideShow {
     0% {
         opacity: 0;
         -moz-transform:scale(1);
    }
     5% {
         opacity: 1
    }
     25% {
         opacity: 1;
    }
     30% {
         opacity: 0;
         -moz-transform:scale(1.1);
    }
     100% {
         opacity: 0;
         -moz-transformm:scale(1);
    }
}
 @-webkit-keyframes slideShow {
     0% {
         opacity: 0;
         -webkit-transform:scale(1);
    }
     5% {
         opacity: 1
    }
     25% {
         opacity: 1;
    }
     30% {
         opacity: 0;
         -webkit-transform:scale(1.1);
    }
     100% {
         opacity: 0;
         -webkit-transformm:scale(1);
    }
}

<section id="head">
    <div class="pic-wrapper">
        <div id="hero">
            <h1>Slideshow Heading</h1></div>
        <figure class="pic-1" style="background-image: url(https://images.pexels.com/photos/258109/pexels-photo-258109.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)"></figure>
        <figure class="pic-2" style="background-image: url(https://images.pexels.com/photos/206359/pexels-photo-206359.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)"></figure>
        <figure class="pic-3" style="background-image: url(https://images.pexels.com/photos/210186/pexels-photo-210186.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)"></figure>
        <figure class="pic-4" style="background-image: url(https://images.pexels.com/photos/1166209/pexels-photo-1166209.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260)"></figure>
    </div>
</section>

<section>
    <h2>New Section</2>
</section>


问:
Selective Automatic Schema Generation settings per entity in Hibernate
Is it possible to selectively choose to which entities or datasources the schema generation settings of Hibernate apply?

hibernate.hbm2ddl.auto=none

I´d like to use existing tables of a database that I don´t want to modify, but also create some new ones automatically.

答:
I´ve found a nice article that describes how to do that by defining multiple configuration classes pointing to different entity packages. It seems the only way is to do that programmatically.

For the existing database table where I don´t want to create or update any tables I´d have the following config with hibernate.hbm2ddl.auto set to none

```<code>@PropertySource({"classpath:existing-database.properties"})
@EnableJpaRepositories(basePackages = "com.project.model.existing")
@Configuration
public class ExistingDatabaseConfig {

    @Autowired
    private Environment env;

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean userEntityManager() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(userDataSource());
        em.setPackagesToScan("com.project.model.existing");

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);

        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto", "none");
        properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));

        em.setJpaPropertyMap(properties);

        return em;
    }

    @Primary
    @Bean
    public DataSource userDataSource() {

        DriverManagerDataSource dataSource
                = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("user.jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.user"));
        dataSource.setPassword(env.getProperty("jdbc.pass"));

        return dataSource;
    }

}
</code>```

And for those entities that where tables should be created I´d have a separate config with hibernate.hbm2ddl.auto set to create-or-update:

```<code>@PropertySource({"classpath:not-existing-database.properties"})
@EnableJpaRepositories(basePackages = "com.project.model.notexisting")
@Configuration
public class NotExistingDatabaseConfig {

    @Autowired
    private Environment env;

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean userEntityManager() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(userDataSource());
        em.setPackagesToScan("com.project.model.notexisting");

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);

        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto", "create-or-update");
        properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));

        em.setJpaPropertyMap(properties);

        return em;
    }

    @Primary
    @Bean
    public DataSource userDataSource() {

        DriverManagerDataSource dataSource
                = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("user.jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.user"));
        dataSource.setPassword(env.getProperty("jdbc.pass"));

        return dataSource;
    }

}
</code>```

Body:
I´ve found a nice article that describes how to do that by defining multiple configuration classes pointing to different entity packages. It seems the only way is to do that programmatically.

For the existing database table where I don´t want to create or update any tables I´d have the following config with hibernate.hbm2ddl.auto set to none

@PropertySource({"classpath:existing-database.properties"})
@EnableJpaRepositories(basePackages = "com.project.model.existing")
@Configuration
public class ExistingDatabaseConfig {

    @Autowired
    private Environment env;

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean userEntityManager() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(userDataSource());
        em.setPackagesToScan("com.project.model.existing");

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);

        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto", "none");
        properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));

        em.setJpaPropertyMap(properties);

        return em;
    }

    @Primary
    @Bean
    public DataSource userDataSource() {

        DriverManagerDataSource dataSource
                = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("user.jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.user"));
        dataSource.setPassword(env.getProperty("jdbc.pass"));

        return dataSource;
    }

}

And for those entities that where tables should be created I´d have a separate config with hibernate.hbm2ddl.auto set to create-or-update:

@PropertySource({"classpath:not-existing-database.properties"})
@EnableJpaRepositories(basePackages = "com.project.model.notexisting")
@Configuration
public class NotExistingDatabaseConfig {

    @Autowired
    private Environment env;

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean userEntityManager() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(userDataSource());
        em.setPackagesToScan("com.project.model.notexisting");

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);

        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto", "create-or-update");
        properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));

        em.setJpaPropertyMap(properties);

        return em;
    }

    @Primary
    @Bean
    public DataSource userDataSource() {

        DriverManagerDataSource dataSource
                = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("user.jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.user"));
        dataSource.setPassword(env.getProperty("jdbc.pass"));

        return dataSource;
    }

}


问:
Can anyone tell me how to compile sass into css automatically?
I had to rewrite this every time I want to see a live preview.</p>

```<code>sass stylesheet.scss stylesheet.css
</code>```

答:
you can use this code

sass --watch file.sass:file.css

or

sass --watch foldersass:foldercss

ContentLicense: CC BY-SA 3.0

Body:
I had to rewrite this every time I want to see a live preview.

sass stylesheet.scss stylesheet.css


问:
Could not find or load main class in Eclipse Spring boot project
When i run a spring boot java project in eclipse , I am getting the below error.
Error: Could not find or load main class com.accenture.icoe.importdata.BatchImportMsApplication</p>

答:
Try below steps:

Step 1: Project -> Clean

Step 2: Try updating the project by right-clicking on it. Maven -> Update Project


问:
swift - cannot play a video loaded with AVAssetResourceLoaderDelegate
I'm trying to play a video with AVPlayer that was loaded inside AVAssetResourceLoaderDelegate but I always get a blank screen and the video never plays.

This is the code:

```<code>let asset = AVURLAsset(url: URL(string: "fakescheme://video.mp4")!)
asset.resourceLoader.setDelegate(ResourceLoaderDelegate(), queue: DispatchQueue.main)
let item = AVPlayerItem(asset: asset)
let player = AVPlayer(playerItem: item)

let playerLayer = AVPlayerLayer(player: self.player)
playerLayer!.frame = self.view.bounds;
self.view.layer.addSublayer(self.playerLayer!)
player!.play()

...

class ResourceLoaderDelegate: NSObject, AVAssetResourceLoaderDelegate, URLSessionDelegate, URLSessionDataDelegate, URLSessionTaskDelegate {
    public func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource resourceLoadingRequest: AVAssetResourceLoadingRequest) -> Bool {

        var newRequest = URLRequest(url: URL(string: "https://example.com/video.mp4")!)
        newRequest.allHTTPHeaderFields = resourceLoadingRequest.request.allHTTPHeaderFields

        let sessionTask = URLSession.shared.dataTask(with: newRequest) { data, response, error in
            resourceLoadingRequest.contentInformationRequest?.contentType = "video/mp4"
            resourceLoadingRequest.contentInformationRequest?.isByteRangeAccessSupported = true
            resourceLoadingRequest.contentInformationRequest?.contentLength = Int64(data.count)

            resourceLoadingRequest.response = response

            resourceLoadingRequest.dataRequest?.respond(with: data)
            resourceLoadingRequest.finishLoading()
        }

        sessionTask.resume()
        return true
    }
}
</code>```

This is the basic idea:

The fakescheme:// causes the resourceLoader() delegate to be called, inside it a new HTTP request is made to download the actual video.

And then it calls resourceLoadingRequest.dataRequest?.respond(with: data) that was supposed to cause AVPlayer to play the downloaded video.
The data variable is properly populated, but yet I always get a black screen.

The video file is also fine, it plays if I feed it directly into AVURLAsset().

I tried a million things and combinations, but can't make it play using the delegate. Any help will be greatly appreciated!

EDIT: I'll add some more info.

I tried doing this with an AES encrypted video where it uses 3 files - .m3u8, the encryption key and the .ts video.
I managed to make it download the .m3u8 and the key using the delegate, but again when I try to do it with the video file, I get black screen.

This leads me to thinking it may require the download to happen in portions, but I'm not sure how to properly do that.
I also can't find any documentation about it, such as - should you set the HTTP headers as if this is coming from a web server, should you set contentInformationRequest, etc. The delegate gets called 2 times:

```<code>// first time:
resourceLoadingRequest.dataRequest!.requestedLength == 2,
resourceLoadingRequest.dataRequest!.requestsAllDataToEndOfResource == false

// second time:
resourceLoadingRequest.dataRequest!.requestedLength == MAX_INT,
resourceLoadingRequest.dataRequest!.requestsAllDataToEndOfResource == true
</code>```

I'm not sure what to make of that - I give it the entire video both times, but no success.

答:
I finally got it to work. So there are 2 problems with the above code:

contentType should be AVFileType.mp4.rawValue, which is "public.mpeg-4". Passing "video/mp4" or another value breaks it

resourceLoadingRequest.dataRequest!.requestedLength Indeed needs to be respected, so the video file needs to be sent in chunks as requested.

This is the working delegate code:

```<code>// this IF is an ugly way to catch the first request to the delegate
// in this request you should populate the contentInformationRequest struct with the size of the video, etc
if (resourceLoadingRequest.dataRequest!.requestedLength == 2) {
    let bytes : [UInt8] = [0x0, 0x0] // these are the first 2 bytes of the video, as requested
    let data = Data(bytes: bytes, count: bytes.count)

    resourceLoadingRequest.contentInformationRequest?.contentType = AVFileType.mp4.rawValue // this is public.mpeg-4, video/mp4 does not work
    resourceLoadingRequest.contentInformationRequest?.isByteRangeAccessSupported = true
    resourceLoadingRequest.contentInformationRequest?.contentLength = Int64(videoSize)

    resourceLoadingRequest.dataRequest!.respond(with: data)
    resourceLoadingRequest.finishLoading()

    return true
}

// here we are at the second request. the OS may request the entire file, or a portion of it
// here we don't need to set any headers or contentInformationRequest, just reply with the requested data
// take a look at resourceLoadingRequest.dataRequest!.requestedLength, requestedOffset, currentOffset, requestsAllDataToEndOfResource
resourceLoadingRequest.dataRequest?.respond(with: data)
resourceLoadingRequest.finishLoading()

return true
</code>```

This is the code of the whole file for reference:

```<code>import Foundation
import AVKit

class ResourceLoaderDelegate: NSObject, AVAssetResourceLoaderDelegate, URLSessionDelegate, URLSessionDataDelegate, URLSessionTaskDelegate {
    public func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource resourceLoadingRequest: AVAssetResourceLoadingRequest) -> Bool {
        if ((resourceLoadingRequest.request.url?.absoluteString.contains(".mp4"))!) {
            // replace the fakeScheme and get the original video url
            var originalVideoURLComps = URLComponents(url: resourceLoadingRequest.request.url!, resolvingAgainstBaseURL: false)!
            originalVideoURLComps.scheme = "file"
            let originalVideoURL = originalVideoURLComps.url

            var videoSize = 0
            do {
                let value = try originalVideoURL!.resourceValues(forKeys: [.fileSizeKey])
                videoSize = value.fileSize!
            } catch {
                print("error getting video size")
            }

            if (resourceLoadingRequest.contentInformationRequest != nil) {
                // this is the first request where we should tell the OS what file is to be downloaded
                let bytes : [UInt8] = [0x0, 0x0]    // TODO: repeat .requestedLength times?
                let data = Data(bytes: bytes, count: bytes.count)

                resourceLoadingRequest.contentInformationRequest?.contentType = AVFileType.mp4.rawValue // this is public.mpeg-4, video/mp4 does not work
                resourceLoadingRequest.contentInformationRequest?.isByteRangeAccessSupported = true
                resourceLoadingRequest.contentInformationRequest?.contentLength = Int64(videoSize)

                resourceLoadingRequest.dataRequest!.respond(with: data)
                resourceLoadingRequest.finishLoading()

                return true
            }

            // this is the second request where the actual file is to be downloaded

            let requestedLength = resourceLoadingRequest.dataRequest!.requestedLength
            let requestedOffset = resourceLoadingRequest.dataRequest!.requestedOffset
            let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: requestedLength)

            let inputStream = InputStream(url: originalVideoURL!)   // TODO: keep the stream open until a new file is requested?
            inputStream!.open()

            if (requestedOffset > 0) {
                // move the stream pointer to the requested position
                let buffer2 = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(requestedOffset))
                inputStream!.read(buffer2, maxLength: Int(requestedOffset)) // TODO: the requestedOffset may be int64, but this gets truncated to int!
                buffer2.deallocate()
            }
            inputStream!.read(buffer, maxLength: requestedLength)

            // decrypt the video
            if (requestedOffset == 0) { // TODO: this == 0 may not always work?
                // if you use custom encryption, you can decrypt the video here, buffer[] holds the bytes
            }

            let data = Data(bytes: buffer, count: requestedLength)

            resourceLoadingRequest.dataRequest?.respond(with: data)
            resourceLoadingRequest.finishLoading()

            buffer.deallocate()
            inputStream!.close()

            return true
        }

        return false
    }
}
</code>```

Body:
I'm trying to play a video with AVPlayer that was loaded inside AVAssetResourceLoaderDelegate but I always get a blank screen and the video never plays.

This is the code:

let asset = AVURLAsset(url: URL(string: "fakescheme://video.mp4")!)
asset.resourceLoader.setDelegate(ResourceLoaderDelegate(), queue: DispatchQueue.main)
let item = AVPlayerItem(asset: asset)
let player = AVPlayer(playerItem: item)

let playerLayer = AVPlayerLayer(player: self.player)
playerLayer!.frame = self.view.bounds;
self.view.layer.addSublayer(self.playerLayer!)
player!.play()

...

class ResourceLoaderDelegate: NSObject, AVAssetResourceLoaderDelegate, URLSessionDelegate, URLSessionDataDelegate, URLSessionTaskDelegate {
    public func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource resourceLoadingRequest: AVAssetResourceLoadingRequest) -> Bool {

        var newRequest = URLRequest(url: URL(string: "https://example.com/video.mp4")!)
        newRequest.allHTTPHeaderFields = resourceLoadingRequest.request.allHTTPHeaderFields

        let sessionTask = URLSession.shared.dataTask(with: newRequest) { data, response, error in
            resourceLoadingRequest.contentInformationRequest?.contentType = "video/mp4"
            resourceLoadingRequest.contentInformationRequest?.isByteRangeAccessSupported = true
            resourceLoadingRequest.contentInformationRequest?.contentLength = Int64(data.count)

            resourceLoadingRequest.response = response

            resourceLoadingRequest.dataRequest?.respond(with: data)
            resourceLoadingRequest.finishLoading()
        }

        sessionTask.resume()
        return true
    }
}

This is the basic idea:

The fakescheme:// causes the resourceLoader() delegate to be called, inside it a new HTTP request is made to download the actual video.

And then it calls resourceLoadingRequest.dataRequest?.respond(with: data) that was supposed to cause AVPlayer to play the downloaded video.
The data variable is properly populated, but yet I always get a black screen.

The video file is also fine, it plays if I feed it directly into AVURLAsset().

I tried a million things and combinations, but can't make it play using the delegate. Any help will be greatly appreciated!

EDIT: I'll add some more info.

I tried doing this with an AES encrypted video where it uses 3 files - .m3u8, the encryption key and the .ts video.
I managed to make it download the .m3u8 and the key using the delegate, but again when I try to do it with the video file, I get black screen.

This leads me to thinking it may require the download to happen in portions, but I'm not sure how to properly do that.
I also can't find any documentation about it, such as - should you set the HTTP headers as if this is coming from a web server, should you set contentInformationRequest, etc. The delegate gets called 2 times:

// first time:
resourceLoadingRequest.dataRequest!.requestedLength == 2,
resourceLoadingRequest.dataRequest!.requestsAllDataToEndOfResource == false

// second time:
resourceLoadingRequest.dataRequest!.requestedLength == MAX_INT,
resourceLoadingRequest.dataRequest!.requestsAllDataToEndOfResource == true

I'm not sure what to make of that - I give it the entire video both times, but no success.

Body:
I finally got it to work. So there are 2 problems with the above code:

contentType should be AVFileType.mp4.rawValue, which is "public.mpeg-4". Passing "video/mp4" or another value breaks it

resourceLoadingRequest.dataRequest!.requestedLength Indeed needs to be respected, so the video file needs to be sent in chunks as requested.

This is the working delegate code:

// this IF is an ugly way to catch the first request to the delegate
// in this request you should populate the contentInformationRequest struct with the size of the video, etc
if (resourceLoadingRequest.dataRequest!.requestedLength == 2) {
    let bytes : [UInt8] = [0x0, 0x0] // these are the first 2 bytes of the video, as requested
    let data = Data(bytes: bytes, count: bytes.count)

    resourceLoadingRequest.contentInformationRequest?.contentType = AVFileType.mp4.rawValue // this is public.mpeg-4, video/mp4 does not work
    resourceLoadingRequest.contentInformationRequest?.isByteRangeAccessSupported = true
    resourceLoadingRequest.contentInformationRequest?.contentLength = Int64(videoSize)

    resourceLoadingRequest.dataRequest!.respond(with: data)
    resourceLoadingRequest.finishLoading()

    return true
}

// here we are at the second request. the OS may request the entire file, or a portion of it
// here we don't need to set any headers or contentInformationRequest, just reply with the requested data
// take a look at resourceLoadingRequest.dataRequest!.requestedLength, requestedOffset, currentOffset, requestsAllDataToEndOfResource
resourceLoadingRequest.dataRequest?.respond(with: data)
resourceLoadingRequest.finishLoading()

return true

This is the code of the whole file for reference:

import Foundation
import AVKit

class ResourceLoaderDelegate: NSObject, AVAssetResourceLoaderDelegate, URLSessionDelegate, URLSessionDataDelegate, URLSessionTaskDelegate {
    public func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource resourceLoadingRequest: AVAssetResourceLoadingRequest) -> Bool {
        if ((resourceLoadingRequest.request.url?.absoluteString.contains(".mp4"))!) {
            // replace the fakeScheme and get the original video url
            var originalVideoURLComps = URLComponents(url: resourceLoadingRequest.request.url!, resolvingAgainstBaseURL: false)!
            originalVideoURLComps.scheme = "file"
            let originalVideoURL = originalVideoURLComps.url

            var videoSize = 0
            do {
                let value = try originalVideoURL!.resourceValues(forKeys: [.fileSizeKey])
                videoSize = value.fileSize!
            } catch {
                print("error getting video size")
            }

            if (resourceLoadingRequest.contentInformationRequest != nil) {
                // this is the first request where we should tell the OS what file is to be downloaded
                let bytes : [UInt8] = [0x0, 0x0]    // TODO: repeat .requestedLength times?
                let data = Data(bytes: bytes, count: bytes.count)

                resourceLoadingRequest.contentInformationRequest?.contentType = AVFileType.mp4.rawValue // this is public.mpeg-4, video/mp4 does not work
                resourceLoadingRequest.contentInformationRequest?.isByteRangeAccessSupported = true
                resourceLoadingRequest.contentInformationRequest?.contentLength = Int64(videoSize)

                resourceLoadingRequest.dataRequest!.respond(with: data)
                resourceLoadingRequest.finishLoading()

                return true
            }

            // this is the second request where the actual file is to be downloaded

            let requestedLength = resourceLoadingRequest.dataRequest!.requestedLength
            let requestedOffset = resourceLoadingRequest.dataRequest!.requestedOffset
            let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: requestedLength)

            let inputStream = InputStream(url: originalVideoURL!)   // TODO: keep the stream open until a new file is requested?
            inputStream!.open()

            if (requestedOffset > 0) {
                // move the stream pointer to the requested position
                let buffer2 = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(requestedOffset))
                inputStream!.read(buffer2, maxLength: Int(requestedOffset)) // TODO: the requestedOffset may be int64, but this gets truncated to int!
                buffer2.deallocate()
            }
            inputStream!.read(buffer, maxLength: requestedLength)

            // decrypt the video
            if (requestedOffset == 0) { // TODO: this == 0 may not always work?
                // if you use custom encryption, you can decrypt the video here, buffer[] holds the bytes
            }

            let data = Data(bytes: buffer, count: requestedLength)

            resourceLoadingRequest.dataRequest?.respond(with: data)
            resourceLoadingRequest.finishLoading()

            buffer.deallocate()
            inputStream!.close()

            return true
        }

        return false
    }
}


问:
Java Single Client Thread for multiple Server communication for IOT project
I want to create a client Thread for TCP IP communication. But the client thread should be able to communicate with minimum 10000 servers in the same time. As I want to communicate with millions of servers(Practically GPRS based field devices), its not a good practice to start millions of client threads and manage it.
I have tried with NIO Selector to do this. But I found that its only possible for the server thread.
ThreadPoolExecutor also I have tried. That also failed to manage huge number of connections in the same time.
Please give a good suggestion to manage huge number of servers without starting too many threads.</p>

答:
If you need to perform network I/O with pure Java, you have three options: old I/O, new I/O (nio) and new I/O 2 (nio2). Old I/O uses blocking calls, so basically you'll need one thread per connection. You don't want to do that, so you should use nio or nio2. There's actually no restriction on selector to be usable with only server, you can use it for client connections.

Also please note that using nio or nio2 is not the easiest task in the world. Consider using netty library which was created exactly for your use-case: to help writing scalable network applications. It's not the easiest library to use as well, but I still recommend it, because it implements a lot of things for you. Also there are a lot of protocol implementations for netty, so chances are, you won't even need to write that much code.

Most of network examples are about servers indeed, because that's what people generally write. But it's perfectly possible to write non-blocking network clients in the same way.


问:
How to unsubscribe to all the subscriptions on param change in angular
I am developing page which can display job details of a job, for this purpose I am using NGRX store to dispatch actions and subscribing to it to display the data like below

```<code>this.store.dispatch(new LoadJobDetails(jobIdsObject));
this.subs.add(
    this.store.pipe(select(state => state.chatbotStoreData.jobDetailsObject)).subscribe(
      (data) => {
          if(data) {
            this.jobDetails = data;
            this.getJobHomeSteps();
          }
      }
    )
);

getJobHomeSteps() {
this.store.dispatch(new LoadJobStepsDetails(this.jobId));
this.subs.add(
    this.store.pipe(select(state => state.chatbotStoreData.jobHomeStepsDetailsObject)).subscribe(
      (data) => {
          if(data) {
            this.jobStepsDetails = data;
          }
      }
    )
);
}

</code>```

and in ngondestroy I am unsubscribing to all the subscriptions like below,

```<code>ngOnDestroy(){
this.subs.unsubscribe();
}
</code>```

This is working fine, but I have sidenav menu with list of jobs, on click of each job, job details page update with clicked job details. Here, on click of each job, intial subscription is happening many times and dispatch API's are calling multiple times because I can't able to unsubscribe previous job subscriptions.

How can I unsubscribe to all the subscriptions in that particular component on params change, or else any other way I can solve this problem. Any help would be appreciated, thanks!!!

答:
```<code> getSearchResultsObservable(control: FormControl): Observable<any> {
    return control.valueChanges.pipe(
      debounceTime(100),
      distinctUntilChanged(),
      switchMap(data => this.getSearchResults(control.value))
    );
  }
</code>```

Body:
I am developing page which can display job details of a job, for this purpose I am using NGRX store to dispatch actions and subscribing to it to display the data like below

this.store.dispatch(new LoadJobDetails(jobIdsObject));
this.subs.add(
    this.store.pipe(select(state => state.chatbotStoreData.jobDetailsObject)).subscribe(
      (data) => {
          if(data) {
            this.jobDetails = data;
            this.getJobHomeSteps();
          }
      }
    )
);

getJobHomeSteps() {
this.store.dispatch(new LoadJobStepsDetails(this.jobId));
this.subs.add(
    this.store.pipe(select(state => state.chatbotStoreData.jobHomeStepsDetailsObject)).subscribe(
      (data) => {
          if(data) {
            this.jobStepsDetails = data;
          }
      }
    )
);
}

and in ngondestroy I am unsubscribing to all the subscriptions like below,

ngOnDestroy(){
this.subs.unsubscribe();
}

This is working fine, but I have sidenav menu with list of jobs, on click of each job, job details page update with clicked job details. Here, on click of each job, intial subscription is happening many times and dispatch API's are calling multiple times because I can't able to unsubscribe previous job subscriptions.

How can I unsubscribe to all the subscriptions in that particular component on params change, or else any other way I can solve this problem. Any help would be appreciated, thanks!!!


问:
Modeling many to many relations with postgreSQL
I work in cattle production and I am learning about database design with postgreSQL. Now I am working on an entity attribute relationship model for a database that allows to register the allocation of the pastures in which cattle graze. In the logic of this business an animal can be assigned to several grazing groups during its life. Each grazing group in turn has a duration and is composed of several pastures in which the animals graze according to a rotation calendar. In this way, at a specific time, animals graze in a pasture that is part of a grazing group.

I have a situation in which many grazing groups can be assigned to many animals as well as many pastures. Trying to model this problem I find a fan trap because there are two one-to-many relationships for a single table. According to this, I would like to ask you about how one can deal with this type of relationship in which one entity relates to two others in the form of many-to-many relationships.

I put a diagram on the problem.

model diagram

Thanks

答:
Traditionally, using a link table (the ones you call assignment) between two tables has been the right way to do many-to-many relationships. Other choices include having an ARRAY of animal ids in grazing group, using JSONB fields etc. Those might prove to be problematic later, so I'd recommend going the old way.

If you want to keep track of history, you can add an active boolean field (to the link table probably) to indicate which assignment is current or have a start date and end date for each assignment. This also makes it possible to plan future assignments. To make things easier, make VIEWs showing only current assignment and further VIEWs to show JOINed tables.

Since there's no clear question in your post, I'd just say you are going the right way.


问:
What does a lock statement do under the hood?
I see that for using objects which are not thread safe we wrap the code with a lock like this:

```<code>private static readonly Object obj = new Object();

lock (obj)
{
    // thread unsafe code
}
</code>```

So, what happens when multiple threads access the same code (let's assume that it is running in a ASP.NET web application). Are they queued? If so how long will they wait?

What is the performance impact because of using locks?

答:
The lock statement is translated by C# 3.0 to the following:

```<code>var temp = obj;

Monitor.Enter(temp);

try
{
    // body
}
finally
{
    Monitor.Exit(temp);
}
</code>```

In C# 4.0 this has changed and it is now generated as follows:

```<code>bool lockWasTaken = false;
var temp = obj;
try
{
    Monitor.Enter(temp, ref lockWasTaken);
    // body
}
finally
{
    if (lockWasTaken)
    {
        Monitor.Exit(temp);
    }
}
</code>```

You can find more info about what Monitor.Enter does here. To quote MSDN:

Use Enter to acquire the Monitor on
  the object passed as the parameter. If
  another thread has executed an Enter
  on the object but has not yet executed
  the corresponding Exit, the current
  thread will block until the other
  thread releases the object. It is
  legal for the same thread to invoke
  Enter more than once without it
  blocking; however, an equal number of
  Exit calls must be invoked before
  other threads waiting on the object
  will unblock.

The Monitor.Enter method will wait infinitely; it will not time out.

Body:
I see that for using objects which are not thread safe we wrap the code with a lock like this:

private static readonly Object obj = new Object();

lock (obj)
{
    // thread unsafe code
}

So, what happens when multiple threads access the same code (let's assume that it is running in a ASP.NET web application). Are they queued? If so how long will they wait?

What is the performance impact because of using locks?

Body:
The lock statement is translated by C# 3.0 to the following:

var temp = obj;

Monitor.Enter(temp);

try
{
    // body
}
finally
{
    Monitor.Exit(temp);
}

In C# 4.0 this has changed and it is now generated as follows:

bool lockWasTaken = false;
var temp = obj;
try
{
    Monitor.Enter(temp, ref lockWasTaken);
    // body
}
finally
{
    if (lockWasTaken)
    {
        Monitor.Exit(temp);
    }
}

You can find more info about what Monitor.Enter does here. To quote MSDN:

Use Enter to acquire the Monitor on
  the object passed as the parameter. If
  another thread has executed an Enter
  on the object but has not yet executed
  the corresponding Exit, the current
  thread will block until the other
  thread releases the object. It is
  legal for the same thread to invoke
  Enter more than once without it
  blocking; however, an equal number of
  Exit calls must be invoked before
  other threads waiting on the object
  will unblock.

The Monitor.Enter method will wait infinitely; it will not time out.


问:
FERNET_KEY configuration is missing when creating a new environment with the same DAGS
I'm using Composer (Airflow) in Google Cloud. I want to create a new environment and take my same DAGs and Variables from the old environment into the new one.

To accomplish this I do the following:

I check several of my variables and export them to a JSON file.

In my new environment I import this same JSON file.

I use gsutil and upload my same DAGs to the new environment

However, in the new environment, all of my DAGs are breaking, due to a FERNET_KEY configuration is missing. My best guess is that this is related to importing my variables that were encrypted using a separate Fernet key but I'm unsure.

Has anyone encountered this issue before? If so, how did you fix it?

答:
As per documentation, the Fernet Key is generated by Composer and it is intended to be unique. The fernet key value can be retrieved from the Composer Airflow Configuration (Composer bucket -> airflow.cfg). You need to check if fernet_key exists.

There is a known issue due to a race condition in binary rollouts that can cause a new fernet key to be set in the webserver, making previously encrypted values in the metadata database unable to be decrypted.

What you can try, is to recreate the key Composer object path in the Airflow UI under Admin -> Variables.


问:
Run-length decompression using C++
I have a text file with a string which I encoded.

Let's say it is: aaahhhhiii kkkjjhh ikl wwwwwweeeett

Here the code for encoding, which works perfectly fine:

```<code>void Encode(std::string &inputstring, std::string &outputstring)
{
    for (int i = 0; i < inputstring.length(); i++) {
        int count = 1;
        while (inputstring[i] == inputstring[i+1]) {
            count++;
            i++;
        }
        if(count <= 1) {
            outputstring += inputstring[i];
        } else {
            outputstring += std::to_string(count);
            outputstring += inputstring[i];
        }
    }
}
</code>```

Output is as expected: 3a4h3i 3k2j2h ikl 6w4e2t

Now, I'd like to decompress the output - back to original.

And I am struggling with this since a couple days now.

My idea so far:

```<code>void Decompress(std::string &compressed, std::string &original)
{
    char currentChar = 0;
    auto n = compressed.length();
    for(int i = 0; i < n; i++) {

        currentChar = compressed[i++];

        if(compressed[i] <= 1) {
            original += compressed[i];
        } else if (isalpha(currentChar)) {
            //
        } else {
            //
            int number = isnumber(currentChar).....
            original += number;
        }
    }
}
</code>```

I know my Decompress function seems a bit messy, but I am pretty lost with this one.
Sorry for that.

Maybe there is someone out there at stackoverflow who would like to help a lost and beginner soul.

Thanks for any help, I appreciate it.

答:
```<code>#include "string"
#include "iostream"

void Encode(std::string& inputstring, std::string& outputstring)
{
    for (unsigned int i = 0; i < inputstring.length(); i++) {
        int count = 1;
        while (inputstring[i] == inputstring[i + 1]) {
            count++;
            i++;
        }
        if (count <= 1) {
            outputstring += inputstring[i];
        }
        else {
            outputstring += std::to_string(count);
            outputstring += inputstring[i];
        }
    }
}

bool alpha_or_space(const char c)
{
    return isalpha(c) || c == ' ';
}

void Decompress(std::string& compressed, std::string& original)
{
    size_t i = 0;
    size_t repeat;
    while (i < compressed.length())
    {
        // normal alpha charachers
        while (alpha_or_space(compressed[i]))
            original.push_back(compressed[i++]);

        // repeat number
        repeat = 0;
        while (isdigit(compressed[i]))
            repeat = 10 * repeat + (compressed[i++] - '0');

        // unroll releat charachters
        auto char_to_unroll = compressed[i++];
        while (repeat--)
            original.push_back(char_to_unroll);
    }
}

int main()
{
    std::string deco, outp, inp = "aaahhhhiii kkkjjhh ikl wwwwwweeeett";

    Encode(inp, outp);
    Decompress(outp, deco);

    std::cout << inp << std::endl << outp << std::endl<< deco;

    return 0;
}
</code>```

Title: Run-length decompression using C++

Body:
I have a text file with a string which I encoded.

Let's say it is: aaahhhhiii kkkjjhh ikl wwwwwweeeett

Here the code for encoding, which works perfectly fine:

void Encode(std::string &inputstring, std::string &outputstring)
{
    for (int i = 0; i < inputstring.length(); i++) {
        int count = 1;
        while (inputstring[i] == inputstring[i+1]) {
            count++;
            i++;
        }
        if(count <= 1) {
            outputstring += inputstring[i];
        } else {
            outputstring += std::to_string(count);
            outputstring += inputstring[i];
        }
    }
}

Output is as expected: 3a4h3i 3k2j2h ikl 6w4e2t

Now, I'd like to decompress the output - back to original.

And I am struggling with this since a couple days now.

My idea so far:

void Decompress(std::string &compressed, std::string &original)
{
    char currentChar = 0;
    auto n = compressed.length();
    for(int i = 0; i < n; i++) {

        currentChar = compressed[i++];

        if(compressed[i] <= 1) {
            original += compressed[i];
        } else if (isalpha(currentChar)) {
            //
        } else {
            //
            int number = isnumber(currentChar).....
            original += number;
        }
    }
}

I know my Decompress function seems a bit messy, but I am pretty lost with this one.
Sorry for that.

Maybe there is someone out there at stackoverflow who would like to help a lost and beginner soul.

Thanks for any help, I appreciate it.


问:
SQL stored proc using where in statement
I am trying to inserting data from a table to another table. But I need using multiple specific IDs in where clause. And, I need to define these IDs while running the proc. The query is below,

```<code>CREATE PROCEDURE insert_hh
@id int
AS
BEGIN
SET IDENTITY_INSERT test_HH ON
INSERT INTO test_HH
(ID,Beneficiary_Name,Family_Members,
[M_50_yrs],
[F_50_yrs],
[M_50_18],
[F_50_18],
[M_18_15],
[F_18_15],
[M_15_5],
[F_15_5],
[M_5_2],
[F_5_2],
[M_2],
[F_2],
Beneficiary_Status,
Reason_of_Rejection)
SELECT ID,Beneficiary_Name,Family_Members,
[M_50_yrs],
[F_50_yrs],
[M_50_18],
[F_50_18],
[M_18_15],
[F_18_15],
[M_15_5],
[F_15_5],
[M_5_2],
[F_5_2],
[M_2],
[F_2],
Beneficiary_Status,
Reason_of_Rejection
FROM HH
WHERE ID IN ((@id))
SET IDENTITY_INSERT test_HH OFF
END
</code>```

For now, I can insert only one ID for each time. Can you help me to insert multiple IDs in the same proc?
Thanks.

答:
```<code>CREATE PROCEDURE insert_hh
@id NVARCHAR(MAX)
AS
BEGIN
SET IDENTITY_INSERT test_HH ON

INSERT INTO test_HH
(ID,Beneficiary_Name,Family_Members,[M_50_yrs],[F_50_yrs],[M_50_18],[F_50_18],
[M_18_15],[F_18_15],[M_15_5],[F_15_5],[M_5_2],[F_5_2],[M_2],[F_2],
Beneficiary_Status,Reason_of_Rejection)

SELECT ID,Beneficiary_Name,Family_Members,[M_50_yrs],[F_50_yrs],[M_50_18],
[F_50_18],[M_18_15],[F_18_15],[M_15_5],[F_15_5],[M_5_2],[F_5_2],[M_2],[F_2],
Beneficiary_Status,Reason_of_Rejection

FROM HH
CROSS APPLY STRING_SPLIT(@id, ',')
WHERE HH.ID = value

SET IDENTITY_INSERT test_HH OFF
END
</code>```

modelling fiddle

Pay attention - the parameter datatype is changed.

Body:
I am trying to inserting data from a table to another table. But I need using multiple specific IDs in where clause. And, I need to define these IDs while running the proc. The query is below,

CREATE PROCEDURE insert_hh
@id int
AS
BEGIN
SET IDENTITY_INSERT test_HH ON
INSERT INTO test_HH
(ID,Beneficiary_Name,Family_Members,
[M_50_yrs],
[F_50_yrs],
[M_50_18],
[F_50_18],
[M_18_15],
[F_18_15],
[M_15_5],
[F_15_5],
[M_5_2],
[F_5_2],
[M_2],
[F_2],
Beneficiary_Status,
Reason_of_Rejection)
SELECT ID,Beneficiary_Name,Family_Members,
[M_50_yrs],
[F_50_yrs],
[M_50_18],
[F_50_18],
[M_18_15],
[F_18_15],
[M_15_5],
[F_15_5],
[M_5_2],
[F_5_2],
[M_2],
[F_2],
Beneficiary_Status,
Reason_of_Rejection
FROM HH
WHERE ID IN ((@id))
SET IDENTITY_INSERT test_HH OFF
END

For now, I can insert only one ID for each time. Can you help me to insert multiple IDs in the same proc?
Thanks.

Body:
CREATE PROCEDURE insert_hh
@id NVARCHAR(MAX)
AS
BEGIN
SET IDENTITY_INSERT test_HH ON

INSERT INTO test_HH
(ID,Beneficiary_Name,Family_Members,[M_50_yrs],[F_50_yrs],[M_50_18],[F_50_18],
[M_18_15],[F_18_15],[M_15_5],[F_15_5],[M_5_2],[F_5_2],[M_2],[F_2],
Beneficiary_Status,Reason_of_Rejection)

SELECT ID,Beneficiary_Name,Family_Members,[M_50_yrs],[F_50_yrs],[M_50_18],
[F_50_18],[M_18_15],[F_18_15],[M_15_5],[F_15_5],[M_5_2],[F_5_2],[M_2],[F_2],
Beneficiary_Status,Reason_of_Rejection

FROM HH
CROSS APPLY STRING_SPLIT(@id, ',')
WHERE HH.ID = value

SET IDENTITY_INSERT test_HH OFF
END

modelling fiddle

Pay attention - the parameter datatype is changed.


问:
MySQL query to assign a unique random number to each row
I wish to attach a column to my table which will be a random number from a sequential list = to the number of rows.

So, if my table had 999 rows, then the numbers 1 to 999 would be assigned randomly and uniquely.

Now, I figured that I could add a dummy TempRandomColumn=Rand(), sort by that and add the numbers sequentially using PHP. But that means 999 MySQL statements.

Is there a way to do this using a single MySQL statement?

Thanks for any pointers.

答:
```<code>SET @r := 0;
UPDATE  items2
SET     author_id = (@r := @r + 1)
ORDER BY
        RAND()
</code>```

OwnerDisplayName: Smokey McTokes

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Quassnoi


问:
Sharing data between android users
I'm having trouble understanding the top level of abstraction of this problem.

The Problem:
Users A and B download application X. A wants to send application-specific data to B. How does user A link with B?

My incredibly messy solution:
 - User A clicks a button on the application that opens up a list of contacts. user A selects user B from the list. User B's email address was stored in A's address book. Application creates a sort of "share ID"  and sends it to user B via that email address. User B's application gets that ID from the mail, then User A and B use the share ID to connect to a server and share between each other via the sserver.

There must be a better way? The two problems are:
1. It shouldn't need a server (should it? could it be free?)
2. There must be better ways of the users connecting to each other than sending ID's or links etc by gmail.

This solution should be so so simple, but I can't get my head round it. If this question is not sufficient to get a good answer, please please tell me what I need to do to get into the way of thinking about how mobile users can interract with each other as simply as possible, with as few clicks as possible, (Mobile 2.0 or whatever the modern day thing is!)

For example: A mother and a child have an android smart phone. They each download the "ChildLeash" app. Child wishes to configure the app to send updates to Mother, so that Mother can keep track of Child's location and so on. The problem is some how Child needs to tell the app what location Mother is at for the data to be sent to. What is a user-friendly way for Child to Identify Mother's phone? (Mother's IP address? Phone number? Email address? OpenIDs? NFC/Bluetooth?) So that it can then communicate?

答:
You could use push notifications, as provided by the Android Cloud to Device Messaging Framework. There's an Android blog post about this. Problem is, this seems beta and not yet available to all developers (you need a specific signup).

Regarding "IP Adresss", P2P and such, this generally won't work. See: Is peer-to-peer communication over 3G/4G possible for smart phones?

If messages are not urgent, then you could use AlarmManager to have your app wake up every hour or so, and check for new messages by connecting to a server. Not sure that would work for your "ChildLeash" example. Another similar solution would be to use a Service to poll the server.

Title: Sharing data between android users


问:
Lxml xpath returns an empty array
Well guys, Im scraping : https://twitter.com/iForex_com/status/1019547735614255104

I would appreciate it if someone can help me out

```<code>import requests
from lxml import html

        finalurl = f"https://www.twitter.com/user/status/{id}"
        response = requests.get(finalurl,allow_redirects=True)
            tree = html.fromstring(response.content)
            print("getting photolink")
            postPhotoLink = tree.xpath('//*[@id="react-root"]/div/div/div/main/div/div/div/div[1]/div/div[2]/div/section/div/div/div/div[1]/div/article/div/div[4]/div/div/div/a/div/div[2]/div/img/@src')
                        print(postPhotoLink)
</code>```

Result :

getting photolink
[]

答:
Try with this XPath, it should work :

```<code>(//img[@class='css-9pa8cd'])[2]/@src
</code>```

If it doesn't work, try with this XPath since the code changes once you get the html.

```<code>//img[@data-aria-label-part='']/@src
</code>```

Selenium isn't required.

Title: Lxml xpath returns an empty array

Body:
Well guys, Im scraping : https://twitter.com/iForex_com/status/1019547735614255104

I would appreciate it if someone can help me out

import requests
from lxml import html

        finalurl = f"https://www.twitter.com/user/status/{id}"
        response = requests.get(finalurl,allow_redirects=True)
            tree = html.fromstring(response.content)
            print("getting photolink")
            postPhotoLink = tree.xpath('//*[@id="react-root"]/div/div/div/main/div/div/div/div[1]/div/div[2]/div/section/div/div/div/div[1]/div/article/div/div[4]/div/div/div/a/div/div[2]/div/img/@src')
                        print(postPhotoLink)

Result :

getting photolink
[]

Body:
Try with this XPath, it should work :

(//img[@class='css-9pa8cd'])[2]/@src

If it doesn't work, try with this XPath since the code changes once you get the html.

//img[@data-aria-label-part='']/@src

Selenium isn't required.


问:
How to add white space at the last position of a string?
I am trying to add 2 white space at the last position of a string but when I set this in a label I found no space. But if I added 2 white space with another character, it works ok. Then I tried to add 2 white space with some extra character and then trim these extra characters. But for all these case I observed no space when I placed this in a text label. I am trying this for the right alignment.

```<code>let name: String = self.cityModelArr[indexPos].countryShortName+"  12"
let endIndex = name.index(name.endIndex, offsetBy: -2)
let truncated = String(name[..<endIndex])
self.testLabel.text = truncated
</code>```

I have tried some more solutions from the internet but failed to achieve my goal.

答:
You may use \t at end of string to add space.</p>

```<code>self.testLabel.text = "\(self.cityModelArr[indexPos].countryShortName)\t"
</code>```

Body:
I am trying to add 2 white space at the last position of a string but when I set this in a label I found no space. But if I added 2 white space with another character, it works ok. Then I tried to add 2 white space with some extra character and then trim these extra characters. But for all these case I observed no space when I placed this in a text label. I am trying this for the right alignment.

let name: String = self.cityModelArr[indexPos].countryShortName+"  12"
let endIndex = name.index(name.endIndex, offsetBy: -2)
let truncated = String(name[..<endIndex])
self.testLabel.text = truncated

I have tried some more solutions from the internet but failed to achieve my goal.

Body:
You may use \t at end of string to add space.

self.testLabel.text = "\(self.cityModelArr[indexPos].countryShortName)\t"


问:
CakePHP 2 not recognizing file uploaded via ajax
I'm having a terrible time trying to pass a file from a view to a controller using Ajax with CakePHP 2.10.7.

My view has the following input:

<input type="file" id="background_image_file" name="background_image_file" style="display:none;" accept="image/png, image/jpeg">
```

<p>And my JavaScript looks like this:</p>

<pre class="lang-js prettyprint-override"><code>$('#staff-bg-image-container').on('click', () => $('#background_image_file').trigger('click') );
$('#background_image_file').on('change', upload_background);

function upload_background()
{
    var file = this.files[0];
    data = new FormData();
    data.append('file', file);

    $.ajax({
        url: '/staff/ajaxUploadBackgroundImage',
        type: 'POST',
        data: data,
        contentType: false,
        processData: false,
        cache: false,
        success: function(res){
            console.log(res);
        },
    });
}
</code>```

But when I send this request to the controller the $this->request->data array is empty. I have tried doing this using XMLHttpRequest instead of jQuery as well, but the result was the same. Why is CakePHP not recognizing the file?

Edit: I can access the file using the $_FILES globals array. However, according to the CakePHP documentation it should be present in the request data array. I would appreciate if you could tell me why it is not.

答:
What I would do in this case, first of all you are trying to upload and save with just one onchange event. In this case, my approach would be to create a button which you would do an onclick event in order to save the image that you just uploaded. Therefore, the markup should be like this :

```<code>  <div id="staff-bg-image-container">
    <img src='/files/<?php echo $data['staff']['background_image_file']; ?>' id="bgimg" class="profile_image" width="450" alt="Image" />
 <!-- Image uploading box exists here. -->
  </div>
 <input type="file" id="background_image_file" name="background_image_file"
   accept="image/png, image/jpeg"  onchange="readImage(this);">
  <button id="saveimg" style="margin-top: 10px;" class="btn-web-admin btn-save
   upload_img"><?php echo 'Save Image'; ?>
    </button>
</code>```

Your Javascript therefore should go like:

```<code>  function readImage(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
                $('#background_image_file').attr('src',e.target.result); //
               setting ur image here
               $('#saveimg').show();
       };
       reader.readAsDataURL(input.files[0]);   // Read in the image file as a data URL.             }
   }
}

   $('#saveimg').on('click', function(e){
            e.preventDefault();
            var _validFileExtensions = [".jpg", ".jpeg", ".gif", ".png"];
            var validate_img = false;
            var sFileName = $('#background_image_file').val();
            for (var j = 0; j < _validFileExtensions.length; j++){
                var sCurExtension = _validFileExtensions[j];
                if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                    validate_img = true;
                    break;
                }
            }

            if(validate_img){
                var data = new FormData();
                var file = $('#background_image_file')files[0].;

                data.append('file');
                $.ajax({
                    type: "POST",
                    url: "/staff/ajaxUploadBackgroundImage",
                    data: data,
                    contentType: false,
                    cache: false,
                    processData: false,
                    success: function(data) {
                        var img = new Image();

                         img.onload = function() {
                            var width = img.width;
                            var height = img.height;
                         }
                        img.src = ($('#bgimg')[0]).src;
                    },
                    error: function(a, b, c){
                        console.log('Select a valid image.');
                        console.log(a);
                        console.log(b);
                        console.log(c);
                        return false;
                    }
                });
            }else{
                console.log('Select a valid image.');
            }
    });
</code>```

Also a last hint that I would give you as you are using a FormData, in your Controller instead of having a $this->request->data, I would advise you to use
$this->request->form as you are supossedly uploading an image with an Ajax request.

```<code>     $dataimg = $this->request->form['file'];
     $this->set('image', $dataimg);
</code>```

I hope that can help you to get a hint of why it is not working.

Body:
I'm having a terrible time trying to pass a file from a view to a controller using Ajax with CakePHP 2.10.7.

My view has the following input:

<input type="file" id="background_image_file" name="background_image_file" style="display:none;" accept="image/png, image/jpeg">

And my JavaScript looks like this:

$('#staff-bg-image-container').on('click', () => $('#background_image_file').trigger('click') );
$('#background_image_file').on('change', upload_background);

function upload_background()
{
    var file = this.files[0];
    data = new FormData();
    data.append('file', file);

    $.ajax({
        url: '/staff/ajaxUploadBackgroundImage',
        type: 'POST',
        data: data,
        contentType: false,
        processData: false,
        cache: false,
        success: function(res){
            console.log(res);
        },
    });
}

But when I send this request to the controller the $this->request->data array is empty. I have tried doing this using XMLHttpRequest instead of jQuery as well, but the result was the same. Why is CakePHP not recognizing the file?

Edit: I can access the file using the $_FILES globals array. However, according to the CakePHP documentation it should be present in the request data array. I would appreciate if you could tell me why it is not.

Body:
What I would do in this case, first of all you are trying to upload and save with just one onchange event. In this case, my approach would be to create a button which you would do an onclick event in order to save the image that you just uploaded. Therefore, the markup should be like this :

  <div id="staff-bg-image-container">
    <img src='/files/<?php echo $data['staff']['background_image_file']; ?>' id="bgimg" class="profile_image" width="450" alt="Image" />
 <!-- Image uploading box exists here. -->
  </div>
 <input type="file" id="background_image_file" name="background_image_file"
   accept="image/png, image/jpeg"  onchange="readImage(this);">
  <button id="saveimg" style="margin-top: 10px;" class="btn-web-admin btn-save
   upload_img"><?php echo 'Save Image'; ?>
    </button>

Your Javascript therefore should go like:

  function readImage(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
                $('#background_image_file').attr('src',e.target.result); //
               setting ur image here
               $('#saveimg').show();
       };
       reader.readAsDataURL(input.files[0]);   // Read in the image file as a data URL.             }
   }
}

   $('#saveimg').on('click', function(e){
            e.preventDefault();
            var _validFileExtensions = [".jpg", ".jpeg", ".gif", ".png"];
            var validate_img = false;
            var sFileName = $('#background_image_file').val();
            for (var j = 0; j < _validFileExtensions.length; j++){
                var sCurExtension = _validFileExtensions[j];
                if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                    validate_img = true;
                    break;
                }
            }

            if(validate_img){
                var data = new FormData();
                var file = $('#background_image_file')files[0].;

                data.append('file');
                $.ajax({
                    type: "POST",
                    url: "/staff/ajaxUploadBackgroundImage",
                    data: data,
                    contentType: false,
                    cache: false,
                    processData: false,
                    success: function(data) {
                        var img = new Image();

                         img.onload = function() {
                            var width = img.width;
                            var height = img.height;
                         }
                        img.src = ($('#bgimg')[0]).src;
                    },
                    error: function(a, b, c){
                        console.log('Select a valid image.');
                        console.log(a);
                        console.log(b);
                        console.log(c);
                        return false;
                    }
                });
            }else{
                console.log('Select a valid image.');
            }
    });

Also a last hint that I would give you as you are using a FormData, in your Controller instead of having a $this->request->data, I would advise you to use
$this->request->form as you are supossedly uploading an image with an Ajax request.

     $dataimg = $this->request->form['file'];
     $this->set('image', $dataimg);

I hope that can help you to get a hint of why it is not working.


问:
Hiding multiple tag with same name or class
I have using prototype 1.5. Can you please tell me, how can i hide/show the div tag with same name or class. </p>

```<code>Element.hide('indicate')
</code>```

<p>But, the above line only satisfy to hide the first element only. "indicate" is the id. </p>

答:
Prototype provides the $$() function which you can use to query any CSS selector.

So if you have multiple items with a single class, you can query them like this:

```<code>$$('.indicate');
</code>```

See the Prototype manual: http://www.prototypejs.org/api/utility/dollar-dollar

By the way, since you're using Prototype 1.5, I could also mention that it gives you a .getElementsByClassName() function as well. However, this has now been deprecated in more recent versions since its functionality is already covered by $$(), and to avoid confusion, since modern browsers implement a native function with the same name, but different syntax.

So don't use it, but for the sake of completeness, here is the manual link: http://www.prototypejs.org/api/element/getElementsByClassName

Body:
I have using prototype 1.5. Can you please tell me, how can i hide/show the div tag with same name or class.

Element.hide('indicate')

But, the above line only satisfy to hide the first element only. "indicate" is the id.

Body:
Prototype provides the $$() function which you can use to query any CSS selector.

So if you have multiple items with a single class, you can query them like this:

$$('.indicate');

See the Prototype manual: http://www.prototypejs.org/api/utility/dollar-dollar

By the way, since you're using Prototype 1.5, I could also mention that it gives you a .getElementsByClassName() function as well. However, this has now been deprecated in more recent versions since its functionality is already covered by $$(), and to avoid confusion, since modern browsers implement a native function with the same name, but different syntax.

So don't use it, but for the sake of completeness, here is the manual link: http://www.prototypejs.org/api/element/getElementsByClassName