问:
I am trying to insert records into a an object list but nothing gets inserted when I call the method. What am I doing wrong?
I'm attempting to insert data into a list using a method but nothing I attempt to insert shows up after I call the method. Can someone tell me what I'm doing wrong? I'm calling InsertMedicationOrder.

```<code>    private List<Medication> Meds;

    private List<MedOrder> MedOrder_;

    public FakeMedicationAccessor()
    {
        MedOrder_ = new List<MedOrder>()
        {
            new MedOrder(){}
        };
    }

    public int InsertMedicationOrder(int orderID, int employeeID, int itemID, string itemName, int quantity)
    {
        MedOrder_.Add(GetMedicationOrder(orderID, employeeID, itemID, itemName, quantity));

        return 0;
    }

    public MedOrder GetMedicationOrder(int orderID, int employeeID, int itemID,string itemName, int quantity)
    {
        return new MedOrder
        {
            outgoingOrderID = orderID,
            employeeID = employeeID,
            itemID = itemID,
            itemName = itemName,
            quantityOrdered = quantity,
            itemCategoryID = "Medication"
        };
    }
</code>```

The method is passed into here-

```<code>public bool CreateMedicationOrder(int orderID, int employeeID, int itemID, string itemName, int quantity)
{
    bool result = false;
    try
    {
        result = (1 == _activityAccessor.InsertMedicationOrder(orderID, employeeID, itemID, itemName, quantity));
    }
    catch (System.ApplicationException ex)
    {
        throw new ApplicationException("Meds not ordered", ex);
    }
    return result;
}
</code>```

And called here

```<code>public void OrderMedications()
{
    _medicationManager = new MedicationManager();
    int orderID = 1;
    int employeeID = 66;
    int itemID = 1;
    string itemName = "Med_A";

    _medicationManager.CreateMedicationOrder(orderID, employeeID, itemID, itemName, Int32.Parse(Quantity_input.Text));
}
</code>```

Instantiation of FakeMedicationAccessor

```<code>  private IMedicationAccessor _activityAccessor;

    public MedicationManager()
    {
        _activityAccessor = new FakeMedicationAccessor();

    }

    public MedicationManager(IMedicationAccessor MedicationManager)
    {
        _activityAccessor = MedicationManager;

    }
</code>```

答:
Please try with a singleton instance of the MedicationManager class. Each time you are creating an object of MedicationManager classs which will in turn create a new instance of FakeMedicationAccessor class.

```<code>    public void OrderMedications()
    {
        if(_medicationManager == null)
        {
            _medicationManager = new MedicationManager();
        }
        int orderID = 1;
        int employeeID = 66;
        int itemID = 1;
        string itemName = "Med_A";

        _medicationManager.CreateMedicationOrder(orderID, employeeID, itemID, itemName, Int32.Parse(Quantity_input.Text));
    }
</code>```

Do that null check whereever you create a new instance of MedicationManager

Body:
I'm attempting to insert data into a list using a method but nothing I attempt to insert shows up after I call the method. Can someone tell me what I'm doing wrong? I'm calling InsertMedicationOrder.

    private List<Medication> Meds;

    private List<MedOrder> MedOrder_;

    public FakeMedicationAccessor()
    {
        MedOrder_ = new List<MedOrder>()
        {
            new MedOrder(){}
        };
    }

    public int InsertMedicationOrder(int orderID, int employeeID, int itemID, string itemName, int quantity)
    {
        MedOrder_.Add(GetMedicationOrder(orderID, employeeID, itemID, itemName, quantity));

        return 0;
    }

    public MedOrder GetMedicationOrder(int orderID, int employeeID, int itemID,string itemName, int quantity)
    {
        return new MedOrder
        {
            outgoingOrderID = orderID,
            employeeID = employeeID,
            itemID = itemID,
            itemName = itemName,
            quantityOrdered = quantity,
            itemCategoryID = "Medication"
        };
    }

The method is passed into here-

public bool CreateMedicationOrder(int orderID, int employeeID, int itemID, string itemName, int quantity)
{
    bool result = false;
    try
    {
        result = (1 == _activityAccessor.InsertMedicationOrder(orderID, employeeID, itemID, itemName, quantity));
    }
    catch (System.ApplicationException ex)
    {
        throw new ApplicationException("Meds not ordered", ex);
    }
    return result;
}

And called here

public void OrderMedications()
{
    _medicationManager = new MedicationManager();
    int orderID = 1;
    int employeeID = 66;
    int itemID = 1;
    string itemName = "Med_A";

    _medicationManager.CreateMedicationOrder(orderID, employeeID, itemID, itemName, Int32.Parse(Quantity_input.Text));
}

Instantiation of FakeMedicationAccessor

  private IMedicationAccessor _activityAccessor;

    public MedicationManager()
    {
        _activityAccessor = new FakeMedicationAccessor();

    }

    public MedicationManager(IMedicationAccessor MedicationManager)
    {
        _activityAccessor = MedicationManager;

    }

Body:
Please try with a singleton instance of the MedicationManager class. Each time you are creating an object of MedicationManager classs which will in turn create a new instance of FakeMedicationAccessor class.

    public void OrderMedications()
    {
        if(_medicationManager == null)
        {
            _medicationManager = new MedicationManager();
        }
        int orderID = 1;
        int employeeID = 66;
        int itemID = 1;
        string itemName = "Med_A";

        _medicationManager.CreateMedicationOrder(orderID, employeeID, itemID, itemName, Int32.Parse(Quantity_input.Text));
    }

Do that null check whereever you create a new instance of MedicationManager


来源: stackexchange

问:
Can I selectively create a backup of Postgres database, with only certian tables?
Can I programatically(or whichever way works fine) create the backup of a database, with only the tables I want? I have around 100 tables in my database and I want only 10 tables backup(ofcourse all are interdependant). How can I achieve this? And by the way I have a postgresql database.</p>

答:
Of course. pg_dump lets you pass list of tables with parameter -t

To clear some doubts. True, the -t parameter accepts only one pattern. But it's a pattern very similar to regular expression, so if you want to dump tables A, B & C you can do:

```<code>pg_dump -t '(A|B|C)'
</code>```

OwnerDisplayName: Maddy

ContentLicense: CC BY-SA 2.5

Body:
Of course. pg_dump lets you pass list of tables with parameter -t

To clear some doubts. True, the -t parameter accepts only one pattern. But it's a pattern very similar to regular expression, so if you want to dump tables A, B & C you can do:

pg_dump -t '(A|B|C)'


问:
php java batch processing
I work in Linux. I have 3 file (about 2Gb each containing human genome sequence). I have java codes to process those files via web interface developed in PHP. The processing time is about 24 hours or even more.

How can i run the Java code from PHP so that the processing does not terminate when I close the browser.

Since the processing time is so long, it is not practicable to keep the browser open until the process get completed.

I assume it requires batch processing.

答:
This is my proposed solution:

1) Create a db table or a config file where to store a flag, "add_process_to_queue" for example.

2) From your PHP panel, you could set this flag to 1

3) Set up a cron job that checks for this flag and if it is set to 1, the job resets to 0 and starts the Java program

ContentLicense: CC BY-SA 3.0

Title: php java batch processing


问:
How to specify name for routes of a resource route
My need is that if in case I changed the route

```<code>Route::resource('/admin/users','AdminUserscontroller');
</code>```

TO:

```<code>Route::resource('/admin/admin_users','AdminUserscontroller');
</code>```

I have to  change all the anchor tag link one by one,, How to avoid that?

MY anchor link as following

```<code><a class="nav-link collapsed" href="{{route('users.index')}}" data-toggle="collapse" data-target="#collapseLayouts" aria-expanded="false" aria-controls="collapseLayouts">
<div class="sb-nav-link-icon"><i class="fas fa-columns"></i></div>
</code>```

Users

```<code><div class="sb-sidenav-collapse-arrow"><i class="fas fa-angle-down"></i></div></a>
</code>```

答:
Add 3rd parameter to resource method, which takes array, include key 'names' to overwrite the route names</p>

```<code>Route::resource('/admin/admin_users', 'AdminUserscontroller', [
    'names' => [
        'index' => 'users.index',
        'store' => 'users.store',
        //other routes of this resource as required
    ]
]);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My need is that if in case I changed the route

Route::resource('/admin/users','AdminUserscontroller');

TO:

Route::resource('/admin/admin_users','AdminUserscontroller');

I have to  change all the anchor tag link one by one,, How to avoid that?

MY anchor link as following

Users

Body:
Add 3rd parameter to resource method, which takes array, include key 'names' to overwrite the route names

Route::resource('/admin/admin_users', 'AdminUserscontroller', [
    'names' => [
        'index' => 'users.index',
        'store' => 'users.store',
        //other routes of this resource as required
    ]
]);


问:
Why my Angular 8 project doesn't work on GitHub pages
could you help me? I'm trying to deploy an Angular 8 personal project to GitHub pages but it appears blank, and I don't know the why.

It's the first time that I try to deploy using GH-pages, I've not used the angular cli tool for deploying on gh, merely I've created a new repository and then I've added all the compiled files.

this is my repository.
https://github.com/Gerguevara/angularnews

this is the gh-pages url
https://gerguevara.github.io/angularnews/

Also I've tried to deploy it using NOW but I couldn't, I got the same issue.

答:
I must say this is interesting because I was able to get it to load. Proof

Have you tried just dropping it into a web server and see how it operates. Understand that loading the files locally will give you issues because local file access is not allowed without permissions.

Just for a little additional help.

One thing I did notice is in your first news item I seen:

[[getSimpleString(data.title)]] [[getSimpleString(data.description)]] [[getSimpleString(data.videoCountText)]]

This issue shows you need to be a little more defensive in your programming. Make sure that only data that can be displayed properly is returned from your API or server call. Also, you could make each news item a component and hide/show the component only if sufficient data is available for display.

Happy programming ;-)


问:
Is it possible to trigger a build with another release in VSTS?
We created a nuget package and use VSTS release pipeline to release it.

Then we have a UI project that demos the usage of the nuget package.

Ideally, I would like to trigger the UI project's build automatically every time our nuget package is updated.

So in the UI project's project file, I did this:

```<code><ItemGroup>
    <PackageReference Include="TheNugetPackageIwant" Version="1.*" />
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
  </ItemGroup>
