问:
Elastic Beanstalk Nginx Serve Static Files
I am new to Elastic Beanstalk, trying to serve a Node.js Express app and utilize serving our static files separately with Nginx. None of the tutorials I've come across are explicit in how to define the virtual path.

I'm attempting to do this through the AWS console in the browser. I am trying to add a virtual path/directory setup for the static files. In the console I'm at

Elastic Beanstalk > myapp > configuration > Static Files

But no matter what I add here I get this error message:

I've also tried adding the full directory path (/var/app/current/dist/public/images/). Is there another .ebextensions/*.conf file I need to add? I don't have a lot of experience with Nginx so if the fix is a .conf file I wouldn't know what it is

答:
This is a known bug, They only support python when it comes to the web console. if your application is in nodejs you would need to set these properties from the cli.

you can setup the values from cli this way

aws elasticbeanstalk update-environment --environment-id your_enviornment_id --option-settings 'Namespace=aws:elasticbeanstalk:container:nodejs:staticfiles,OptionName=/assets,Value=/static/assets'
```

or editing the config file from eb config.

Body:
This is a known bug, They only support python when it comes to the web console. if your application is in nodejs you would need to set these properties from the cli.

you can setup the values from cli this way

aws elasticbeanstalk update-environment --environment-id your_enviornment_id --option-settings 'Namespace=aws:elasticbeanstalk:container:nodejs:staticfiles,OptionName=/assets,Value=/static/assets'

or editing the config file from eb config.


来源: stackexchange

问:
Spark 2.2.0: How to remove Specific Duplicates from a Dataset of a list column
GoodMorning to everyone and have a nice a day. I have a dataset like below

```<code>+-----+------------+
|Text2|Set         |
+-----+------------+
|seven|[3]         |
|one  |[1, 5, 2, 3]|
|six  |[5]         |
|five |[5, 2, 4]   |
+-----+------------+
</code>```

What I would like to do is remove specific duplicates from the set of Colum. For example, let’s assume I want to remove number 3 and 4 together.

Imagine an output like above. As we can see both 3,4 deleted from every row of the column Set

```<code>+-----+------------+
|Text2|Set         |
+-----+------------+
|one  |[1, 5, 2]   |
|six  |[5]         |
|five |[5, 2]      |
+-----+------------+
</code>```

What is the most efficient way to do it with the Dataset api? because let’s assume that I need this operation for a large data

From what i am thinking is to map first and the perform a reduce as the most efficient way to achieve it but I am not sure that what I am saying now is a stupidity solution.

Here is my Java code example

```<code> List<Row> data = Arrays.asList(
                RowFactory.create("seven", Arrays.asList(3)),
                RowFactory.create("one", Arrays.asList(1, 5, 2, 3)),
                RowFactory.create("six", Arrays.asList(5)),
                RowFactory.create("five", Arrays.asList(5, 2, 4))
        );

        StructType schema = new StructType(new StructField[]{
                new StructField("Text2", DataTypes.StringType, false, Metadata.empty()),
                new StructField("Set", DataTypes.createArrayType(DataTypes.IntegerType), false, Metadata.empty())
        });

        Dataset<Row> df = spark.createDataFrame(data, schema);
        df.show(false);
</code>```

I would be grateful if someone will give me a solution base on my problem

答:
Lets say df is your initial data frame below code filter the way you are expecting.

```<code>Dataset<Row> df = sparkSession.createDataFrame(data, schema);

    UDF3<WrappedArray<Integer>,Integer,Integer,List<Integer>> filterFunction =  (WrappedArray<Integer> input, Integer filtVal1,Integer filtVal2) -> {
        List<Integer> newLst= new ArrayList<>(JavaConversions.asJavaList(input));
        newLst.removeIf(x -> x==filtVal1 || x==filtVal2);
        return newLst;
    };

    sparkSession.udf().register("filterFunction", filterFunction, DataTypes.createArrayType(DataTypes.IntegerType));

    Dataset<Row> filteredDf= df.withColumn("Set_temp", functions.callUDF("filterFunction", df.col("Set"),functions.lit(3),functions.lit(4))).drop("Set").withColumnRenamed("Set_temp", "Set").filter("size(Set_temp)>0");

    filteredDf.show();

  +-----+---------+
  |Text2|      Set|
   +-----+---------+
  |  one|[1, 5, 2]|
  |  six|      [5]|
  | five|   [5, 2]|
  +-----+---------+
</code>```

ContentLicense: CC BY-SA 3.0

Body:
GoodMorning to everyone and have a nice a day. I have a dataset like below

+-----+------------+
|Text2|Set         |
+-----+------------+
|seven|[3]         |
|one  |[1, 5, 2, 3]|
|six  |[5]         |
|five |[5, 2, 4]   |
+-----+------------+

What I would like to do is remove specific duplicates from the set of Colum. For example, let’s assume I want to remove number 3 and 4 together.

Imagine an output like above. As we can see both 3,4 deleted from every row of the column Set

+-----+------------+
|Text2|Set         |
+-----+------------+
|one  |[1, 5, 2]   |
|six  |[5]         |
|five |[5, 2]      |
+-----+------------+

What is the most efficient way to do it with the Dataset api? because let’s assume that I need this operation for a large data

From what i am thinking is to map first and the perform a reduce as the most efficient way to achieve it but I am not sure that what I am saying now is a stupidity solution.

Here is my Java code example

 List<Row> data = Arrays.asList(
                RowFactory.create("seven", Arrays.asList(3)),
                RowFactory.create("one", Arrays.asList(1, 5, 2, 3)),
                RowFactory.create("six", Arrays.asList(5)),
                RowFactory.create("five", Arrays.asList(5, 2, 4))
        );

        StructType schema = new StructType(new StructField[]{
                new StructField("Text2", DataTypes.StringType, false, Metadata.empty()),
                new StructField("Set", DataTypes.createArrayType(DataTypes.IntegerType), false, Metadata.empty())
        });

        Dataset<Row> df = spark.createDataFrame(data, schema);
        df.show(false);

I would be grateful if someone will give me a solution base on my problem

Body:
Lets say df is your initial data frame below code filter the way you are expecting.

Dataset<Row> df = sparkSession.createDataFrame(data, schema);

    UDF3<WrappedArray<Integer>,Integer,Integer,List<Integer>> filterFunction =  (WrappedArray<Integer> input, Integer filtVal1,Integer filtVal2) -> {
        List<Integer> newLst= new ArrayList<>(JavaConversions.asJavaList(input));
        newLst.removeIf(x -> x==filtVal1 || x==filtVal2);
        return newLst;
    };

    sparkSession.udf().register("filterFunction", filterFunction, DataTypes.createArrayType(DataTypes.IntegerType));

    Dataset<Row> filteredDf= df.withColumn("Set_temp", functions.callUDF("filterFunction", df.col("Set"),functions.lit(3),functions.lit(4))).drop("Set").withColumnRenamed("Set_temp", "Set").filter("size(Set_temp)>0");

    filteredDf.show();

  +-----+---------+
  |Text2|      Set|
   +-----+---------+
  |  one|[1, 5, 2]|
  |  six|      [5]|
  | five|   [5, 2]|
  +-----+---------+


问:
Angular 4 and Asp.net core error: no 'access-control-allow-origin' header is present on the requested resource Origin 'http://localhost:42000'
I have an application in Angular 4 for file upload and a server in .NET Core 2.

This is my api method:

```<code>    [HttpPost]
    [Route("PostFileUploadIFile")]
    public async Task<IActionResult> PostFileUpload(APIDocumentsSettings aPIDocumentsSettings)
    {
        try
        {
            var fileUpload = aPIDocumentsSettings.FileForUpload;
            if (fileUpload.Length < 0 || fileUpload == null)
            {
                return BadRequest(new ResponseMessage { StatusCode = 500, Message = "Error", Description = "Incorrect Base64 format" });
            }

            string fileDir = Path.Combine(hostingEnvironment.WebRootPath, aPIDocumentsSettings.DocumentType, aPIDocumentsSettings.Version);
            if (!Directory.Exists(fileDir))
            {
                Directory.CreateDirectory(fileDir);
            }
            string file = Path.Combine(fileDir, DateTime.Now.Ticks + ".pdf");
            if (!string.IsNullOrEmpty(fileUpload.FileName))
            {
                byte[] filebytes = Convert.FromBase64String(fileUpload.FileName);
                FileStream fs = new FileStream(file,
                                               FileMode.CreateNew,
                                               FileAccess.Write,
                                               FileShare.None);
                fs.Write(filebytes, 0, filebytes.Length);
                fs.Close();
            }
            using (var fs = new FileStream(Path.Combine(file), FileMode.Create))
            {
                await fileUpload.CopyToAsync(fs);
            }

            if (String.IsNullOrEmpty(file))
            {
                return BadRequest(new ResponseMessage { StatusCode = 500, Message = "Error", Description = "File Upload Failed, Path not found!" });
            }

            return Ok(file.Substring(file.LastIndexOf(aPIDocumentsSettings.DocumentType)));

        }
        catch (Exception ex)
        {
            return BadRequest(new ResponseMessage { StatusCode = 500, Message = "Error", Description = "Exception Occurs" + ex.Message });
        }
    }
