问:
MS Project 2016 - VBA Cycle Time Issues (Extraction to Excel)
I have numerous macros that seem to be slowing down when interfacing with MS Project (e.g., reading data and processing it) in MS Office 2016. It could be my underlying code, mechanisms for obtaining/storing the data, but I'm not sure and would appreciate input.

I was just writing a new macro for extracting MSP data into an array (held in memory I thought this would be fastest, but it seemed to struggle to even do this). The idea being that the array memory access 'should' be faster than bridging from MS Excel to the Project referenced when needing to extract/place data? Perhaps this is incorrect.

Aim: Hold 3 parts of each MS Project Resource in Array, eventually iterate over array and place into Excel for additional use/processing.

The initial 'read' never quite completed (at 926 of my 1300 resources) before I broke the code to review.

Ideas on the below, or for interfacing with the MSP 2016 Reference library? It seems to have become very slow compared to just working within MS Excel.

Subroutine:

```<code>  Private Sub cb_IMSResourceImport_Click()
        Dim Prj As Project
        Set Prj = GetObject(Me.cboMaintainToProject.Value)
        Dim ResourceMatrix() As String
        Prj.Application.WindowActivate Prj.Name

        ReDim ResourceMatrix(Prj.Resources.Count, 2)

    ActiveWorkbook.Sheets("Resource Table").Range("A2:C" & C`Str(ActiveWorkbook.ActiveSheet.UsedRange.Rows.Count)).ClearContents

       For i = 1 To UBound(ResourceMatrix)
            ResourceMatrix(i - 1, 0) = Prj.Resources(i).ID
            ResourceMatrix(i - 1, 1) = Prj.Resources(i).Name
            ResourceMatrix(i - 1, 2) = Prj.Resources(i).Code
       Next i

       For i = 0 To UBound(ResourceMatrix)
            ActiveWorkbook.Sheets("Resource Table").Cells(i + 1, 1).Value = ResourceMatrix(i, 0)
            ActiveWorkbook.Sheets("Resource Table").Cells(i + 1, 2).Value = ResourceMatrix(i, 1)
            ActiveWorkbook.Sheets("Resource Table").Cells(i + 1, 3).Value = ResourceMatrix(i, 2)
       Next i

End Sub
</code>```

答:
Using Project 2013 and a mocked-up schedule with 2000 resources, your code took less than 2 minutes to run. That said, if you have many schedules open, calculation left on, etc. it could take longer.

However, there is another way to copy data such as this from Project to Excel that is very fast—use the clipboard.

```<code>Private Sub ExtractResources()

    Dim prj As MSProject.Project
    Set prj = GetObject(Me.cboMaintainToProject.Value)
    Dim msp As MSProject.Application
    Set msp = prj.Application
    msp.WindowActivate prj.Name

    ActiveWorkbook.Sheets("Resource Table").Range("A2:C" & CStr(ActiveWorkbook.ActiveSheet.UsedRange.Rows.Count)).ClearContents

    msp.ViewApply "Resource Sheet"

    msp.SelectSheet
    msp.EditCopy
    ActiveWorkbook.Sheets("Resource Table").Range("A2").PasteSpecial xlPasteValues

End Sub
</code>```

Note: Modify the Resource View (or create your own) to define which columns to export out of Project. If you want the ID column to be exported, check the definition of the table used with the resource view to make sure the first column is not locked, otherwise it won't be included in the SelectSheet method.

Body:
I have numerous macros that seem to be slowing down when interfacing with MS Project (e.g., reading data and processing it) in MS Office 2016. It could be my underlying code, mechanisms for obtaining/storing the data, but I'm not sure and would appreciate input.

I was just writing a new macro for extracting MSP data into an array (held in memory I thought this would be fastest, but it seemed to struggle to even do this). The idea being that the array memory access 'should' be faster than bridging from MS Excel to the Project referenced when needing to extract/place data? Perhaps this is incorrect.

Aim: Hold 3 parts of each MS Project Resource in Array, eventually iterate over array and place into Excel for additional use/processing.

The initial 'read' never quite completed (at 926 of my 1300 resources) before I broke the code to review.

Ideas on the below, or for interfacing with the MSP 2016 Reference library? It seems to have become very slow compared to just working within MS Excel.

Subroutine:

  Private Sub cb_IMSResourceImport_Click()
        Dim Prj As Project
        Set Prj = GetObject(Me.cboMaintainToProject.Value)
        Dim ResourceMatrix() As String
        Prj.Application.WindowActivate Prj.Name

        ReDim ResourceMatrix(Prj.Resources.Count, 2)

    ActiveWorkbook.Sheets("Resource Table").Range("A2:C" & C`Str(ActiveWorkbook.ActiveSheet.UsedRange.Rows.Count)).ClearContents

       For i = 1 To UBound(ResourceMatrix)
            ResourceMatrix(i - 1, 0) = Prj.Resources(i).ID
            ResourceMatrix(i - 1, 1) = Prj.Resources(i).Name
            ResourceMatrix(i - 1, 2) = Prj.Resources(i).Code
       Next i

       For i = 0 To UBound(ResourceMatrix)
            ActiveWorkbook.Sheets("Resource Table").Cells(i + 1, 1).Value = ResourceMatrix(i, 0)
            ActiveWorkbook.Sheets("Resource Table").Cells(i + 1, 2).Value = ResourceMatrix(i, 1)
            ActiveWorkbook.Sheets("Resource Table").Cells(i + 1, 3).Value = ResourceMatrix(i, 2)
       Next i

End Sub

Body:
Using Project 2013 and a mocked-up schedule with 2000 resources, your code took less than 2 minutes to run. That said, if you have many schedules open, calculation left on, etc. it could take longer.

However, there is another way to copy data such as this from Project to Excel that is very fast—use the clipboard.

Private Sub ExtractResources()

    Dim prj As MSProject.Project
    Set prj = GetObject(Me.cboMaintainToProject.Value)
    Dim msp As MSProject.Application
    Set msp = prj.Application
    msp.WindowActivate prj.Name

    ActiveWorkbook.Sheets("Resource Table").Range("A2:C" & CStr(ActiveWorkbook.ActiveSheet.UsedRange.Rows.Count)).ClearContents

    msp.ViewApply "Resource Sheet"

    msp.SelectSheet
    msp.EditCopy
    ActiveWorkbook.Sheets("Resource Table").Range("A2").PasteSpecial xlPasteValues

End Sub

Note: Modify the Resource View (or create your own) to define which columns to export out of Project. If you want the ID column to be exported, check the definition of the table used with the resource view to make sure the first column is not locked, otherwise it won't be included in the SelectSheet method.


来源: stackexchange

问:
JavaScript variable before and after declaration?
```<code>function a(){
   console.log(typeof b); // function
   function b() {
     var c = 52;
     console.log(c);
   }
   var b = 88;
   console.log(typeof b); // number
}
</code>```

Could anyone answer, how javaScript compiles or handles this particular case ? I know javaScript gives preference to function declaration when it comes to hoisting. But how a same identifier b holds two different values under same block or in same lexical scoping?

Someone could say like, okay, I'm going to use b as a function before it's declaration and as number after assigning it a number.

答:
You can understand as such there are two phase of code execution

Creation phase

Execution phase