</code>```

I think this will make the UI project to always use the latest package (assume we always stick version 1).

However, how can I trigger the UI project to build automatically when a new nuget package becomes available? From devop, it seems a build can only be triggered by another build.

Is there a way to walk around it?

答:
You could use the Rest API and trigger the build pipeline from the context of the release whenever you publish the nuget package.

First make sure that your Service Account running the pipeline has access to queue a build.

Next in your release definition Select the Agent Job and in the options make sure that it can access the OAuth token.

Then add a powerShell Script in your release definition to queue the build. Note that you need to go and find the BuildDefinitionId of the Build you want to queue.

```<code>#Need to find the ID of your build definition. Just open the Defintion in the web UI it will be in the url
$BuildDefintionId = 37

$Body = @"
{
    "definition": {
        "id": $BuildDefintionId
    }
}
"@

Write-host $Body

try {
    $url = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/build/builds?api-version=5.1"
    Write-Host "URL: $url"
    $response = Invoke-RestMethod -Uri $url -Method POST -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"} -Body $Body -ContentType application/json
  if ($response -ne $Null) {
    Write-Host "*******************Bingo*********************************"
  }
}
catch {
  Write-Error $_
  Write-Error $_.Exception.Message
}
</code>```

If that seems like too much work and you have the option, you can also try out an extension to do the heavy lifting for you.

Body:
We created a nuget package and use VSTS release pipeline to release it.

Then we have a UI project that demos the usage of the nuget package.

Ideally, I would like to trigger the UI project's build automatically every time our nuget package is updated.

So in the UI project's project file, I did this:

<ItemGroup>
    <PackageReference Include="TheNugetPackageIwant" Version="1.*" />
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
  </ItemGroup>

I think this will make the UI project to always use the latest package (assume we always stick version 1).

However, how can I trigger the UI project to build automatically when a new nuget package becomes available? From devop, it seems a build can only be triggered by another build.

Is there a way to walk around it?

Body:
You could use the Rest API and trigger the build pipeline from the context of the release whenever you publish the nuget package.

First make sure that your Service Account running the pipeline has access to queue a build.

Next in your release definition Select the Agent Job and in the options make sure that it can access the OAuth token.

Then add a powerShell Script in your release definition to queue the build. Note that you need to go and find the BuildDefinitionId of the Build you want to queue.

#Need to find the ID of your build definition. Just open the Defintion in the web UI it will be in the url
$BuildDefintionId = 37

$Body = @"
{
    "definition": {
        "id": $BuildDefintionId
    }
}
"@

Write-host $Body

try {
    $url = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/build/builds?api-version=5.1"
    Write-Host "URL: $url"
    $response = Invoke-RestMethod -Uri $url -Method POST -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"} -Body $Body -ContentType application/json
  if ($response -ne $Null) {
    Write-Host "*******************Bingo*********************************"
  }
}
catch {
  Write-Error $_
  Write-Error $_.Exception.Message
}

If that seems like too much work and you have the option, you can also try out an extension to do the heavy lifting for you.


问:
Heroku error with Golang web server: Web process failed to bind to $PORT within 60 seconds of launch
I am trying to run my golang web app on heroku. It will upload successfully but then it will crash with a code of "H10". However, it also gives me error R10 and states: " Web process failed to bind to $PORT within 60 seconds of launch".

Is there an issue with it trying to find the port which is clearly set in the file (and works on my computer) or is there some other issue. There is currently no database linked to the app (which according to heroku is a common cause for this crash) but it is using gorilla/mux as a dependency that is vendored so that could be the issue.

答:
See this

It appears you cannot specify an arbitrary port but must check the environment for the PORT assigned by heroku for your deployment.

You may do this with e.g.

```<code>port:=os.Getenv("PORT")
</code>```

Then use port with your server.

Please include code (even a repro) with questions to make it easier for us to understand the problem.

Body:
See this

It appears you cannot specify an arbitrary port but must check the environment for the PORT assigned by heroku for your deployment.

You may do this with e.g.

port:=os.Getenv("PORT")

Then use port with your server.

Please include code (even a repro) with questions to make it easier for us to understand the problem.


问:
Variable "x" which I mention outside the function has some problem I guess . Function is not accessing the variable don't know why
Variable "x" which I mention outside the function has some problem I guess . Function is not accessing the variable don't know why .
here is my javascript function  below if any one require my html code a can also provide

HTML Snippet

```<code><div class="row">
  <div class="col lg-3"></div>
  <div class="col lg-6 text-center">
     <div id="1">shahmir</div> </div>
     <div class="col lg-3"></div>
  </div>
</div>
</code>```

```

答:
The function can't see the outer x because it has it's own x variable received as an argument, that's called variable shadowing (https://en.wikipedia.org/wiki/Variable_shadowing)

I'm taking a wild guess of what you're trying to do:

```<code><script>
    function add(){
      var a = document.getElementById('input').value;

      document.getElementById('1').innerHTML += ('<br />' + a);
    }
</script>
</code>```

Body:
Variable "x" which I mention outside the function has some problem I guess . Function is not accessing the variable don't know why .
here is my javascript function  below if any one require my html code a can also provide

HTML Snippet

shahmir

Body:
The function can't see the outer x because it has it's own x variable received as an argument, that's called variable shadowing (https://en.wikipedia.org/wiki/Variable_shadowing)

I'm taking a wild guess of what you're trying to do:

<script>
    function add(){
      var a = document.getElementById('input').value;

      document.getElementById('1').innerHTML += ('<br />' + a);
    }
</script>


答:
You have two variables with same name x. When you are incrementing it inside function "add", it is taking the value of parameter "x" not the variable "x" defined by you.

If you want to fix this code. Do as below:
- Move declaration of x before calling function
- Replaces local parameter x with y
- Remove function keyword when you are calling function

var x = 1;
add();

function add(y) {
  var a = document.getElementById("input").value;

  x++; // x will become 2, so check  for 2 in next statement.
  if (x === 2)
    document.getElementById("1").innerHTML = a;
}```

Title: Variable "x" which I mention outside the function has some problem I guess . Function is not accessing the variable don't know why


问:
Creating a java Script function to make an api call and retrieve the data
A JavaScript function is needed to make an API call to Github and receive a response as JSON data.
The api link is as follows - https://api.github.com/users</p>

答:
Use Axios to fetch the data. Maybe you should consider reframing the question. How to get the users using https://api.github.com/users

```<code>const axios = require("axios");

async function getUsers() {
    try {
        let users = await axios.get('https://api.github.com/users');
        return {
            status: "SUCCESS",
            data: users
        }
    } catch (e) {
        return {
            status: "ERROR",
            data: ""
        }
    }
}

getUsers().then((users)=>{
    console.log(users.data);
}).catch(e => {
    console.log(e,"error while fetching users");
})
</code>```

Body:
Use Axios to fetch the data. Maybe you should consider reframing the question. How to get the users using https://api.github.com/users

const axios = require("axios");

async function getUsers() {
    try {
        let users = await axios.get('https://api.github.com/users');
        return {
            status: "SUCCESS",
            data: users
        }
    } catch (e) {
        return {
            status: "ERROR",
            data: ""
        }
    }
}

getUsers().then((users)=>{
    console.log(users.data);
}).catch(e => {
    console.log(e,"error while fetching users");
})


问:
Spring-boot restapi page call
I got a simple spring boot application. I am trying load the html file through a rest controller. Below is my folder structure. I am unable to load test.html (just as helloworld code inside it)

```<code>@RequestMapping("/show1")
public ModelAndView showpage1() {
    System.out.println("## show1");
    ModelAndView modelAndView = new ModelAndView();
     modelAndView.setViewName("test");
     return modelAndView;
}
</code>```

My test.html content

```<code><h1> hello World </h1>
</code>```

答:
Try doing this :

```<code> @RequestMapping("/show1")
            public String showpage1() {
                return "test";
            }
</code>```

where test.html is your page

Title: Spring-boot restapi page call

Body:
I got a simple spring boot application. I am trying load the html file through a rest controller. Below is my folder structure. I am unable to load test.html (just as helloworld code inside it)

@RequestMapping("/show1")
public ModelAndView showpage1() {
    System.out.println("## show1");
    ModelAndView modelAndView = new ModelAndView();
     modelAndView.setViewName("test");
     return modelAndView;
}

My test.html content

 hello World

Body:
Try doing this :

 @RequestMapping("/show1")
            public String showpage1() {
                return "test";
            }

where test.html is your page


问:
" Query was empty " error on empty image upload form field
Hi Guys i have a mysql dbase with various fields , one of which stores the file/URL to an image location. User can update / edit  the dbase when required by pre populating an php update form with that particular records data, and re-submit the changes.

it all works well except when user leaves the " Upload Image" form field blank , they then get the error " Query Was Empty" .

The reason the upload image field is left blank is because it already has an image on the dbase for that record and would like to keep it, but still update any other required data.

Also when prepopulating the update form, it cannot prepopulate the image upload field , which i believe is for security purposes, so if user does not browse to select an image and leaves the field blank , it will wipe the existing image on dbase when the form was eventually processed.

Currently i use validation to find empty form fields and point user to go back and upload an image.

I dont know how to overcome the issue without using validation to force user to re upload an image which they may not know how to do or even want to.

Any Ideas ?

```<code><?php
// get variables from form post for which record to change, and what to do with it
$action = $_GET['action'];
$id = $_GET['id'];