</code>```

This is my APIDocumentsSettings Model:

```<code>public class APIDocumentsSettings
{
    public IFormFile FileForUpload { get; set; }
    public string Version { get; set; }
    public string DocumentType { get; set; }
}
</code>```

This is contained in the startup of the web api project:

```<code>public class Startup
{
    public Startup(IConfiguration configuration)
    {
        this.Configuration = configuration;
    }

    public IConfiguration Configuration { get; }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<MastersDbContext>(options =>             options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection")));
        services.AddMvc();
        //services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
        services.AddAuthentication()
         .AddOAuthValidation();
        services.AddAuthentication(options =>
        {
            options.DefaultScheme = OAuthValidationDefaults.AuthenticationScheme;
        });
        services.AddAuthorization(options =>
        {
            options.AddPolicy("RequiredApplicationManagerRole", policy => policy.RequireRole("ApplicationManager"));
            options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator"));
            options.AddPolicy("RequireUserRole", policy => policy.RequireRole("User"));
        });
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info
            {
                Version = "v1",
                Title = "Masters API",
                Description = "Masters API give access to all Masters table Web APIs",
                TermsOfService = "None"
            });
        });
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "Masters API");
        });

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseCors(builder =>
            builder.WithOrigins("*")
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowAnyOrigin()
            );
        app.UseMvc();
        app.UseAuthentication();
        app.UseStaticFiles();

    }
}
</code>```

This is my angular code:

```
@Injectable()
export class DocumentupdatingService
{
  apiRoot:string="http://localhost:8080/api/v1/";</p>

<code>constructor(private _http:Http)
{ }

create(documentupdating:DocumentsUpdating)
{
  return this._http.post(this.apiRoot+'DocumentsSettings',documentupdating)
}

destroy(documentupdating:DocumentsUpdating)
{
  return this._http.delete(this.apiRoot+documentupdating.id).map(res=>res.json())
}
update(documentupdating:DocumentsUpdating)
{
  return this._http.put(this.apiRoot+'DocumentsSettings/'+documentupdating.id,documentupdating)
}
getAllDocuments()
{
  return this._http.get("http://192.168.91.39:8080/api/v1/DocumentsSettings").map(res=>res.json())
}

uploadFile(formdata:FormData)
{
  console.log(formdata.get('FileForUpload'))
  console.log(formdata.get('Version'))
  console.log(formdata.get('DocumentType'))
  let myHeader = new Headers();
  myHeader.append('Content-Type','multipart/form-data');
  let options=new RequestOptions({headers:myHeader});
  return this._http.post(this.apiRoot+'DocumentsSettings/PostFileUploadIFile/',{'FileForUpload':formdata.get('FileForUpload'),'Version':formdata.get('Version').toString,'DocumentType':formdata.get('DocumentType')},options)
}
</code>```

}

After Uploading file I get following error:

I have uploaded file through PostMan and its working.

答:
You'are having CORS issues.

PostMan works and your app doesn't because the browser is blocking your request.

This happens because your app is running in a different origin from your backend.

The browser uses preflight request to know if your backend authorize request from your origin. https://developer.mozilla.org/pt-BR/docs/Glossary/Preflight_request

You should configure a proxy in your dev-server: https://webpack.js.org/configuration/dev-server/#devserver-proxy

Body:
I have an application in Angular 4 for file upload and a server in .NET Core 2.

This is my api method:

    [HttpPost]
    [Route("PostFileUploadIFile")]
    public async Task<IActionResult> PostFileUpload(APIDocumentsSettings aPIDocumentsSettings)
    {
        try
        {
            var fileUpload = aPIDocumentsSettings.FileForUpload;
            if (fileUpload.Length < 0 || fileUpload == null)
            {
                return BadRequest(new ResponseMessage { StatusCode = 500, Message = "Error", Description = "Incorrect Base64 format" });
            }

            string fileDir = Path.Combine(hostingEnvironment.WebRootPath, aPIDocumentsSettings.DocumentType, aPIDocumentsSettings.Version);
            if (!Directory.Exists(fileDir))
            {
                Directory.CreateDirectory(fileDir);
            }
            string file = Path.Combine(fileDir, DateTime.Now.Ticks + ".pdf");
            if (!string.IsNullOrEmpty(fileUpload.FileName))
            {
                byte[] filebytes = Convert.FromBase64String(fileUpload.FileName);
                FileStream fs = new FileStream(file,
                                               FileMode.CreateNew,
                                               FileAccess.Write,
                                               FileShare.None);
                fs.Write(filebytes, 0, filebytes.Length);
                fs.Close();
            }
            using (var fs = new FileStream(Path.Combine(file), FileMode.Create))
            {
                await fileUpload.CopyToAsync(fs);
            }

            if (String.IsNullOrEmpty(file))
            {
                return BadRequest(new ResponseMessage { StatusCode = 500, Message = "Error", Description = "File Upload Failed, Path not found!" });
            }

            return Ok(file.Substring(file.LastIndexOf(aPIDocumentsSettings.DocumentType)));

        }
        catch (Exception ex)
        {
            return BadRequest(new ResponseMessage { StatusCode = 500, Message = "Error", Description = "Exception Occurs" + ex.Message });
        }
    }

This is my APIDocumentsSettings Model:

public class APIDocumentsSettings
{
    public IFormFile FileForUpload { get; set; }
    public string Version { get; set; }
    public string DocumentType { get; set; }
}

This is contained in the startup of the web api project:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        this.Configuration = configuration;
    }

    public IConfiguration Configuration { get; }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<MastersDbContext>(options =>             options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection")));
        services.AddMvc();
        //services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
        services.AddAuthentication()
         .AddOAuthValidation();
        services.AddAuthentication(options =>
        {
            options.DefaultScheme = OAuthValidationDefaults.AuthenticationScheme;
        });
        services.AddAuthorization(options =>
        {
            options.AddPolicy("RequiredApplicationManagerRole", policy => policy.RequireRole("ApplicationManager"));
            options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator"));
            options.AddPolicy("RequireUserRole", policy => policy.RequireRole("User"));
        });
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info
            {
                Version = "v1",
                Title = "Masters API",
                Description = "Masters API give access to all Masters table Web APIs",
                TermsOfService = "None"
            });
        });
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "Masters API");
        });

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseCors(builder =>
            builder.WithOrigins("*")
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowAnyOrigin()
            );
        app.UseMvc();
        app.UseAuthentication();
        app.UseStaticFiles();

    }
}

This is my angular code:

@Injectable()
export class DocumentupdatingService
{
  apiRoot:string="http://localhost:8080/api/v1/";

constructor(private _http:Http)
{ }

create(documentupdating:DocumentsUpdating)
{
  return this._http.post(this.apiRoot+'DocumentsSettings',documentupdating)
}

destroy(documentupdating:DocumentsUpdating)
{
  return this._http.delete(this.apiRoot+documentupdating.id).map(res=>res.json())
}
update(documentupdating:DocumentsUpdating)
{
  return this._http.put(this.apiRoot+'DocumentsSettings/'+documentupdating.id,documentupdating)
}
getAllDocuments()
{
  return this._http.get("http://192.168.91.39:8080/api/v1/DocumentsSettings").map(res=>res.json())
}

uploadFile(formdata:FormData)
{
  console.log(formdata.get('FileForUpload'))
  console.log(formdata.get('Version'))
  console.log(formdata.get('DocumentType'))
  let myHeader = new Headers();
  myHeader.append('Content-Type','multipart/form-data');
  let options=new RequestOptions({headers:myHeader});
  return this._http.post(this.apiRoot+'DocumentsSettings/PostFileUploadIFile/',{'FileForUpload':formdata.get('FileForUpload'),'Version':formdata.get('Version').toString,'DocumentType':formdata.get('DocumentType')},options)
}

}

After Uploading file I get following error:

I have uploaded file through PostMan and its working.


问:
How to pass file object with multiple attribute via jQuery ajax
I am trying to pass a file object with multiple attribute via AJAX in my WordPress application but not being able to capture them in the process function.

HTML:

```<code><form enctype="multipart/form-data" method="post">
   <input type="text" id="album_title" name="album_title" />
   <input type="file" multiple" id="photo_upload" name="photo_upload[]" class="files-data" />
   <input type="button" value="Submit" onclick="uploadPhoto();" />
</form>
</code>```

JS:

```<code>var formData = new FormData();

formData.append('album_title', jQuery('#album_title').val());
formData.append('security', mbAlbumUploader.ajax_nonce);

jQuery.each(jQuery('.files-data'), function(i, obj) {
   jQuery.each(obj.files, function(j, file){
       formData.append('files[' + j + ']', file);
   });
});

jQuery.ajax({
   url: 'mbAlbumUploader.ajax_url,'
   type: 'post',
   data: formData,
   dataType: 'json',
   processData: false,
   contentType: false,
   success: function(response) {
     alert(response.files);
   }
});
</code>```

PHP function:

```<code>function uploadPhoto() {
   $fileName_str = '';
   foreach($_FILES['photo_upload']['name'] as $f=>$name) {
      $extension = pathinfo($name, PATHINFO_EXTENSION);
      $fileName_str .= $name . ', ';
   }
   die(wp_json_encode(array(
     'files' => $fileName_str;
   )));
}
</code>```

What I am doing wrong?

答:
Try to run ajax request by click event or submit event. I made few changes this is script below. Assuming your button has update class.

HTML

```<code><form enctype="multipart/form-data" method="post">
    <input type="text" id="album_title" name="album_title" />
  <input id="file" name="file[]" type="file"  multiple/>
  <input class="update" type="submit" />
</form>
</code>```

JavaScript

```<code>$(".update").click(function(e) {
        // Stops the form from reloading
        e.preventDefault();

            $.ajax({
            url: 'upload.php',
            type: 'POST',
            contentType:false,
            processData: false,
            data: function(){
                var data = new FormData();

                data.append('album_title', jQuery('#album_title').val());
                data.append('security', mbAlbumUploader.ajax_nonce);

                jQuery.each(jQuery('#file')[0].files, function(i, file) {
                    data.append('file-'+i, file);
                });
                data.append('body' , $('#body').val());
                data.append('uid', $('#uid').val());
                return data;
            }(),
                success: function(result) {
                alert(result);
                },
            error: function(xhr, result, errorThrown){
                alert('Request failed.');
            }
            });
            $('#picture').val('');
    $('#body').val('');
    });
</code>```

PHP (upload.php)

You can Access your files from $_FILES global.

Body:
I am trying to pass a file object with multiple attribute via AJAX in my WordPress application but not being able to capture them in the process function.

HTML:

<form enctype="multipart/form-data" method="post">
   <input type="text" id="album_title" name="album_title" />
   <input type="file" multiple" id="photo_upload" name="photo_upload[]" class="files-data" />
   <input type="button" value="Submit" onclick="uploadPhoto();" />
</form>

JS:

var formData = new FormData();

formData.append('album_title', jQuery('#album_title').val());
formData.append('security', mbAlbumUploader.ajax_nonce);

jQuery.each(jQuery('.files-data'), function(i, obj) {
   jQuery.each(obj.files, function(j, file){
       formData.append('files[' + j + ']', file);
   });
});

jQuery.ajax({
   url: 'mbAlbumUploader.ajax_url,'
   type: 'post',
   data: formData,
   dataType: 'json',
   processData: false,
   contentType: false,
   success: function(response) {
     alert(response.files);
   }
});

PHP function:

function uploadPhoto() {
   $fileName_str = '';
   foreach($_FILES['photo_upload']['name'] as $f=>$name) {
      $extension = pathinfo($name, PATHINFO_EXTENSION);
      $fileName_str .= $name . ', ';
   }
   die(wp_json_encode(array(
     'files' => $fileName_str;
   )));
}

What I am doing wrong?

Body:
Try to run ajax request by click event or submit event. I made few changes this is script below. Assuming your button has update class.

HTML

<form enctype="multipart/form-data" method="post">
    <input type="text" id="album_title" name="album_title" />
  <input id="file" name="file[]" type="file"  multiple/>
  <input class="update" type="submit" />
</form>

JavaScript

$(".update").click(function(e) {
        // Stops the form from reloading
        e.preventDefault();

            $.ajax({
            url: 'upload.php',
            type: 'POST',
            contentType:false,
            processData: false,
            data: function(){
                var data = new FormData();

                data.append('album_title', jQuery('#album_title').val());
                data.append('security', mbAlbumUploader.ajax_nonce);

                jQuery.each(jQuery('#file')[0].files, function(i, file) {
                    data.append('file-'+i, file);
                });
                data.append('body' , $('#body').val());
                data.append('uid', $('#uid').val());
                return data;
            }(),
                success: function(result) {
                alert(result);
                },
            error: function(xhr, result, errorThrown){
                alert('Request failed.');
            }
            });
            $('#picture').val('');
    $('#body').val('');
    });

PHP (upload.php)

You can Access your files from $_FILES global.


问:
How to update SQL Table from two gridviews
Merging three gridview into one.
This is the First Gridview

```<code>ItemCode  Itemname  NewCode   SellingPrice   PurchasePrice   MRP
   1         Soap         1
   2         Bag          2
   3         Cycle        3
   4         Scissors     4
   5         Pen          5
</code>```

This is the Second Gridview

```<code> ItemCode   NewCode
 1          55874
 2          889746210
 5          466897
</code>```

This is the Third Gridview

```<code>ItemCode   SellingPrice   PurchasePrice   MRP
 1            25               20          25
 2            150              130         150
 3            7500             6500        7500
 4            20               17          17
 5            10               8           10
</code>```

I want the first gridview to be updated with the above values and save it into the database

```<code>ItemCode  Itemname  NewCode   SellingPrice   PurchasePrice   MRP
1         Soap       55874         25            20          25
2         Bag        889746210     150           130         150
3         Cycle      3             7500          6500        7500
4         Scissors   4             20            17          17
5         Pen        466897        10            8           10
</code>```

答:
This is what I was looking for</p>

```<code>string connectionstring = ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
        SqlConnection con = new SqlConnection(connectionstring);
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from tbl_eon",con);
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                SqlCommand cmd2 = new SqlCommand("Update tbl_All set NewCode='" + dt.Rows[i]["EanCode"].ToString() + "' where ItemCode='" + dt.Rows[i]["ItemCode"] + "'", con);
                cmd2.ExecuteNonQuery();
            }
        }