Creation phase:- During creation phase function is hoisted at top as it is, while the variable are hoisted but there is no value assigned to it ( or you can say it's value is undefined )

Execution phase:- During execution context it assigns value to variable when it reaches line where assignment is happening

so in your code during creation phase function b is hoisted, compiler will read it like this

```<code>function a(){
   function b(){
     var c = 52;
     console.log(c);
   }
   console.log(typeof b); // function
   b = 88;
   console.log(typeof b); // number
}
</code>```

so when you reach to the line

```<code>b = 88
</code>```

it assign a new value to variable b which is of type number

ContentLicense: CC BY-SA 4.0

Body:
function a(){
   console.log(typeof b); // function
   function b() {
     var c = 52;
     console.log(c);
   }
   var b = 88;
   console.log(typeof b); // number
}

Could anyone answer, how javaScript compiles or handles this particular case ? I know javaScript gives preference to function declaration when it comes to hoisting. But how a same identifier b holds two different values under same block or in same lexical scoping?

Someone could say like, okay, I'm going to use b as a function before it's declaration and as number after assigning it a number.

Body:
You can understand as such there are two phase of code execution

Creation phase

Execution phase

Creation phase:- During creation phase function is hoisted at top as it is, while the variable are hoisted but there is no value assigned to it ( or you can say it's value is undefined )

Execution phase:- During execution context it assigns value to variable when it reaches line where assignment is happening

so in your code during creation phase function b is hoisted, compiler will read it like this

function a(){
   function b(){
     var c = 52;
     console.log(c);
   }
   console.log(typeof b); // function
   b = 88;
   console.log(typeof b); // number
}

so when you reach to the line

b = 88

it assign a new value to variable b which is of type number


问:
Layout changing(resizing) when switching from mobile to desktop
The whole layout resizes when I change from desktop to mobile view. Elements with a width of 500px that should take up the entire screen don't.

I want mobile to look the same as desktop.

I've tried adding <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no/> to every index.php, but nothing changed.

Desktop view
Moblie view

答: I added <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> to another index.php and it worked :D


问:
Force StandardOutputEncoding to UTF8
I'm looking to parse UTF8 characters from the standard output stream of another application in my C# project. Using the default approach, characters outside of the ANSI spectrum are corrupted when read from the process' standard output stream.

Now according to Microsoft, what I need to do is set the StandardOutputEncoding:

If the value of the StandardOutputEncoding property is Nothing, the process uses the default standard output encoding for the standard output. The StandardOutputEncoding property must be set before the process is started. Setting this property does not guarantee that the process will use the specified encoding. The application should be tested to determine which encodings the process supports.

However, try as I might to set StandardOutputEncoding to UTF8/CP65001 the output as read, when dumped to a binary file, shows the same castration of foreign language characters. They are always read as '?' (aka 0x3F) instead of what they're supposed to be.

I know the assumption at this point would be that the application whose output I'm parsing is simply not sending UTF8 output, but this is definitely not the case as when I attempt to dump the output of the application to a file from the commandline after forcing the codepage of the commandprompt to 65001, everything looks fine.

```<code>chcp 65001 && slave.exe > file.txt
</code>```

By this, I know for a fact that the application slave.txt is capable of spitting out UTF8-encoded standard output, but try as I might, I'm unable to get StandardOutputEncoding to do the same in my C# application.

Each and every time I end up dealing with encoding in .NET, I wish I were back in the C++ world were everything required more work but was so much more transparent. I'm contemplating writing a C application to read the output of slave.txt into a UTF8-encoded text file ready for C# parsing, but I'm holding off on that approach for now.

答:
modern .NET option:

```<code>Console.OutputEncoding = System.Text.Encoding.UTF8;
</code>```

Source

ContentLicense: CC BY-SA 3.0

Title: Force StandardOutputEncoding to UTF8

Body:
I'm looking to parse UTF8 characters from the standard output stream of another application in my C# project. Using the default approach, characters outside of the ANSI spectrum are corrupted when read from the process' standard output stream.

Now according to Microsoft, what I need to do is set the StandardOutputEncoding:

If the value of the StandardOutputEncoding property is Nothing, the process uses the default standard output encoding for the standard output. The StandardOutputEncoding property must be set before the process is started. Setting this property does not guarantee that the process will use the specified encoding. The application should be tested to determine which encodings the process supports.

However, try as I might to set StandardOutputEncoding to UTF8/CP65001 the output as read, when dumped to a binary file, shows the same castration of foreign language characters. They are always read as '?' (aka 0x3F) instead of what they're supposed to be.

I know the assumption at this point would be that the application whose output I'm parsing is simply not sending UTF8 output, but this is definitely not the case as when I attempt to dump the output of the application to a file from the commandline after forcing the codepage of the commandprompt to 65001, everything looks fine.

chcp 65001 && slave.exe > file.txt

By this, I know for a fact that the application slave.txt is capable of spitting out UTF8-encoded standard output, but try as I might, I'm unable to get StandardOutputEncoding to do the same in my C# application.

Each and every time I end up dealing with encoding in .NET, I wish I were back in the C++ world were everything required more work but was so much more transparent. I'm contemplating writing a C application to read the output of slave.txt into a UTF8-encoded text file ready for C# parsing, but I'm holding off on that approach for now.

Body:
modern .NET option:

Console.OutputEncoding = System.Text.Encoding.UTF8;

Source


问:
CSS two column form Divs using current form style
I have the following style for my form:

```<code>.UserForm {

  &__form {
    padding: 10px 24px;
    width: 100%;
  }
  &__form-row {
    display: flex;
    align-items: flex-start;
    justify-content: flex-end;
    flex-wrap: wrap;

    .form-field,
    .form-select,
    .textarea {
      width: 60%;
    }

    .profile-image {
       width: 60%;
    }

    .form-label {
      margin-right: 12px;
      width: 30%;
      // text-align: right;
    }

    & > .Password {
      width: 70%;
      max-width: 60%!important;
      margin: 0;
    }

  }
}
</code>```

And this is the HTML

```<code><form name="setUser" autocomplete="off" class="UserForm__form">
    <div class="form-row UserForm__form-row">
      <label class="form-label" for="firstName">First Name</label>
      <input
        v-focus
        id="firstName"
        name="firstName"
        class="form-field"
      >
      <span
        v-show="errors.has('firstName')"
        class="form-help is-danger"
      >{{ errors.first('firstName') }}</span>
    </div>

<div class="form-row UserForm__form-row">
  <label class="form-label" for="lastName">Last Name</label>
  <input
    id="lastName"
    name="lastName"
    class="form-field"
  >
  <span
    v-show="errors.has('lastName')"
    class="form-help is-danger"
  >{{ errors.first('lastName') }}</span>
</div>

</form>
</code>```

This is how it looks like:

What I need is that only for first name field row I have to add other column so the text field is smaller so I can add a checkbox just to the right of the field.

Something like this:

答:
you can try this:</p>

```<code>In yout HTML, add a label for the checkbox:

<label class="myCheckbox">
    <input type="checkbox" />
    Active
</label>

And in the SCSS, add this styles after the form-field width:

.form-field:first-of-type {
    width: 40%;
}
.myCheckbox {
    width: 20%;
}
</code>```

Body:
I have the following style for my form:

.UserForm {

  &__form {
    padding: 10px 24px;
    width: 100%;
  }
  &__form-row {
    display: flex;
    align-items: flex-start;
    justify-content: flex-end;
    flex-wrap: wrap;

    .form-field,
    .form-select,
    .textarea {
      width: 60%;
    }

    .profile-image {
       width: 60%;
    }

    .form-label {
      margin-right: 12px;
      width: 30%;
      // text-align: right;
    }

    & > .Password {
      width: 70%;
      max-width: 60%!important;
      margin: 0;
    }

  }
}

And this is the HTML

<form name="setUser" autocomplete="off" class="UserForm__form">

      First Name
      <input
        v-focus
        id="firstName"
        name="firstName"
        class="form-field"
      >
      {{ errors.first('firstName') }}

  Last Name
  <input
    id="lastName"
    name="lastName"
    class="form-field"
  >
  {{ errors.first('lastName') }}

</form>

This is how it looks like:

What I need is that only for first name field row I have to add other column so the text field is smaller so I can add a checkbox just to the right of the field.

Something like this:

Body:
you can try this:

In yout HTML, add a label for the checkbox:

<label class="myCheckbox">
    <input type="checkbox" />
    Active
</label>

And in the SCSS, add this styles after the form-field width:

.form-field:first-of-type {
    width: 40%;
}
.myCheckbox {
    width: 20%;
}


问:
Github: Several commits behind, no shown differences
In my github fork (master branch) of the public repository geopandas I can see the following notification:

This branch is 28 commits behind geopandas:master.

I think this means that I somehow need to merge those commits from the remote master to my remote fork. However when I open the "Compare" tab (to check what these 28 commits are), it shows the following:

I would have expected to see a list of the 28 commits and what they are. So I conclude that there is something fundamentally flawed in my understanding of how the forking workflow works.

Why does the "28 commits behind" message not imply actual changes in the compare tab?

答:
This is not a symmetric comparison in the case of a pull request. One branch is the source, the other is the destination.

As alfunx points out in comment, you have here your branch as the source, which is the contrary of what you wanted.

Swap the repos in the select boxes to make geopandas/geopandas the source.


问:
VS 2017 Metadata file '.dll could not be found
I know there is another question with exact the same problem, but I went trough all those answers, and none helped me. :( (This was the question.)

I just created a new ASP.NET MVC project and joined a few '.dll's in the solution. Now when I try to build the project I get the error message shown below on 3 of the 5 libraries.

```<code>Error   CS0006  Metadata file 'C:\Users\...\source\Database\bin\Debug\DataAccessLayer.dll' could not be found   Logic   C:\Users\...\source\Logic\CSC   1   Active

Error   CS0006  Metadata file 'C:\Users\...\source\Logic\bin\Debug\Logic.dll' could not be found    PTS2-MVC    C:\Users\...\source\PTS2-MVC\CSC    1   Active

Error   CS0006  Metadata file 'C:\Users\...\source\PTS2-MVC\bin\PTS2-MVC.dll' could not be found    PTS2-MVC.Tests  C:\Users\...\source\PTS2-MVC.Tests\CSC  1   Active
</code>```

When I go to the bin\debug folder of that .dll, I see that it is empty, and the other .dll where I do not get an error message, is not empty. But I am clueless how to fix this or what I did to make this happen.

The most common answer is to go to the properties of the solution and go to configuration and uncheck -> apply -> check and apply again, but that didn't work

答:
For me what worked was:

Uninstall and then reinstall the referenced Nuget package that has the error.

Body:
I know there is another question with exact the same problem, but I went trough all those answers, and none helped me. :( (This was the question.)

I just created a new ASP.NET MVC project and joined a few '.dll's in the solution. Now when I try to build the project I get the error message shown below on 3 of the 5 libraries.

Error   CS0006  Metadata file 'C:\Users\...\source\Database\bin\Debug\DataAccessLayer.dll' could not be found   Logic   C:\Users\...\source\Logic\CSC   1   Active

Error   CS0006  Metadata file 'C:\Users\...\source\Logic\bin\Debug\Logic.dll' could not be found    PTS2-MVC    C:\Users\...\source\PTS2-MVC\CSC    1   Active

Error   CS0006  Metadata file 'C:\Users\...\source\PTS2-MVC\bin\PTS2-MVC.dll' could not be found    PTS2-MVC.Tests  C:\Users\...\source\PTS2-MVC.Tests\CSC  1   Active

When I go to the bin\debug folder of that .dll, I see that it is empty, and the other .dll where I do not get an error message, is not empty. But I am clueless how to fix this or what I did to make this happen.

The most common answer is to go to the properties of the solution and go to configuration and uncheck -> apply -> check and apply again, but that didn't work


问:
HTML email is showing as code rather than the css page
I wanted to make an automated html/css email, where I have used the mail() function but it is showing as code

I have provided the doctype and stuff in the header but still it is showing as code:

I also concatenated the header giving the doctype into the header but it still doesn't work.

This is my code:

```<code>
<?php

    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }
$email_from = "info@domain.com";
    $email_message = "

<html xmlns='http://www.w3.org/1999/xhtml' xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:v='urn:schemas-microsoft-com:vml' style='line-height: inherit;'>
<head>

<meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
<meta content='width=device-width' name='viewport'>

<meta content='IE=edge' http-equiv='X-UA-Compatible'>

<title></title>

<style id='media-query' type='text/css'>
@media only screen and (min-width: 670px) {
  .block-grid {
    width: 650px !important;
  }

  .desktop_hide {
    display: block !important;
    max-height: none !important;
  }
}
</style>
</head>
<body class='clean-body' style='line-height: inherit; margin: 0; padding: 0; -webkit-text-size-adjust: 100%; background-color: #FFFFFF;'>
<style id='media-query-bodytag' type='text/css'>

</tr>
</tbody>
</table>
</
</table>
</body>
</html>";

$to = "email@gmail.com";
$subject = "Enquiry";
$txt = $email_message;
$headers1="<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional //EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>";
$headers2 = "From:". $email_from . "\r\n" .
"CC: email@gmail.com";
$headers=$headers1.$headers2;

if (mail($to,$subject,$txt,$headers))
{
    //echo "Thank You for contacting us, we will get back to you soon";
}
?>

</code>```

答:
I believe you need to set the Mime and Content Type to send a message containing HTML. Add the following to $headers.</p>

```<code>$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html\r\n";
</code>```

Body:
I wanted to make an automated html/css email, where I have used the mail() function but it is showing as code

I have provided the doctype and stuff in the header but still it is showing as code:

I also concatenated the header giving the doctype into the header but it still doesn't work.

This is my code:

<?php

    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }
$email_from = "info@domain.com";
    $email_message = "

<meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
<meta content='width=device-width' name='viewport'>

<meta content='IE=edge' http-equiv='X-UA-Compatible'>

<title></title>

Body:
I believe you need to set the Mime and Content Type to send a message containing HTML. Add the following to $headers.

$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html\r\n";


问:
How to display every image inside an image folder in react
I have an image folder in my create-react-app project with a bunch of images. I want to display every single image in the components.

```<code>├── Components
│   ├── Icons
│   │   ├── Icon.jsx (I want to display every single icon)
│
│
├── Images
│   ├── Icons
│   │   ├── ... (over 100 SVG icons)
</code>```

In my .jsx file, I want to loop over every image/icon and display it.

Icons.jsx

```<code>import React, { Component } from 'react';
import Icons from '../../Images/Icons';

class Icons extends Component {
  render() {
    return (
      //Loop over every icon and display it
    );
  }
}
</code>```

答:
I'd take a look at https://github.com/react-icons/react-icons/blob/master/packages/react-icons/scripts/build.js. The author takes many folders of svg's and turns them into usable components in react.  It's a repeatable workflow that should work for your svg icon pack as well if you retrofit that script into your app.

In some ways for webpack, you'd need something like an index.js file in that '../../Images/Icons' folder that exports all the icons for easy import elsewhere.

You can do some quick and dirty bash tricks (like lsa) and with your editor (multi-cursor/find-and-replace) to get the filenames and make that index.js file once.  Then adding to it will not take much effort. But it's probably better to use a script that can generate an "exports file" on demand from a folder of svgs.

Body:
I have an image folder in my create-react-app project with a bunch of images. I want to display every single image in the components.

├── Components
│   ├── Icons
│   │   ├── Icon.jsx (I want to display every single icon)
│
│
├── Images
│   ├── Icons
│   │   ├── ... (over 100 SVG icons)

In my .jsx file, I want to loop over every image/icon and display it.

Icons.jsx

import React, { Component } from 'react';
import Icons from '../../Images/Icons';

class Icons extends Component {
  render() {
    return (
      //Loop over every icon and display it
    );
  }
}


问:
How to unit test function in React App with JEST
Hi I am quite new in testing in JEST that why I want to ask you about some support.

I`m trying to test function from App.js component in my App.test.js
but I recive a error:

TypeError: _App.default.avg is not a function.

Here is my App.js component

```<code>class App extends React.Component {

 state={ }

 avg = (elements) => {
 let sum=0;
 for(let i=0; i<elements.length; i++){
     sum += elements[i].main.temp;
 }
 return (sum/elements.length).toFixed(2);
 }

  render() {
    return(
      <BrowserRouter>
          <AppContext.Provider value={contextElements}>
              <div className="App container">
                <Route path="/" component={SettingsBar}/>
                <Route path="/settings" component={SettingsView}/>
                <Route exact path="/" component={RootView}/>
                <Route  path="/itemview" component={ItemView}/>
              </div>
          </AppContext.Provider>
      </BrowserRouter>

    )
  }
}
export default App;
</code>```

And App.test.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

describe('avg', () => {

     it('should return 3 for given array [1,2,3,4,5]', () => {
         expect(App.avg([1,2,3,4,5])).toBe(3);
     });

});
</code>```

What I`m doing wrong?

答:
You may want to try making an instance of your App.js class.

So after import you could try something like

const myApp = new App();

Then, in your expect, call myApp.avg(arguments).

Body:
Hi I am quite new in testing in JEST that why I want to ask you about some support.

I`m trying to test function from App.js component in my App.test.js
but I recive a error:

TypeError: _App.default.avg is not a function.

Here is my App.js component

class App extends React.Component {

 state={ }

 avg = (elements) => {
 let sum=0;
 for(let i=0; i<elements.length; i++){
     sum += elements[i].main.temp;
 }
 return (sum/elements.length).toFixed(2);
 }

  render() {
    return(
      <BrowserRouter>
          <AppContext.Provider value={contextElements}>

                <Route path="/" component={SettingsBar}/>
                <Route path="/settings" component={SettingsView}/>
                <Route exact path="/" component={RootView}/>
                <Route  path="/itemview" component={ItemView}/>

          </AppContext.Provider>
      </BrowserRouter>

    )
  }
}
export default App;

And App.test.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

describe('avg', () => {

     it('should return 3 for given array [1,2,3,4,5]', () => {
         expect(App.avg([1,2,3,4,5])).toBe(3);
     });

});

What I`m doing wrong?


答:
Set the header to support html email template. Add this code in header.</p>

```<code>"Content-Type: text/html; charset=UTF-8"
</code>```

Title: HTML email is showing as code rather than the css page

Body:
Set the header to support html email template. Add this code in header.

"Content-Type: text/html; charset=UTF-8"


问:
insert in for each with async await
error on query execution

```<code>var records = [{name:'John',age:24},{name:'Sarah',age:28},{name:'Linda',age:23}];

connection.getSession().then(session => {
   async function insertRecords() {
      await Promise.all(records.map(async function (element) {
         let util = {};
         util['name'] = element['name'];
         util['age'] = element['age'] || null;
         let query = `INSERT INTO users SET
           name =?,
           age=?
           ON DUPLICATE KEY UPDATE
            name=VALUES(name),
            age=VALUES(age)`;

        session.sql(query).bind([util.name, util.age]).execute()
           .then(() => {})
           .catch((error) => {
              console.error('cannot execute the query');
              console.error('error', error);
           });
      }))
   }

   insertRecords()
      .then(data => console.log('data', data))
      .catch(err => console.log('err', err))

}).catch((err) => {
    console.error(err);
    session.close();
});
</code>```

I am getting the following error on execution.

{ severity: 0,
     code: 5015,
     sqlState: 'HY000',
     msg: 'Too many arguments' } }

答:
In your Promise.all, you map on records but your resolver function doesn't return anything. You would need to return a promise. To do so, you should just replace your session.sql block with the following: return session.sql(query).bind([util.name, util.age]).execute().

That would return an array of Promises to Promise.all, and it would work. The error handling is already done when you call your insertRecords function so you don't need to worry about it in your resolver.

Title: insert in for each with async await

Body:
error on query execution

var records = [{name:'John',age:24},{name:'Sarah',age:28},{name:'Linda',age:23}];

connection.getSession().then(session => {
   async function insertRecords() {
      await Promise.all(records.map(async function (element) {
         let util = {};
         util['name'] = element['name'];
         util['age'] = element['age'] || null;
         let query = `INSERT INTO users SET
           name =?,
           age=?
           ON DUPLICATE KEY UPDATE
            name=VALUES(name),
            age=VALUES(age)`;

        session.sql(query).bind([util.name, util.age]).execute()
           .then(() => {})
           .catch((error) => {
              console.error('cannot execute the query');
              console.error('error', error);
           });
      }))
   }

   insertRecords()
      .then(data => console.log('data', data))
      .catch(err => console.log('err', err))

}).catch((err) => {
    console.error(err);
    session.close();
});

I am getting the following error on execution.

{ severity: 0,
     code: 5015,
     sqlState: 'HY000',
     msg: 'Too many arguments' } }


问:
What are the options for the -Encoding parameter in the Import-DbaCsv tool?
I can't figure out what the Import-DbaCsv tool is expecting for the -Encoding parameter.

The docs aren't helpful - https://docs.dbatools.io/#Import-DbaCsv

I've tried UTF-8, UTF8, and UTF in upper case, lower case, with quotes, and without quotes.

I always get and error message like this:

Cannot convert the "UTF-8" value of type "System.String" to type "System.Text.Encoding"

答:
The expected type is System.Text.Encoding, but there are no built-in string-to-Encoding conversions that apply here.

You can fix that by applying a PSTypeConverter:

```<code>using namespace System.Management.Automation
using namespace System.Text

class PSTextEncodingConverter : PSTypeConverter {
    hidden
    [hashtable]
    $ConversionTable = @{
        'ASCII'               = [System.Text.Encoding]::ASCII
        'ANSI'                = [System.Text.Encoding]::ASCII

        'UTF7'                = [System.Text.Encoding]::UTF7
        'UTF-7'               = [System.Text.Encoding]::UTF7

        'UTF8'                = [System.Text.Encoding]::UTF8
        'UTF-8'               = [System.Text.Encoding]::UTF8

        'Unicode'             = [System.Text.Encoding]::Unicode
        'UTF16LE'             = [System.Text.Encoding]::Unicode
        'LittleEndianUnicode' = [System.Text.Encoding]::Unicode

        'UTF16BE'             = [System.Text.Encoding]::BigEndianUnicode
        'BigEndianUnicode'    = [System.Text.Encoding]::BigEndianUnicode

        'UTF32'               = [System.Text.Encoding]::UTF32
        'UTF-32'              = [System.Text.Encoding]::UTF32

        'Default'             = [System.Text.Encoding]::Default
    }

    [bool]
    CanConvertFrom([object]$value, [type]$targetType) {
        return (
            $this.IsEncodingType($targetType)
        ) -and (
            (
                $value -is $targetType
            ) -or (
                (
                    $value -is [string]
                ) -and (
                    "$value" -in $this.ConversionTable.Keys
                )
            )
        )
    }

    [object]
    ConvertFrom([object]$value, [Type]$targetType, [IFormatProvider]$format, [bool]$ignoreCase) {
        if ($value -is $targetType) {
            return $value
        }

        if ($this.ConversionTable.Contains("$value")) {
            return $this.ConversionTable["$value"]
        }

        throw "Failed to convert '$value' to [$($targetType.FullName)]."
    }

    [bool]
    CanConvertTo([object]$value, [Type]$targetType) {
        return $this.CanConvertFrom($value, $targetType)
    }

    [object]
    ConvertTo([object]$value, [Type]$targetType, [IFormatProvider]$format, [bool]$ignoreCase) {
        return $this.ConvertFrom($value, $targetType, $format, $ignoreCase)
    }

    [bool]
    IsEncodingType([type]$targetType) {
        $type = $targetType
        do {
            if ($type -eq [Encoding]) {
                return $true
            }
        } while (($type = $type.BaseType) -ne $null)

        return $false
    }
}
</code>```

Then register the type converter with Update-TypeData:

```<code>Update-TypeData -TypeName System.Text.Encoding -TypeConverter PSTextEncodingConverter
</code>```

Now any parameter that expects an instance of [Encoding] will accept the string value UTF-8 or UTF8 in its place:

```<code>Import-DbaCsv -Path .\file.csv -SqlInstance sqlsrv -Database db1 -Encoding UTF8
</code>```

Body:
The expected type is System.Text.Encoding, but there are no built-in string-to-Encoding conversions that apply here.

You can fix that by applying a PSTypeConverter:

using namespace System.Management.Automation
using namespace System.Text

class PSTextEncodingConverter : PSTypeConverter {
    hidden
    [hashtable]
    $ConversionTable = @{
        'ASCII'               = [System.Text.Encoding]::ASCII
        'ANSI'                = [System.Text.Encoding]::ASCII

        'UTF7'                = [System.Text.Encoding]::UTF7
        'UTF-7'               = [System.Text.Encoding]::UTF7

        'UTF8'                = [System.Text.Encoding]::UTF8
        'UTF-8'               = [System.Text.Encoding]::UTF8

        'Unicode'             = [System.Text.Encoding]::Unicode
        'UTF16LE'             = [System.Text.Encoding]::Unicode
        'LittleEndianUnicode' = [System.Text.Encoding]::Unicode

        'UTF16BE'             = [System.Text.Encoding]::BigEndianUnicode
        'BigEndianUnicode'    = [System.Text.Encoding]::BigEndianUnicode

        'UTF32'               = [System.Text.Encoding]::UTF32
        'UTF-32'              = [System.Text.Encoding]::UTF32

        'Default'             = [System.Text.Encoding]::Default
    }

    [bool]
    CanConvertFrom([object]$value, [type]$targetType) {
        return (
            $this.IsEncodingType($targetType)
        ) -and (
            (
                $value -is $targetType
            ) -or (
                (
                    $value -is [string]
                ) -and (
                    "$value" -in $this.ConversionTable.Keys
                )
            )
        )
    }

    [object]
    ConvertFrom([object]$value, [Type]$targetType, [IFormatProvider]$format, [bool]$ignoreCase) {
        if ($value -is $targetType) {
            return $value
        }

        if ($this.ConversionTable.Contains("$value")) {
            return $this.ConversionTable["$value"]
        }

        throw "Failed to convert '$value' to [$($targetType.FullName)]."
    }

    [bool]
    CanConvertTo([object]$value, [Type]$targetType) {
        return $this.CanConvertFrom($value, $targetType)
    }

    [object]
    ConvertTo([object]$value, [Type]$targetType, [IFormatProvider]$format, [bool]$ignoreCase) {
        return $this.ConvertFrom($value, $targetType, $format, $ignoreCase)
    }

    [bool]
    IsEncodingType([type]$targetType) {
        $type = $targetType
        do {
            if ($type -eq [Encoding]) {
                return $true
            }
        } while (($type = $type.BaseType) -ne $null)

        return $false
    }
}

Then register the type converter with Update-TypeData:

Update-TypeData -TypeName System.Text.Encoding -TypeConverter PSTextEncodingConverter

Now any parameter that expects an instance of [Encoding] will accept the string value UTF-8 or UTF8 in its place:

Import-DbaCsv -Path .\file.csv -SqlInstance sqlsrv -Database db1 -Encoding UTF8


问:
Cloud Endpoints - Is implementing JWT Possible?
I'm working on a website and there is existing auth using Google cloud Datastore. I can't seem to find any documentation showing how I can generate a JSON web token compatible with cloud Endpoints for the end users. </p>

<p>Any links you can scavenge are greatly appreciated. </p>

答:
I'm working on a website and there is existing auth using Google cloud
  Datastore.

If your current auth system is generating your own OAuth tokens, you cannot use those tokens with Google Cloud Endpoints. You must generate your tokens via Google mechanisms (Google Accounts). Otherwise, Google services cannot validate your tokens. Check to see if your backend is creating tokens or using Google OAuth to create tokens. However, there are three types of tokens: Access Token, Refresh Token, and Client ID Token. You backend may need to be modified to generate Client ID (OIDC) Tokens. Some systems just generate the first two.

The following assumes Google issued OAuth tokens.

Yes, it is possible and very easy. I will show you an example.

Note: I wrote an article on how to generate OAuth 2.0 Tokens with CURL including the Client ID token. Google OAuth 2.0 – Testing with Curl – Refresh Access Token My article shows you the steps so that you can code in any language.

Using the CLI, generate an OAuth 2.0 Client ID Token:

```<code>gcloud config config-helper --format "value(credential.id_token)" --force-auth-refresh
</code>```

Save the generated token. Call it TOKEN for this example.

URL is the endpoint URL.

Now make a request to your endpoint:

```<code>curl -H "Authorization: Bearer TOKEN" URL
</code>```

If you are curious to see what is inside the TOKEN JWT:

curl https://oauth2.googleapis.com/tokeninfo?id_token=TOKEN

The returned JSON will look like this:

```<code>{
  "aud": "https://cloudtask-abcdefabcdef-uc.a.run.app",
  "azp": "0123456789077420983142",
  "email": "cloudtask@development.iam.gserviceaccount.com",
  "email_verified": "true",
  "exp": "1559029789",
  "iat": "1559026189",
  "iss": "https://accounts.google.com",
  "sub": "012345678901234567892",
  "alg": "RS256",
  "kid": "0123456789012345678901234567890123456789c3",
  "typ": "JWT"
}
</code>```

I can't seem to find any documentation showing how I can generate a
  JSON web token compatible with cloud Endpoints for the end users.

Here is a link with details on Google Cloud Endpoints Authentication:

Google ID token authentication

You may wonder why you cannot use your own tokens. The reason is that Google cannot verify the signature on the token.

OAuth tokens (Signed-JWT) are signed using a Private Key. They are validated using the Public Key. Google publishes the Public Keys at https://www.googleapis.com/oauth2/v1/certs

This allows Google and others to validate Google signed data. When you generate a token, Google cannot access your Public Key to validate the signature. Therefore, you must use Google generated tokens so that Google can validate them.

Body:
I'm working on a website and there is existing auth using Google cloud Datastore. I can't seem to find any documentation showing how I can generate a JSON web token compatible with cloud Endpoints for the end users.

Any links you can scavenge are greatly appreciated.

Body:
I'm working on a website and there is existing auth using Google cloud
  Datastore.

If your current auth system is generating your own OAuth tokens, you cannot use those tokens with Google Cloud Endpoints. You must generate your tokens via Google mechanisms (Google Accounts). Otherwise, Google services cannot validate your tokens. Check to see if your backend is creating tokens or using Google OAuth to create tokens. However, there are three types of tokens: Access Token, Refresh Token, and Client ID Token. You backend may need to be modified to generate Client ID (OIDC) Tokens. Some systems just generate the first two.

The following assumes Google issued OAuth tokens.

Yes, it is possible and very easy. I will show you an example.

Note: I wrote an article on how to generate OAuth 2.0 Tokens with CURL including the Client ID token. Google OAuth 2.0 – Testing with Curl – Refresh Access Token My article shows you the steps so that you can code in any language.

Using the CLI, generate an OAuth 2.0 Client ID Token:

gcloud config config-helper --format "value(credential.id_token)" --force-auth-refresh

Save the generated token. Call it TOKEN for this example.

URL is the endpoint URL.

Now make a request to your endpoint:

curl -H "Authorization: Bearer TOKEN" URL

If you are curious to see what is inside the TOKEN JWT:

curl https://oauth2.googleapis.com/tokeninfo?id_token=TOKEN

The returned JSON will look like this:

{
  "aud": "https://cloudtask-abcdefabcdef-uc.a.run.app",
  "azp": "0123456789077420983142",
  "email": "cloudtask@development.iam.gserviceaccount.com",
  "email_verified": "true",
  "exp": "1559029789",
  "iat": "1559026189",
  "iss": "https://accounts.google.com",
  "sub": "012345678901234567892",
  "alg": "RS256",
  "kid": "0123456789012345678901234567890123456789c3",
  "typ": "JWT"
}

I can't seem to find any documentation showing how I can generate a
  JSON web token compatible with cloud Endpoints for the end users.

Here is a link with details on Google Cloud Endpoints Authentication:

Google ID token authentication

You may wonder why you cannot use your own tokens. The reason is that Google cannot verify the signature on the token.

OAuth tokens (Signed-JWT) are signed using a Private Key. They are validated using the Public Key. Google publishes the Public Keys at https://www.googleapis.com/oauth2/v1/certs

This allows Google and others to validate Google signed data. When you generate a token, Google cannot access your Public Key to validate the signature. Therefore, you must use Google generated tokens so that Google can validate them.


答:
As far as I know, those aren't 2 different references.

Internally,
function b(){/*Code Here*/} is executed as var b = function(){/*Code Here*/}
Hence, the first typeof(b) returns function.

And when var b = 88; executes, this basically assigns 88 to the already existing reference of b.
Hence, the second typeof(b) returns number.

Runtime image for reference:

Title: JavaScript variable before and after declaration?


问:
shell script to generate a map
I'd like to have a script (bash) to generate an img (gif, jpg, etc.) of a (openstreetmap or googlemap) map given a location, like this:

```<code>$ genmap.sh 45.5 9.5
</code>```

(parameters are lat & long)

or:

```<code>$ genmap.sh 45.5 9.5 12
</code>```

(parameters are lat & long and zoom)

etc. etc.

can you point me to something on the net?

thank you

答:
OpenStreetMap has an exporting API, which you could use with, say, wget:

http://tile.openstreetmap.org/cgi-bin/export?bbox=-3.296,58.906,-2.781,59.139&scale=435000&format=png

Currently though, it gives over-load errors.

Title: shell script to generate a map

Body:
I'd like to have a script (bash) to generate an img (gif, jpg, etc.) of a (openstreetmap or googlemap) map given a location, like this:

$ genmap.sh 45.5 9.5

(parameters are lat & long)

or:

$ genmap.sh 45.5 9.5 12

(parameters are lat & long and zoom)

etc. etc.

can you point me to something on the net?

thank you


问:
405 Method Not Allowed for DELETE
I'm getting a '405 Method Not Allowed' when I attempt for a DELETE without passing the resource Id which needs to be deleted.Here is my URL

```<code>http://localhost:8080/api/vendors/delete/1234/
</code>```

where ideally I should have given the ID at the end of the URL like:

```<code>http://localhost:8080/api/vendors/delete/1234/{id}
</code>```

I'm convinced it should be a 405 but my QA team thinks otherwise. They say it should be a 400. Can someone point out to me any resource which clearly specifies what HTTP code it should be for this scenario.

答:
As per my opinion 404 Not Found or 400 Bad Request is a good option.
Please refer to this answer as well
HTTP Status Codes</p>

Title: 405 Method Not Allowed for DELETE

Body:
I'm getting a '405 Method Not Allowed' when I attempt for a DELETE without passing the resource Id which needs to be deleted.Here is my URL

http://localhost:8080/api/vendors/delete/1234/

where ideally I should have given the ID at the end of the URL like:

http://localhost:8080/api/vendors/delete/1234/{id}

I'm convinced it should be a 405 but my QA team thinks otherwise. They say it should be a 400. Can someone point out to me any resource which clearly specifies what HTTP code it should be for this scenario.


问:
Read NFC tag until it is detached and update the UI while reading the tag
I want to read an NFC tag until the device moves away from the NFC tag. Then I want to do some activities. I have managed to do this using a while loop to read the tag and catching the InterruptedException. And I also want to update the UI while reading the tag inside the while loop. I couldn't find a way to update the UI when I'm in the while loop.

The data to update the UI comes from an onLocationChanged-listener.

```<code>public void onLocationChanged(Location location) {
    if (location.hasSpeed()) {
        /*double speed=location.getSpeed() * 3.6;;
        while (1==1)
        {*/
        speed = location.getSpeed() * 3.6;
        String units="km/h";
        s= new SpannableString(String.format(Locale.ENGLISH, "%.0f %s", speed, units));
        s.setSpan(new RelativeSizeSpan(0.45f), s.length()-units.length()-1, s.length(), 0);
        updateUI();

    }
}

public void updateUI(){
    drivingMode=findViewById(R.id.txtDriving);
    currentSpeed = findViewById(R.id.valSpeed);
      if (currentSpeed!=null) {
        currentSpeed.setText(s);
        if (speed > 10) {
            drivingMode.setText(R.string.msg_driving);
            isDriving = true;
        } else {
            drivingMode.setText(R.string.msg_notDriving);
            isDriving=false;
        }
    }
}

private void readFromNFC( Ndef ndef)  {
            try
            {
                ndef.connect();
                NdefMessage ndefMessage = ndef.getNdefMessage();
                ndef.close();
                String message = new String(ndefMessage.getRecords()[0].getPayload());
                // Log.d(TAG, "readFromNFC Before Pass: " + message);
                //Toast.makeText(this, "Text" + message, Toast.LENGTH_LONG).show();
                if (message.equals("in")) {
                    Toast.makeText(this.getApplicationContext(), R.string.message_nfc_holder_detected, Toast.LENGTH_LONG).show();
                    if (isDialogshowing) {
                        dialog.dismiss();
                        isEmergency=false;
                    }
                    while (1 == 1) {
                        ndef.connect();
                        ndefMessage = ndef.getNdefMessage();
                        message = new String(ndefMessage.getRecords()[0].getPayload());
                        //Log.d(TAG, "readFromNFCPassed: " + message);
                        TimeUnit.SECONDS.sleep(1);
                        ndef.close();
                        updateUI();
                    }

                } else {
                    Toast.makeText(this.getApplicationContext(), R.string.message_nfc_holder_error, Toast.LENGTH_LONG).show();
                    ndef.close();
                }

            } catch (IOException | FormatException | InterruptedException e ) {
                e.printStackTrace();
                Toast.makeText(this.getApplicationContext(), R.string.message_nfc_holder_detached, Toast.LENGTH_LONG).show();
                if(isDriving) {
                    activateEmergency();
                }
                else
                {
                    if (isDialogshowing) {
                        dialog.dismiss();
                        dialog.dismiss();
                        isDialogshowing = false;
                    }

                }
            }
}
</code>```

答:
In order to continuously read the UI thread without blocking the main UI thread, you could use an AsyncTask. This also allows you to publish status updates to the UI (thread) using an onProgressUpdate() callback.

You AsyncTask could look something like this:

```<code>private class ProcessNFCTask extends AsyncTask<Ndef, NdefMessage, Void> {
    protected Void doInBackground(Ndef... tag) {
        // This happens on the worker thread!

        // TODO: content of readFromNFC(Ndef ndef);
        // Instead of calling updateUI(), you would call publishProgress(message).
        // You can use whatever represents your progress instead of "message".
        // Instead of doing your finalization stuff (what you currently have
        // in the catch clause) here, you would want to do that in
        // onPostExecute() instead.
    }

    protected void onProgressUpdate(NdefMessage... progress) {
        // This happens on the UI thread!

        // You may also use the progress status information provided in
        // "progress" here. This is what you pass to publishProgress(...).
        updateUI();
    }

    protected void onPostExecute(Void result) {
        // This happens on the UI thread!

        // TODO: Whatever you want to do when you are finished reading, e.g.:
        if (isDriving) {
            activateEmergency();
        } else {
            if (isDialogshowing) {
                dialog.dismiss();
                dialog.dismiss();
                isDialogshowing = false;
            }
        }
    }
</code>```

}

Body:
I want to read an NFC tag until the device moves away from the NFC tag. Then I want to do some activities. I have managed to do this using a while loop to read the tag and catching the InterruptedException. And I also want to update the UI while reading the tag inside the while loop. I couldn't find a way to update the UI when I'm in the while loop.

The data to update the UI comes from an onLocationChanged-listener.

public void onLocationChanged(Location location) {
    if (location.hasSpeed()) {
        /*double speed=location.getSpeed() * 3.6;;
        while (1==1)
        {*/
        speed = location.getSpeed() * 3.6;
        String units="km/h";
        s= new SpannableString(String.format(Locale.ENGLISH, "%.0f %s", speed, units));
        s.setSpan(new RelativeSizeSpan(0.45f), s.length()-units.length()-1, s.length(), 0);
        updateUI();

    }
}

public void updateUI(){
    drivingMode=findViewById(R.id.txtDriving);
    currentSpeed = findViewById(R.id.valSpeed);
      if (currentSpeed!=null) {
        currentSpeed.setText(s);
        if (speed > 10) {
            drivingMode.setText(R.string.msg_driving);
            isDriving = true;
        } else {
            drivingMode.setText(R.string.msg_notDriving);
            isDriving=false;
        }
    }
}

private void readFromNFC( Ndef ndef)  {
            try
            {
                ndef.connect();
                NdefMessage ndefMessage = ndef.getNdefMessage();
                ndef.close();
                String message = new String(ndefMessage.getRecords()[0].getPayload());
                // Log.d(TAG, "readFromNFC Before Pass: " + message);
                //Toast.makeText(this, "Text" + message, Toast.LENGTH_LONG).show();
                if (message.equals("in")) {
                    Toast.makeText(this.getApplicationContext(), R.string.message_nfc_holder_detected, Toast.LENGTH_LONG).show();
                    if (isDialogshowing) {
                        dialog.dismiss();
                        isEmergency=false;
                    }
                    while (1 == 1) {
                        ndef.connect();
                        ndefMessage = ndef.getNdefMessage();
                        message = new String(ndefMessage.getRecords()[0].getPayload());
                        //Log.d(TAG, "readFromNFCPassed: " + message);
                        TimeUnit.SECONDS.sleep(1);
                        ndef.close();
                        updateUI();
                    }

                } else {
                    Toast.makeText(this.getApplicationContext(), R.string.message_nfc_holder_error, Toast.LENGTH_LONG).show();
                    ndef.close();
                }

            } catch (IOException | FormatException | InterruptedException e ) {
                e.printStackTrace();
                Toast.makeText(this.getApplicationContext(), R.string.message_nfc_holder_detached, Toast.LENGTH_LONG).show();
                if(isDriving) {
                    activateEmergency();
                }
                else
                {
                    if (isDialogshowing) {
                        dialog.dismiss();
                        dialog.dismiss();
                        isDialogshowing = false;
                    }

                }
            }
}

Body:
In order to continuously read the UI thread without blocking the main UI thread, you could use an AsyncTask. This also allows you to publish status updates to the UI (thread) using an onProgressUpdate() callback.

You AsyncTask could look something like this:

private class ProcessNFCTask extends AsyncTask<Ndef, NdefMessage, Void> {
    protected Void doInBackground(Ndef... tag) {
        // This happens on the worker thread!

        // TODO: content of readFromNFC(Ndef ndef);
        // Instead of calling updateUI(), you would call publishProgress(message).
        // You can use whatever represents your progress instead of "message".
        // Instead of doing your finalization stuff (what you currently have
        // in the catch clause) here, you would want to do that in
        // onPostExecute() instead.
    }

    protected void onProgressUpdate(NdefMessage... progress) {
        // This happens on the UI thread!

        // You may also use the progress status information provided in
        // "progress" here. This is what you pass to publishProgress(...).
        updateUI();
    }

    protected void onPostExecute(Void result) {
        // This happens on the UI thread!

        // TODO: Whatever you want to do when you are finished reading, e.g.:
        if (isDriving) {
            activateEmergency();
        } else {
            if (isDialogshowing) {
                dialog.dismiss();
                dialog.dismiss();
                isDialogshowing = false;
            }
        }
    }

}


问:
Java - TreeSet accepting duplicates
I'm having some problems with TreeSet: why does this one accept duplicates? I thought TreeSets detected them through the Comparator, and automatically remove them. Please help me, I'm kind of new to both Java and StackOverflow.

```<code>import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

public class SortedSongs
{
    private Set songs;
    public SortedSongs()
    {
         Comparator<Song> comp = (Song c1, Song c2)-> c1.toString().compareTo(c2.toString());
         songs = new TreeSet<>(comp);
    }
}
</code>```

edit: this is how I implemented hashCode and equals:

```<code>@Override
public int hashCode()
{
    return Objects.hash(name, author);
}

@Override
public boolean equals(Object o)
{
    return o == null ? false : o.getClass() != getClass() ? false
        : o.hashCode() == hashCode();
}
</code>```

edit2:
This is the updated equals method, toString and compareTo for class Song

```<code>@Override
public boolean equals(Object o)
{
    if (this==o) return true;
    if (getClass()!=o.getClass()) return false;
    return name.equals(((Song) o).name) && author.equals(((Song) o).author);
}
@Override
public String toString() {return name + " - " + author;}

public int compareTo(Song other)
{
    if (name.equals(other.name))
        return author.equals(other.author) ? 0 : author.compareTo(other.author);
    return name.compareTo(other.name);
}
</code>```

So now the Comparator in SortedSongs

```<code>Comparator<Song> comp = (Song c1, Song c2)-> c1.compareTo(c2);
</code>```

Still not working though, I feel as if I'm missing something obvious

edit3:
Solved, I actually made a mistake with my Test class. Embarrassing. Sorry, didn't mean to waste your time, I hope this will be helpful to someone.

答:
TreeSet delegates under the hood to TreeMap implementation with dummy values.
So, instead of allowing duplicates with tricky comparator, it would be easier and more memory-efficient to switch to TreeMap with values holding duplicate counts.

Here is an example: How do I use a TreeSet in Java that allows Duplicates?.

Title: Java - TreeSet accepting duplicates

Body:
I'm having some problems with TreeSet: why does this one accept duplicates? I thought TreeSets detected them through the Comparator, and automatically remove them. Please help me, I'm kind of new to both Java and StackOverflow.

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

public class SortedSongs
{
    private Set songs;
    public SortedSongs()
    {
         Comparator<Song> comp = (Song c1, Song c2)-> c1.toString().compareTo(c2.toString());
         songs = new TreeSet<>(comp);
    }
}

edit: this is how I implemented hashCode and equals:

@Override
public int hashCode()
{
    return Objects.hash(name, author);
}

@Override
public boolean equals(Object o)
{
    return o == null ? false : o.getClass() != getClass() ? false
        : o.hashCode() == hashCode();
}

edit2:
This is the updated equals method, toString and compareTo for class Song

@Override
public boolean equals(Object o)
{
    if (this==o) return true;
    if (getClass()!=o.getClass()) return false;
    return name.equals(((Song) o).name) && author.equals(((Song) o).author);
}
@Override
public String toString() {return name + " - " + author;}

public int compareTo(Song other)
{
    if (name.equals(other.name))
        return author.equals(other.author) ? 0 : author.compareTo(other.author);
    return name.compareTo(other.name);
}

So now the Comparator in SortedSongs

Comparator<Song> comp = (Song c1, Song c2)-> c1.compareTo(c2);

Still not working though, I feel as if I'm missing something obvious

edit3:
Solved, I actually made a mistake with my Test class. Embarrassing. Sorry, didn't mean to waste your time, I hope this will be helpful to someone.


问:
RxJs - Can I use a BehaviorSubject to create a timer?
I created a time loader that I can stop and restart using observable interval:

```<code>   start(time) {

    this.max = time;
    this.intervalObs = Observable.interval(time)
      .takeWhile(_ => !this.isFinished)
      .do(i =>{this.current += 1 ; console.log(this.current);} )
     this.intervalSub$ = this.intervalObs.subscribe();
  }

  finish() {
    this.intervalSub$.unsubscribe();
  }
</code>```

and I want to do the exact same thing using behavior subjects. Is it possible and how ?

答:
You're doing something wrong. Subjects are both Observer and Observable. In your example, at least the way I understood it, you're using.. an interval, which means .interval() implementation is sufficient.

So the question is - what are you trying to achieve?

Body:
I created a time loader that I can stop and restart using observable interval:

   start(time) {

    this.max = time;
    this.intervalObs = Observable.interval(time)
      .takeWhile(_ => !this.isFinished)
      .do(i =>{this.current += 1 ; console.log(this.current);} )
     this.intervalSub$ = this.intervalObs.subscribe();
  }

  finish() {
    this.intervalSub$.unsubscribe();
  }

and I want to do the exact same thing using behavior subjects. Is it possible and how ?


问:
Python get least significant digits from a float (without using string operations)
Assuming I have the float 12345.6789 and I want to get the six least significant digits (i.e. 45.6789) as an int (i.e. 456789) using bit operations in python (v. 2.6).

How do I do that?

Thanks

PS I do not want to use string operations even if it would be rather easy to: for any float f:

```<code>int(str(int(f * 1000))[-10:])
</code>```

EDIT:  This original question is pointless, as shown by comments within.  Many apologies... instead methods on getting the least significant digits without using strings are shown below (using ints and modulus)

Body:
Assuming I have the float 12345.6789 and I want to get the six least significant digits (i.e. 45.6789) as an int (i.e. 456789) using bit operations in python (v. 2.6).

How do I do that?

Thanks

PS I do not want to use string operations even if it would be rather easy to: for any float f:

int(str(int(f * 1000))[-10:])

EDIT:  This original question is pointless, as shown by comments within.  Many apologies... instead methods on getting the least significant digits without using strings are shown below (using ints and modulus)

Body:
>>> int(12345.6789*10000)%1000000
456789

but that is not bit operations


问:
pagination and sorting on 'ngOnInit' is not working after placing my constructor
I have a mat-table using pagination and sorting, it works properly until I place my constructor: "constructor(private _router: Router){}". The table is still showing, but pagination and sorting doesn't. It shows everything all at once. I am new to angular and I'm having trouble identifying the problem.

I tried placing the contents on 'ngOnInit' on the constructor, and in still didn't seem to work.

```<code>export class LogsComponent implements OnInit {
  constructor(private _router: Router){} //If i place this, it works but pagination doesn't

  ngOnInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  dataSource = new MatTableDataSource(EXAMPLE_DATA);
  displayedColumns = ['id', 'name', 'role', 'date'];

  applyFilter(filterValue: string, _router: Router) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }
}
</code>```

Here is my HTML code:

```<code>//The one I use on mg 'logs' page
<div *ngIf="_router.url == '/logs'">
   <div class="table">
      //table here
   </div>
</div>

//The on I use on the dashboard
<div *ngIf="_router.url != '/logs'">
   <div class="table">
      //table here
   </div>
</div>
</code>```

I'd like to know why is this not working, I've read from some pages that the constructor gets read first before the ngOnInit(). But its not working in my case, can someone point out what I'm doing wrong? Thank you very much!

答:
Do you see any error in the console?
If you didn't import the router module you will see a StaticInjectorError.
To fix this error add the following to your app.module.ts</p>

```<code>import { RouterModule } from '@angular/router';

 @NgModule({
  imports: [
    ...,
    RouterModule.forRoot([])
</code>```

Body:
I have a mat-table using pagination and sorting, it works properly until I place my constructor: "constructor(private _router: Router){}". The table is still showing, but pagination and sorting doesn't. It shows everything all at once. I am new to angular and I'm having trouble identifying the problem.

I tried placing the contents on 'ngOnInit' on the constructor, and in still didn't seem to work.

export class LogsComponent implements OnInit {
  constructor(private _router: Router){} //If i place this, it works but pagination doesn't

  ngOnInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  dataSource = new MatTableDataSource(EXAMPLE_DATA);
  displayedColumns = ['id', 'name', 'role', 'date'];

  applyFilter(filterValue: string, _router: Router) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }
}

Here is my HTML code:

//The one I use on mg 'logs' page

      //table here

//The on I use on the dashboard

      //table here

I'd like to know why is this not working, I've read from some pages that the constructor gets read first before the ngOnInit(). But its not working in my case, can someone point out what I'm doing wrong? Thank you very much!

Body:
Do you see any error in the console?
If you didn't import the router module you will see a StaticInjectorError.
To fix this error add the following to your app.module.ts

import { RouterModule } from '@angular/router';

 @NgModule({
  imports: [
    ...,
    RouterModule.forRoot([])


问:
Extracting gene location from FASTA file
I am trying to extract the gene location from a fasta file using BioPython but the function .location is not working. I would like to avoid regex because this function will have to work with different files and the all have slightly different headers.

The header looks like:
 >X dna:chromosome chromosome:GRCh38:X:111410060:111411807:-1

I would like the output to be:
start = 111410060
end = 111411807

答:
If the headers of your different fasta files always end with '...chr:start:end:strand' and the different parts are separated by ':' you could try to split .description by .split(":") and select the penultimate and antepenultimate  position of the resulting list.

The following works for me with your example header:

```<code>from Bio import SeqIO
path = 'fasta_test.fasta'
records = SeqIO.parse(open(path), 'fasta')
record = next(records)
parts = record.description.split(":")
print('start =', parts[-3], 'end =', parts[-2])
</code>```

Body:
If the headers of your different fasta files always end with '...chr:start:end:strand' and the different parts are separated by ':' you could try to split .description by .split(":") and select the penultimate and antepenultimate  position of the resulting list.

The following works for me with your example header:

from Bio import SeqIO
path = 'fasta_test.fasta'
records = SeqIO.parse(open(path), 'fasta')
record = next(records)
parts = record.description.split(":")
print('start =', parts[-3], 'end =', parts[-2])


问:
I have problem linking my css to html using external method of writing css
Have been trying to link my html and my css writing code using css external method, can anybody put me through please?</p>

答:
You can inspect in chrome developer tool to and see if the external file shows 404 error (Console tab).
Alternatively, make sure the external CSS file path is correct.

Extenal CSS referencing:

```<code><head>
<link rel="stylesheet" type="text/css" href="mystyle.css"/>
</head>
</code>```

Hope this helps.

Body:
You can inspect in chrome developer tool to and see if the external file shows 404 error (Console tab).
Alternatively, make sure the external CSS file path is correct.

Extenal CSS referencing:

<head>
<link rel="stylesheet" type="text/css" href="mystyle.css"/>
</head>

Hope this helps.


问:
c# Thread in 100% CPU
I have a complex system with several threads. sometimes i see the application in 100% cpu and force to restart the system. I have no idea which thread caused it and which code caused it.
I need something that will give me the state of each thread in the system (i.e. in which line the thread is now) so i can find which code causes the 100% CPU

(in java you have the thread dump kill -3 which gives you the state of each thread)

Can you help please?

答: People have suggested Process Explorer to me before.</p>

Title: c# Thread in 100% CPU


问:
Set value based on drop down selection using script
Because prices change over time, I don't want to tie in the price permanently to another cell. So I'd like the script to set the price based on drop down selection.

I have Services sheet with Cost column:

I'd like the script to apply the cost based on selection like so (in Selection sheet):

Here's the example spreadsheet:
https://docs.google.com/spreadsheets/d/1O1rZUstDNSXPdUVXvaDfPO4rAQs2cJWHimfGxbddtNU/edit#gid=232108540

How can I set value Cost in Services sheet to Selection sheet with script?

答:
Try this:

```<code>function cost() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Services');
  var rg=sh.getRange(2,1,sh.getLastRow()-1,2);
  var vA=rg.getValues();
  var costObj={}
  for(var i=0;i<vA.length;i++) {
    costObj[vA[i][0]]=vA[i][1];
  }
  var selsh=ss.getSheetByName('Selection');
  var selrg=selsh.getRange(2,1,selsh.getLastRow()-1,2);
  var vB=selrg.getValues();
  for(var j=0;j<vB.length;j++) {
    vB[j][1]=costObj[vB[j][0]];
  }
  selrg.setValues(vB);
  //if you only want to set columnB you can do this instead of the above line
  //var vC=vB.map(function(r){return [r[1]]});
  //selsh.getRange(2,2,vC.length,1).setValues(vC);
}
</code>```

As an onEdit():

```<code>function cost(e) {//Installable onEdit()
  var sh=e.range.getSheet();
  var name=sh.getName();
  if(name!='Selection')return;
  if(e.value && e.range.columnStart==1) {
    e.range.offset(0,1).setValue(getCostObj()[e.value]);
  }
}
function getCostObj() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Services');
  var rg=sh.getRange(2,1,sh.getLastRow()-1,2);
  var vA=rg.getValues();
  var costObj={}
  for(var i=0;i<vA.length;i++) {
    costObj[vA[i][0]]=vA[i][1];
  }
  return costObj;
}
</code>```

Body:
Try this:

function cost() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Services');
  var rg=sh.getRange(2,1,sh.getLastRow()-1,2);
  var vA=rg.getValues();
  var costObj={}
  for(var i=0;i<vA.length;i++) {
    costObj[vA[i][0]]=vA[i][1];
  }
  var selsh=ss.getSheetByName('Selection');
  var selrg=selsh.getRange(2,1,selsh.getLastRow()-1,2);
  var vB=selrg.getValues();
  for(var j=0;j<vB.length;j++) {
    vB[j][1]=costObj[vB[j][0]];
  }
  selrg.setValues(vB);
  //if you only want to set columnB you can do this instead of the above line
  //var vC=vB.map(function(r){return [r[1]]});
  //selsh.getRange(2,2,vC.length,1).setValues(vC);
}

As an onEdit():

function cost(e) {//Installable onEdit()
  var sh=e.range.getSheet();
  var name=sh.getName();
  if(name!='Selection')return;
  if(e.value && e.range.columnStart==1) {
    e.range.offset(0,1).setValue(getCostObj()[e.value]);
  }
}
function getCostObj() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Services');
  var rg=sh.getRange(2,1,sh.getLastRow()-1,2);
  var vA=rg.getValues();
  var costObj={}
  for(var i=0;i<vA.length;i++) {
    costObj[vA[i][0]]=vA[i][1];
  }
  return costObj;
}


问:
Is there a way to calculate DISTINCTCOUNT as SUMX in DAX?
I want to calculate the distinct sum for every row in a dataset.

I have tried to combine SUMX and DISTINCTCOUNT, without a good result.

When combining SUMX and DISTINCTCOUNT I get the wrong figures:

```<code>SUMX (
    VALUES ( d_CXMeasure[CX Measure Code] );
    CALCULATE (
        DISTINCTCOUNT ( d_Response[ResponseId] );
        FILTER ( f_CX; f_CX[CX Measure Code] = "RCX_TOP_IM" )
    )
)
</code>```

If I only use DISTINCTCOUNT I get the correct value on the totals, the same amount is expected for every row in the column

```<code>CALCULATE (
    DISTINCTCOUNT ( f_CX[ResponseID] );
    FILTER ( f_CX; f_CX[CX Measure Code] = "RCX_TOP_IM" )
)
</code>```

```<code>        Result  Expected Result
        225     999
        118     999
        352     999
        399     999
        230     999
        117     999
        239     999
        162     999
        142     999
        204     999
        399     999
TOTALS  999     999
</code>```

答:
I'm not sure why you are splitting out by d_CXMeasure[CX Measure Code] if you want the sum to ignore that, but in any case, you should be able to get your Expected Result by removing the filter context like this:

```<code>SUMX (
    VALUES ( d_CXMeasure[CX Measure Code] );
    CALCULATE (
        DISTINCTCOUNT ( d_Response[ResponseId] );
        FILTER ( f_CX; f_CX[CX Measure Code] = "RCX_TOP_IM" );
        ALL( d_CXMeasure[CX Measure Code] )
    )
)
</code>```

Body:
I want to calculate the distinct sum for every row in a dataset.

I have tried to combine SUMX and DISTINCTCOUNT, without a good result.

When combining SUMX and DISTINCTCOUNT I get the wrong figures:

SUMX (
    VALUES ( d_CXMeasure[CX Measure Code] );
    CALCULATE (
        DISTINCTCOUNT ( d_Response[ResponseId] );
        FILTER ( f_CX; f_CX[CX Measure Code] = "RCX_TOP_IM" )
    )
)

If I only use DISTINCTCOUNT I get the correct value on the totals, the same amount is expected for every row in the column

CALCULATE (
    DISTINCTCOUNT ( f_CX[ResponseID] );
    FILTER ( f_CX; f_CX[CX Measure Code] = "RCX_TOP_IM" )
)

        Result  Expected Result
        225     999
        118     999
        352     999
        399     999
        230     999
        117     999
        239     999
        162     999
        142     999
        204     999
        399     999
TOTALS  999     999

Body:
I'm not sure why you are splitting out by d_CXMeasure[CX Measure Code] if you want the sum to ignore that, but in any case, you should be able to get your Expected Result by removing the filter context like this:

SUMX (
    VALUES ( d_CXMeasure[CX Measure Code] );
    CALCULATE (
        DISTINCTCOUNT ( d_Response[ResponseId] );
        FILTER ( f_CX; f_CX[CX Measure Code] = "RCX_TOP_IM" );
        ALL( d_CXMeasure[CX Measure Code] )
    )
)


问:
how to extract from a numpy array all the zero and non zero values in a new array?
Given a numpy array:

```<code>arr = [0,0,0,0,0,2,0]
</code>```

How can I extract in a new array all the zero elements:

```<code>new_arr = [0,0,0,0,0,0]
</code>```

And the non zero elements:

```<code>new_arr_2 = [2]
</code>```

I tried by transforming the array into a list and with a for loop. Also, I tried with:

```<code>np.argwhere(arr == 0).ravel()
</code>```

However, I am just getting the indices. Any idea of how to extract zero, and non zero, or even specific number values with numpy?

答:
By using numpy.where, you can get the indices of items satisfying your condition and get the corresponding value:

```<code>import numpy as np

arr = np.array([0,0,0,0,0,2,0])

new_arr_0 = arr[np.where(arr==0)]
new_arr_no_0 = arr[np.where(arr!=0)]
</code>```

Of course, as suggested by @Sheldore and @DeveshKumarSingh you can simply go with:

```<code>new_arr_0 = arr[arr==0]
new_arr_no_0 = arr[arr!=0]
</code>```

For small arrays you should not find large differences in terms of computational speed.

Body:
Given a numpy array:

arr = [0,0,0,0,0,2,0]

How can I extract in a new array all the zero elements:

new_arr = [0,0,0,0,0,0]

And the non zero elements:

new_arr_2 = [2]

I tried by transforming the array into a list and with a for loop. Also, I tried with:

np.argwhere(arr == 0).ravel()

However, I am just getting the indices. Any idea of how to extract zero, and non zero, or even specific number values with numpy?

Body:
By using numpy.where, you can get the indices of items satisfying your condition and get the corresponding value:

import numpy as np

arr = np.array([0,0,0,0,0,2,0])

new_arr_0 = arr[np.where(arr==0)]
new_arr_no_0 = arr[np.where(arr!=0)]

Of course, as suggested by @Sheldore and @DeveshKumarSingh you can simply go with:

new_arr_0 = arr[arr==0]
new_arr_no_0 = arr[arr!=0]

For small arrays you should not find large differences in terms of computational speed.


问:
How to pass variable from controller to javascript?
im working on a laravel project. im trying to do auto-complete search box by retrieving data from the database. not sure how to foreach the collection and get it working in js

```<code>controller

$tag = DB::table('tags')->get(['title']);
</code>```

```<code>view

//get each title for autocomplete
@foreach($tag as $key => $tag)
  <p>{{$tag->title}}</p>
@endforeach

<script>
    //im guessing im passing a tag collection right here??
    //so how do i foreach tag->title variable right here in js to get the title only?
    var tag = {!! json_encode($tag) !!};

    $(function() {

      var content = [
        { title: tag }
        // etc
      ];

      $('.ui.search')
      .search({
        source: content
       });
   });
</script>
</code>```

update:
im using the pluck
update my view

```<code>var tag = {!! json_encode($tag) !!};

    $(function() {

      var content = [
        { title: tag }
        // etc
      ];

      $('.ui.search')
      .search({
        source: content
       });
   });
</code>```

答:
No need to json_encode

Just change your view file code as per below

```<code><script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script>

<script>
    $(document).ready(function(){

        var tag = {!! $tag !!} ;

        console.log(tag); //here I console the tag data, you can use tag data as per your requirement

    });
</script>
</code>```

Body:
im working on a laravel project. im trying to do auto-complete search box by retrieving data from the database. not sure how to foreach the collection and get it working in js

controller

$tag = DB::table('tags')->get(['title']);

view

//get each title for autocomplete
@foreach($tag as $key => $tag)

{{$tag->title}}

@endforeach

update:
im using the pluck
update my view

var tag = {!! json_encode($tag) !!};

    $(function() {

      var content = [
        { title: tag }
        // etc
      ];

      $('.ui.search')
      .search({
        source: content
       });
   });

Body:
No need to json_encode

Just change your view file code as per below

<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script>

<script>
    $(document).ready(function(){

        var tag = {!! $tag !!} ;

        console.log(tag); //here I console the tag data, you can use tag data as per your requirement

    });
</script>


问:
Remove Duplicate value from List<T>
I have one list which has data and sometimes it contains duplicate rows and I want to remove that duplicate row for that I used below code

```<code>num = numDetailsTemp.Distinct().ToList();
var query = num.GroupBy(o => new { o.Number })
                                  .Select(group =>
                                        new
                                        {
                                            Name = group.Key,
                                            Numbers = group.OrderByDescending(x => x.Date)
                                        })
                                  .OrderBy(group => group.Numbers.First().Date);
                            List<NumberDetails> numTemp = new List<NumberDetails>();

                            foreach (var group in query)
                            {
                                foreach (var numb in group.Numbers)
                                {
                                    numTemp.Add(numb);
                                    break;
                                }
                            }
                            num = numTemp;
</code>```

The below image shows the duplicate value from the list.

And when I apply remove duplicate it give me an output

But I want to remove that row which not contains alter no or id proof and date like shown in first image first row not, contains AlterNo and ID Proof and date and the second row contains that so I want to remove the first row and display only second row. The date is compulsory to check and after that AlterNo and ID Proof.

答:
So you have a sequence of NumberDetails, and a definition about when you would consider to NumberDetails equal.

Once you have found which NumberDetails are equal, you want to eliminate the duplicates, except one: a duplicate that has values for AlterNo and IdProof.

Alas you didn't specify what you want if there are no duplicates with values for AlterNo and IdProof. Nor what you want if there are several duplicates with values for AlterNo and IdProof.

But let's assume that if there are several of these items, you don't care: just pick one, because they are duplicates anyway.

In your requirement you speak about duplicates. So let's write a class that implements your requirements of equality:

```<code>class NumberDetailEqualityComparer : IEqualityComparer<NumberDetail>
{
    public static IEQualityComparer<NumberDetail> Default {get;} = new NumberDetaulEqualityComparer();

    public bool Equals(NumberDetail x, NumberDetail y)
    {
         if (x == null) return y == null;              // true if both null
         if (y == null) return false;                  // because x not null and y null
         if (Object.ReferenceEquals(x, y) return true; // because same object
         if (x.GetType() != y.GetType()) return false; // because not same type

         // by now we are out of quick checks, we need a value check
         return x.Number == y.Number
             && x.FullName == y.FullName
             && ...
             // etc, such that this returns true if according your definition
             // x and y are equal
    }
</code>```

You also need to implement GetHashCode. You can return anything you want, as long as you
are certain that if x and y are equal, then they return the same HashCode
Furthermore it would be more efficient that if x and y not equal,
then there is a high probability for different HashCode.

Something like:

```<code>public int GetHashCode(NumberDetail numberDetail)
{
    const int prime1 = 12654365;
    const int prime2 = 54655549;

    if (numberDetail == null) return prime1;

    int hash = prime1;
    unsafe
    {
        hash = prime2 * hash + numberDetail.Number.GetHashCode();
        hash = prime2 * hash + numberDetail.FullName.GetHashCode();
        hash = prime2 * hash + numberDetail.Date.GetHashCode();
        ...
    }
    return hash;
</code>```

Of course you have to check if any of the properties equal NULL before asking the HashCode.

Obviously in your equality (and thus in GetHashCode) you don't look at AlterNo nor IdProof.

Once that you've defined precisely when you consider two NumberDetails equal, you can make groups of equal NumberDetails

```<code>var groupsEqualNumberDetails = numberDetails.GroupBy(

    // keySelector: make groups with equal NumberDetails:
    numberDetail => numberDetail,

    // ResultSelector: take the key and all NumberDetails thas equal this key:
    // and keep the first one that has values for AlterNo and IdProof
    (key, numberDetailsEqualToKey) => numberDetailsEqualToKey
          .Where(numberDetail => numberDetail.AlterNo != null
                              && numberDetail.IdProof != null)
          .FirstOrDefault(),

    // KeyComparer: when do you consider two NumberDetails equal?
    NumberDetailEqualityComparer.Default;
}
</code>```

Title: Remove Duplicate value from List<T>

Body:
I have one list which has data and sometimes it contains duplicate rows and I want to remove that duplicate row for that I used below code

num = numDetailsTemp.Distinct().ToList();
var query = num.GroupBy(o => new { o.Number })
                                  .Select(group =>
                                        new
                                        {
                                            Name = group.Key,
                                            Numbers = group.OrderByDescending(x => x.Date)
                                        })
                                  .OrderBy(group => group.Numbers.First().Date);
                            List<NumberDetails> numTemp = new List<NumberDetails>();

                            foreach (var group in query)
                            {
                                foreach (var numb in group.Numbers)
                                {
                                    numTemp.Add(numb);
                                    break;
                                }
                            }
                            num = numTemp;

The below image shows the duplicate value from the list.

And when I apply remove duplicate it give me an output

But I want to remove that row which not contains alter no or id proof and date like shown in first image first row not, contains AlterNo and ID Proof and date and the second row contains that so I want to remove the first row and display only second row. The date is compulsory to check and after that AlterNo and ID Proof.

Body:
So you have a sequence of NumberDetails, and a definition about when you would consider to NumberDetails equal.

Once you have found which NumberDetails are equal, you want to eliminate the duplicates, except one: a duplicate that has values for AlterNo and IdProof.

Alas you didn't specify what you want if there are no duplicates with values for AlterNo and IdProof. Nor what you want if there are several duplicates with values for AlterNo and IdProof.

But let's assume that if there are several of these items, you don't care: just pick one, because they are duplicates anyway.

In your requirement you speak about duplicates. So let's write a class that implements your requirements of equality:

class NumberDetailEqualityComparer : IEqualityComparer<NumberDetail>
{
    public static IEQualityComparer<NumberDetail> Default {get;} = new NumberDetaulEqualityComparer();

    public bool Equals(NumberDetail x, NumberDetail y)
    {
         if (x == null) return y == null;              // true if both null
         if (y == null) return false;                  // because x not null and y null
         if (Object.ReferenceEquals(x, y) return true; // because same object
         if (x.GetType() != y.GetType()) return false; // because not same type

         // by now we are out of quick checks, we need a value check
         return x.Number == y.Number
             && x.FullName == y.FullName
             && ...
             // etc, such that this returns true if according your definition
             // x and y are equal
    }

You also need to implement GetHashCode. You can return anything you want, as long as you
are certain that if x and y are equal, then they return the same HashCode
Furthermore it would be more efficient that if x and y not equal,
then there is a high probability for different HashCode.

Something like:

public int GetHashCode(NumberDetail numberDetail)
{
    const int prime1 = 12654365;
    const int prime2 = 54655549;

    if (numberDetail == null) return prime1;

    int hash = prime1;
    unsafe
    {
        hash = prime2 * hash + numberDetail.Number.GetHashCode();
        hash = prime2 * hash + numberDetail.FullName.GetHashCode();
        hash = prime2 * hash + numberDetail.Date.GetHashCode();
        ...
    }
    return hash;

Of course you have to check if any of the properties equal NULL before asking the HashCode.

Obviously in your equality (and thus in GetHashCode) you don't look at AlterNo nor IdProof.

Once that you've defined precisely when you consider two NumberDetails equal, you can make groups of equal NumberDetails

var groupsEqualNumberDetails = numberDetails.GroupBy(

    // keySelector: make groups with equal NumberDetails:
    numberDetail => numberDetail,

    // ResultSelector: take the key and all NumberDetails thas equal this key:
    // and keep the first one that has values for AlterNo and IdProof
    (key, numberDetailsEqualToKey) => numberDetailsEqualToKey
          .Where(numberDetail => numberDetail.AlterNo != null
                              && numberDetail.IdProof != null)
          .FirstOrDefault(),

    // KeyComparer: when do you consider two NumberDetails equal?
    NumberDetailEqualityComparer.Default;
}


问:
error: "Failed to connect to *** - getaddrinfo ENOTFOUND" using postman with a get statement of "http://localhost:9000/Product"
I am struggling making a connection to my ms sql db. I have my config setup like this:
exports.dbConfig = {
    user: "sa",
    password: "****",
    server: "UCPRC-ROCK-4/DAVIDSQL",
    database: "****",
    port: 1433
};

However when I try to connect it can't find my DB, throwing the error "getaddrinfo ENOTFOUND UCPRC-ROCK-4/DAVIDSQL". I am working locally and I have checked to make sure all services, and dbconfigurations are setup properly.

I try to create a connection as followed:
`exports.executeSql = function (sql, callback) { //executes sql function

```<code>var conn = new sqlDB.ConnectionPool(settings.dbConfig);//new connection

conn.connect() //open connection
     .then(function () {//if susceful connection proceded here
        var req = new sqlDB.Request(conn); //a request to the db
        req.query(sql)
            .then(function (recordset) {//if the req is a success execute this function
                callback(recordset);
            })
            .catch(function (err) {//if the request is an error then we come here and throw err
                console.log(err);
                callback(null, err);
        });
    })
    .catch(function (err) { //if there is an error connecting to db
        console.log(err);
        callback(null, err);
    });
</code>```

};`

Is there something I am doing wrong

答:
Named instance should be separated with a "\", not a "/".

Please try:

```<code>exports.dbConfig = {
    user: "sa",
    password: "****",
    server: "UCPRC-ROCK-4\\DAVIDSQL",
    database: "****",
    port: 1433
};
</code>```

Body:
I am struggling making a connection to my ms sql db. I have my config setup like this:
exports.dbConfig = {
    user: "sa",
    password: "****",
    server: "UCPRC-ROCK-4/DAVIDSQL",
    database: "****",
    port: 1433
};

However when I try to connect it can't find my DB, throwing the error "getaddrinfo ENOTFOUND UCPRC-ROCK-4/DAVIDSQL". I am working locally and I have checked to make sure all services, and dbconfigurations are setup properly.

I try to create a connection as followed:
`exports.executeSql = function (sql, callback) { //executes sql function

var conn = new sqlDB.ConnectionPool(settings.dbConfig);//new connection

conn.connect() //open connection
     .then(function () {//if susceful connection proceded here
        var req = new sqlDB.Request(conn); //a request to the db
        req.query(sql)
            .then(function (recordset) {//if the req is a success execute this function
                callback(recordset);
            })
            .catch(function (err) {//if the request is an error then we come here and throw err
                console.log(err);
                callback(null, err);
        });
    })
    .catch(function (err) { //if there is an error connecting to db
        console.log(err);
        callback(null, err);
    });

};`

Is there something I am doing wrong

Body:
Named instance should be separated with a "\", not a "/".

Please try:

exports.dbConfig = {
    user: "sa",
    password: "****",
    server: "UCPRC-ROCK-4\\DAVIDSQL",
    database: "****",
    port: 1433
};


问:
how to load form with many controls Smooth on Winform?
I have a C# program with a DataGridView on the form.

When the user selects a row and presses a button, I present control panel with some textboxes that fill from the DataGridView.

When the control panel is shown,  I see the controls building on the screen and it's not pleasing to the eye.

How do I show this control panel instantly?

Thanks in advance

答:
One of two situations are occurring:

Either: you have a very large number of controls on the panel.

Or: you are doing some other data loading in the middle of populating the panel.

For the first one, the easiest thing I know of to get the control handles going is to draw it off screen or behind another control and then reposition it when it's all ready.

For the second one, I'd create the panel first then connect the bindings / populate afterwards.

Without some sample code about how you create the panel and how you supply the data, I can only speculate.


问:
Layout changing(resizing) when switching from mobile to desktop
The whole layout resizes when I change from desktop to mobile view. Elements with a width of 500px that should take up the entire screen don't.

I want mobile to look the same as desktop.

I've tried adding <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no/> to every index.php, but nothing changed.

Desktop view
Moblie view

答:
the syntax is missing some chars (commas, quotation marks). You can try if this works:</p>

```<code><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
</code>```

Body:
the syntax is missing some chars (commas, quotation marks). You can try if this works:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />


问:
405 Method Not Allowed for DELETE
I'm getting a '405 Method Not Allowed' when I attempt for a DELETE without passing the resource Id which needs to be deleted.Here is my URL

```<code>http://localhost:8080/api/vendors/delete/1234/
</code>```

where ideally I should have given the ID at the end of the URL like:

```<code>http://localhost:8080/api/vendors/delete/1234/{id}
</code>```

I'm convinced it should be a 405 but my QA team thinks otherwise. They say it should be a 400. Can someone point out to me any resource which clearly specifies what HTTP code it should be for this scenario.

答:
For your main question, if the method is DELETE and the path /api/vendors/delete/1234/ is valid for other methods but not for DELETE, then 405 Method Not Allowed ("A request method is not supported for the requested resource") is correct, since there is a "resource" at that path that doesn't support delete, e.g. it might support GET to retrieve a list of vendors.

If there is no resource there, i.e. the method doesn't matter, then 404 Not Found ("The requested resource could not be found") would be the correct response.

If the method is DELETE, not GET, PUT, POST, or any of the others, you shouldn't need .../delete/... in the path.

If you're trying to delete Vendor 1234, then path should be http://localhost:8080/api/vendor/1234 and the method should be DELETE. The action handler should use /api/vendor/{id} in the declaration.

Title: 405 Method Not Allowed for DELETE

Body:
I'm getting a '405 Method Not Allowed' when I attempt for a DELETE without passing the resource Id which needs to be deleted.Here is my URL

http://localhost:8080/api/vendors/delete/1234/

where ideally I should have given the ID at the end of the URL like:

http://localhost:8080/api/vendors/delete/1234/{id}

I'm convinced it should be a 405 but my QA team thinks otherwise. They say it should be a 400. Can someone point out to me any resource which clearly specifies what HTTP code it should be for this scenario.


问:
How does one test if a file is LOCKED and/or read-only without opening?
Is there a portable (std::filesystem) method of testing if a file is "locked" or has "read-only" permissions? MacOS Finder, for example, has a "Locked" setting, which is DIFFERENT than the standard POSIX "permissions".

I need to test if a file can be deleted BEFORE I try to do the delete operation.  Ideally, I'd like to avoid OPENING the file for R/W as a test.

This is during a SAVE/RENAME process, and (at least in past MacOS filesystems), OS calls to "exchange" two files worked even if the file was "Locked" in the Finder.  Because the of the complexity surrounding how files are saved, and how PREVIOUS versions are "preserved", it's just better to know ahead of time so the operation can be avoided.

FURTHER NOTE:  Opening a stream as R/W (std::ios::out | std::ios::in) on a LOCKED file with Read & Write permissions will fail with errno = 1 (operation not permitted).  If the file is Read only but not locked, it'll fail with errno 13 (permission denied).

A MacOS (Cocoa) specific approach to testing the lock bit is discussed here:

How to check whether a file is locked in Cocoa?

答:
OK -- this may not be the precise answer, but it APPEARS that you can do THIS (as suggested here:

```<code>#include <sys/stat.h>

bool IsLocked(std::string& thePath)
{
    bool isLocked = false;

    struct stat buf;
    int retval = stat(thePath.c_str(), &buf);     // NOTE: retval could be an error, like ENOENT (file doesn't exist)
    if (0 != (buf.st_flags & UF_IMMUTABLE)) {
        isLocked = true;
         //is immutable
    }

    return isLocked;
}
</code>```

In my own code I deal with retval errors in a more robust manner.  You should, too!

But NOTE: while this DOES correctly indicate the status of the Finder's Lock bit/flag for the file, it DOES NOT reflect if the file is "read only".  The documentation on UF_IMMUTABLE says "file may not be changed" -- which is obviously NOT accurate.

Body:
OK -- this may not be the precise answer, but it APPEARS that you can do THIS (as suggested here:

#include <sys/stat.h>

bool IsLocked(std::string& thePath)
{
    bool isLocked = false;

    struct stat buf;
    int retval = stat(thePath.c_str(), &buf);     // NOTE: retval could be an error, like ENOENT (file doesn't exist)
    if (0 != (buf.st_flags & UF_IMMUTABLE)) {
        isLocked = true;
         //is immutable
    }

    return isLocked;
}

In my own code I deal with retval errors in a more robust manner.  You should, too!

But NOTE: while this DOES correctly indicate the status of the Finder's Lock bit/flag for the file, it DOES NOT reflect if the file is "read only".  The documentation on UF_IMMUTABLE says "file may not be changed" -- which is obviously NOT accurate.