// THE DELETE OPTION
if($action == 'delete')
{
// set up delete query
$query = "DELETE FROM tablename WHERE id ='$id' ";
// do the query
mysql_query($query) or die('Error, query failed');
echo "<center><h3><font color=#000000>Deleted Successfully!</font></h3>";
}
// THE ADD OR EDIT OPTION
elseif (isset($_POST['add']) || isset($_POST['edit']))
{
//ADD
// File upload handling
if (isset($_POST['add'])&& $_FILES['field_3']['name']!='')
{
$field_3_filename = "file_3_".date("sihdmY").substr($_FILES['field_3']['name'],strlen($_FILES['field_3']['name'])-4);

if(!move_uploaded_file($_FILES['field_3']['tmp_name'], "./files/".$field_3_filename))
{
 die("File " .  $_FILES['field_3']['name'] . " was not uploaded.");
}

// set up insert query
$query = "INSERT into tablename(,field_1,field_2,field_3) VALUES ('" . $_POST['field_1'] . "','" . $_POST['field_2'] . "','" . "./files/".$field_3_filename . "')";
}
//EDIT
if (isset($_POST['edit'])&& $_FILES['field_3']['name']!='')
{
$field_3_filename = "file_3_".date("sihdmY").substr($_FILES['field_3']['name'],strlen($_FILES['field_3']['name'])-4);

if(!move_uploaded_file($_FILES['field_3']['tmp_name'], "./files/".$field_3_filename))
{
 die("File " .  $_FILES['field_3']['name'] . " was not uploaded.");
}
//Post..Variables..for..Update
$name = $_POST['field_1'];
$email = $_POST['field_2'];
$image  = $_POST['field_3'];

//UPDATE..QUERY
$query = "UPDATE tablename SET field_1 = '$name',field_2 = '$email',field_3 = '" . "./files/".$field_3_filename . "' WHERE id='$id'";
}
//DO...QUERY
mysql_query($query) or die(mysql_error());
echo "<center><h3><font color=#000000>Updated Successfully!</font></h3>
<br />";

//EDIT FORM
}
else
{
   // load stored values for editing event but not image field as will not prepopulate field due to security
   if($action == 'edit')
   {
      $query = "SELECT * FROM tablename WHERE id='$id'";
      $result = mysql_query($query);
      $name = mysql_result($result,0,"field_1");
      $email = mysql_result($result,0,"field_2");
   }
?>
</code>```

答:
Well only upload/update the db-table-field when the user sends an image. If not, than don't touch this field:</p>

```<code><?php
// Check if form was submitted
if(count($_POST) > 0)
{
    // Check if new image was uploaded
    if(isset($_FILE) && !empty($_FILE['image']['tmp_name']))
    {
          // Here update the whole db-table, also the image/url-column...
    }
    else
    {
         // Here update the db-table, but not the image/url-column...
    }

}
</code>```

Body:
Hi Guys i have a mysql dbase with various fields , one of which stores the file/URL to an image location. User can update / edit  the dbase when required by pre populating an php update form with that particular records data, and re-submit the changes.

it all works well except when user leaves the " Upload Image" form field blank , they then get the error " Query Was Empty" .

The reason the upload image field is left blank is because it already has an image on the dbase for that record and would like to keep it, but still update any other required data.

Also when prepopulating the update form, it cannot prepopulate the image upload field , which i believe is for security purposes, so if user does not browse to select an image and leaves the field blank , it will wipe the existing image on dbase when the form was eventually processed.

Currently i use validation to find empty form fields and point user to go back and upload an image.

I dont know how to overcome the issue without using validation to force user to re upload an image which they may not know how to do or even want to.

Any Ideas ?

<?php
// get variables from form post for which record to change, and what to do with it
$action = $_GET['action'];
$id = $_GET['id'];

// THE DELETE OPTION
if($action == 'delete')
{
// set up delete query
$query = "DELETE FROM tablename WHERE id ='$id' ";
// do the query
mysql_query($query) or die('Error, query failed');
echo "
Deleted Successfully!
";
}
// THE ADD OR EDIT OPTION
elseif (isset($_POST['add']) || isset($_POST['edit']))
{
//ADD
// File upload handling
if (isset($_POST['add'])&& $_FILES['field_3']['name']!='')
{
$field_3_filename = "file_3_".date("sihdmY").substr($_FILES['field_3']['name'],strlen($_FILES['field_3']['name'])-4);

if(!move_uploaded_file($_FILES['field_3']['tmp_name'], "./files/".$field_3_filename))
{
 die("File " .  $_FILES['field_3']['name'] . " was not uploaded.");
}

// set up insert query
$query = "INSERT into tablename(,field_1,field_2,field_3) VALUES ('" . $_POST['field_1'] . "','" . $_POST['field_2'] . "','" . "./files/".$field_3_filename . "')";
}
//EDIT
if (isset($_POST['edit'])&& $_FILES['field_3']['name']!='')
{
$field_3_filename = "file_3_".date("sihdmY").substr($_FILES['field_3']['name'],strlen($_FILES['field_3']['name'])-4);

if(!move_uploaded_file($_FILES['field_3']['tmp_name'], "./files/".$field_3_filename))
{
 die("File " .  $_FILES['field_3']['name'] . " was not uploaded.");
}
//Post..Variables..for..Update
$name = $_POST['field_1'];
$email = $_POST['field_2'];
$image  = $_POST['field_3'];

//UPDATE..QUERY
$query = "UPDATE tablename SET field_1 = '$name',field_2 = '$email',field_3 = '" . "./files/".$field_3_filename . "' WHERE id='$id'";
}
//DO...QUERY
mysql_query($query) or die(mysql_error());
echo "
Updated Successfully!

";

//EDIT FORM
}
else
{
   // load stored values for editing event but not image field as will not prepopulate field due to security
   if($action == 'edit')
   {
      $query = "SELECT * FROM tablename WHERE id='$id'";
      $result = mysql_query($query);
      $name = mysql_result($result,0,"field_1");
      $email = mysql_result($result,0,"field_2");
   }
?>

Body:
Well only upload/update the db-table-field when the user sends an image. If not, than don't touch this field:

<?php
// Check if form was submitted
if(count($_POST) > 0)
{
    // Check if new image was uploaded
    if(isset($_FILE) && !empty($_FILE['image']['tmp_name']))
    {
          // Here update the whole db-table, also the image/url-column...
    }
    else
    {
         // Here update the db-table, but not the image/url-column...
    }

}


问:
Firefox - How to view network request that opens new window
I am trying to debug (someone else's) site where there is a button that opens a new browser window that leads to a 404. I am trying to determine if the new window is opened with a POST, but the old window's dev network tools don't show the request since it occurs in a new window. And when I open the dev tools in the new window, the request has already been made and doesn't show up.

How do I view this network request in the dev tools?

答:
You can use a proxy to view the traffic.

or

Maybe I should introduce you to my main man, Edgar Charles!

https://www.charlesproxy.com/


问:
How to download a page in Angular 8 with TS in pdf format
this is the function i'm calling for downloading the page

```<code>printComponent(cmpName) {
let printContents = document.getElementById(cmpName).innerHTML;
let originalContents = document.body.innerHTML;

document.body.innerHTML = printContents;

window.print();

document.body.innerHTML = originalContents;}
</code>```

it is working but a intermediate step comes. the project requires direct download

答:
You can use pdfmake</p>

```<code>export class AppComponent {
  generatePdf(cmpName){
  const documentDefinition = { content: document.getElementById(cmpName).innerHTML
 };
  pdfmake.createPdf(documentDefinition).open();
 }
}
</code>```

Body:
this is the function i'm calling for downloading the page

printComponent(cmpName) {
let printContents = document.getElementById(cmpName).innerHTML;
let originalContents = document.body.innerHTML;

document.body.innerHTML = printContents;

window.print();

document.body.innerHTML = originalContents;}

it is working but a intermediate step comes. the project requires direct download

Body:
You can use pdfmake

export class AppComponent {
  generatePdf(cmpName){
  const documentDefinition = { content: document.getElementById(cmpName).innerHTML
 };
  pdfmake.createPdf(documentDefinition).open();
 }
}


问:
'C:\Program' is not recognized error
I've recently tried changing my environment variables to set paths to javac.exe (among other things). It was working fine until, all of a sudden, I started getting this error. For example, I declared a JAVA_HOME variable to be

C:\Program Files\Java\jdk1.7.0_25

After which, I add

%JAVA_HOME%\bin

to the PATH variable, but this gives me an error:

'C:\Program' is not recognized as an internal or external command, operable command or batch file.

This error makes it seem like it's running into problems with the space in "Program Files". This is weird, though, since it wasn't doing this for a good while, then started. Further, there are other variables with spaces in them that work just fine. I've tried deleting the variable and recreating it, putting quotes around JAVA_HOME (which goes to the correct path, but does not find javac.exe correctly)..

Any tips on what I might do?

This is on Windows 7.

EDIT:

The environment variables were set by going Control Panel > Advanced System Settings > Environment Variables. The value of the variables were set by copying the address of the folder I want through an Explorer window. I added it to the PATH environment variable by appending the address with a space between the preceding variable and a semicolon at the end, as such:

C:\Users\Demo_User_1\AppData\Roaming\npm; %JAVA_HOME%

where the JAVA_HOME variable is defined as such:

C:\Program Files\Java\jdk1.7.0_25

I test the value of the variable through a command prompt by typing %JAVA_HOME%, and that's where I get the resulting error of "'C:\Program' is not recognized..."

The results of 'set' are as follows:

```<code>C:\Users\Demo_User_1>set
ALLUSERSPROFILE=C:\ProgramData
ANDROID_HOME=C:\Users\Demo_User_1\Desktop\Android\adt-bundle-windows-x86_64-2013
0717\sdk
APPDATA=C:\Users\Demo_User_1\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
COMPUTERNAME=DEMO_USER_1-HP
ComSpec=C:\Windows\system32\cmd.exe
FP_NO_HOST_CHECK=NO
HOMEDRIVE=C:
HOMEPATH=\Users\Demo_User_1
JAVA_HOME=C:\Program Files\Java\jdk1.7.0_25
LOCALAPPDATA=C:\Users\Demo_User_1\AppData\Local
LOGONSERVER=\\DEMO_USER_1-HP
NUMBER_OF_PROCESSORS=4
OnlineServices=Online Services
OS=Windows_NT
Path=C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Clien
t\;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files
(x86)\Common Files\Microsoft Shared\Windows Live;C:\Windows\system32;C:\Windows;
C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program
Files (x86)\Windows Live\Shared;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\
x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C:\Program Files\Intel\I
ntel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Managem
ent Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engin
e Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Compone
nts\IPT;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\Wir
elessCommon\;C:\Program Files\Microsoft\Web Platform Installer\;C:\Program Files
 (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\;C:\Program Files (x86)\Windows
Kits\8.0\Windows Performance Toolkit\;C:\Program Files\Microsoft SQL Server\110\
Tools\Binn\;C:\Program Files\nodejs\; C:\Users\Demo_User_1\Desktop\Android\adt-b
undle-windows-x86_64-20130717\sdk/platform-tools; C:\Users\Demo_User_1\Desktop\A
ndroid\adt-bundle-windows-x86_64-20130717\sdk\tools; %JAVA_HOME%; %ANT_HOME%/bin
; C:\Program Files\Java\jdk1.7.0_25\bin; C:\Users\Demo_User_1\AppData\Roaming\np
m; "%JAVA_HOME%"; ;C:\Users\Demo_User_1\Desktop\Android\adt-bundle-windows-x86_6
4-20130717\sdk/tools; C:\Users\Demo_User_1\Desktop\Android\adt-bundle-windows-x8
6_64-20130717\sdk/platform-tools
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PCBRAND=Pavilion
Platform=MCD
PROCESSOR_ARCHITECTURE=AMD64
PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 58 Stepping 9, GenuineIntel
PROCESSOR_LEVEL=6
PROCESSOR_REVISION=3a09
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)
ProgramW6432=C:\Program Files
PROMPT=$P$G
PSModulePath=C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
PUBLIC=C:\Users\Public
SESSIONNAME=Console
SystemDrive=C:
SystemRoot=C:\Windows
TEMP=C:\Users\DEMO_U~1\AppData\Local\Temp
TMP=C:\Users\DEMO_U~1\AppData\Local\Temp
USERDOMAIN=Demo_User_1-HP
USERNAME=Demo_User_1
USERPROFILE=C:\Users\Demo_User_1
VS110COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools
\
windir=C:\Windows
windows_tracing_flags=3
windows_tracing_logfile=C:\BVTBin\Tests\installpackage\csilogfile.log
</code>```

答:
It is very clear that , this is caused due to the blank space. Just add quotes to the phrase it foldername which contains a blank space
C:\"Program Files"\Java\jdk1.7.0_25</p>

Title: 'C:\Program' is not recognized error

Body:
I've recently tried changing my environment variables to set paths to javac.exe (among other things). It was working fine until, all of a sudden, I started getting this error. For example, I declared a JAVA_HOME variable to be

C:\Program Files\Java\jdk1.7.0_25

After which, I add

%JAVA_HOME%\bin

to the PATH variable, but this gives me an error:

'C:\Program' is not recognized as an internal or external command, operable command or batch file.

This error makes it seem like it's running into problems with the space in "Program Files". This is weird, though, since it wasn't doing this for a good while, then started. Further, there are other variables with spaces in them that work just fine. I've tried deleting the variable and recreating it, putting quotes around JAVA_HOME (which goes to the correct path, but does not find javac.exe correctly)..

Any tips on what I might do?

This is on Windows 7.

EDIT:

The environment variables were set by going Control Panel > Advanced System Settings > Environment Variables. The value of the variables were set by copying the address of the folder I want through an Explorer window. I added it to the PATH environment variable by appending the address with a space between the preceding variable and a semicolon at the end, as such:

C:\Users\Demo_User_1\AppData\Roaming\npm; %JAVA_HOME%

where the JAVA_HOME variable is defined as such:

C:\Program Files\Java\jdk1.7.0_25

I test the value of the variable through a command prompt by typing %JAVA_HOME%, and that's where I get the resulting error of "'C:\Program' is not recognized..."

The results of 'set' are as follows:

C:\Users\Demo_User_1>set
ALLUSERSPROFILE=C:\ProgramData
ANDROID_HOME=C:\Users\Demo_User_1\Desktop\Android\adt-bundle-windows-x86_64-2013
0717\sdk
APPDATA=C:\Users\Demo_User_1\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
COMPUTERNAME=DEMO_USER_1-HP
ComSpec=C:\Windows\system32\cmd.exe
FP_NO_HOST_CHECK=NO
HOMEDRIVE=C:
HOMEPATH=\Users\Demo_User_1
JAVA_HOME=C:\Program Files\Java\jdk1.7.0_25
LOCALAPPDATA=C:\Users\Demo_User_1\AppData\Local
LOGONSERVER=\\DEMO_USER_1-HP
NUMBER_OF_PROCESSORS=4
OnlineServices=Online Services
OS=Windows_NT
Path=C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Clien
t\;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files
(x86)\Common Files\Microsoft Shared\Windows Live;C:\Windows\system32;C:\Windows;
C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program
Files (x86)\Windows Live\Shared;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\
x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C:\Program Files\Intel\I
ntel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Managem
ent Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engin
e Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Compone
nts\IPT;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\Wir
elessCommon\;C:\Program Files\Microsoft\Web Platform Installer\;C:\Program Files
 (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\;C:\Program Files (x86)\Windows
Kits\8.0\Windows Performance Toolkit\;C:\Program Files\Microsoft SQL Server\110\
Tools\Binn\;C:\Program Files\nodejs\; C:\Users\Demo_User_1\Desktop\Android\adt-b
undle-windows-x86_64-20130717\sdk/platform-tools; C:\Users\Demo_User_1\Desktop\A
ndroid\adt-bundle-windows-x86_64-20130717\sdk\tools; %JAVA_HOME%; %ANT_HOME%/bin
; C:\Program Files\Java\jdk1.7.0_25\bin; C:\Users\Demo_User_1\AppData\Roaming\np
m; "%JAVA_HOME%"; ;C:\Users\Demo_User_1\Desktop\Android\adt-bundle-windows-x86_6
4-20130717\sdk/tools; C:\Users\Demo_User_1\Desktop\Android\adt-bundle-windows-x8
6_64-20130717\sdk/platform-tools
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PCBRAND=Pavilion
Platform=MCD
PROCESSOR_ARCHITECTURE=AMD64
PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 58 Stepping 9, GenuineIntel
PROCESSOR_LEVEL=6
PROCESSOR_REVISION=3a09
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)
ProgramW6432=C:\Program Files
PROMPT=$P$G
PSModulePath=C:\Windows\system32\WindowsPowerShell\v1.0\Modules\
PUBLIC=C:\Users\Public
SESSIONNAME=Console
SystemDrive=C:
SystemRoot=C:\Windows
TEMP=C:\Users\DEMO_U~1\AppData\Local\Temp
TMP=C:\Users\DEMO_U~1\AppData\Local\Temp
USERDOMAIN=Demo_User_1-HP
USERNAME=Demo_User_1
USERPROFILE=C:\Users\Demo_User_1
VS110COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools
\
windir=C:\Windows
windows_tracing_flags=3
windows_tracing_logfile=C:\BVTBin\Tests\installpackage\csilogfile.log


问:
How to draw green lines on black region of an image?
This is the original picture：

I want to draw a green line on the area marked by the red part：

I want this effect：

Or like this：

But I use the following code to test, the effect is not good：

```<code>import cv2
import numpy as np

img = cv2.imread(r"E:\test_opencv\images\luyuan1.jpg")
blur_img = cv2.GaussianBlur(img, (3, 3), 0)
gray = cv2.cvtColor(blur_img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 150, 250, apertureSize=3)
rho = 1  #Distance resolution of the accumulator in pixels.
theta = np.pi/180 # Angle resolution of the accumulator in radians.
threshold  = 100 #Accumulator threshold parameter. Only those lines are returned that get enough votes ( >\texttt{threshold} ).
lines = cv2.HoughLines(edges, rho, theta, threshold)
if lines is not None:
    for i in range(len(lines)):
        for r,th in lines[i]:
            a = np.cos(th)
            b = np.sin(th)
            x0 = a*r
            y0 = b*r
            x1 = int(x0 + 1000*(-b))
            y1 = int(y0 + 1000*(a))
            x2 = int(x0 - 1000*(-b))
            y2 = int(y0 - 1000*(a))

            cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)
            print(x1,y1,x2,y2)