</code>```

Body:
Merging three gridview into one.
This is the First Gridview

ItemCode  Itemname  NewCode   SellingPrice   PurchasePrice   MRP
   1         Soap         1
   2         Bag          2
   3         Cycle        3
   4         Scissors     4
   5         Pen          5

This is the Second Gridview

 ItemCode   NewCode
 1          55874
 2          889746210
 5          466897

This is the Third Gridview

ItemCode   SellingPrice   PurchasePrice   MRP
 1            25               20          25
 2            150              130         150
 3            7500             6500        7500
 4            20               17          17
 5            10               8           10

I want the first gridview to be updated with the above values and save it into the database

ItemCode  Itemname  NewCode   SellingPrice   PurchasePrice   MRP
1         Soap       55874         25            20          25
2         Bag        889746210     150           130         150
3         Cycle      3             7500          6500        7500
4         Scissors   4             20            17          17
5         Pen        466897        10            8           10

Body:
This is what I was looking for

string connectionstring = ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
        SqlConnection con = new SqlConnection(connectionstring);
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from tbl_eon",con);
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                SqlCommand cmd2 = new SqlCommand("Update tbl_All set NewCode='" + dt.Rows[i]["EanCode"].ToString() + "' where ItemCode='" + dt.Rows[i]["ItemCode"] + "'", con);
                cmd2.ExecuteNonQuery();
            }
        }


问:
Why .ents is not working on proper ways when i clall the function
```<code>import re
import spacy
import nltk
from nltk.corpus import stopwords
stop = stopwords.words('english')
from nltk.corpus import wordnet

inputfile = open('file.txt', 'r')
String= inputfile.read()
nlp = spacy.load('en_core_web_sm')

def candidate_name_extractor(input_string, nlp):
    input_string = str(input_string)

    doc = nlp(input_string)
    print(doc)
    # Extract entities
    doc_entities = doc.ents
    #print(doc_entities)
    # Subset to person type entities
    doc_persons = filter(lambda x: x.label_ == 'PERSON', doc_entities)
    doc_persons = filter(lambda x: len(x.text.strip().split()) >= 2, doc_persons)
    doc_persons = list(map(lambda x: x.text.strip(), doc_persons))
    candidate_name = doc_persons[0]
    return candidate_name

if __name__ == '__main__':
    names = candidate_name_extractor(String, nlp)

print(names)
</code>```

When I run this program, and print nlp(input_string) then works fine. But when it execute the line "doc_entities=doc.ents",

It removes upper three line which contain name mobile and email and
I want to extract the name from it.

where is problem Either "doc_entities = doc.ents" is not working on proper way or what?

答:
So I slightly rewrote your example to be a little more straightforward, and it's working fine for me. I think a lot of the problems you're experiencing might be related to the nested filtering and the string operations – which you can easily drop, because spaCy already does all of this for you.

Here, I'm simply iterating over the entities found in the text, and if the entity label is PERSON, and the entity consists of two or more token, we assume it's a person name and print the entity text. Each entry in doc.ents is a Span object, and its length is the length of tokens. So there's no need to split the string – you can simply use len(ent).

```<code>nlp = spacy.load('en_core_web_sm')
doc = nlp(u"John Smith")  # or whatever else

for ent in doc.ents:
    if ent.label_ == 'PERSON' and len(ent) >= 2:
        print('The candidate name is: ', ent.text)  # do something with the entity
</code>```

Of course, this will only return a result if spaCy's model actually recognises that name as an entity. The default models are trained on general-purpose news and web text, so if you're processing a CV, you might not always get perfect results without fine-tuning on your use case.

It's not entirely clear from your question what you want to do with the phone number or email address – but all of this information will still be available in your doc. For example, let's say you also wanted to extract an email address, the easiest way to do this would be to use the like_email attribute on the token:

```<code>doc = nlp(u"John Smith, john@smith.com")
email_addresses = [token.text for token in doc if token.like_email]
# ['john@smith.com']
</code>```

Body:
import re
import spacy
import nltk
from nltk.corpus import stopwords
stop = stopwords.words('english')
from nltk.corpus import wordnet

inputfile = open('file.txt', 'r')
String= inputfile.read()
nlp = spacy.load('en_core_web_sm')

def candidate_name_extractor(input_string, nlp):
    input_string = str(input_string)

    doc = nlp(input_string)
    print(doc)
    # Extract entities
    doc_entities = doc.ents
    #print(doc_entities)
    # Subset to person type entities
    doc_persons = filter(lambda x: x.label_ == 'PERSON', doc_entities)
    doc_persons = filter(lambda x: len(x.text.strip().split()) >= 2, doc_persons)
    doc_persons = list(map(lambda x: x.text.strip(), doc_persons))
    candidate_name = doc_persons[0]
    return candidate_name

if __name__ == '__main__':
    names = candidate_name_extractor(String, nlp)

print(names)

When I run this program, and print nlp(input_string) then works fine. But when it execute the line "doc_entities=doc.ents",

It removes upper three line which contain name mobile and email and
I want to extract the name from it.

where is problem Either "doc_entities = doc.ents" is not working on proper way or what?

Body:
So I slightly rewrote your example to be a little more straightforward, and it's working fine for me. I think a lot of the problems you're experiencing might be related to the nested filtering and the string operations – which you can easily drop, because spaCy already does all of this for you.

Here, I'm simply iterating over the entities found in the text, and if the entity label is PERSON, and the entity consists of two or more token, we assume it's a person name and print the entity text. Each entry in doc.ents is a Span object, and its length is the length of tokens. So there's no need to split the string – you can simply use len(ent).

nlp = spacy.load('en_core_web_sm')
doc = nlp(u"John Smith")  # or whatever else

for ent in doc.ents:
    if ent.label_ == 'PERSON' and len(ent) >= 2:
        print('The candidate name is: ', ent.text)  # do something with the entity

Of course, this will only return a result if spaCy's model actually recognises that name as an entity. The default models are trained on general-purpose news and web text, so if you're processing a CV, you might not always get perfect results without fine-tuning on your use case.

It's not entirely clear from your question what you want to do with the phone number or email address – but all of this information will still be available in your doc. For example, let's say you also wanted to extract an email address, the easiest way to do this would be to use the like_email attribute on the token:

doc = nlp(u"John Smith, john@smith.com")
email_addresses = [token.text for token in doc if token.like_email]
# ['john@smith.com']


问:
find total data in N*N matrix
a matrix  consists of N × N blocks .the block number is equal to the sum  of the row number and the column number. each block consists  of data, and data is equal to  difference  of  sum of even and odd digits of the block number . calculate total data of n*n blocks

i/o format

```<code>lets n = 4
so
matrix will be
2 3 4 5
3 4 5 6
4 5 6 7
5 6 7 8
</code>```

so total data  = 2+3+4+5+3+4+5+6+4+5+6+7+5+6+7+8=80

if number of block is 4256 in any case then data in it will be abs(diff(sum(even digits)- sum(odd digits))) which is abs((4+2+6)-(5))= 7

my naive attempt

```<code>n = int(raw_input())
sum1=0
sum2=0
for i in range(1,n+1):
    for j in range(1,n+1):
        sum1 = i+j
        diffsum = diff(sum1)
        sum2 = sum2+diffsum
print sum2
</code>```

 again optimized attempt

```<code>def diff(sum1):
    sum1 = str(sum1)
    m = sum([int(i) for i in sum1 if int(i) % 2 == 0])
    f = sum([int(i) for i in sum1 if int(i) % 2 != 0])
    return abs(m - f)

n = int(raw_input())
sum1 = 0
k = 1
# t1 = time.time()
p = 2 * n
for i in range(2, n + 2):
    diffsum = diff(i)
    diffsum1 = diff(p)
    sum1 = sum1 + (diffsum * k)
    sum1 = sum1 + (diffsum1 * k)
    p = p - 1
    k = k + 1
sum1 = sum1 - (diff(n + 1) * n)
print sum1
</code>```

 diff is common function in both case. i need more optmization with the following algorithm

答:
Your optimised approach calculates the digit sum only once for each number, so at first sight, there isn't anything to be gained from memoisation.

You can improve the performance of your diff function by merging the two loops into one and use a dictionary to look up whether you add or subtract a digit:

```<code>value = dict(zip("0123456789", (0, -1, 2, -3, 4,-5, 6,-7, 8,-9)))

def diff2(s):
    s = str(s)
    return abs(sum([value[i] for i in s]))
</code>```

This will require a conversion to string. You can get a bit faster (but not much) by calculating the digits by hand:

```<code>dvalue = [0, -1, 2, -3, 4,-5, 6,-7, 8,-9]

def diff(s):
    t = 0

    while s:
        t += dvalue[s % 10]
        s //= 10

    return abs(t)