# cv2.imshow('canny', edges)
cv2.imshow('Result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

The effect is this：

How should I modify it, I don't think edge detection and Huff transform are feasible.

I also tried using the following code：

```<code>import cv2
import numpy as np

src = cv2.imread(r"E:\test_opencv\images\luyuan1.jpg")
cv2.imshow("src", src)

hsv = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)
low_hsv = np.array([0, 0, 46])
high_hsv = np.array([180, 43, 220])
mask = cv2.inRange(hsv, lowerb=low_hsv, upperb=high_hsv)
cv2.imshow("mask", mask)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

But the effect is not good：

答:
You could use medianBlur instead of gaussianBlur. With a large enough ksize you would be able to remove most textures such as the stripe pattern on the wall, while retaining a decent contrast between the two types of flooring.

You would then have to increase the aptureSize for the canny algorithm to account for this change.

I.e.

```<code>...
blur_img = cv2.medianBlur(img, 101)
gray = cv2.cvtColor(blur_img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 150, 250, apertureSize=5)
...
</code>```

(or alternatively converting to gray, then blurring)

Body:
This is the original picture：

I want to draw a green line on the area marked by the red part：

I want this effect：

Or like this：

But I use the following code to test, the effect is not good：

import cv2
import numpy as np

img = cv2.imread(r"E:\test_opencv\images\luyuan1.jpg")
blur_img = cv2.GaussianBlur(img, (3, 3), 0)
gray = cv2.cvtColor(blur_img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 150, 250, apertureSize=3)
rho = 1  #Distance resolution of the accumulator in pixels.
theta = np.pi/180 # Angle resolution of the accumulator in radians.
threshold  = 100 #Accumulator threshold parameter. Only those lines are returned that get enough votes ( >\texttt{threshold} ).
lines = cv2.HoughLines(edges, rho, theta, threshold)
if lines is not None:
    for i in range(len(lines)):
        for r,th in lines[i]:
            a = np.cos(th)
            b = np.sin(th)
            x0 = a*r
            y0 = b*r
            x1 = int(x0 + 1000*(-b))
            y1 = int(y0 + 1000*(a))
            x2 = int(x0 - 1000*(-b))
            y2 = int(y0 - 1000*(a))

            cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)
            print(x1,y1,x2,y2)
# cv2.imshow('canny', edges)
cv2.imshow('Result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

The effect is this：

How should I modify it, I don't think edge detection and Huff transform are feasible.

I also tried using the following code：

import cv2
import numpy as np

src = cv2.imread(r"E:\test_opencv\images\luyuan1.jpg")
cv2.imshow("src", src)

hsv = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)
low_hsv = np.array([0, 0, 46])
high_hsv = np.array([180, 43, 220])
mask = cv2.inRange(hsv, lowerb=low_hsv, upperb=high_hsv)
cv2.imshow("mask", mask)
cv2.waitKey(0)
cv2.destroyAllWindows()

But the effect is not good：

Body:
You could use medianBlur instead of gaussianBlur. With a large enough ksize you would be able to remove most textures such as the stripe pattern on the wall, while retaining a decent contrast between the two types of flooring.

You would then have to increase the aptureSize for the canny algorithm to account for this change.

I.e.

...
blur_img = cv2.medianBlur(img, 101)
gray = cv2.cvtColor(blur_img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 150, 250, apertureSize=5)
...

(or alternatively converting to gray, then blurring)


问:
Run script in ajax
can i run a java script in ajax? I've tried to embed some java script on the php that was triggered by an ajax command, the script is intended to change html attribute in the parent page. it doesn't work, when i look at the console  in firebug it only print the script and doesn't even make an alert.

tnx so much for the rplies.

答:
You need to evaluate the response text.

E.G. returning alert('foobar') in the ajax, you can then do eval(ajaxResponseText).

using a library like Prototype.js you can tell it to automatically evaluate script tags within the response text.

Title: Run script in ajax


问:
Failed Activity not running
I have an Azure Data Factory v2 Pipeline with a copy data activity.  If the activity fails a Lookup activity should be run.  Unfortunately the Lookup never runs.  Why doesn't it run on failure of the copy data activity?  How do I get this to work?

I'm expecting the "Set load of file to failed" activity to run because the Load Zipped File to Import Destination" activity failed.  In fact in the output you can see the Status is "Failed" but no other activity is run.

Later I updated the Copy Activity to skip incompatible rows which caused the Copy data activity to succeed.  The expected number of rows loaded now doesn't match the total number of rows loaded, so the If Condition activity goes to the failure route.  Why would the Lookup run from the If Condition only triggering the failure Activity vs the Copy Data activity?

答:
Activity dependencies are a logical AND. The lookup activity Set load of file to failed will only execute if both the Copy data activity and the If condition fail. It's not one or the other - it's both. I blogged about this here.

It's common to redesign this as:
A. Use multiple failure activities. Instead of having the one set load of file to failed at the end, copy that activity and have the copy data activity link to the new one on failure.
B. Create a parent pipeline and use an execute pipeline activity. Then add a single failure dependency from the execute pipeline activity to Set load of file to failed activity emphasized text.

Title: Failed Activity not running


答:
This happened because you didn't set your app base href before deploy to github. Your app is looking for files in "https://gerguevara.github.io/" directory, not in your respository "https://gerguevara.github.io/angularnews" directory

In your index.html file the <base href="/"> part suppose to be <base href="angularnews">. You can either change that with CLI or with your IDE

Title: Why my Angular 8 project doesn't work on GitHub pages

Body:
could you help me? I'm trying to deploy an Angular 8 personal project to GitHub pages but it appears blank, and I don't know the why.

It's the first time that I try to deploy using GH-pages, I've not used the angular cli tool for deploying on gh, merely I've created a new repository and then I've added all the compiled files.

this is my repository.
https://github.com/Gerguevara/angularnews

this is the gh-pages url
https://gerguevara.github.io/angularnews/

Also I've tried to deploy it using NOW but I couldn't, I got the same issue.


问:
replace multiple values in a column and keep other values unchanged in pandas dataframe
I have an example dataframe like below:

```<code>df = pd.DataFrame({'name': ['red', 'orange', 'blue'],
                   'value': [22,44,66]})

    name    value
0   red     22
1   orange  44
2   blue    66
</code>```

I need to replace red with 1 and blue with 2, leaving orange as it is, in the column name.

I use map function like below:

```<code>df.name.map({'red': 0, 'blue': 1})
</code>```

I got result like:

```<code>    name    value
0   0.0     22
1   NaN     44
2   1.0     66
</code>```

In the column, orange becomes NaN

What is the best way to replace the values?

I do not want to use df.name.str.replace(..) many times to replace many values. In my real data, there are 10 values to replace in a column.
Thanks.

答:
One way can be creating your custom dict and overiding __missing__

```<code>import pandas as pd
df = pd.DataFrame({'name': ['red', 'orange', 'blue'],
               'value': [22,44,66]})

class Foo(dict):
    def __missing__(self, key):
       return key
df.name.map(Foo({'red': 0, 'blue': 1}))
</code>```

From the documentation Series.map
:

When arg is a dictionary, values in Series that are not in the dictionary (as keys) are converted to NaN. However, if the dictionary is a dict subclass that defines missing (i.e. provides a method for default values), then this default is used rather than NaN.

Body:
I have an example dataframe like below:

df = pd.DataFrame({'name': ['red', 'orange', 'blue'],
                   'value': [22,44,66]})

    name    value
0   red     22
1   orange  44
2   blue    66

I need to replace red with 1 and blue with 2, leaving orange as it is, in the column name.

I use map function like below:

df.name.map({'red': 0, 'blue': 1})

I got result like:

    name    value
0   0.0     22
1   NaN     44
2   1.0     66

In the column, orange becomes NaN

What is the best way to replace the values?

I do not want to use df.name.str.replace(..) many times to replace many values. In my real data, there are 10 values to replace in a column.
Thanks.

Body:
One way can be creating your custom dict and overiding __missing__

import pandas as pd
df = pd.DataFrame({'name': ['red', 'orange', 'blue'],
               'value': [22,44,66]})

class Foo(dict):
    def __missing__(self, key):
       return key
df.name.map(Foo({'red': 0, 'blue': 1}))

From the documentation Series.map
:

When arg is a dictionary, values in Series that are not in the dictionary (as keys) are converted to NaN. However, if the dictionary is a dict subclass that defines missing (i.e. provides a method for default values), then this default is used rather than NaN.


问:
How to return Map object from Cypress each?
So, I write TAF to automate user cases using Cypress. I'm a novice in it.

I need to return from Cypress each command a Map with some values to use it in next command as input value.

In DOM there are some amount of canvas tags like this:

```<code><canvas class="leaflet-tile leaflet-tile-loaded" width="256" height="256" style="width: 256px; height: 256px; transform: translate3d(613px, 246px, 0px); opacity: 1;"></canvas>
</code>```

From style attribute I need to extract two coordinates, so, just transform value:

```<code>width: 256px; height: 256px; transform: translate3d(613px, 246px, 0px); opacity: 1;
</code>```

to

```<code>613 246
</code>```

and set it like a key to Map object. And as value I need to set a buffer of encoded canvas data.

So, I add custom command like this:

```<code>function convertCanvasMatrixToPictureCommand() {
  Cypress.Commands.add('renderCanvasMatrixToPng', { prevSubject: true }, (subject, savePath) => {
    const bufferMap = new Map();
    cy.wrap(subject)
      .each(canvas => {
        Cypress.Blob.canvasToBlob(canvas.get(0))
          .then(blob => Cypress.Blob.blobToArrayBuffer(blob))
          .then(buff => {
            const coordinates = extract(canvas.attr('style'));
            const buffer = Buffer.from(buff);
            bufferMap.set(coordinates, buffer);
          });
      // and here in some way I need to return bufferMap obj
      // to use it as input data in next cypress task:
      })
      .task('mergeImages', { buffers: bufferMap, savePath: 'cypress/snapshots' });
  });
}
</code>```

mergeImages task will proceed the map and using specified sorting, merge all canvases to a single PNG image.

But is it possible in some way to return this map from each command?

This bufferMap object valid only inside each command. But out of each it still empty

cy.wprap() also not resolve this issue. Or I use it incorrect...

Thanks!

答:
A couple of problems with the custom command

to make sure you wait on the results of .each(), must return the promise created bt Cypress.Blob.canvasToBlob() chain.

follow the .each() with a .then() to ensure completion, and return `bufferMap here.

Problems with .task()

it does not like being called within the custom command, so call it after

CypressError: cy.then() failed because you are mixing up async and sync code.

it does not like a Map() object as a parameter, convert to a plain object

Test

describe('leaflet', () => {

  it('processes', () => {

    Cypress.Commands.add('renderCanvasMatrixToPng', {prevSubject: true}, (subjects, savePath) => {
      const bufferMap = new Map();
      cy.wrap(subjects)
        .each((canvas, i) => {
          return Cypress.Blob.canvasToBlob(canvas.get(0))   // <- add return here
            .then(blob => Cypress.Blob.blobToArrayBuffer(blob))
            .then(buff => {
              var view = new Int8Array(buff);  // not sure why this is needed
              const buffer = Buffer.from(view);

              // get coords here
              const coords = 1000 + i // for purpose of demo
              bufferMap.set(coords, buffer)
            })
        })
        .then(_ => {                           // <- wait for previous to complete
          console.log('bufferMap inside command', bufferMap)  // [[Entries]]
                                                              //  0: {0 => Uint8Array(27209)}
                                                              //  1: {1 => Uint8Array(1179)}
          return bufferMap;
        })
    });

    cy.visit('http://cartodb.github.io/Leaflet.CanvasLayer/example.html')

    cy.get('canvas').renderCanvasMatrixToPng().then(bufferMap => {
      console.log('bufferMap outside command', bufferMap)  // [[Entries]]
                                                           //    0: {1000 => Uint8Array(25218)}
                                                           //    1: {1001 => Uint8Array(1179)}
      const asObject = Object.fromEntries(bufferMap);
      cy.task('mergeImages', { buffers: asObject, savePath: 'cypress/snapshots' });
    })

  })
})
```

<hr>

<p><strong>Task for demo</strong></p>

<pre class="lang-js prettyprint-override"><code>module.exports = (on, config) => {
  ...
  on('task', {
    mergeImages(options) {
      const { buffers, savePath } = options;

      console.log('buffers', buffers);
      /* In terminal

        buffers {
          '1000': {
            type: 'Buffer',
            data: [
              137,  80,  78,  71,  13,  10,  26,  10,   0,   0,   0,  13,
              ... 33137 more items
            ]
          },
          '1001': {
            type: 'Buffer',
            data: [
              137,  80,  78,  71,  13,  10,  26,  10,   0,   0,   0,  13,
              ... 1079 more items
            ]
          }
        }
      */

      return null;
    }
  })
}
</code>```

Alternative command (my preference)

Cypress.Commands.add('renderCanvasMatrixToPng', { prevSubject: true }, (subjects, savePath) => {
  const bufferPromises = Array.from(subjects).map(canvas => {
    return Cypress.Blob.canvasToBlob(canvas)
      .then(blob => Cypress.Blob.blobToArrayBuffer(blob))
      .then(buff => {
        const view = new Int8Array(buff);
        const buffer = Buffer.from(view);
        return buffer;
      })
  })
  return Promise.all(bufferPromises).then(buffers => {
    const bufferMap = new Map();
    buffers.forEach((buffer, i) => {
      // get coords here
      const coords = 1000 + i // for purpose of demo
      bufferMap.set(coords, buffer)
    })
    return bufferMap;
  })
});
```

Body:
So, I write TAF to automate user cases using Cypress. I'm a novice in it.

I need to return from Cypress each command a Map with some values to use it in next command as input value.

In DOM there are some amount of canvas tags like this:

<canvas class="leaflet-tile leaflet-tile-loaded" width="256" height="256" style="width: 256px; height: 256px; transform: translate3d(613px, 246px, 0px); opacity: 1;"></canvas>

From style attribute I need to extract two coordinates, so, just transform value:

width: 256px; height: 256px; transform: translate3d(613px, 246px, 0px); opacity: 1;

to

613 246

and set it like a key to Map object. And as value I need to set a buffer of encoded canvas data.

So, I add custom command like this:

function convertCanvasMatrixToPictureCommand() {
  Cypress.Commands.add('renderCanvasMatrixToPng', { prevSubject: true }, (subject, savePath) => {
    const bufferMap = new Map();
    cy.wrap(subject)
      .each(canvas => {
        Cypress.Blob.canvasToBlob(canvas.get(0))
          .then(blob => Cypress.Blob.blobToArrayBuffer(blob))
          .then(buff => {
            const coordinates = extract(canvas.attr('style'));
            const buffer = Buffer.from(buff);
            bufferMap.set(coordinates, buffer);
          });
      // and here in some way I need to return bufferMap obj
      // to use it as input data in next cypress task:
      })
      .task('mergeImages', { buffers: bufferMap, savePath: 'cypress/snapshots' });
  });
}

mergeImages task will proceed the map and using specified sorting, merge all canvases to a single PNG image.

But is it possible in some way to return this map from each command?

This bufferMap object valid only inside each command. But out of each it still empty

cy.wprap() also not resolve this issue. Or I use it incorrect...

Thanks!

Body:
A couple of problems with the custom command

to make sure you wait on the results of .each(), must return the promise created bt Cypress.Blob.canvasToBlob() chain.

follow the .each() with a .then() to ensure completion, and return `bufferMap here.

Problems with .task()

it does not like being called within the custom command, so call it after

CypressError: cy.then() failed because you are mixing up async and sync code.

it does not like a Map() object as a parameter, convert to a plain object

Test

describe('leaflet', () => {

  it('processes', () => {

    Cypress.Commands.add('renderCanvasMatrixToPng', {prevSubject: true}, (subjects, savePath) => {
      const bufferMap = new Map();
      cy.wrap(subjects)
        .each((canvas, i) => {
          return Cypress.Blob.canvasToBlob(canvas.get(0))   // <- add return here
            .then(blob => Cypress.Blob.blobToArrayBuffer(blob))
            .then(buff => {
              var view = new Int8Array(buff);  // not sure why this is needed
              const buffer = Buffer.from(view);

              // get coords here
              const coords = 1000 + i // for purpose of demo
              bufferMap.set(coords, buffer)
            })
        })
        .then(_ => {                           // <- wait for previous to complete
          console.log('bufferMap inside command', bufferMap)  // [[Entries]]
                                                              //  0: {0 => Uint8Array(27209)}
                                                              //  1: {1 => Uint8Array(1179)}
          return bufferMap;
        })
    });

    cy.visit('http://cartodb.github.io/Leaflet.CanvasLayer/example.html')

    cy.get('canvas').renderCanvasMatrixToPng().then(bufferMap => {
      console.log('bufferMap outside command', bufferMap)  // [[Entries]]
                                                           //    0: {1000 => Uint8Array(25218)}
                                                           //    1: {1001 => Uint8Array(1179)}
      const asObject = Object.fromEntries(bufferMap);
      cy.task('mergeImages', { buffers: asObject, savePath: 'cypress/snapshots' });
    })

  })
})

Task for demo

module.exports = (on, config) => {
  ...
  on('task', {
    mergeImages(options) {
      const { buffers, savePath } = options;

      console.log('buffers', buffers);
      /* In terminal

        buffers {
          '1000': {
            type: 'Buffer',
            data: [
              137,  80,  78,  71,  13,  10,  26,  10,   0,   0,   0,  13,
              ... 33137 more items
            ]
          },
          '1001': {
            type: 'Buffer',
            data: [
              137,  80,  78,  71,  13,  10,  26,  10,   0,   0,   0,  13,
              ... 1079 more items
            ]
          }
        }
      */

      return null;
    }
  })
}

Alternative command (my preference)

Cypress.Commands.add('renderCanvasMatrixToPng', { prevSubject: true }, (subjects, savePath) => {
  const bufferPromises = Array.from(subjects).map(canvas => {
    return Cypress.Blob.canvasToBlob(canvas)
      .then(blob => Cypress.Blob.blobToArrayBuffer(blob))
      .then(buff => {
        const view = new Int8Array(buff);
        const buffer = Buffer.from(view);
        return buffer;
      })
  })
  return Promise.all(bufferPromises).then(buffers => {
    const bufferMap = new Map();
    buffers.forEach((buffer, i) => {
      // get coords here
      const coords = 1000 + i // for purpose of demo
      bufferMap.set(coords, buffer)
    })
    return bufferMap;
  })
});


问:
iPhone : How do I add existing project in "git local repository"?
I have existing project and I want to add it in "git local repository".

How can I do that ?

答: It's pretty simple, assuming you've got git installed. http://tiredblogger.wordpress.com/2009/11/09/creating-local-git-repositories-yeah-its-that-simple/.</p>


问:
How to make a bash script to check if a program or library exists
I want to make a function to check if the program or library is already installed.

Thats what I do now:

```<code>dpkg --status software-properties-common | grep -q not-installed
if [ $? -eq 0 ]; then
    sudo apt-get install -y software-properties-common
fi
</code>```

What I want:

```<code>isPackageNotInstalled() {???}

if [ $(isPackageNotInstalled 'software-properties-common') ]; then
   sudo apt-get install -y software-properties-common
fi
</code>```

any help would be greatly appreciated.

答:
This script works in #archlinux also, based on the the answer already chosen.

```<code>isPackageNotInstalled() {

    pacman -Ss $1 &&> /dev/null
    if [ $? -eq 0 ]; then
    echo "$1: Already installed"
    else
    sudo pacman -S $1
    fi
    }

isPackageNotInstalled $1
</code>```

for yaourt

```<code>isPackageNotInstalled() {

    yaourt -Ss $1 &&> /dev/null
    if [ $? -eq 0 ]; then
    echo "$1: Already installed"
    else
    yaourt -S $1
    fi
    }

isPackageNotInstalled $1
</code>```

Body:
I want to make a function to check if the program or library is already installed.

Thats what I do now:

dpkg --status software-properties-common | grep -q not-installed
if [ $? -eq 0 ]; then
    sudo apt-get install -y software-properties-common
fi

What I want:

isPackageNotInstalled() {???}

if [ $(isPackageNotInstalled 'software-properties-common') ]; then
   sudo apt-get install -y software-properties-common
fi

any help would be greatly appreciated.

Body:
This script works in #archlinux also, based on the the answer already chosen.

isPackageNotInstalled() {

    pacman -Ss $1 &&> /dev/null
    if [ $? -eq 0 ]; then
    echo "$1: Already installed"
    else
    sudo pacman -S $1
    fi
    }

isPackageNotInstalled $1

for yaourt

isPackageNotInstalled() {

    yaourt -Ss $1 &&> /dev/null
    if [ $? -eq 0 ]; then
    echo "$1: Already installed"
    else
    yaourt -S $1
    fi
    }

isPackageNotInstalled $1


答:
You are passing x into the function. This will make a new variable called x which will be used within the function. It is different to the var x defined above.

Change to

```

<p>or if you want to be able to use the function in other places.</p>

<pre class="lang-html prettyprint-override"><code><script>
  var x = 1;

  function add(x) {
    var a = document.getElementById("input").value;

    x++;
    if (x == 1) document.getElementById("1").innerHTML = a;
    return x;
  }

  x = add(x);
</script>
</code>```

Body:
Variable "x" which I mention outside the function has some problem I guess . Function is not accessing the variable don't know why .
here is my javascript function  below if any one require my html code a can also provide

HTML Snippet

shahmir

Body:
You are passing x into the function. This will make a new variable called x which will be used within the function. It is different to the var x defined above.

Change to

<script>
  var x = 1;

  function add() {
    var a = document.getElementById("input").value;

    x++;
    if (x == 1) document.getElementById("1").innerHTML = a;
  }

  function add();
</script>

or if you want to be able to use the function in other places.

<script>
  var x = 1;

  function add(x) {
    var a = document.getElementById("input").value;

    x++;
    if (x == 1) document.getElementById("1").innerHTML = a;
    return x;
  }

  x = add(x);
</script>


问:
Problems with clicking a button
I wanted the program to click the 'PLAY' Button on spotify to play a song, but sadly I get this error

selenium.common.exceptions.JavascriptException: Message: javascript error: arguments[0].click is not a function

The code I tried is

```<code>  WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.XPATH,"//*[text()='PLAY']")))
  time.sleep(1)
  driver.execute_script("arguments[0].click();", driver.find_element_by_xpath("//*[text()='PLAY']"))
</code>```

Can someone help me to find the button and click it, I tried also the

```<code>driver.find_element_by_xpath("//*[text()='PLAY']").click()
</code>```

But I get the error element is not interactable

答:
EC has a good method for verifying element is clickable before making an action element_to_be_clickable.

Also, I found over 20 elements on Spotify using your XPath, so I modified it to look for button instead of *.

Try this:

```<code>WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.XPATH,"//button[text()='PLAY']")))
driver.find_element_by_xpath("//button[text()='PLAY']").click()
</code>```

I hope this helps. Good luck!

Title: Problems with clicking a button

Body:
I wanted the program to click the 'PLAY' Button on spotify to play a song, but sadly I get this error

selenium.common.exceptions.JavascriptException: Message: javascript error: arguments[0].click is not a function

The code I tried is

  WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.XPATH,"//*[text()='PLAY']")))
  time.sleep(1)
  driver.execute_script("arguments[0].click();", driver.find_element_by_xpath("//*[text()='PLAY']"))

Can someone help me to find the button and click it, I tried also the

driver.find_element_by_xpath("//*[text()='PLAY']").click()

But I get the error element is not interactable

Body:
EC has a good method for verifying element is clickable before making an action element_to_be_clickable.

Also, I found over 20 elements on Spotify using your XPath, so I modified it to look for button instead of *.

Try this:

WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.XPATH,"//button[text()='PLAY']")))
driver.find_element_by_xpath("//button[text()='PLAY']").click()

I hope this helps. Good luck!


问:
Automatically no-overwrite in ssh-keygen
If I run

ssh-keygen -t rsa -N "" -f id_rsa

and the file id_rsa already exists, it will prompt me whether I want to overwrite:

```<code>id_rsa already exists.
Overwrite (y/n)?
</code>```

How do I automatically answer no in a bash script? I checked man ssh-keygen but couldn't find any such option.

答:
You can use here-string to automatically answer n to the Overwrite (y/n)? question.

ssh-keygen -t rsa -N "" -f id_rsa <<< n
```

Body:
If I run

ssh-keygen -t rsa -N "" -f id_rsa

and the file id_rsa already exists, it will prompt me whether I want to overwrite:

id_rsa already exists.
Overwrite (y/n)?

How do I automatically answer no in a bash script? I checked man ssh-keygen but couldn't find any such option.


问:
Why is my clientWidth and offsetWidth equal?

var mydiv = document.getElementById("mydiv");
console.log("offset width = " + mydiv.offsetWidth);
console.log("client width = " + mydiv.clientWidth);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#div1 {
  height: 5000px;
  width: 5000px;
  background-color: #000000;
}</code>```