</code>```

Finally, you can make use of the fact that you calculate all digit sums from 2 up to 2·n sequentially. Store the digits of the current number in an array, then implement an odometer-like counter. When you increment that counter, keep track of the odd and even digit sums. In 9 of 10 cases, you just have to adjust the last digit by removing its value from the respective sum and by adding the next digit to the other sum.

Here's a program that does this. The function next increments the counter and keeps the digit sums of even and odd numbers in sums[0] and sums[1]. The main program is basically the same as yours, except that the loop has been split into two: One where k increases and one where it decreases.

```<code>even = set(range(0, 10, 2))

def next(num, sums):
    o = num[0]
    if o in even:
        sums[0] -= o
        sums[1] += o + 1
    else:
        sums[0] += o + 1
        sums[1] -= o

    num[0] += 1

    i = 0
    while num[i] == 10:
        sums[0] -= 10
        num[i] = 0

        i += 1
        o = num[i]
        if o in even:
            sums[0] -= o
            sums[1] += o + 1
        else:
            sums[0] += o + 1
            sums[1] -= o

        num[i] += 1

n = int(raw_input())
total = 0

m = len(str(2 * n + 1))
num = [0] * m
num[0] = 2
sums = [2, 0]

k = 1
for i in range(2, n + 2):
    total += abs(sums[0] - sums[1]) * k
    k += 1
    next(num, sums)

k = n
for i in range(n + 2, 2*n + 1):
    k -= 1
    total += abs(sums[0] - sums[1]) * k
    next(num, sums)

print total
</code>```

I've said above that memoisation isn't useful for this approach. That's not true. You could store the even and odd digit sums of number i and make use of it when calculating the numbers 10 * i to 10 * i + 9. When you call diff in order of increasing i, you will have access to the stored sums of i // 10.

This isn't significantly faster than the odometer approach, but the implementation is clearer at the cost of additional memory. (Preallocated arrays work better than dictionaries for big n. You don't need to reserve space for numbers above (2*n + 11) / 10.)

```<code>def diff(s):
    d = s % 10

    e = ememo[s / 10]
    o = omemo[s / 10]

    if d in even:
        e += d
    else:
        o += d

    if s < smax:
        ememo[s] = e
        omemo[s] = o

    return e, o

n = int(raw_input())

total = 0

even = set(range(0, 10, 2))
smax = (2*n + 11) / 10
omemo = smax * [0]
ememo = smax * [0]
omemo[1] = 1

k = 1
for i in range(2, n + 2):
    e, o = diff(i)
    total += abs(e - o) * k
    k += 1

k = n
for i in range(n + 2, 2*n + 1):
    k -= 1
    e, o = diff(i)
    total += abs(e - o) * k

print total
</code>```

This could be made even faster if one could find a closed formula for the digit sums, but I think that the absolute function prevents such a solution.

Title: find total data in N*N matrix

Body:
a matrix  consists of N × N blocks .the block number is equal to the sum  of the row number and the column number. each block consists  of data, and data is equal to  difference  of  sum of even and odd digits of the block number . calculate total data of n*n blocks

i/o format

lets n = 4
so
matrix will be
2 3 4 5
3 4 5 6
4 5 6 7
5 6 7 8

so total data  = 2+3+4+5+3+4+5+6+4+5+6+7+5+6+7+8=80

if number of block is 4256 in any case then data in it will be abs(diff(sum(even digits)- sum(odd digits))) which is abs((4+2+6)-(5))= 7

my naive attempt

n = int(raw_input())
sum1=0
sum2=0
for i in range(1,n+1):
    for j in range(1,n+1):
        sum1 = i+j
        diffsum = diff(sum1)
        sum2 = sum2+diffsum
print sum2

 again optimized attempt

def diff(sum1):
    sum1 = str(sum1)
    m = sum([int(i) for i in sum1 if int(i) % 2 == 0])
    f = sum([int(i) for i in sum1 if int(i) % 2 != 0])
    return abs(m - f)

n = int(raw_input())
sum1 = 0
k = 1
# t1 = time.time()
p = 2 * n
for i in range(2, n + 2):
    diffsum = diff(i)
    diffsum1 = diff(p)
    sum1 = sum1 + (diffsum * k)
    sum1 = sum1 + (diffsum1 * k)
    p = p - 1
    k = k + 1
sum1 = sum1 - (diff(n + 1) * n)
print sum1

 diff is common function in both case. i need more optmization with the following algorithm

Body:
Your optimised approach calculates the digit sum only once for each number, so at first sight, there isn't anything to be gained from memoisation.

You can improve the performance of your diff function by merging the two loops into one and use a dictionary to look up whether you add or subtract a digit:

value = dict(zip("0123456789", (0, -1, 2, -3, 4,-5, 6,-7, 8,-9)))

def diff2(s):
    s = str(s)
    return abs(sum([value[i] for i in s]))

This will require a conversion to string. You can get a bit faster (but not much) by calculating the digits by hand:

dvalue = [0, -1, 2, -3, 4,-5, 6,-7, 8,-9]

def diff(s):
    t = 0

    while s:
        t += dvalue[s % 10]
        s //= 10

    return abs(t)

Finally, you can make use of the fact that you calculate all digit sums from 2 up to 2·n sequentially. Store the digits of the current number in an array, then implement an odometer-like counter. When you increment that counter, keep track of the odd and even digit sums. In 9 of 10 cases, you just have to adjust the last digit by removing its value from the respective sum and by adding the next digit to the other sum.

Here's a program that does this. The function next increments the counter and keeps the digit sums of even and odd numbers in sums[0] and sums[1]. The main program is basically the same as yours, except that the loop has been split into two: One where k increases and one where it decreases.

even = set(range(0, 10, 2))

def next(num, sums):
    o = num[0]
    if o in even:
        sums[0] -= o
        sums[1] += o + 1
    else:
        sums[0] += o + 1
        sums[1] -= o

    num[0] += 1

    i = 0
    while num[i] == 10:
        sums[0] -= 10
        num[i] = 0

        i += 1
        o = num[i]
        if o in even:
            sums[0] -= o
            sums[1] += o + 1
        else:
            sums[0] += o + 1
            sums[1] -= o

        num[i] += 1

n = int(raw_input())
total = 0

m = len(str(2 * n + 1))
num = [0] * m
num[0] = 2
sums = [2, 0]

k = 1
for i in range(2, n + 2):
    total += abs(sums[0] - sums[1]) * k
    k += 1
    next(num, sums)

k = n
for i in range(n + 2, 2*n + 1):
    k -= 1
    total += abs(sums[0] - sums[1]) * k
    next(num, sums)

print total

I've said above that memoisation isn't useful for this approach. That's not true. You could store the even and odd digit sums of number i and make use of it when calculating the numbers 10 * i to 10 * i + 9. When you call diff in order of increasing i, you will have access to the stored sums of i // 10.

This isn't significantly faster than the odometer approach, but the implementation is clearer at the cost of additional memory. (Preallocated arrays work better than dictionaries for big n. You don't need to reserve space for numbers above (2*n + 11) / 10.)

def diff(s):
    d = s % 10

    e = ememo[s / 10]
    o = omemo[s / 10]

    if d in even:
        e += d
    else:
        o += d

    if s < smax:
        ememo[s] = e
        omemo[s] = o

    return e, o

n = int(raw_input())

total = 0

even = set(range(0, 10, 2))
smax = (2*n + 11) / 10
omemo = smax * [0]
ememo = smax * [0]
omemo[1] = 1

k = 1
for i in range(2, n + 2):
    e, o = diff(i)
    total += abs(e - o) * k
    k += 1

k = n
for i in range(n + 2, 2*n + 1):
    k -= 1
    e, o = diff(i)
    total += abs(e - o) * k

print total

This could be made even faster if one could find a closed formula for the digit sums, but I think that the absolute function prevents such a solution.


问:
How do I kill all the processes in Mysql "show processlist"?
Because I see a lot of processes there, and the "time" column shows big values for all of them.</p>

答: I used the command flush tables to kill all inactive connections which where actually the mass problem.


问:
Websphere instalation v 7 Error
I'm trying to install websphere application server v7

I followed the steps

and when I click on next after after entering security administration password I got this error message

```<code>System Prerequisite Check

The system prerequisite check failed. The error messages are as follows:

Unable to retrieve information from the minimal service level (MSL) file of the installation.
</code>```

thanks for helping

答: You can use the instructions in this IBM Technote to disable MSL checking (you'll need to substitute v70 for v80 in the property name).  I must also point out that you're trying to install a version of WAS that goes out of service in 5 months.  You may instead want to invest in installation of a more modern version of WAS like v9.</p>

Title: Websphere instalation v 7 Error

Body:
I'm trying to install websphere application server v7

I followed the steps

and when I click on next after after entering security administration password I got this error message

System Prerequisite Check

The system prerequisite check failed. The error messages are as follows:

Unable to retrieve information from the minimal service level (MSL) file of the installation.

thanks for helping


问:
Wordpress JS files are loading twice
I want to include Bootstrap 4 to my WordPress installation. This is how I include it within my functions.php in the child theme.

```<code>// Bootstrap 4
function bootstrap() {
    wp_enqueue_style('bootstrap-css', get_stylesheet_directory_uri() . '/css/bootstrap.min.css' );
    wp_enqueue_script( 'jquery-slim', 'https://code.jquery.com/jquery-3.2.1.slim.min.js', array(), '3.2.1', true );
    wp_enqueue_script( 'popper', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js', array('jquery-slim'), '4.0.0', true );
    wp_enqueue_script( 'bootstrap-js', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js', array('jquery-slim'), '4.0.0', true );
}

add_action( 'wp_enqueue_scripts', 'bootstrap');
</code>```

When I test my site on pingdom or GTMetrix they say it is loaded twice. Why?

```<code>The following resources have identical contents, but are served from different URLs. Serve these resources from a consistent URL to save 1 request(s) and 68.0KiB.

https://code.jquery.com/jquery-3.2.1.slim.min.js
https://code.jquery.com/jquery-3.2.1.slim.min.js?ver=3.2.1

https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js
https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js?ver=4.0.0
</code>```

The parent theme is not loading any of these files. But why is e.g. the popper.js not loading twice?

答:
Well, WP itself includes jquery and bootstrap, and if you want yours specific ones you should deregister the core/default ones, then register yours (without jquery and bootstrap it wont do much):

```<code>wp_deregister_script('jquery'); //because its a Core-Registered Script
wp_register_script('jquery', 'THE PATH TO THE FILE', array(), '', FALSE);
</code>```

The answer is here: https://wordpress.stackexchange.com/a/284620

Title: Wordpress JS files are loading twice

Body:
I want to include Bootstrap 4 to my WordPress installation. This is how I include it within my functions.php in the child theme.

// Bootstrap 4
function bootstrap() {
    wp_enqueue_style('bootstrap-css', get_stylesheet_directory_uri() . '/css/bootstrap.min.css' );
    wp_enqueue_script( 'jquery-slim', 'https://code.jquery.com/jquery-3.2.1.slim.min.js', array(), '3.2.1', true );
    wp_enqueue_script( 'popper', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js', array('jquery-slim'), '4.0.0', true );
    wp_enqueue_script( 'bootstrap-js', 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js', array('jquery-slim'), '4.0.0', true );
}

add_action( 'wp_enqueue_scripts', 'bootstrap');

When I test my site on pingdom or GTMetrix they say it is loaded twice. Why?

The following resources have identical contents, but are served from different URLs. Serve these resources from a consistent URL to save 1 request(s) and 68.0KiB.

https://code.jquery.com/jquery-3.2.1.slim.min.js
https://code.jquery.com/jquery-3.2.1.slim.min.js?ver=3.2.1

https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js
https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js?ver=4.0.0

The parent theme is not loading any of these files. But why is e.g. the popper.js not loading twice?

Body:
Well, WP itself includes jquery and bootstrap, and if you want yours specific ones you should deregister the core/default ones, then register yours (without jquery and bootstrap it wont do much):

wp_deregister_script('jquery'); //because its a Core-Registered Script
wp_register_script('jquery', 'THE PATH TO THE FILE', array(), '', FALSE);

The answer is here: https://wordpress.stackexchange.com/a/284620


问:
Cocoa Bad Habits
What are those bad habits you've developed since you've started coding in Cocoa?

I think making a list of bad habits and actively adding to it and, more importantly, breaking those habits is a good technique to produce your code quality. So start now, get your bad habits off your chest. Maybe other people share your bad habits.

答:
Bad habit: Retaining my Java mindset.

My Java background leads me to obsessively check for a null before even thinking about doing anything with a variable, when I could be making use of Objective-C's ability to send a message to nil.  (See: "Sending a message to nil?")

Instead of trying to preemptively catch a nil, I have to remind myself that Objective-C allows me to simply write code that gracefully works with return values of 0 or nil.

OwnerDisplayName: schwa

ContentLicense: CC BY-SA 2.5

Title: Cocoa Bad Habits

OwnerDisplayName: Jeff


问:
Spring boot + Jackson. How to serialize collections which have null value as empty lists?
In my entity I have:

```<code>private Set<Account> accounts;
</code>```

Now it is being serialized like this:

```<code>"accounts": null
</code>```

I need to change it to

```<code>"accounts": []
</code>```

I have many (150+) entities which have this problem - how can configure jackson mapper to achieve this?

答:
You could remove the "accounts" completely from the json annotating your pojo with:

```<code>@JsonInclude(JsonInclude.Include.NON_NULL)
</code>```

maybe this helps

Body:
In my entity I have:

private Set<Account> accounts;

Now it is being serialized like this:

"accounts": null

I need to change it to

"accounts": []

I have many (150+) entities which have this problem - how can configure jackson mapper to achieve this?

Body:
You could remove the "accounts" completely from the json annotating your pojo with:

@JsonInclude(JsonInclude.Include.NON_NULL)

maybe this helps


答:
Enable CORS in your Asp.net Core 2 application.
Add this code to ConfigureServices method :

```<code> services.AddCors(options =>
    {
       options.AddPolicy("AllowAllOrigins",
    builder =>
    {
        builder.AllowAnyOrigin();
    });
    });
</code>```

For more details fellow this tutorial https://learn.microsoft.com/en-us/aspnet/core/security/cors

Title: Angular 4 and Asp.net core error: no 'access-control-allow-origin' header is present on the requested resource Origin 'http://localhost:42000'

Body:
Enable CORS in your Asp.net Core 2 application.
Add this code to ConfigureServices method :

 services.AddCors(options =>
    {
       options.AddPolicy("AllowAllOrigins",
    builder =>
    {
        builder.AllowAnyOrigin();
    });
    });

For more details fellow this tutorial https://learn.microsoft.com/en-us/aspnet/core/security/cors


问:
Search for a string in Data.Table in R
I am new to programming and doing some basic analysis in R Environment

I have two data tables
1) DT1 with one column and 500 rows, containing list of countries
2) DT2 with 5 columns X 10000 rows, and in 1 column i have a text

Problem:
I want to search in DT2$Text column if any country name appears from DT1.
Can someone let me some piece of code for this such that the DT1 countries are searched in DT2$Text column for whole of DT2?

Thanks all in advance.

答:
```<code>DT1[,appear := lapply(.SD,function(x){any(grepl(x,DT2$Text))}),.SDcols = yourcolumninDT1]
</code>```

should help you.
If you want a proper answer you should give a reproducible example

Title: Search for a string in Data.Table in R

Body:
DT1[,appear := lapply(.SD,function(x){any(grepl(x,DT2$Text))}),.SDcols = yourcolumninDT1]

should help you.
If you want a proper answer you should give a reproducible example


问:
Google Drive permissions for shared spreadsheet export by API V3
How to set permissions for google drive shared spreadsheet for allow export it by Drive API V3? (spreadsheet shared for you by other user and you can get export it by GUI)

I've got this:

```<code>Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "Insufficient Permission",
    "reason" : "insufficientPermissions"
  } ],
  "message" : "Insufficient Permission"
}
        at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)
        at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
        at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:321)
        at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1065)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
        at Quickstart.main(Quickstart.java:121)
</code>```

答:
The problem was here:
If you run java app firs time, you need installed web browser on running host, which opens and asks for confirm permissions and create /.credentials/gdrive/
StoredCredential. This file can be changed by single way - delete and recreate it by browser.  You can copy this file to GUI-less host for running of yours console app. </p>

Body:
How to set permissions for google drive shared spreadsheet for allow export it by Drive API V3? (spreadsheet shared for you by other user and you can get export it by GUI)

I've got this:

Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "Insufficient Permission",
    "reason" : "insufficientPermissions"
  } ],
  "message" : "Insufficient Permission"
}
        at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)
        at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
        at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:321)
        at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1065)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
        at Quickstart.main(Quickstart.java:121)


问:
Script keeps dying out after a while, not a timeout / memory issue
I have a long running script that dies out for no reason. It's supposed to run for over 8 hours, but dies out after an hour or two, no errors, nothing. I tried running it via CLI and via http, no difference.

I have the following parameters set:

```<code>set_time_limit(0);
ini_set('memory_limit', '1024M');
</code>```

I've been monitoring the memory usage, and it doesn't go over 200M

Is there anything else that I'm missing. Why would it die out?

答:
Maybe it segafults.
Try to launch your script on this way:

```<code>$ ulimt -c unlimited
$ php script.php
</code>```

And see if you find a core dump file (core.xxxx) in the running directory when it dies

Body:
I have a long running script that dies out for no reason. It's supposed to run for over 8 hours, but dies out after an hour or two, no errors, nothing. I tried running it via CLI and via http, no difference.

I have the following parameters set:

set_time_limit(0);
ini_set('memory_limit', '1024M');

I've been monitoring the memory usage, and it doesn't go over 200M

Is there anything else that I'm missing. Why would it die out?

Body:
Maybe it segafults.
Try to launch your script on this way:

$ ulimt -c unlimited
$ php script.php

And see if you find a core dump file (core.xxxx) in the running directory when it dies


问:
Realm IllegalStateException
I'm trying to use realm as a persistence method of the downloaded data from an API. I'm getting the error: *

Caused by: java.lang.IllegalStateException: This Realm instance has
  already been closed, making it unusable.

and I don't know what I'm doing wrong with the persistence methods. My class for persistence is the next:

```<code>public class PersistenceManager {

    @Inject
    public PersistenceManager(){}

    public void saveHabitants(final List<Habitant> habitants){

        Realm realm = Realm.getDefaultInstance(); // opens db
        try {
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    realm.insertOrUpdate(habitants);
                }
            });
        } finally {
            realm.close();
        }

    }

    public void saveHabitant(final Habitant habitant){

        Realm realm = Realm.getDefaultInstance();
        try {
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    realm.insertOrUpdate(habitant);
                }
            });
        } finally {
            realm.close();
        }

    }

    public List<Habitant> loadHabitants(){

        Realm realm = Realm.getDefaultInstance();
        List<Habitant> results;

        try {
            results = realm.where(Habitant.class).findAll();
        } finally {
            realm.close();
        }

        return results;
    }

    public List<Habitant> loadHabitants(int indexFrom, int limit){

        Realm realm = Realm.getDefaultInstance();
        List<Habitant> results;

        try {
            results = realm.where(Habitant.class).findAll();
            results.subList(indexFrom, limit);
        } finally {
            realm.close();
        }

        return results;
    }

    public Habitant loadHabitant(long id){

        Realm realm = Realm.getDefaultInstance();
        Habitant result;

        try {
            result = realm.where(Habitant.class).equalTo("id", id).findFirst();
        } finally {
            realm.close();
        }

        return result;
    }

}
</code>```

When I used the method loadHabitants(int indexFrom, int limit) is when I get this error.

答:
A RealmResults is accessible through lazy loading (per accessor) for as long as there is at least 1 open Realm instance on the given thread.

I actually intended to refer to the documentation, but for some reason I couldn't find it? Anyways, a RealmResults is accessed lazily, so when there are no open Realm instances, it becomes invalid, and can no longer be accessed. This is true for RealmObjects as well.

The docs do say:

...RealmObjects and RealmResults are accessed through a lazy cache...

so you cannot return a managed RealmResults, and expect it to remain open, if you close the thread-local Realm instance it is associated with.

Two solutions:

1.) refer to the documentation on how to properly manage Realm lifecycle on UI thread and background thread

2.) use realm.copyFromRealm(), which eagerly evaluates the whole data set, creates a detached copy of it. Please note that this is not a free operation, larger data sets can easily cause UI thread to freeze up if you use copyFromRealm() on UI thread.

```<code>public List<Habitant> loadHabitants(int indexFrom, int limit){
    try(Realm realm = Realm.getDefaultInstance()) {
        List<Habitant> results = realm.where(Habitant.class).findAll();
        results = new ArrayList<>(results.subList(indexFrom, limit));
        for(int i = 0, size = results.size(); i < size; i++) {
            results.set(i, realm.copyFromRealm(results.get(i)));
        }
        return Collections.unmodifiableList(results);
    }
}
</code>```

Title: Realm IllegalStateException

Body:
I'm trying to use realm as a persistence method of the downloaded data from an API. I'm getting the error: *

Caused by: java.lang.IllegalStateException: This Realm instance has
  already been closed, making it unusable.

and I don't know what I'm doing wrong with the persistence methods. My class for persistence is the next:

public class PersistenceManager {

    @Inject
    public PersistenceManager(){}

    public void saveHabitants(final List<Habitant> habitants){

        Realm realm = Realm.getDefaultInstance(); // opens db
        try {
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    realm.insertOrUpdate(habitants);
                }
            });
        } finally {
            realm.close();
        }

    }

    public void saveHabitant(final Habitant habitant){

        Realm realm = Realm.getDefaultInstance();
        try {
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    realm.insertOrUpdate(habitant);
                }
            });
        } finally {
            realm.close();
        }

    }

    public List<Habitant> loadHabitants(){

        Realm realm = Realm.getDefaultInstance();
        List<Habitant> results;

        try {
            results = realm.where(Habitant.class).findAll();
        } finally {
            realm.close();
        }

        return results;
    }

    public List<Habitant> loadHabitants(int indexFrom, int limit){

        Realm realm = Realm.getDefaultInstance();
        List<Habitant> results;

        try {
            results = realm.where(Habitant.class).findAll();
            results.subList(indexFrom, limit);
        } finally {
            realm.close();
        }

        return results;
    }

    public Habitant loadHabitant(long id){

        Realm realm = Realm.getDefaultInstance();
        Habitant result;

        try {
            result = realm.where(Habitant.class).equalTo("id", id).findFirst();
        } finally {
            realm.close();
        }

        return result;
    }

}

When I used the method loadHabitants(int indexFrom, int limit) is when I get this error.

Body:
A RealmResults is accessible through lazy loading (per accessor) for as long as there is at least 1 open Realm instance on the given thread.

I actually intended to refer to the documentation, but for some reason I couldn't find it? Anyways, a RealmResults is accessed lazily, so when there are no open Realm instances, it becomes invalid, and can no longer be accessed. This is true for RealmObjects as well.

The docs do say:

...RealmObjects and RealmResults are accessed through a lazy cache...

so you cannot return a managed RealmResults, and expect it to remain open, if you close the thread-local Realm instance it is associated with.

Two solutions:

1.) refer to the documentation on how to properly manage Realm lifecycle on UI thread and background thread

2.) use realm.copyFromRealm(), which eagerly evaluates the whole data set, creates a detached copy of it. Please note that this is not a free operation, larger data sets can easily cause UI thread to freeze up if you use copyFromRealm() on UI thread.

public List<Habitant> loadHabitants(int indexFrom, int limit){
    try(Realm realm = Realm.getDefaultInstance()) {
        List<Habitant> results = realm.where(Habitant.class).findAll();
        results = new ArrayList<>(results.subList(indexFrom, limit));
        for(int i = 0, size = results.size(); i < size; i++) {
            results.set(i, realm.copyFromRealm(results.get(i)));
        }
        return Collections.unmodifiableList(results);
    }
}


问:
Xamarin.Forms - DisplayAlert with Italic font attribute
I need to display an alert with some part of the message in italics and the other part normal, something like this:

```<code>var title = "Title";
var body = "This part in Italic. This part normal.";
Application.Current.MainPage.DisplayAlert(title, body, "OK");
</code>```

With the part that says: "This part in Italic." in italics and the other one in normal text.

Is it possible to do? If yes, how?

Thanks in advance!

答:
I ended up creating a native alert controller like this:</p>

```<code>void PromptRichTextPopup(string title, string richMessage, string normalMessage, Action onOkCallback, Action onCancel = null) {
            var vc = UIKit.UIApplication.SharedApplication.KeyWindow.RootViewController;
            // take top presented view controller
            while (vc.PresentedViewController != null) {
                vc = vc.PresentedViewController;
            }

            var alertvc = UIAlertController.Create(title, string.Empty, UIAlertControllerStyle.Alert);
            var leftAligned = new NSMutableParagraphStyle();
            leftAligned.Alignment = UITextAlignment.Left;

            var colorTitle = new NSAttributedString(str: title, font: UIFont.BoldSystemFontOfSize(18), foregroundColor: Xamarin.Forms.Color.FromHex("#61acad").ToUIColor());

            alertvc.SetValueForKey(colorTitle, new NSString("attributedTitle"));

            var margin = 5f;
            var height = 30f;
            var width = 256f;

            var container = new UIView(new CGRect(margin, margin, width, height * 4));

            var message = new NSMutableAttributedString(str: richMessage, font: UIFont.ItalicSystemFontOfSize(14), foregroundColor: UIColor.Black);
            message.Append(new NSMutableAttributedString(str: " " + normalMessage, font: UIFont.SystemFontOfSize(14), foregroundColor: UIColor.Black));
            var lblText = new UILabel(new CGRect(0, -(height / 2), width, height * 2)) { AttributedText = message };
            lblText.LineBreakMode = UILineBreakMode.WordWrap;
            lblText.Lines = 0;
            container.AddSubview(lblText);

            var cancel = new UIButton(new CGRect(0, height, width / 2, height * 2));
            cancel.SetTitle("NO", UIControlState.Normal);
            cancel.AddTarget((sender, e) => alertvc.DismissViewController(true, null), UIControlEvent.TouchUpInside);
            cancel.SetTitleColor(UIColor.Blue, UIControlState.Normal);
            if (onCancel != null) {
                cancel.AddTarget((sender, e) => {
                    onCancel();
                },
                UIControlEvent.TouchUpInside);
            }
            container.AddSubview(cancel);

            var ok = new UIButton(new CGRect(width / 2, height, width / 2, height * 2));
            ok.SetTitle("YES", UIControlState.Normal);
            Action okAction = async () => {
                ok.Enabled = false;
                await uiHelper.RunBlocking(() => {
                    onOkCallback();
                });
                alertvc.DismissViewController(true, null);
            };
            ok.SetTitleColor(UIColor.Blue, UIControlState.Normal);
            container.AddSubview(ok);
            ok.AddTarget((sender, e) => {
                okAction();
            }, UIControlEvent.TouchUpInside);

            var controller = new UIViewController();
            controller.View.AddSubview(container);
            alertvc.SetValueForKey(controller, new NSString("contentViewController"));
            vc.PresentViewController(alertvc, true, null);
        }