```
</div>
</div>
</p>

<p>I have a div on a webpage where the content requires a vertical scrollbar. Using javascript, I'm trying to calculate the offsetWidth and clientWidth so that I can ultimately calculate the width of the vertical scrollbar but apparently they are equal. I have:</p>

<p>html:</p>

```

```

<p>css:</p>

```#div1 {
  height: 5000px;
  width: 5000px;
  background-color: #000000;
}
```

<p>js:</p>

```var mydiv = document.getElementById("mydiv");
console.log("offset width = " + mydiv.offsetWidth);
console.log("client width = " + mydiv.clientWidth);
```

答:
Main difference between clientWidth and offsetWidth :

(1) clientWidth is the inner width (ie. the space inside an element including padding but excluding borders and scrollbars)

(2) offsetWidth is the outer width (ie. the space occupied by the element, including padding and borders)

As I can see in your CSS border and scrollbars is missing that is why you are getting same width in both case.

I have made updated CSS and now you will get different values. Please check below snippet:

var mydiv = document.getElementById("mydiv");
console.log("offset width = " + mydiv.offsetWidth);
console.log("client width = " + mydiv.clientWidth);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#mydiv {
        padding: 20px;
        border: 20px solid red;
      }</code>```

```

Body:
var mydiv = document.getElementById("mydiv");
console.log("offset width = " + mydiv.offsetWidth);
console.log("client width = " + mydiv.clientWidth);

#div1 {
  height: 5000px;
  width: 5000px;
  background-color: #000000;
}

I have a div on a webpage where the content requires a vertical scrollbar. Using javascript, I'm trying to calculate the offsetWidth and clientWidth so that I can ultimately calculate the width of the vertical scrollbar but apparently they are equal. I have:

html:

css:

#div1 {
  height: 5000px;
  width: 5000px;
  background-color: #000000;
}

js:

var mydiv = document.getElementById("mydiv");
console.log("offset width = " + mydiv.offsetWidth);
console.log("client width = " + mydiv.clientWidth);

Body:
Main difference between clientWidth and offsetWidth :

(1) clientWidth is the inner width (ie. the space inside an element including padding but excluding borders and scrollbars)

(2) offsetWidth is the outer width (ie. the space occupied by the element, including padding and borders)

As I can see in your CSS border and scrollbars is missing that is why you are getting same width in both case.

I have made updated CSS and now you will get different values. Please check below snippet:

var mydiv = document.getElementById("mydiv");
console.log("offset width = " + mydiv.offsetWidth);
console.log("client width = " + mydiv.clientWidth);

#mydiv {
        padding: 20px;
        border: 20px solid red;
      }

<div id="mydiv">
    <div id="div1"></div>
    <div id="div2"></div>
    <div id="div3"></div>
  </div>


问:
Hiding Tab Bar and adding toolbar at that location
I am developing a tab Bar based Application.On a particular view controller I have to hide the tab Bar and add toolBar there.What I did is
self.tabBarController.tabBar.hidden = YES; to hide the tab Bar.The tab bar is hidden properly but the tool Bar is not showing at that location.the space of tabBar is showing blank and toolBar is coming up.Please tell me how to sort out this problem.
Thanks in advance.

答:
When you are pushing your viewcontroller(having no tabbar) add the line:

yourviewcontroller.hidesBottomBarWhenPushed=YES;

Hope it helps....


问:
how to fix error with quandl function get (Status 404) (Quandl Error QECx02)?
Hi everyone python is throwing this error everytime i try to run this code.

I have tried both methods that are applied there in the code and its not running with either of :

```<code>api_key = open('apikey.txt', 'r').read()

for x in friddy_states[0][1]:
   query ='CMHC/HPPU50_BC'+str(x)
   df= quandl.get(query, authtoken=api_key)
</code>```

and also tried this way:

```<code>quandl.ApiConfig.api_key = 'MY API FROM QUANDL'

for x in friddy_states[0][1]:
   query ='CMHC/HPPU50_BC'+str(x)
   df= quandl.get(query)
</code>```

both methods showed on quandl documentation and noone is working!
THIS IS THE ACTUAL CODE:

```<code>import quandl
import pandas as pd
import pickle

api_key = open('apikey.txt', 'r').read()

quandl.ApiConfig.api_key = 'MY API FROM QUANDL'

df = quandl.get('CMHC/HPPU50_BC', authoken= api_key)

friddy_states =
pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states')

main_df = pd.DataFrame()

for x in friddy_states[0][1]:

    query ='CMHC/HPPU50_BC'+str(x)

    df= quandl.get(query, authtoken=api_key)

    if main_df.empty:
        main_df = df
    else:
        main_df = main_df.join(df)

print(main_df.head())
</code>```

got super stuck, help is appreciate

答:
I am noticing a missing t in your get request for authtoken. </p>

```<code>df = quandl.get('CMHC/HPPU50_BC', authoken= api_key)
</code>```

Body:
Hi everyone python is throwing this error everytime i try to run this code.

I have tried both methods that are applied there in the code and its not running with either of :

api_key = open('apikey.txt', 'r').read()

for x in friddy_states[0][1]:
   query ='CMHC/HPPU50_BC'+str(x)
   df= quandl.get(query, authtoken=api_key)

and also tried this way:

quandl.ApiConfig.api_key = 'MY API FROM QUANDL'

for x in friddy_states[0][1]:
   query ='CMHC/HPPU50_BC'+str(x)
   df= quandl.get(query)

both methods showed on quandl documentation and noone is working!
THIS IS THE ACTUAL CODE:

import quandl
import pandas as pd
import pickle

api_key = open('apikey.txt', 'r').read()

quandl.ApiConfig.api_key = 'MY API FROM QUANDL'

df = quandl.get('CMHC/HPPU50_BC', authoken= api_key)

friddy_states =
pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states')

main_df = pd.DataFrame()

for x in friddy_states[0][1]:

    query ='CMHC/HPPU50_BC'+str(x)

    df= quandl.get(query, authtoken=api_key)

    if main_df.empty:
        main_df = df
    else:
        main_df = main_df.join(df)

print(main_df.head())

got super stuck, help is appreciate

Body:
I am noticing a missing t in your get request for authtoken.

df = quandl.get('CMHC/HPPU50_BC', authoken= api_key)


问:
program to handle Heterogeneous Lists in Scala;
I have to find out the maximum/minimum from this list:

```<code> val data= List(List(1,2), List(3,4,91,9,10),11,211,456,345)
</code>```

From some stack over flow example ,i can see below solution:

```<code>val flatdata=data.collect{case i:Int => List(i); case l @ a :: b => l}.flatten
</code>```

[
But this is giving error]

Can some one please help.
want the solution using pure scala and not spark

答:
One thing wrong with your code is that the result is List[Any], which isn't going to be terribly useful.

This gives a compiler warning but produces a List[Int] result.

```<code>data.flatMap{case li:List[Int] => li; case i:Int => List(i)}
</code>```

Body:
I have to find out the maximum/minimum from this list:

 val data= List(List(1,2), List(3,4,91,9,10),11,211,456,345)

From some stack over flow example ,i can see below solution:

val flatdata=data.collect{case i:Int => List(i); case l @ a :: b => l}.flatten

[
But this is giving error]

Can some one please help.
want the solution using pure scala and not spark

Body:
One thing wrong with your code is that the result is List[Any], which isn't going to be terribly useful.

This gives a compiler warning but produces a List[Int] result.

data.flatMap{case li:List[Int] => li; case i:Int => List(i)}


问:
What does (_) mean when calling a function?
I’ve seen the notation used elsewhere but, just as an example, I recently read about replacing

```<code>ChangeNotifierProvider(
  create: (BuildContext context) => MyCounter()
</code>```

with

```<code> ChangeNotifierProvider(
    create: (_) => MyCounter()
</code>```

What does the latter notation mean? Is the BuildContext parameter optional and the caller chosen to not supply it?

答: It's a variable named _ typically because you plan to not use it and throw it away. For example, you can use the name x or foo instead. The difference between (_) and () is simple in that one function takes an argument and the other doesn't.

Body:
I’ve seen the notation used elsewhere but, just as an example, I recently read about replacing

ChangeNotifierProvider(
  create: (BuildContext context) => MyCounter()

with

 ChangeNotifierProvider(
    create: (_) => MyCounter()

What does the latter notation mean? Is the BuildContext parameter optional and the caller chosen to not supply it?


问:
Compare line by line within a linux file
I have a file (test1.txt) like this:

```<code>100 100
200 200
300 HR
400 IT
500 500
600 600
</code>```

And I want to desired output like this:

```<code>100 100 0
200 200 0
300 HR  1
400 IT  1
500 500 0
600 600 0
</code>```

I already try to run this command:

```<code>#!/bin/bash

awk1=`awk '{print $1}' test1.txt`
awk2=`awk '{print $2}' test1.txt`

if [ "$awk1" = "$awk2" ]; then
        echo "0"
else
        echo "1"
fi
</code>```

but the result is not as I expected.

答:
A variation is just to check field equality between $1==$2, and if they are equal, append " 0", otherwise append " 1", e.g.

```<code>$ awk '$1==$2{print $0" 0"; next } {print $0" 1"}' file
100 100 0
200 200 0
300 HR 1
400 IT 1
500 500 0
600 600 0
</code>```

Which can be shortened to awk '{print  $0, $1!=$2}' file with a slight loss in readability.

Body:
I have a file (test1.txt) like this:

100 100
200 200
300 HR
400 IT
500 500
600 600

And I want to desired output like this:

100 100 0
200 200 0
300 HR  1
400 IT  1
500 500 0
600 600 0

I already try to run this command:

#!/bin/bash

awk1=`awk '{print $1}' test1.txt`
awk2=`awk '{print $2}' test1.txt`

if [ "$awk1" = "$awk2" ]; then
        echo "0"
else
        echo "1"
fi

but the result is not as I expected.

Body:
A variation is just to check field equality between $1==$2, and if they are equal, append " 0", otherwise append " 1", e.g.

$ awk '$1==$2{print $0" 0"; next } {print $0" 1"}' file
100 100 0
200 200 0
300 HR 1
400 IT 1
500 500 0
600 600 0

Which can be shortened to awk '{print  $0, $1!=$2}' file with a slight loss in readability.


问:
Python gdb support - /path/to/checkout
I am enabling gdb for Python support with Python 3.6.9 and gdb 8.1.0 on Ubuntu 18.04.

In the document https://devguide.python.org/gdb/ it says, "When CPython is built you will notice a python-gdb.py file in the root directory of your checkout.  Read the module docstring for details on how to use the file to enhance gdb for easier debugging of a CPython process. To activate support, you must add the directory containing python-gdb.py to GDB’s “auto-load-safe-path”. Put this in your ~/.gdbinit file:  add-auto-load-safe-path /path/to/checkout"

On my distro (Ubuntu 18.04), gdb was installed by default, so I didn't build it from source with ./configure --with-python.  At the time of install I did not anticipate needing Python support.  When I search for  python-gdb.py using locate python-gdb.py it shows that  python-gdb.py does not exist.

My questions are:

Can I update my gdb installation to enable Python support?

What do I use for /path/to/checkout in the string "add-auto-load-safe-path /path/to/checkout."

Thanks for any help.

答: I think if you are running GDB v7 or above, you are already set. At least it worked for me on Raspbian 7.12</p>

Title: Python gdb support - /path/to/checkout


问:
how to extract specifc numbers from a text string?
How could I extract different number values within text strings?

The goal is to extract the numbers after specific text strings for example: the number 290 below is between "NBF " and " +".

For cell A1: USD 1009  SUBJECT TO: NBF 290 + GFS 60 + IPS 18 + CCT 15 + BLF 75/20’DV

Result Desired would be:

CELL B1 1009

CELL C1 290 (number after NBF and before " +")

CELL D1 60 (number after GFS)

CELL E1 18 (number after IPS)

CELL F1 15 (number after CCT)

CELL G1 75 (number after BLF)

Usually I would use text to columns, but there are different lengths to the cells containing all info, so it doesnt always cuts the information properly.

答:
Please refer to below picture with criteria header put in row 1 B1:H1

In B2, formula copied across and down :

```<code>=IFERROR(LOOKUP(9^9,0+MID($A2,FIND(B$1,$A2)+LEN(B$1)+1,ROW($1:$9))),"")
</code>```

Body:
Please refer to below picture with criteria header put in row 1 B1:H1

In B2, formula copied across and down :

=IFERROR(LOOKUP(9^9,0+MID($A2,FIND(B$1,$A2)+LEN(B$1)+1,ROW($1:$9))),"")


问:
Extension issue when elements are accessed directly by their id, not getElementById
Even though it is not recommended, JavaScript allows you to access elements by their id without the use of getElementById.

```<code><iframe id="myframe" />
<script>
    var i = window.myframe;
</script>
</code>```

This presents a problem for extensions that need to access said elements when they themselves are being accessed.  The way to do this is to call Object.defineProperty() on the prototype for getElementById so that when it is called, you can then access the element.  But when referencing an element directly getElementById is not called so consequently, they are a blind spot for the extension.  I've tried the following but without any luck.

Iterating over the DOM in the content script doesn't seem to work because the full DOM isn't loaded yet.

Setting a listener for 'DOMContentLoaded' isn't an option because by that time the page's scripts would have already run and potentially accessed the elements.

Attempting to insert the script before the first script on the page but again, at that point nothing really exists yet.

Does anyone know the internal mechanism that JavaScript uses when an element is referenced like this?  I'm curious if there is another function that it calls internally which could possibly be hooked like getElementById.  Or is there a way to ensure the content script code is run after the DOM loads but before the page scripts runs?

答:
Or is there a way to ensure the content script code is run after the DOM loads but before the page scripts runs?

A problem is that page scripts can run before the DOM is fully loaded. For example, below:

```<code><div id="foo"></div>
<script>
foo.textContent = 'foo';
</script>
<div id="bar"></div>
</code>```

the script will run before the bar element is created (before the DOM is loaded).

It's possible to find all elements with IDs currently in the DOM with [id], and it's possible to reassign those properties on the window by simply reassigning the property - or, if you want to run code when the element is retrieved, you can use Object.defineProperty to turn it into a getter. You need to be able to find the IDs and reassign them before scripts load, which can be accomplished with a subtree MutationObserver - right before a

<script>
console.log('Lower script about to reference foo');
foo.textContent = 'foo';
console.log('Lower script has finished referencing foo');
</script>

```

It can benefit from some polishing, but that's the general idea.

Body:
Even though it is not recommended, JavaScript allows you to access elements by their id without the use of getElementById.

This presents a problem for extensions that need to access said elements when they themselves are being accessed.  The way to do this is to call Object.defineProperty() on the prototype for getElementById so that when it is called, you can then access the element.  But when referencing an element directly getElementById is not called so consequently, they are a blind spot for the extension.  I've tried the following but without any luck.

Iterating over the DOM in the content script doesn't seem to work because the full DOM isn't loaded yet.

Setting a listener for 'DOMContentLoaded' isn't an option because by that time the page's scripts would have already run and potentially accessed the elements.

Attempting to insert the script before the first script on the page but again, at that point nothing really exists yet.

Does anyone know the internal mechanism that JavaScript uses when an element is referenced like this?  I'm curious if there is another function that it calls internally which could possibly be hooked like getElementById.  Or is there a way to ensure the content script code is run after the DOM loads but before the page scripts runs?

Body:
Or is there a way to ensure the content script code is run after the DOM loads but before the page scripts runs?

A problem is that page scripts can run before the DOM is fully loaded. For example, below:

<div id="foo"></div>
<script>
foo.textContent = 'foo';
</script>
<div id="bar"></div>

the script will run before the bar element is created (before the DOM is loaded).

It's possible to find all elements with IDs currently in the DOM with [id], and it's possible to reassign those properties on the window by simply reassigning the property - or, if you want to run code when the element is retrieved, you can use Object.defineProperty to turn it into a getter. You need to be able to find the IDs and reassign them before scripts load, which can be accomplished with a subtree MutationObserver - right before a <script> is inserted, iterate over the [id]s in the DOM, and reassign them:

console.log('(empty JS block inserted by Stack Snippet editor)');

<script>
  new MutationObserver((mutations) => {
    // Check to see if a script was inserted
    if (mutations.every(
      mutation => [...mutation.addedNodes].every(
        addedNode => addedNode.tagName !== 'SCRIPT'
      )
    )) {
      // No scripts inserted
      return;
    }
    console.log('id reassignment running');
    for (const elm of document.querySelectorAll('[id]')) {
      Object.defineProperty(window, elm.id, {
        get() {
          console.log('Custom code running');
          return elm;
        },
        configurable: true
      });
    }
  })
    .observe(document.body, { childList: true, subtree: true });
</script>
<div id="foo"></div>
<script>
console.log('Lower script about to reference foo');
foo.textContent = 'foo';
console.log('Lower script has finished referencing foo');
</script>
<div id="bar"></div>

It can benefit from some polishing, but that's the general idea.


问:
php java batch processing
I work in Linux. I have 3 file (about 2Gb each containing human genome sequence). I have java codes to process those files via web interface developed in PHP. The processing time is about 24 hours or even more.

How can i run the Java code from PHP so that the processing does not terminate when I close the browser.

Since the processing time is so long, it is not practicable to keep the browser open until the process get completed.

I assume it requires batch processing.

答:
As far as I understand your question you want to call your java code from the PHP? correct? so here is the solution

```<code><?php
    //use system call to execute java class or jar
    system('java yourclass', $retval);
?>
</code>```

use the above php script. to execute your java code.

To get the process inforamtion see follwoing

PHP getting process information

Title: php java batch processing

Body:
As far as I understand your question you want to call your java code from the PHP? correct? so here is the solution

<?php
    //use system call to execute java class or jar
    system('java yourclass', $retval);
?>

use the above php script. to execute your java code.

To get the process inforamtion see follwoing

PHP getting process information


问:
how to make bootstrap table clickable
I have a bootstrap like this in main.html page:

```<code><table class="table table-striped">
 <thead>
    <tr>
     <th scope="col">#</th>
     <th scope="col">First</th>
     <th scope="col">Last</th>
     <th scope="col">Handle</th>
   </tr>
 </thead>
 <tbody>
  <tr>
    <th scope="row">1</th>
    <td>Mark</td>
    <td>Otto</td>
    <td>@mdo</td>
 </tr>
 <tr>
   <th scope="row">2</th>
   <td>Jacob</td>
   <td>Thornton</td>
   <td>@fat</td>
</tr>
<tr>
  <th scope="row">3</th>
  <td>Larry</td>
  <td>the Bird</td>
  <td>@twitter</td>
</tr>
</tbody>
</table>
</code>```

My requirement is:

When I click on any row of the table( either on the text or even in the space between two columns) it has to redirect to another Html page.

how can I do that?

答:
First, i suggest to add class to
 tag (so if you plan to have multiple tables in page it does not affect other table)

Then, i assume your using jquery and you have dynamic table rows.

```<code>#.link is the class <tr class="link" data-href="https://google.com">...</tr>
#:not(a) => added this so you can add other link `<a>` to your row (remove it if not needed...)

// same page redirect
$(document).on('click', 'tr.link:not(a)', function(e){
  e.stopPropagation(); // only add this if you have <a> tag in row
  window.location.href = $(this).data('href'); // dynamic link
});

// new tab redirect
$(document).on('click', 'tr.link', function(){
  $('<a href="'+ $(this).attr('data-href') +'" target="_blank">External Link</a>')[0].click();
});
</code>```

Title: how to make bootstrap table clickable

Body:
I have a bootstrap like this in main.html page:

     #
     First
     Last
     Handle

    1
    Mark
    Otto
    @mdo

   2
   Jacob
   Thornton
   @fat

  3
  Larry
  the Bird
  @twitter

My requirement is:

When I click on any row of the table( either on the text or even in the space between two columns) it has to redirect to another Html page.

how can I do that?

Body:
First, i suggest to add class to <tr> tag (so if you plan to have multiple tables in page it does not affect other table)

Then, i assume your using jquery and you have dynamic table rows.

#.link is the class <tr class="link" data-href="https://google.com">...</tr>
#:not(a) => added this so you can add other link `<a>` to your row (remove it if not needed...)

// same page redirect
$(document).on('click', 'tr.link:not(a)', function(e){
  e.stopPropagation(); // only add this if you have <a> tag in row
  window.location.href = $(this).data('href'); // dynamic link
});

// new tab redirect
$(document).on('click', 'tr.link', function(){
  $('<a href="'+ $(this).attr('data-href') +'" target="_blank">External Link</a>')[0].click();
});