</code>```

Body:
I need to display an alert with some part of the message in italics and the other part normal, something like this:

var title = "Title";
var body = "This part in Italic. This part normal.";
Application.Current.MainPage.DisplayAlert(title, body, "OK");

With the part that says: "This part in Italic." in italics and the other one in normal text.

Is it possible to do? If yes, how?

Thanks in advance!

Body:
I ended up creating a native alert controller like this:

void PromptRichTextPopup(string title, string richMessage, string normalMessage, Action onOkCallback, Action onCancel = null) {
            var vc = UIKit.UIApplication.SharedApplication.KeyWindow.RootViewController;
            // take top presented view controller
            while (vc.PresentedViewController != null) {
                vc = vc.PresentedViewController;
            }

            var alertvc = UIAlertController.Create(title, string.Empty, UIAlertControllerStyle.Alert);
            var leftAligned = new NSMutableParagraphStyle();
            leftAligned.Alignment = UITextAlignment.Left;

            var colorTitle = new NSAttributedString(str: title, font: UIFont.BoldSystemFontOfSize(18), foregroundColor: Xamarin.Forms.Color.FromHex("#61acad").ToUIColor());

            alertvc.SetValueForKey(colorTitle, new NSString("attributedTitle"));

            var margin = 5f;
            var height = 30f;
            var width = 256f;

            var container = new UIView(new CGRect(margin, margin, width, height * 4));

            var message = new NSMutableAttributedString(str: richMessage, font: UIFont.ItalicSystemFontOfSize(14), foregroundColor: UIColor.Black);
            message.Append(new NSMutableAttributedString(str: " " + normalMessage, font: UIFont.SystemFontOfSize(14), foregroundColor: UIColor.Black));
            var lblText = new UILabel(new CGRect(0, -(height / 2), width, height * 2)) { AttributedText = message };
            lblText.LineBreakMode = UILineBreakMode.WordWrap;
            lblText.Lines = 0;
            container.AddSubview(lblText);

            var cancel = new UIButton(new CGRect(0, height, width / 2, height * 2));
            cancel.SetTitle("NO", UIControlState.Normal);
            cancel.AddTarget((sender, e) => alertvc.DismissViewController(true, null), UIControlEvent.TouchUpInside);
            cancel.SetTitleColor(UIColor.Blue, UIControlState.Normal);
            if (onCancel != null) {
                cancel.AddTarget((sender, e) => {
                    onCancel();
                },
                UIControlEvent.TouchUpInside);
            }
            container.AddSubview(cancel);

            var ok = new UIButton(new CGRect(width / 2, height, width / 2, height * 2));
            ok.SetTitle("YES", UIControlState.Normal);
            Action okAction = async () => {
                ok.Enabled = false;
                await uiHelper.RunBlocking(() => {
                    onOkCallback();
                });
                alertvc.DismissViewController(true, null);
            };
            ok.SetTitleColor(UIColor.Blue, UIControlState.Normal);
            container.AddSubview(ok);
            ok.AddTarget((sender, e) => {
                okAction();
            }, UIControlEvent.TouchUpInside);

            var controller = new UIViewController();
            controller.View.AddSubview(container);
            alertvc.SetValueForKey(controller, new NSString("contentViewController"));
            vc.PresentViewController(alertvc, true, null);
        }


问:
OpenGL copy ColorAttachment0 from a Renderbuffer to a Texture2D
I'm using OpenTK and C#.
I'm rendering to a renderbuffer and I need to copy it's contents(ColorAttachment0) to a Texture2D so I can do some post-processing on it, and the draw it to the screen. How do I do this?
I would use texture instead of a renderbuffer, but I need to Anti-alias the framebuffer, and using GL.RenderbufferStorageMultisample is the only way I know how to.</p>

答:
Just create another FBO and attach the texture to it. Bind the multisampled FBO to GL_READ_FRAMEBUFFER and the texture FBO to GL_DRAW_FRAMEBUFFER. Then call glBlitFramebuffer with the correct parameters. This will copy and resolve the samples to make non-multisampled data, and output it to the texture.

If you want to resolve the samples directly, you can use the GL_ARB_texture_multisample extension.


问:
CSS background grids: horizontal repeating-linear-gradient with single vertical column
I'm trying to create a specific background pattern on a single element using only CSS. The image below shows the end result I am aiming for:

I can create the repeating horizontal stripes using the following:

```<code>  background-image: repeating-linear-gradient(
                  to bottom,
                  #f7f7f8 0,
                  #f7f7f8 32px,
                  rgba(255, 255, 255, 0) 32px,
                  rgba(255, 255, 255, 0) 64px
  );
</code>```

But I am struggling to combine this with the vertical bar to the right. I'm not even sure if it's possible to achieve what I want... It needs to:

Be a set distance, in pixels, from the right hand edge

Be a fixed width, in pixels

Completely overlay the horizontal grid beneath, ie. it should be the same color regardless of the underlying color- no transparency.

Is this possible?

答:
You can lay 2 gradients on top of each others. first is always on top of next.

html {
  min-height: 100%;
  background: linear-gradient(
      to left,
      transparent 140px,
      grey 140px,
      grey 143px,
      transparent 143px
    ),
    repeating-linear-gradient(
      to bottom,
      lightgrey 0,
      lightgrey 20px,
      transparent 20px,
      transparent 40px
    );
}```

Body:
I'm trying to create a specific background pattern on a single element using only CSS. The image below shows the end result I am aiming for:

I can create the repeating horizontal stripes using the following:

  background-image: repeating-linear-gradient(
                  to bottom,
                  #f7f7f8 0,
                  #f7f7f8 32px,
                  rgba(255, 255, 255, 0) 32px,
                  rgba(255, 255, 255, 0) 64px
  );

But I am struggling to combine this with the vertical bar to the right. I'm not even sure if it's possible to achieve what I want... It needs to:

Be a set distance, in pixels, from the right hand edge

Be a fixed width, in pixels

Completely overlay the horizontal grid beneath, ie. it should be the same color regardless of the underlying color- no transparency.

Is this possible?


问:
How to move content of folder to unique folders every three hours in linux platform?
Whenvever my computer starts up I want to move contents of a folder to a unique folders.

For Example, Folder "A" has some Pictures then in the start up I want to MOVE the contents to a new folder "B". Again after 3 Hours I want to Move the contents from Folder "A" to newly Created Folder "C". Every Three hours I want a new folder to made for keeping the Content. Can any one help?

答:
I created a script that creates backup accordingly to specified parameters. To add it to your system do following steps:

You could save as something like folder_backup (don't forget to make script executable by performing $ chmod +x folder_backup).

(OPTIONAL step) After that you could copy it to /usr/local/bin if you want your script to be executable as command from any directory (sudo cp folder_backup /usr/local/bin).

Now you are ready to execute script with either typing $ ./folder_backup or $ folder_backup (if you copied / moved it to /usr/local/bin or other bin directory).

Usage: folder_backup FOLDER_NAME [BACKUP_FOLDER_NAME]
(backup folder name is optional, if you won't specify it will save backup at FOLDER_NAME_Year-Month-Day_Hour:Minutes.

Now that you have everything needed you just have to execute script in while or for loop for example: while true; do sleep TIME_IN_SECONDS; folder_backup FOLDER_NAME; done. This will create backup folders with timestamps if specified folder is not empty. For your specific case TIME_IN_SECONDS should be 10800, so command would look like while true; do sleep 10800; folder_backup A; done However you could write your own algorithm of backup folder naming and add it as second variable after name A. Also you should note that this won't run in background, if you want it to run in background simply add & to end of while loop (after done).

Hope this is what you seek!!!

#!/bin/bash

create_backup () {
    # Check if 2 arguments are given to function.
    if [ -z ${3+x} ]; then
        # Check if folder from which we will make backup exists.
        if [ -d ${1} ]; then
            echo "Creating backup in ${2} of folder ${1}..."
            mkdir -p ${2}
            mv ${1}/* ${2}/
            echo "Backup stored in ${2}."
        else
            echo "There is no folder in ${1}!"
            exit 1
        fi
    else
        echo "You must specify folder and backup folder name!"
        exit 1
    fi
}

if [ -z ${2+x} ]; then
    # Only main folder specified
    main_folder=${1}
    date_stamp=`date +%Y-%m-%d_%H:%M`
    backup_folder=${main_folder}_"${date_stamp}
elif [ -z ${3+x} ]; then
    main_folder=${1}
    backup_folder=${2}
else
    echo "Specify folder path or folder name and backup folder path!"
    exit 1
fi

create_backup ${main_folder} ${backup_folder}
```


问:
Error: No value for "ColumnName". Get JSON value in Android
I want to get f_index value from JSON into my Android App. I am getting an error "No value for f_index.

```<code>W/System.err: org.json.JSONException: No value for f_index
</code>```

If I remove the below line then I am able to get the lat, long and is_local values properly and further use them.

```<code>ill_id_data.add(ill_jo.getInt("f_index"));
</code>```

I am not able to understand what is going wrong here?

JSON received in the app which I pass to parse method.

```<code>{
"server_response": [{
    "f_index": "3",
    "lat": "21.9159",
    "long": "78.1021",
    "is_local": "0"
}, {
    "f_index": "6",
    "lat": "25.0751",
    "long": "54.9476",
    "is_local": "0"
}, {
    "f_index": "7",
    "lat": "14.6773",
    "long": "75.542",
    "is_local": "1"
}, {
    "f_index": "8",
    "lat": "21.9159",
    "long": "78.1021",
    "is_local": "0"
}, {
    "f_index": "9",
    "lat": "25.8079",
    "long": "86.0449",
    "is_local": "1"
}]
}
</code>```

Code for parsing the JSON in my App.

```<code>ArrayList<Double> ill_lat_data = new ArrayList<Double>(3);
ArrayList<Double> ill_long_data = new ArrayList<Double>(3);
ArrayList<Interger> ill_id_data = new ArrayList<Integer>(3);
ArrayList<Integer> ill_is_local_data = new ArrayList<Integer>(3);

public void parseIndexLatLngJSON() {

    int count_ill = 0;

    try {
        ill_json_object = new JSONObject(json_index_latlng);
        ill_json_array = gm_json_object.getJSONArray("server_response");

        while (count_ill < ill_json_array.length()) {
            JSONObject ill_jo = ill_json_array.getJSONObject(count_ill);

            ill_id_data.add(ill_jo.getInt("f_index"));
            Log.d("tag_last_check", String.valueOf(ill_jo.getInt("f_index")));
            ill_lat_data.add(ill_jo.getDouble("lat"));
            ill_is_local_data.add(ill_jo.getInt("is_local"));
            ill_long_data.add(ill_jo.getDouble("long"));

            count_ill++;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
</code>```

This is my php file.

```<code>$sql="SELECT id,lat,`long` FROM newsphere_one WHERE lat != 0 OR `long` != 0;";

$con=mysqli_connect($host,$hostname,$password,$db);

$result = mysqli_query($con,$sql);

$response = array();

while($row=mysqli_fetch_array($result)){
array_push($response, array("f_index" => $row[0],"lat" => $row[1],"long" => $row[2],"is_local" => $row[3]));
}

echo json_encode(array("server_response"=>$response));
</code>```

答:
In php

change the below line from

```<code>array_push($response, array("f_index" => $row[0],"lat" => $row[1],"long" => $row[2],"is_local" => $row[3]));
</code>```

to

```<code>array_push($response, array("f_index" => intval($row[0]),"lat" => $row[1],"long" => $row[2],"is_local" => $row[3]));
</code>```

use intval($row[0]) to convert to integer

or

use floatval($row[0]) to convert to float

Body:
I want to get f_index value from JSON into my Android App. I am getting an error "No value for f_index.

W/System.err: org.json.JSONException: No value for f_index

If I remove the below line then I am able to get the lat, long and is_local values properly and further use them.

ill_id_data.add(ill_jo.getInt("f_index"));

I am not able to understand what is going wrong here?

JSON received in the app which I pass to parse method.

{
"server_response": [{
    "f_index": "3",
    "lat": "21.9159",
    "long": "78.1021",
    "is_local": "0"
}, {
    "f_index": "6",
    "lat": "25.0751",
    "long": "54.9476",
    "is_local": "0"
}, {
    "f_index": "7",
    "lat": "14.6773",
    "long": "75.542",
    "is_local": "1"
}, {
    "f_index": "8",
    "lat": "21.9159",
    "long": "78.1021",
    "is_local": "0"
}, {
    "f_index": "9",
    "lat": "25.8079",
    "long": "86.0449",
    "is_local": "1"
}]
}

Code for parsing the JSON in my App.

ArrayList<Double> ill_lat_data = new ArrayList<Double>(3);
ArrayList<Double> ill_long_data = new ArrayList<Double>(3);
ArrayList<Interger> ill_id_data = new ArrayList<Integer>(3);
ArrayList<Integer> ill_is_local_data = new ArrayList<Integer>(3);

public void parseIndexLatLngJSON() {

    int count_ill = 0;

    try {
        ill_json_object = new JSONObject(json_index_latlng);
        ill_json_array = gm_json_object.getJSONArray("server_response");

        while (count_ill < ill_json_array.length()) {
            JSONObject ill_jo = ill_json_array.getJSONObject(count_ill);

            ill_id_data.add(ill_jo.getInt("f_index"));
            Log.d("tag_last_check", String.valueOf(ill_jo.getInt("f_index")));
            ill_lat_data.add(ill_jo.getDouble("lat"));
            ill_is_local_data.add(ill_jo.getInt("is_local"));
            ill_long_data.add(ill_jo.getDouble("long"));

            count_ill++;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

This is my php file.

$sql="SELECT id,lat,`long` FROM newsphere_one WHERE lat != 0 OR `long` != 0;";

$con=mysqli_connect($host,$hostname,$password,$db);

$result = mysqli_query($con,$sql);

$response = array();

while($row=mysqli_fetch_array($result)){
array_push($response, array("f_index" => $row[0],"lat" => $row[1],"long" => $row[2],"is_local" => $row[3]));
}

echo json_encode(array("server_response"=>$response));

Body:
In php

change the below line from

array_push($response, array("f_index" => $row[0],"lat" => $row[1],"long" => $row[2],"is_local" => $row[3]));

to

array_push($response, array("f_index" => intval($row[0]),"lat" => $row[1],"long" => $row[2],"is_local" => $row[3]));

use intval($row[0]) to convert to integer

or

use floatval($row[0]) to convert to float


问:
Round Display Picture
Im creating an application which includes the home screen. This will have a biography of the client. Im trying to create a header, which will include the title and a round display image. From the code i used 3 divs, which will hold the wrapper, title and picture. I done the display:flex which will have them in 1 line, and flex:1 to move the image to the right. When doing the radius 50% its squishing the photo . Can you help me out?

Thanks. Heres the code.

.headerOfBio {
  display: flex
}

.displayPic {
  flex: 1 background-image: url("../images/displayPicture.jpg") border-radius: 50%
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="quote titleBio">
  <div class="headerOfBio">
    <h3>
      MEET THE <span class="diffColor">FOUNDER</span>
    </h3>

    <div class="displayPic">

    </div>
  </div>

</div></code>```

After adding height and width it becomes like this:

答:
Why have you used flex:1?

Try this...

```<code>.headerOfBio {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.displayPic {
  background: url("https://aeutas.org.au/wp-content/uploads/2014/12/people-icon.png") no-repeat;
  border-radius: 50%;
  height: 100px;
  width: 100px;
  border-radius : 50%;
}
</code>```

https://jsfiddle.net/cd3czf30/1/

Title: Round Display Picture

Body:
Im creating an application which includes the home screen. This will have a biography of the client. Im trying to create a header, which will include the title and a round display image. From the code i used 3 divs, which will hold the wrapper, title and picture. I done the display:flex which will have them in 1 line, and flex:1 to move the image to the right. When doing the radius 50% its squishing the photo . Can you help me out?

Thanks. Heres the code.

.headerOfBio {
  display: flex
}

.displayPic {
  flex: 1 background-image: url("../images/displayPicture.jpg") border-radius: 50%
}

      MEET THE FOUNDER

After adding height and width it becomes like this:

Body:
Why have you used flex:1?

Try this...

.headerOfBio {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.displayPic {
  background: url("https://aeutas.org.au/wp-content/uploads/2014/12/people-icon.png") no-repeat;
  border-radius: 50%;
  height: 100px;
  width: 100px;
  border-radius : 50%;
}

https://jsfiddle.net/cd3czf30/1/


问:
How to size an Image of a button?
I have the following Layout

```<code>            <Button
                android:layout_width="fill_parent"
                android:layout_height="75dp"
                android:drawableLeft="@drawable/binocular"
                android:gravity="left|center_vertical"
                android:text="search" />
</code>```

and it looks like :

The picture is too large. I simply want to align the image to the left with the corredct size, so it fits with the height of the button.

I know I could adjust the bound of the image by code. But I would like to know, if there is a way to do with layout specification.

There is a solution mentoined : how to change a drawableLeft icon size on a button? (accepted answer)

I guess this is the correct one, but I do not understand , where to put the layer-list and how to reference it in the button.

Can someone help ?

答:
You have to create new drawable xml file and there put layer-list code. For example button_background.xml.

Then set on button this drawable

```<code>android:drawableLeft="@drawable/button_background"
</code>```

Title: How to size an Image of a button?

Body:
I have the following Layout

            <Button
                android:layout_width="fill_parent"
                android:layout_height="75dp"
                android:drawableLeft="@drawable/binocular"
                android:gravity="left|center_vertical"
                android:text="search" />

and it looks like :

The picture is too large. I simply want to align the image to the left with the corredct size, so it fits with the height of the button.

I know I could adjust the bound of the image by code. But I would like to know, if there is a way to do with layout specification.

There is a solution mentoined : how to change a drawableLeft icon size on a button? (accepted answer)

I guess this is the correct one, but I do not understand , where to put the layer-list and how to reference it in the button.

Can someone help ?

Body:
You have to create new drawable xml file and there put layer-list code. For example button_background.xml.

Then set on button this drawable

android:drawableLeft="@drawable/button_background"


问:
AWS secure storage for shared configurations
I have a bunch of applications on AWS and some of the configurations (Database connection strings, API keys, etc.) are used by multiple applications. So is there a way to store all configurations in some secure storage with convenient API? Does AWS provide this kind of service?</p>

答:
Check out the new Systems Manager Parameter Store, which is designed for the secure, centralized management of application secrets.

AWS Systems Manager Parameter Store provides secure, hierarchical
  storage for configuration data management and secrets management. You
  can store data such as passwords, database strings, and license codes
  as parameter values. You can store values as plain text or encrypted
  data. You can then reference values by using the unique name that you
  specified when you created the parameter. Highly scalable, available,
  and durable, Parameter Store is backed by the AWS Cloud. Parameter
  Store is offered at no additional charge and includes generous limits

The Parameter Store service offers advantages over using S3 - a common way to secure secrets before the Parameter Store. These advantages include:

Easy creation of namespaces to support different stages of the application lifecycle.

KMS integration that abstracts parameter encryption from the application while requiring the instance or container to have access to the KMS key and for the decryption to take place locally in memory.

Stored history about parameter changes.

A service that can be controlled separately from S3, which is likely used for many other applications.

A purpose-built configuration data store, reducing overhead from implementing multiple systems.

No usage costs.


问:
Don't drop dimensions when subseting 3-dimensional array
Let A be a 1 x 2 x 2-array:

```<code>> A <- array(0, dim=c(1,2,2))
> A
, , 1

     [,1] [,2]
[1,]    0    0

, , 2

     [,1] [,2]
[1,]    0    0
</code>```

Then A[,,1] is dimensionless:

```<code>> A[,,1]
[1] 0 0
</code>```

I would like to have:

```<code>     [,1] [,2]
[1,]    0    0
</code>```

The drop argument does not yield what I want:

```<code>> A[,,1,drop=FALSE]
, , 1

     [,1] [,2]
[1,]    0    0
</code>```

I find that annoying. And buggy, because R identifies vectors to column matrices, not to row matrices.

Of course I could do matrix(A[,,1], 1, 2). Is there a more convenient way?

答:
We can just assign the dim based on the MARGIN we are extracting

```<code>`dim<-`(A[, ,1], apply(A, 3, dim)[,1])
 #     [,1] [,2]
 #[1,]    0    0
</code>```

Using another example

```<code>B <- array(0, dim = c(2, 1, 2))
`dim<-`(B[, ,1], apply(B, 3, dim)[,1])
 #    [,1]
#[1,]    0
#[2,]    0
</code>```

If we are using a package solution, then adrop from abind could get the expected output

```<code>library(abind)
adrop(A[,,1,drop=FALSE], drop = 3)
#      [,1] [,2]
# [1,]    0    0

adrop(B[,,1,drop=FALSE], drop = 3)
#     [,1]
#[1,]    0
#[2,]    0
</code>```

Body:
Let A be a 1 x 2 x 2-array:

> A <- array(0, dim=c(1,2,2))
> A
, , 1

     [,1] [,2]
[1,]    0    0

, , 2

     [,1] [,2]
[1,]    0    0

Then A[,,1] is dimensionless:

> A[,,1]
[1] 0 0

I would like to have:

     [,1] [,2]
[1,]    0    0

The drop argument does not yield what I want:

> A[,,1,drop=FALSE]
, , 1

     [,1] [,2]
[1,]    0    0

I find that annoying. And buggy, because R identifies vectors to column matrices, not to row matrices.

Of course I could do matrix(A[,,1], 1, 2). Is there a more convenient way?

Body:
We can just assign the dim based on the MARGIN we are extracting

`dim<-`(A[, ,1], apply(A, 3, dim)[,1])
 #     [,1] [,2]
 #[1,]    0    0

Using another example

B <- array(0, dim = c(2, 1, 2))
`dim<-`(B[, ,1], apply(B, 3, dim)[,1])
 #    [,1]
#[1,]    0
#[2,]    0

If we are using a package solution, then adrop from abind could get the expected output

library(abind)
adrop(A[,,1,drop=FALSE], drop = 3)
#      [,1] [,2]
# [1,]    0    0

adrop(B[,,1,drop=FALSE], drop = 3)
#     [,1]
#[1,]    0
#[2,]    0


问:
Python - how to replace the same char in a string with random integer for each occurence
i have the following string for Example

```<code>str = "TESTXXXXX"
</code>```

and i want to replace each X with a number, so the output should be something like this:

```<code>TEST98965
</code>```

not :

```<code>TEST66666
</code>```

i made the following python script to do the job.

```<code>from sys import argv
from random import randint

bincode = argv[1].lower()
replaced = bincode.replace('x',str(randint(0,9)))
print replaced
</code>```

it takes a input from a user, and replaces each 'x' with a random number, the problem here is that the script replaces all the 'x' with the same number, i want each 'x' to be replaced with a different number, for example if user input is:

xxx

the output would be something like this:

986

Any suggestions on how to do that?

答:
You can use the re.sub function which supports a function as the replacement.
https://docs.python.org/2/library/re.html#re.sub

The function will be called for each match for the regex pattern and must produce the replacement.

```<code>s = "TESTXXXXX"

import re
import random

def repl_fun(match):
    return str(random.randint(0,9))

replaced = re.sub('X', repl_fun, s)
print replaced

# output example:
# TEST57681
</code>```

Body:
i have the following string for Example

str = "TESTXXXXX"

and i want to replace each X with a number, so the output should be something like this:

TEST98965

not :

TEST66666

i made the following python script to do the job.

from sys import argv
from random import randint

bincode = argv[1].lower()
replaced = bincode.replace('x',str(randint(0,9)))
print replaced

it takes a input from a user, and replaces each 'x' with a random number, the problem here is that the script replaces all the 'x' with the same number, i want each 'x' to be replaced with a different number, for example if user input is:

xxx

the output would be something like this:

986

Any suggestions on how to do that?

Body:
You can use the re.sub function which supports a function as the replacement.
https://docs.python.org/2/library/re.html#re.sub

The function will be called for each match for the regex pattern and must produce the replacement.

s = "TESTXXXXX"

import re
import random

def repl_fun(match):
    return str(random.randint(0,9))

replaced = re.sub('X', repl_fun, s)
print replaced

# output example:
# TEST57681


问:
Alpha / Transparency & MTKView?
I have a Metal fragment shader that returns some transparent colors with an alpha channel and I'd like to reveal a UIView under the MTKView, but they only background result I get is black and "error noise".

MTLRenderPipelineDescriptor:

```<code>pipelineStateDescriptor.isAlphaToCoverageEnabled = true
pipelineStateDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
pipelineStateDescriptor.colorAttachments[0].isBlendingEnabled = true
pipelineStateDescriptor.colorAttachments[0].destinationRGBBlendFactor = .oneMinusSourceAlpha
pipelineStateDescriptor.colorAttachments[0].destinationAlphaBlendFactor = .oneMinusSourceAlpha
</code>```

MTLRenderPassDescriptor:

```<code>renderPassDescriptor.colorAttachments[0].loadAction = .clear
renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 0)
</code>```

If I change the clear color I can see it under the transparent colors, tho if I skip the clear color I see "error noise". Does the clear color alpha channel actually do anything?

Does anyone know how to make a MTKView transparent?

Update:

Here's the magical property to make a MTKView transparent:

```<code>self.isOpaque = false
</code>```

答: If a UIView may have transparent content or otherwise fail to fill itself with opaque drawing, then it should set its opaque (isOpaque) property to false so that it will be properly composited with whatever is behind it. Since, MTKView is a subclass of UIView, this applies to it as well.

Title: Alpha / Transparency & MTKView?

Body:
I have a Metal fragment shader that returns some transparent colors with an alpha channel and I'd like to reveal a UIView under the MTKView, but they only background result I get is black and "error noise".

MTLRenderPipelineDescriptor:

pipelineStateDescriptor.isAlphaToCoverageEnabled = true
pipelineStateDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
pipelineStateDescriptor.colorAttachments[0].isBlendingEnabled = true
pipelineStateDescriptor.colorAttachments[0].destinationRGBBlendFactor = .oneMinusSourceAlpha
pipelineStateDescriptor.colorAttachments[0].destinationAlphaBlendFactor = .oneMinusSourceAlpha

MTLRenderPassDescriptor:

renderPassDescriptor.colorAttachments[0].loadAction = .clear
renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 0)

If I change the clear color I can see it under the transparent colors, tho if I skip the clear color I see "error noise". Does the clear color alpha channel actually do anything?

Does anyone know how to make a MTKView transparent?

Update:

Here's the magical property to make a MTKView transparent:

self.isOpaque = false