问:
How to initialize a method in state in a constructor that is dependent on another methods value
I'm trying to initialize three functions as state in the constructor in order to get the values from those functions and have those values available in state before the first render. However, one of the functions have a variable dependent on the value of a previous function and so I get an error.

How would I fix this problem? Code is below!

App.js file

```<code>import React from "react";
import Calendar from "./Calendar"

function App() {
    return (
        <div>
            <Calendar />
        </div>

    )
}

export default App;
</code>```

Calendar.js file

```<code>import React from "react";

class Calendar extends React.Component {
    constructor() {
        super();

    this.state = {
        //curLastDate() is dependent on lastDayOfMonth()
        lastDayOfMonth: this.storeLastDate(),
        currentLastDate: this.curLastDate()
    }
}
    /*
    Stores the last date of all months of the current year
    Format: [ ["Thu", "Jan", "31", "2019]... ]
    */
    storeLastDate() {
            let date,
                string,
                lastDate,
                list = [];

            date = new Date();

            for (let i = 1; i < 13; i++) {

                lastDate = new Date(date.getFullYear(), i, 0);
                string = lastDate.toDateString().split(" ");
                list.push(string);
            }

            return list;
    }

/*
Finds the matching month of current date
*/
curLastDate() {

    for (let i = 0; i < this.state.lastDayOfMonth.length; i++) {
        if (this.state.currentDate[1] === this.state.lastDayOfMonth[i][1]) {
            console.log(this.state.lastDayOfMonth[i][1]);
            return this.state.lastDayOfMonth[i][1];
        }
    }
}

render() {
    return (
        null
        )
    }

}
export default Calendar;
</code>```

Ultimately, I want to initialize the values I get from the functions to the state before React has its first render. Thanks for the help in advance!

答:
Set the values in componentDidMount and pass a callback to .setState().

```<code>constructor() {
  super();
  this.state = {
    lastDayOfMonth: [],
    currentLastDate: [],
    currentDate: new Date(),
  };
}

storeLastDate = () => {
  let date,
    string,
    lastDate,
    list = [];

  date = new Date();

  for (let i = 1; i < 13; i++) {
    lastDate = new Date(date.getFullYear(), i, 0);
    string = lastDate.toDateString().split(' ');
    list.push(string);
  }

  return list;
}

 /*
  Finds the matching month of current date
*/
curLastDate = () => {
  for (let i = 0; i < this.state.lastDayOfMonth.length; i++) {
    if (this.state.currentDate[1] === this.state.lastDayOfMonth[i][1]) {
      console.log(this.state.lastDayOfMonth[i][1]);
      return this.state.lastDayOfMonth[i][1];
    }
  }
}

componentDidMount = () => {

  const lastDayOfMonth = this.storeLastDate();

  this.setState({
    lastDayOfMonth: lastDayOfMonth
  }, () => {
     this.setState({ currentLastDate: this.curLastDate() });
   }) // curLastDate as callback, which will be executed after setting state
}
</code>```

Body:
I'm trying to initialize three functions as state in the constructor in order to get the values from those functions and have those values available in state before the first render. However, one of the functions have a variable dependent on the value of a previous function and so I get an error.

How would I fix this problem? Code is below!

App.js file

import React from "react";
import Calendar from "./Calendar"

function App() {
    return (

            <Calendar />

    )
}

export default App;

Calendar.js file

import React from "react";

class Calendar extends React.Component {
    constructor() {
        super();

    this.state = {
        //curLastDate() is dependent on lastDayOfMonth()
        lastDayOfMonth: this.storeLastDate(),
        currentLastDate: this.curLastDate()
    }
}
    /*
    Stores the last date of all months of the current year
    Format: [ ["Thu", "Jan", "31", "2019]... ]
    */
    storeLastDate() {
            let date,
                string,
                lastDate,
                list = [];

            date = new Date();

            for (let i = 1; i < 13; i++) {

                lastDate = new Date(date.getFullYear(), i, 0);
                string = lastDate.toDateString().split(" ");
                list.push(string);
            }

            return list;
    }

/*
Finds the matching month of current date
*/
curLastDate() {

    for (let i = 0; i < this.state.lastDayOfMonth.length; i++) {
        if (this.state.currentDate[1] === this.state.lastDayOfMonth[i][1]) {
            console.log(this.state.lastDayOfMonth[i][1]);
            return this.state.lastDayOfMonth[i][1];
        }
    }
}

render() {
    return (
        null
        )
    }

}
export default Calendar;

Ultimately, I want to initialize the values I get from the functions to the state before React has its first render. Thanks for the help in advance!

Body:
Set the values in componentDidMount and pass a callback to .setState().

constructor() {
  super();
  this.state = {
    lastDayOfMonth: [],
    currentLastDate: [],
    currentDate: new Date(),
  };
}

storeLastDate = () => {
  let date,
    string,
    lastDate,
    list = [];

  date = new Date();

  for (let i = 1; i < 13; i++) {
    lastDate = new Date(date.getFullYear(), i, 0);
    string = lastDate.toDateString().split(' ');
    list.push(string);
  }

  return list;
}

 /*
  Finds the matching month of current date
*/
curLastDate = () => {
  for (let i = 0; i < this.state.lastDayOfMonth.length; i++) {
    if (this.state.currentDate[1] === this.state.lastDayOfMonth[i][1]) {
      console.log(this.state.lastDayOfMonth[i][1]);
      return this.state.lastDayOfMonth[i][1];
    }
  }
}

componentDidMount = () => {

  const lastDayOfMonth = this.storeLastDate();

  this.setState({
    lastDayOfMonth: lastDayOfMonth
  }, () => {
     this.setState({ currentLastDate: this.curLastDate() });
   }) // curLastDate as callback, which will be executed after setting state
}


来源: stackexchange

问:
zsh: Print variable with surrounding text if defined?
I want to print a variable with some text before and after it, but to print nothing if it is not defined.  For example, consider a function frotz that formats a two-part message: the second part should appear in parentheses, but the parentheses should not be there if the second part is empty:

```<code>% frotz foo bar
foo (bar)
% frotz foo
foo
</code>```

What is the implementation of frotz?  Obviously I can do it using an if, but I'd like something more concise, presumably using parameter expansion.  However, I haven't been able to find a good way to do it.  For example, this works:

```<code>print "$1${2:+ (}$2${2:+)}"

</code>```

…but requires me to repeat ${2 three times.  Is there a way to do this that only requires writing the name of the possibly-empty variable once?  (For bonus points, I'd like a solution that also works in bash(1), but I'm mostly interested in zsh(1).)

答:
Not quite what you asked for, but using the POSIX :+ operator can eliminate one reference to $2.

```<code>frotz () {
  print "$1${2:+ ($2)}"
}
</code>```

(zsh might have a way to do this with just one reference to $2, but it's not clear to me yet what that would be.)

ContentLicense: CC BY-SA 4.0

Body:
I want to print a variable with some text before and after it, but to print nothing if it is not defined.  For example, consider a function frotz that formats a two-part message: the second part should appear in parentheses, but the parentheses should not be there if the second part is empty:

% frotz foo bar
foo (bar)
% frotz foo
foo

What is the implementation of frotz?  Obviously I can do it using an if, but I'd like something more concise, presumably using parameter expansion.  However, I haven't been able to find a good way to do it.  For example, this works:

print "$1${2:+ (}$2${2:+)}"

…but requires me to repeat ${2 three times.  Is there a way to do this that only requires writing the name of the possibly-empty variable once?  (For bonus points, I'd like a solution that also works in bash(1), but I'm mostly interested in zsh(1).)

Body:
Not quite what you asked for, but using the POSIX :+ operator can eliminate one reference to $2.

frotz () {
  print "$1${2:+ ($2)}"
}

(zsh might have a way to do this with just one reference to $2, but it's not clear to me yet what that would be.)


问:
How to change the class of component after period of time?
I am using a component which renders a SVG image but it does not render the fill. I made two classes </p>

```<code>.svg  {
  fill-opacity: 0;

.svg-show {
  fill-opacity: 1;
  transition: fill-opacity 2s;
}
</code>```

<p>} My question would be how could I apply a classname svg-show to the below component after lets say duration of 200</p>

```<code>  <ReactVivus
            className="svg"
            option={{
              file: forever,
              duration: 200,
              animTimingFunction: "oneByOne",
              type: "delayed",
              onReady: console.log
            }}
            callback={console.log}
          />
</code>```

答:
Have a state variable in your component, then pick the class name based on that variable. In a class component, that would look like this:</p>

```<code>class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false,
    }
  }

  componentDidMount() {
    setTimeout(() => this.setState({ show: true}), 200);
  }

  render() {
    return (
      <ReactVivus
        className={this.state.show ? "svg-show" : "svg"}
        option={{
          file: forever,
          duration: 200,
          animTimingFunction: "oneByOne",
          type: "delayed",
          onReady: console.log
        }}
        callback={console.log}
      />
    )
  }
}
</code>```

Body:
I am using a component which renders a SVG image but it does not render the fill. I made two classes

.svg  {
  fill-opacity: 0;

.svg-show {
  fill-opacity: 1;
  transition: fill-opacity 2s;
}

} My question would be how could I apply a classname svg-show to the below component after lets say duration of 200

  <ReactVivus
            className="svg"
            option={{
              file: forever,
              duration: 200,
              animTimingFunction: "oneByOne",
              type: "delayed",
              onReady: console.log
            }}
            callback={console.log}
          />

Body:
Have a state variable in your component, then pick the class name based on that variable. In a class component, that would look like this:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false,
    }
  }

  componentDidMount() {
    setTimeout(() => this.setState({ show: true}), 200);
  }

  render() {
    return (
      <ReactVivus
        className={this.state.show ? "svg-show" : "svg"}
        option={{
          file: forever,
          duration: 200,
          animTimingFunction: "oneByOne",
          type: "delayed",
          onReady: console.log
        }}
        callback={console.log}
      />
    )
  }
}


问:
How to convert a series of tuples to DataFrame?
I'm trying to add some extra data in additional columns to a data frame.

Consider this example code:

```<code>import pandas
import numpy

def more_data(d):
    return 1, 2

df = pandas.DataFrame({"A":[1, 2, 3], "B":[17, 16, 15]})

x = df.apply(more_data, axis=1)
df1 = pandas.DataFrame(x)
df2 = pandas.concat([df, df1], axis=1)

print(df2)
</code>```

The output is:

```<code>A  B       0
0  1  17  (1, 2)
1  2  16  (1, 2)
2  3  15  (1, 2)
</code>```

No surprise because apply() returns a sequence of tuples, which is faithfully added as a column of tuples to the data frame. What I want, however, is two more columns with the values returned in the tuples. How would that work?

答:
The closest you seem to be able to get is with df.assign:

df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
df.assign(temp1=0, temp2=5)
#    x  y  temp1  temp2
# 0  1  4      0      5
# 1  2  5      0      5
# 2  3  6      0      5
```

<p>You can assign to series, too, so you'd have to get each column result into a series, first. That could be as easy as:</p>

<pre class="lang-py prettyprint-override"><code>s = pd.Series([('a', 'b')] * len(df))
df.assign(s0 = s.apply(lambda x: x[0]), s1 = s.apply(lambda x: x[1]))
#    x  y s0 s1
# 0  1  4  a  b
# 1  2  5  a  b
# 2  3  6  a  b
</code>```

Body:
I'm trying to add some extra data in additional columns to a data frame.

Consider this example code:

import pandas
import numpy

def more_data(d):
    return 1, 2

df = pandas.DataFrame({"A":[1, 2, 3], "B":[17, 16, 15]})

x = df.apply(more_data, axis=1)
df1 = pandas.DataFrame(x)
df2 = pandas.concat([df, df1], axis=1)

print(df2)

The output is:

A  B       0
0  1  17  (1, 2)
1  2  16  (1, 2)
2  3  15  (1, 2)

No surprise because apply() returns a sequence of tuples, which is faithfully added as a column of tuples to the data frame. What I want, however, is two more columns with the values returned in the tuples. How would that work?

Body:
The closest you seem to be able to get is with df.assign:

df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
df.assign(temp1=0, temp2=5)
#    x  y  temp1  temp2
# 0  1  4      0      5
# 1  2  5      0      5
# 2  3  6      0      5

You can assign to series, too, so you'd have to get each column result into a series, first. That could be as easy as:

s = pd.Series([('a', 'b')] * len(df))
df.assign(s0 = s.apply(lambda x: x[0]), s1 = s.apply(lambda x: x[1]))
#    x  y s0 s1
# 0  1  4  a  b
# 1  2  5  a  b
# 2  3  6  a  b


问:
How Can i load third party .dll (COM DLL) in ATL Application with WinCE 5.0 RTOS?
I got the answer and need to understand the following :

I have a WinCe 5.0 ATL application. This application is using third party COM dll and 3rd party application(.exe).As per my understanding on WinCE and Dll loading is as following:

WinCE:

All the dll exported functions should be written in ".Def" file and the dll that need to included during runtime image process should be there in ".bib" file.And one should call DLLExport or loadlibrary (i do not want to go into deep how to use these), to load the DLL.

But in My case: There is no .def file related to the third party dll and .bib file is there, but, the path of the .dll is commented in the file(My code is building successfully and i'm able to make runtime image).

Along with this one more additional file i got : That is, .cfg (i think configuration file) and in that it is written "SERVICE name.dll (for example, this is the 3rd party dll name)".I'm able to see the exported function by using "Dll Export Viewer (a free tool)" but not able to find the use of (calling of) the exported functions from the application.

Can i write .cfg file and include the dll that will be used by application? Can any one pls help me to understand all these??

Thanks in Advance...

答:
I'm not 100% certain I understand the question, so I'll paraphrase what I think you're asking:

You have an ATL application and a COM library that it uses built for Windows CE.

These items are provided by a third-party, so you don't have source code

You want to integrate these items directly into a CE OS build

If my understanding is correct, then the answer is:

Yes, you can do this.  What you need to do is:

Add the binary files (EXE and DLL) to the OS image.  This is done by adding them to your BIB file (PLATFORM.BIB or PROJECT.BIB).  They could be in either the MODULES or FILES section.

Add the requisite registry entries for the COM objects to the platform by adding the entries into your REG file (PLATFORM.REG or PROJECT.REG).

If you don't have the entries for #2, then do the following:

Use Remote Registry Editor to export the entire registry for a device without your COM library installed

Put the COM object onto that device

Call the DllRegisterServer entry point on the COM object (regsvrce or however)

Use Remote Registry Editor to export the entire registry for the device again

Diff the two reg files.  The new entries are the ones you need to put in your REG file

ContentLicense: CC BY-SA 3.0


问:
Sending a interrupt transfer using Libusb 1.0 returns an LIBUSB_ERROR_IO but not when receiving
I am setting up a testing framework (Google Test Framework) for some custom firmware. I am using USB with the Libusb 1.0 library to receive outputs from the firmware, but I also need to simulate an input to the firmware. I am able to receive the outputs to the host ok, but am not able to send the transfer from the host.

The USB descriptor indicates that interrupt transfers to the host contain 3/4 pieces of data which I capture using this data structure:

```<code>typedef struct
{
    uint8_t reportId;
    uint8_t axis[NUM_AXIS];
    uint8_t button;
}usb_report_t;
</code>```

This works fine using this call from libusb

```<code>transfer_error = libusb_interrupt_transfer(dev_handle, 0x81, (unsigned char*)&report, sizeof(report), &transfer_length, 200);
</code>```

My second task namely sending an interrupt transfer I set up using this structure

```<code>typedef struct
{
    uint8_t reportId;
    uint8_t thumper;
}usb_out_report_t;
</code>```

And I send the interrupt transfer using this call

```<code>transfer_error = libusb_interrupt_transfer(dev_handle, 0x01, (unsigned char*)&out_report, sizeof(out_report), &length, 200);
</code>```

This call returns a -1 which is a LIBUSB_ERROR_IO.

While I was attempting to solve this issue I discovered a work around.
If I remove the report ID from the USB descriptor which consequently turns the two structs to

```<code>typedef struct
{
    //uint8_t reportId;
    uint8_t axis[NUM_AXIS];
    uint8_t button;
}usb_report_t;
typedef struct
{
    //uint8_t reportId;
    uint8_t thumper;
}usb_out_report_t;
</code>```

Then the interrupt transfers both in and out work fine. This is ok as a temporary work around but is not an ideal long term solution.

Is there a way to keep the report ID field but have the transfer work both for IN and OUT endpoints?

答:
Had a co-worker help me figure this one out.
So apparently in the libusb source code the hid_open() function parses the USB Descriptor and uses the capabilities.NumberOutputValueCaps to determine whether the report ID is needed for writing the output report. The USB Descriptor in my custom firmware gets parsed by this such that the capabilities.NumberOutputValueCaps = 0. This means the api call does not expect a report ID to be used. </p>

<p>To solve this, we just hard coded a particular value for NumberOutputValueCaps and recompiled the libusb library. This let us have a working test framework for the production version of the firmware. </p>

Body:
I am setting up a testing framework (Google Test Framework) for some custom firmware. I am using USB with the Libusb 1.0 library to receive outputs from the firmware, but I also need to simulate an input to the firmware. I am able to receive the outputs to the host ok, but am not able to send the transfer from the host.

The USB descriptor indicates that interrupt transfers to the host contain 3/4 pieces of data which I capture using this data structure:

typedef struct
{
    uint8_t reportId;
    uint8_t axis[NUM_AXIS];
    uint8_t button;
}usb_report_t;

This works fine using this call from libusb

transfer_error = libusb_interrupt_transfer(dev_handle, 0x81, (unsigned char*)&report, sizeof(report), &transfer_length, 200);

My second task namely sending an interrupt transfer I set up using this structure

typedef struct
{
    uint8_t reportId;
    uint8_t thumper;
}usb_out_report_t;

And I send the interrupt transfer using this call

transfer_error = libusb_interrupt_transfer(dev_handle, 0x01, (unsigned char*)&out_report, sizeof(out_report), &length, 200);

This call returns a -1 which is a LIBUSB_ERROR_IO.

While I was attempting to solve this issue I discovered a work around.
If I remove the report ID from the USB descriptor which consequently turns the two structs to

typedef struct
{
    //uint8_t reportId;
    uint8_t axis[NUM_AXIS];
    uint8_t button;
}usb_report_t;
typedef struct
{
    //uint8_t reportId;
    uint8_t thumper;
}usb_out_report_t;

Then the interrupt transfers both in and out work fine. This is ok as a temporary work around but is not an ideal long term solution.

Is there a way to keep the report ID field but have the transfer work both for IN and OUT endpoints?

Body:
Had a co-worker help me figure this one out.
So apparently in the libusb source code the hid_open() function parses the USB Descriptor and uses the capabilities.NumberOutputValueCaps to determine whether the report ID is needed for writing the output report. The USB Descriptor in my custom firmware gets parsed by this such that the capabilities.NumberOutputValueCaps = 0. This means the api call does not expect a report ID to be used.

To solve this, we just hard coded a particular value for NumberOutputValueCaps and recompiled the libusb library. This let us have a working test framework for the production version of the firmware.


问:
Add scrollbar to ngbTypeahead
ngbTypeahead does not offer scrollbar.
I use this as the recommendation from NgbTypeahead component doesn't scroll inside a scrollable component:

```<code>            <div style="height: 300px; overflow-y: auto; position:relative">
                <input type="text" name="origin" class="form-control form-control-sm" id="origin" [(ngModel)]="data.origin" [editable]="false" [ngbTypeahead]="searchOrigin"
                    [resultFormatter]="formatDropdown" [inputFormatter]="formatSelected" placeholder="Search..."/>
            </div>
</code>```

It works well except that it shows the ugly empty space when the list is not shown (or it does not have focus)

How to remove the empty space and the overlay pops over the other element when the list with a scroll bar appears?

Thank you for your help.

答:
I have solved this problem by moving the "height" style up:

```<code>[style.height]="data.origin? '5rem': dropdownHeight":
</code>```

as I see, for ngbTypeahead, when user has not selected any item, data.origin is undefined, so I want that when user has selected some item from the dropdown list, I set the height to minimum.

in .html file:

```<code>        <div class="form-group row" [class.has-danger]="searchFailedOrigin" [style.height]="data.origin? '5rem': dropdownHeight">

            <label for="origin" class="col-sm-4 col-form-label col-form-label-sm">Origin</label>

            <div class="col-sm-7 col-offset-sm-1" style="overflow-y: auto; position:relative">

                <input type="text" name="origin" class="form-control form-control-sm" id="origin" [(ngModel)]="data.origin" [editable]="false" [ngbTypeahead]="searchOrigin"
                    [resultFormatter]="formatDropdown" [inputFormatter]="formatSelected" placeholder="Search..."/>
            </div>

            <div class="form-control-feedback" *ngIf="searchFailedOrigin">No Airports Found...</div>

        </div>
</code>```

Where dropdownHeight is updated in component .ts file in searchOrigin function:

```<code>searchOrigin = (text$: Observable<string>) => {
    .
    .
    .

    // response is the response from server. It is a list of data filtering by "text"

    this.dropdownHeight = response.data.length <= 1? `5rem`: response.data.length <= 10? `${(response.data.length + 1) * 2.56}rem`: `28rem`;

    // An item in the dropdown list is 2.56rem in height
    // I want the maximum height is 28rem.
    .
    .
    .

}

</code>```

This solution can remove the ugly empty space when not showing the dropdown list, but the dropdown list does not overlay the other elements.

I appreciate any improvement.

Title: Add scrollbar to ngbTypeahead

Body:
ngbTypeahead does not offer scrollbar.
I use this as the recommendation from NgbTypeahead component doesn't scroll inside a scrollable component:

                <input type="text" name="origin" class="form-control form-control-sm" id="origin" [(ngModel)]="data.origin" [editable]="false" [ngbTypeahead]="searchOrigin"
                    [resultFormatter]="formatDropdown" [inputFormatter]="formatSelected" placeholder="Search..."/>

It works well except that it shows the ugly empty space when the list is not shown (or it does not have focus)

How to remove the empty space and the overlay pops over the other element when the list with a scroll bar appears?

Thank you for your help.

Body:
I have solved this problem by moving the "height" style up:

[style.height]="data.origin? '5rem': dropdownHeight":

as I see, for ngbTypeahead, when user has not selected any item, data.origin is undefined, so I want that when user has selected some item from the dropdown list, I set the height to minimum.

in .html file:

        <div class="form-group row" [class.has-danger]="searchFailedOrigin" [style.height]="data.origin? '5rem': dropdownHeight">

            <label for="origin" class="col-sm-4 col-form-label col-form-label-sm">Origin</label>

            <div class="col-sm-7 col-offset-sm-1" style="overflow-y: auto; position:relative">

                <input type="text" name="origin" class="form-control form-control-sm" id="origin" [(ngModel)]="data.origin" [editable]="false" [ngbTypeahead]="searchOrigin"
                    [resultFormatter]="formatDropdown" [inputFormatter]="formatSelected" placeholder="Search..."/>
            </div>

            <div class="form-control-feedback" *ngIf="searchFailedOrigin">No Airports Found...</div>

        </div>

Where dropdownHeight is updated in component .ts file in searchOrigin function:

searchOrigin = (text$: Observable<string>) => {
    .
    .
    .

    // response is the response from server. It is a list of data filtering by "text"

    this.dropdownHeight = response.data.length <= 1? `5rem`: response.data.length <= 10? `${(response.data.length + 1) * 2.56}rem`: `28rem`;

    // An item in the dropdown list is 2.56rem in height
    // I want the maximum height is 28rem.
    .
    .
    .

}

This solution can remove the ugly empty space when not showing the dropdown list, but the dropdown list does not overlay the other elements.

I appreciate any improvement.


问:
Hexdecimal to String Convert - Ruby
I'm trying to convert hexadecimal to string using Ruby and it does not work with some Chinese characters. I am new to Ruby.

Current code is working fine with non-Chinese characters but now code needs to support Chinese characters. It converts HexDecimal to string using ISO-8859-1 and UTF-8 encoder:

```<code>extractpayload = "e5b7b2e5ae8ce68890e38082e68891e4bbace5b086e59ca8e5aea1e6a0b8e5b9b6e7a1aee8aea4e8aea2e58d95e5908ee58f91e8b4a7efbc8ce5b9b6e7ab8be58db3e4bba5e79fade4bfa1e5bda2e5bc8fe9809ae79fa5e682a8e3808220e69fa5e79c8be8aea2e58d95e4bfa1e681afe68896e7aea1e79086e794b5e5ad90e58f91e7a5a8";

gettransformedfullpayload1 = [extractpayload].pack("H*").force_encoding("ISO-8859-1").encode("UTF-8");
</code>```

repl.it link:
https://repl.it/@bonsshah/Ruby-Hexdecimal-to-String-Conversion

Expected output:

已完成。我们将在审核并确认订单后发货，并立即以短信形式通知您。 查看订单信息或管理电子发票
```

<p>Currently getting this wrong output:</p>

<pre class="lang-none prettyprint-override"><code>å·²å®æãæä»¬å°å¨å®¡æ ¸å¹¶ç¡®è®¤è®¢åååè´§ï¼å¹¶ç«å³ä»¥çä¿¡å½¢å¼éç¥æ¨ã æ¥çè®¢åä¿¡æ¯æç®¡ççµååç¥¨
</code>```

Title: Hexdecimal to String Convert - Ruby

Body:
I'm trying to convert hexadecimal to string using Ruby and it does not work with some Chinese characters. I am new to Ruby.

Current code is working fine with non-Chinese characters but now code needs to support Chinese characters. It converts HexDecimal to string using ISO-8859-1 and UTF-8 encoder:

extractpayload = "e5b7b2e5ae8ce68890e38082e68891e4bbace5b086e59ca8e5aea1e6a0b8e5b9b6e7a1aee8aea4e8aea2e58d95e5908ee58f91e8b4a7efbc8ce5b9b6e7ab8be58db3e4bba5e79fade4bfa1e5bda2e5bc8fe9809ae79fa5e682a8e3808220e69fa5e79c8be8aea2e58d95e4bfa1e681afe68896e7aea1e79086e794b5e5ad90e58f91e7a5a8";

gettransformedfullpayload1 = [extractpayload].pack("H*").force_encoding("ISO-8859-1").encode("UTF-8");

repl.it link:
https://repl.it/@bonsshah/Ruby-Hexdecimal-to-String-Conversion

Expected output:

已完成。我们将在审核并确认订单后发货，并立即以短信形式通知您。 查看订单信息或管理电子发票

Currently getting this wrong output:

å·²å®æãæä»¬å°å¨å®¡æ ¸å¹¶ç¡®è®¤è®¢åååè´§ï¼å¹¶ç«å³ä»¥çä¿¡å½¢å¼éç¥æ¨ã æ¥çè®¢åä¿¡æ¯æç®¡ççµååç¥¨

Body:
It's already hex-dumped UTF-8.

str = "e5b7b2e5ae8ce68890e38082e68891e4bbace5b086e59ca8e5aea1e6a0b8e5b9b6e7a1aee8aea4e8aea2e58d95e5908ee58f91e8b4a7efbc8ce5b9b6e7ab8be58db3e4bba5e79fade4bfa1e5bda2e5bc8fe9809ae79fa5e682a8e3808220e69fa5e79c8be8aea2e58d95e4bfa1e681afe68896e7aea1e79086e794b5e5ad90e58f91e7a5a8" => "e5b7b2e5ae8ce68890e38082e68891e4bbace5b086e59ca8e5aea1e6a0b8e5b9b6e7a1aee8aea4e8aea2e58d95e5908ee58f91e8b4a7efbc8ce5b9b6e7ab8be58db3e4bba5e79fade4bfa1e5bda2e5bc8fe9809ae79fa5e682a8e3808220e69fa5e79c8be8aea2e58d95e4bfa1e681afe68896e7aea1e79086e794b5e5ad90e58f91e7a5a8"
[str].pack('H*').force_encoding('utf-8') => "已完成。我们将在审核并确认订单后发货，并立即以短信形式通知您。 查看订单信息或管理电子发票"


问:
Is there any way to run unit and ui tests for azure devops with iOS?
I have researched on app center, for some reason it won't work with our current setup. </p>

<p>I have created a build pipeline for swift codes coming from Xcode. i have my unit and ui tests uploaded as well. I wanted to create a script to trigger test runs in azure devops. Is this possible? I would also want to make sure that running the tests is headless. </p>

答:
Currently, if you are using native iOS and xCode, AppCenter is the only solution for testing per Microsoft Azure DevOps Docs (see below).

https://learn.microsoft.com/en-us/azure/devops/pipelines/languages/xcode?view=azure-devops

I run tests in AppCenter using XCUITests in an Azure Build Pipeline, so it does work.

Body:
I have researched on app center, for some reason it won't work with our current setup.

I have created a build pipeline for swift codes coming from Xcode. i have my unit and ui tests uploaded as well. I wanted to create a script to trigger test runs in azure devops. Is this possible? I would also want to make sure that running the tests is headless.


问:
SED search and replace more than 1 pattern if matched line
How to search and replace multiple patterns for a matched section in a file?
I tried this

```<code>sed '/pattern1,pattern2/s/string1/replace1/g;s/string2/replace2/g' file
</code>```

But it will ignore the pattern1,pattern2 section and do search and replace for the whole file for my second search and replace.

答:
sed is for doing s/old/new on individual strings, that is all. Assuming based on the surrounding description that by /pattern1,pattern2/ you actually meant /pattern1/,/pattern2/ then with any awk in any shell on any UNIX box:

```<code>awk '
/pattern1/ { f=1 }
f {
    gsub(/string1/,"replace1")
    gsub(/string2/,"replace2")
}
/pattern2/ { f=0 }
1' file
</code>```

Body:
How to search and replace multiple patterns for a matched section in a file?
I tried this

sed '/pattern1,pattern2/s/string1/replace1/g;s/string2/replace2/g' file

But it will ignore the pattern1,pattern2 section and do search and replace for the whole file for my second search and replace.

Body:
sed is for doing s/old/new on individual strings, that is all. Assuming based on the surrounding description that by /pattern1,pattern2/ you actually meant /pattern1/,/pattern2/ then with any awk in any shell on any UNIX box:

awk '
/pattern1/ { f=1 }
f {
    gsub(/string1/,"replace1")
    gsub(/string2/,"replace2")
}
/pattern2/ { f=0 }
1' file


问:
JSON to CSV Conversion in Python
There're lots of questions regarding JSON to CSV Conversion in Python , but unfortunately couldn't solve my problem.

I've this simple simple JSON Data which is in a file and looks like this after loading.

Raw data in single line [I've structured this to understand better]:

```<code>{
    "t_id":"80740185.1558980000000.120184.121164",
    "s_id":"80740185",
    "pt_slot":"null:null",
    "ch_id":1,"o_id":121164,"c_id":120184,
    "msg_type":1,
    "amd":"{
                \"msg\":\" some Bengali text\",
                \"mask\":\"1GB_OFFER\",
                \"ec\":\"1\",
                \"time-out\":\"0\",
                \"validity\":\"30052019 000000\"
           }",
    "time":1558960217731,
    "dlr":"1",
    "msisdn":"xxxxx",
    "entity":1
}
</code>```

**After loading to JSON formated data looks like below **

```<code>{
    u't_id': u'80740185.1558980000000.120184.121164',
    u'c_id': 120184,
    u'msg_type': 1,
    u'dlr': u'1',
    u'msisdn': u'xxxxxxxx',
    u'amd': u'{
                "msg":" \u0986\u099c \u09b0\u09be\u09a4 \u09e7\u09e8\u099f\u09be\u09b0 \u09ae\u09a7\u09cd\u09af\u09c7 *21291*609# \u09a1\u09be\u09df\u09be\u09b2\u09c7 \u0995\u09bf\u09a8\u09c1\u09a8 \u09e7\u099c\u09bf\u09ac\u09bf \u09ef\u099f\u09be\u0995\u09be\u09a4\u09c7 (\u09e9\u09a6\u09bf\u09a8)",
                "mask":"1GB_OFFER",
                "ec":"1",
                "time-out":"0",
                "validity":"30052019 000000"
               }',
    u'entity': 1,
    u's_id': u'80740185',
    u'ch_id': 1,
    u'time': 1558960217731,
    u'pt_slot': u'null:null',
    u'o_id': 121164
}
</code>```

I've above very simple JSON Data which I'm trying to convert to CSV data. But getting below error.

Here is my code

```<code>#!/usr/bin/python

import json
import csv

def write_sms_dat_to_csv_file():
    f = csv.writer(open('csv_data.txt','wb+'),delimiter = '|')
    with open('test.dat') as fh:
            data = json.load(fh)

    for dt in data:
            f.writerow([dt['c_id'],dt['msisdn'],dt["amd"]["mask"]])

if __name__=="__main__":
    write_sms_dat_to_csv_file()
</code>```

Error Message

```<code>Traceback (most recent call last):
File "./sms_data_read.py", line 16, in <module>
write_sms_dat_to_csv_file()
File "./sms_data_read.py", line 13, in write_sms_dat_to_csv_file
f.writerow([dt['c_id'],dt['msisdn'],dt['amd']['mask']])
TypeError: string indices must be integers
</code>```

Removing for loops with below statement gives same error:

```<code>f.writerow([data['c_id'],data['msisdn'],data['amd']["mask"]])
</code>```

答:
Looks like the problem is that the dictionary you're trying to access through key 'amd' is actually a string. You can convert it to an actual dictionary by importing ast</p>

```<code>import ast

sub_dict = ast.literal_eval(dt['amd'])
</code>```

Title: JSON to CSV Conversion in Python

Body:
There're lots of questions regarding JSON to CSV Conversion in Python , but unfortunately couldn't solve my problem.

I've this simple simple JSON Data which is in a file and looks like this after loading.

Raw data in single line [I've structured this to understand better]:

{
    "t_id":"80740185.1558980000000.120184.121164",
    "s_id":"80740185",
    "pt_slot":"null:null",
    "ch_id":1,"o_id":121164,"c_id":120184,
    "msg_type":1,
    "amd":"{
                \"msg\":\" some Bengali text\",
                \"mask\":\"1GB_OFFER\",
                \"ec\":\"1\",
                \"time-out\":\"0\",
                \"validity\":\"30052019 000000\"
           }",
    "time":1558960217731,
    "dlr":"1",
    "msisdn":"xxxxx",
    "entity":1
}

**After loading to JSON formated data looks like below **

{
    u't_id': u'80740185.1558980000000.120184.121164',
    u'c_id': 120184,
    u'msg_type': 1,
    u'dlr': u'1',
    u'msisdn': u'xxxxxxxx',
    u'amd': u'{
                "msg":" \u0986\u099c \u09b0\u09be\u09a4 \u09e7\u09e8\u099f\u09be\u09b0 \u09ae\u09a7\u09cd\u09af\u09c7 *21291*609# \u09a1\u09be\u09df\u09be\u09b2\u09c7 \u0995\u09bf\u09a8\u09c1\u09a8 \u09e7\u099c\u09bf\u09ac\u09bf \u09ef\u099f\u09be\u0995\u09be\u09a4\u09c7 (\u09e9\u09a6\u09bf\u09a8)",
                "mask":"1GB_OFFER",
                "ec":"1",
                "time-out":"0",
                "validity":"30052019 000000"
               }',
    u'entity': 1,
    u's_id': u'80740185',
    u'ch_id': 1,
    u'time': 1558960217731,
    u'pt_slot': u'null:null',
    u'o_id': 121164
}

I've above very simple JSON Data which I'm trying to convert to CSV data. But getting below error.

Here is my code

#!/usr/bin/python

import json
import csv

def write_sms_dat_to_csv_file():
    f = csv.writer(open('csv_data.txt','wb+'),delimiter = '|')
    with open('test.dat') as fh:
            data = json.load(fh)

    for dt in data:
            f.writerow([dt['c_id'],dt['msisdn'],dt["amd"]["mask"]])

if __name__=="__main__":
    write_sms_dat_to_csv_file()

Error Message

Traceback (most recent call last):
File "./sms_data_read.py", line 16, in <module>
write_sms_dat_to_csv_file()
File "./sms_data_read.py", line 13, in write_sms_dat_to_csv_file
f.writerow([dt['c_id'],dt['msisdn'],dt['amd']['mask']])
TypeError: string indices must be integers

Removing for loops with below statement gives same error:

f.writerow([data['c_id'],data['msisdn'],data['amd']["mask"]])

Body:
Looks like the problem is that the dictionary you're trying to access through key 'amd' is actually a string. You can convert it to an actual dictionary by importing ast

import ast

sub_dict = ast.literal_eval(dt['amd'])


问:
In a Userform, Link Textbox to the same row as the combobox but different Column
I have created a userform with 2 comboboxes, a textbox and a button that will link the comboboxes/textbox depending on the scenario.

For one of the scenarios, if combobox 2, displays the same text/value currently in the worksheet MRFGLR Range Column A change the value of column AE with the textbox value in the same row as the combobox 2 value in Worksheet MFGLR.
In a Userform, Link Textbox to the same row as the combobox but different Column

I'm having trouble having the code find the same row as combobox2 value and then pasting the textbox1 value 31 columns to the right as that. This is what I have so far.

```<code>With Worksheets("MFGLR").Range("a1:a500")
Set C = .Find(ComboBox2.Value, LookIn:=xlValues)
If Not C Is Nothing Then
    firstAddress = C.Address
    Do
        C.Value = TextBox1.Value
        Set C = .FindNext(C)
    Loop While Not C Is Nothing
End If
End With
</code>```

答:
One way to find which row you need based on the value in "combobox2" would be to use the Range.Find Method. Here is the documentation from Microsoft on how to use the method. You would pass in the value in "combobox2" as the value to find. It also shows you how to catch an error when you don't find the value you are looking for (which in my experience can happen quite often).

The Range.Find method returns a Range Object, which is basically an address for a cell. From there you could use something like .Row to find the row you need and then reference it in combination with your column "AE".

Let me know if this helps! Good Luck!

Body:
I have created a userform with 2 comboboxes, a textbox and a button that will link the comboboxes/textbox depending on the scenario.

For one of the scenarios, if combobox 2, displays the same text/value currently in the worksheet MRFGLR Range Column A change the value of column AE with the textbox value in the same row as the combobox 2 value in Worksheet MFGLR.
In a Userform, Link Textbox to the same row as the combobox but different Column

I'm having trouble having the code find the same row as combobox2 value and then pasting the textbox1 value 31 columns to the right as that. This is what I have so far.

With Worksheets("MFGLR").Range("a1:a500")
Set C = .Find(ComboBox2.Value, LookIn:=xlValues)
If Not C Is Nothing Then
    firstAddress = C.Address
    Do
        C.Value = TextBox1.Value
        Set C = .FindNext(C)
    Loop While Not C Is Nothing
End If
End With


问:
Using wildcard in Gradle Files then copy if it exists
In very brief, I want to find all files that ends with *.sql and copy them if they exist.
There might be 0 or more files in etc directory.

```<code>    File sqlfiles = file('etc/' + '*.sql')
    logger.info("Looking for SQL files: " + sqlfiles);
    if (sqlfiles.exists())
    {
        logger.info("Found log SQL file: " + sqlfiles);

        copy
                {
                    from sqlfiles
                    into "$rpmStoredir"
                }
    }
    else
    {
        logger.warn("No SQL file found - skipping");
    }
</code>```

With my code, the wildcard is not working here.

So adding "include" to the copy as in the below is working but I just want to figure how to add a logger if the file does not exist

```<code>copy
{
    from "etc/"
    include "*.sql"
    into "$rpmStoredir"
}
</code>```

答:
file(...) is the wrong method to use as this returns a single java.io.File

You could do something like

```<code>FileTree myTree = fileTree('etc') {
   include '*.sql'
}
if (myTree.empty) {
  ...
} else {
   copy {
      from myTree
      ...
   }
}
</code>```

See Project.fileTree(Object, Closure) and FileTree

Body:
In very brief, I want to find all files that ends with *.sql and copy them if they exist.
There might be 0 or more files in etc directory.

    File sqlfiles = file('etc/' + '*.sql')
    logger.info("Looking for SQL files: " + sqlfiles);
    if (sqlfiles.exists())
    {
        logger.info("Found log SQL file: " + sqlfiles);

        copy
                {
                    from sqlfiles
                    into "$rpmStoredir"
                }
    }
    else
    {
        logger.warn("No SQL file found - skipping");
    }

With my code, the wildcard is not working here.

So adding "include" to the copy as in the below is working but I just want to figure how to add a logger if the file does not exist

copy
{
    from "etc/"
    include "*.sql"
    into "$rpmStoredir"
}

Body:
file(...) is the wrong method to use as this returns a single java.io.File

You could do something like

FileTree myTree = fileTree('etc') {
   include '*.sql'
}
if (myTree.empty) {
  ...
} else {
   copy {
      from myTree
      ...
   }
}

See Project.fileTree(Object, Closure) and FileTree


问:
Scroll back to the top of scrollable div

```

<pre class="lang-css prettyprint-override"><code>#containerDiv {
  position: absolute;
  top: 0px;
  width: 400px;
  height: 100%;
  padding: 5px;
  font-size: .875em;
  overflow-y: scroll;
}
</code>```

document.getElementById("containerDiv").innerHTML = variableLongText;
```

How to reset the scroll position back to top of container div the next time?

答:
This is the only way it worked for me, with smooth scrolling transition:</p>

```<code>  $('html, body').animate({
    scrollTop: $('#containerDiv').offset().top,
  }, 250);
</code>```

Body:
#containerDiv {
  position: absolute;
  top: 0px;
  width: 400px;
  height: 100%;
  padding: 5px;
  font-size: .875em;
  overflow-y: scroll;
}

document.getElementById("containerDiv").innerHTML = variableLongText;

How to reset the scroll position back to top of container div the next time?

Body:
This is the only way it worked for me, with smooth scrolling transition:

  $('html, body').animate({
    scrollTop: $('#containerDiv').offset().top,
  }, 250);


问:
Identifying the class type for arguments required in gerDeclaredMethod in java
I am using Java Reflection to invoke a method xyz with these 4 parameter types:

```<code>Set<LineItems>
String
Document
Profiler
</code>```

While using getDeclaredMethod I am required to give the method argument type. If String's argument type is String.class, what should be done for Set<LineItems>? Should it be Set.class? (Keeping in mind that Set is an interface)

The function xyz is a default function in interface abc. This interface is being implemented in multiple other classes, so method should be reflected here only. Here is my code:

```<code>Class c = abc.getClass();

Class args[] = new Class[4];
args[0] = Set.class;
args[1] = String.class;
args[2] = Document.class;
args[3] = Profiler.class;

Method m = c.getMethod("xyz",args) ;
</code>```

I'm getting the NoSuchMethodFoundException
I know there could be multiple flaws in this. Any help?

答:
I was able to solve this by :</p>

```<code>Object[] args= new Object[4];
args[0]= setOfItems;
args[1]= aString;
args[2]= document;
args[3]= profiler;

Method m = this.getClass().getMethod("xyz", Set.class, String.class, Document.class, Profiler.class);
Object result = proxy.invoke(m, this, args)
</code>```

Body:
I am using Java Reflection to invoke a method xyz with these 4 parameter types:

Set<LineItems>
String
Document
Profiler

While using getDeclaredMethod I am required to give the method argument type. If String's argument type is String.class, what should be done for Set<LineItems>? Should it be Set.class? (Keeping in mind that Set is an interface)

The function xyz is a default function in interface abc. This interface is being implemented in multiple other classes, so method should be reflected here only. Here is my code:

Class c = abc.getClass();

Class args[] = new Class[4];
args[0] = Set.class;
args[1] = String.class;
args[2] = Document.class;
args[3] = Profiler.class;

Method m = c.getMethod("xyz",args) ;

I'm getting the NoSuchMethodFoundException
I know there could be multiple flaws in this. Any help?

Body:
I was able to solve this by :

Object[] args= new Object[4];
args[0]= setOfItems;
args[1]= aString;
args[2]= document;
args[3]= profiler;

Method m = this.getClass().getMethod("xyz", Set.class, String.class, Document.class, Profiler.class);
Object result = proxy.invoke(m, this, args)


问:
Excluding files of a certain size
I'm trying to generate a .csv file that lists all .txt file in a sub-directory but can exclude a .txt file of a certain size.

Without an if statement around file size, I can successfully generate the .csv file list that has the full paths to the .txt files (1105 files total)

```<code>import os
import csv
import os.path
mtn_path = "TEXT_FILE_PATH\\"
a = open(mtn_path + "output.csv", 'w+', newline='')
num_files = 0
for path, dirnames, filenames in os.walk(mtn_path):
    for filename in [f for f in filenames if f.endswith(".txt")]:
#       if os.stat(filename).st_size > 20000:
            f = os.path.join(path, filename)
            a.write(str(f) + os.linesep)
            num_files = num_files + 1
)
#
print("The total number of text files found was " + str(num_files))
</code>```

When I include the if os.stat line, I get the error:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'INT_NR_H1000Cu_000.mtn_001.txt'

That particular .txt file is the first one listed in the csv file of the working code.

答:
I think you have to include the full path in the if statement. os.path can't find filename

Add full path to the file
os.path.join(path, filename)

Also delete that slash at the end of TEXT_FILE_PATH

```<code>import os
import csv
import os.path
mtn_path = r"TEXT_FILE_PATH"
a = open(mtn_path + "output.csv", 'w+', newline='')
num_files = 0
for path, dirnames, filenames in os.walk(mtn_path):
    for filename in [f for f in filenames if f.endswith(".txt")]:
        if os.stat(os.path.join(path, filename)).st_size > 20000:
            f = os.path.join(path, filename)
            a.write(str(f) + os.linesep)
            num_files = num_files + 1
)
#
print("The total number of text files found was " + str(num_files))
</code>```

Title: Excluding files of a certain size

Body:
I'm trying to generate a .csv file that lists all .txt file in a sub-directory but can exclude a .txt file of a certain size.

Without an if statement around file size, I can successfully generate the .csv file list that has the full paths to the .txt files (1105 files total)

import os
import csv
import os.path
mtn_path = "TEXT_FILE_PATH\\"
a = open(mtn_path + "output.csv", 'w+', newline='')
num_files = 0
for path, dirnames, filenames in os.walk(mtn_path):
    for filename in [f for f in filenames if f.endswith(".txt")]:
#       if os.stat(filename).st_size > 20000:
            f = os.path.join(path, filename)
            a.write(str(f) + os.linesep)
            num_files = num_files + 1
)
#
print("The total number of text files found was " + str(num_files))

When I include the if os.stat line, I get the error:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'INT_NR_H1000Cu_000.mtn_001.txt'

That particular .txt file is the first one listed in the csv file of the working code.

Body:
I think you have to include the full path in the if statement. os.path can't find filename

Add full path to the file
os.path.join(path, filename)

Also delete that slash at the end of TEXT_FILE_PATH

import os
import csv
import os.path
mtn_path = r"TEXT_FILE_PATH"
a = open(mtn_path + "output.csv", 'w+', newline='')
num_files = 0
for path, dirnames, filenames in os.walk(mtn_path):
    for filename in [f for f in filenames if f.endswith(".txt")]:
        if os.stat(os.path.join(path, filename)).st_size > 20000:
            f = os.path.join(path, filename)
            a.write(str(f) + os.linesep)
            num_files = num_files + 1
)
#
print("The total number of text files found was " + str(num_files))


问:
Is there an event that fires before the vscode editor is closed?
My extension should display a message box when the editor is closed.
The user should confirm before the editor is closed.

The only events I could find in the VSCode API are onDidCloseTerminal for the terminal
 and onDidCloseTextDocument for text documents.

答:
Extensions can export a deactivate method along with their activate method that will be invoked when VS Code is shutdown

```<code>export function activate(context: vscode.ExtensionContext) {
  ...
}

// Called when your extension is deactivated
export function deactivate() {
     ...
}
</code>```

See the extension activation docs for more details

Body:
Extensions can export a deactivate method along with their activate method that will be invoked when VS Code is shutdown

export function activate(context: vscode.ExtensionContext) {
  ...
}

// Called when your extension is deactivated
export function deactivate() {
     ...
}

See the extension activation docs for more details


问:
chrome.storage.local Issues with writing keys
I'm trying to integrate chrome's storage into my extension. And I'm having trouble grasping how the data is stored once it's written because nothing I try seems to work.
What I want to be able to do is store an object with a specific key. But that key is generated runtime, dynamically.

So I have something like this so far.

```<code> let storage = {};
storage["status"] = "no status";
chrome.storage.local.set(storage,function(){

});
</code>```

When I do that, the key automatically becomes 'storage' but I don't want to do that. Because I want the key to be unique every time. So ideally what I want to do is this

```<code>let storageid = generateid();//generate unique storage id
let storage = {};
storage["status"] = "no status";
chrome.storage.local.set({storageid: storage},function(){

});
</code>```

But even in that instance the key is still "storageid" not necessarily the value held in the variable storageid.
It's a bit tricky to explain the problem because of my little understanding of how chrome's local storage works. So any help would be greatly appreciated.

答:
When you form your JS object, you are writing {storageid: storage}. This storageid here is still just the string "storageid". What you are looking for is the value of the variable itself.
{[storageid]: storage} interprets the variable storageid into the its value.

Not that it matters when building a Chrome plugin, but I figure it is worth pointing out that this is a more modern syntax of JS and would not work in IE. There, the solution would still have to be.

```<code>var storageObj = {}
storageObj[storageid] = storage
</code>```

Body:
I'm trying to integrate chrome's storage into my extension. And I'm having trouble grasping how the data is stored once it's written because nothing I try seems to work.
What I want to be able to do is store an object with a specific key. But that key is generated runtime, dynamically.

So I have something like this so far.

 let storage = {};
storage["status"] = "no status";
chrome.storage.local.set(storage,function(){

});

When I do that, the key automatically becomes 'storage' but I don't want to do that. Because I want the key to be unique every time. So ideally what I want to do is this

let storageid = generateid();//generate unique storage id
let storage = {};
storage["status"] = "no status";
chrome.storage.local.set({storageid: storage},function(){

});

But even in that instance the key is still "storageid" not necessarily the value held in the variable storageid.
It's a bit tricky to explain the problem because of my little understanding of how chrome's local storage works. So any help would be greatly appreciated.

Body:
When you form your JS object, you are writing {storageid: storage}. This storageid here is still just the string "storageid". What you are looking for is the value of the variable itself.
{[storageid]: storage} interprets the variable storageid into the its value.

Not that it matters when building a Chrome plugin, but I figure it is worth pointing out that this is a more modern syntax of JS and would not work in IE. There, the solution would still have to be.

var storageObj = {}
storageObj[storageid] = storage


问:
Spark - Operation not allowed: alter table replace columns
Looks like hive replace columns is not working with spark 2.2.1 and also with 2.3.1

```<code>alterSchemaSql : alter table myschema.mytable replace columns (a int,b int,d int)
Exception in thread "main" org.apache.spark.sql.catalyst.parser.ParseException:
Operation not allowed: alter table replace columns(line 2, pos 6)
</code>```

Looks like it's been fixed for ADD COLUMNS 2.2 version onwards. It also works for me but replace columns still fails.

Operation not allowed: alter table add columns(line 1, pos 0)

Following docs says it should be supported. Not sure why it's failing for me.
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html#supported-hive-features

https://docs.databricks.com/spark/latest/spark-sql/language-manual/alter-table-or-view.html#replace-columns

答:
Sadly, it seems ALTER TABLE table REPLACE is not implemented by Spark.

Take a look at SparkSqlParser.scala: SparkSqlParser.scala

There, you can see, what SQL statements work with Spark.

Body:
Looks like hive replace columns is not working with spark 2.2.1 and also with 2.3.1

alterSchemaSql : alter table myschema.mytable replace columns (a int,b int,d int)
Exception in thread "main" org.apache.spark.sql.catalyst.parser.ParseException:
Operation not allowed: alter table replace columns(line 2, pos 6)

Looks like it's been fixed for ADD COLUMNS 2.2 version onwards. It also works for me but replace columns still fails.

Operation not allowed: alter table add columns(line 1, pos 0)

Following docs says it should be supported. Not sure why it's failing for me.
https://spark.apache.org/docs/2.2.0/sql-programming-guide.html#supported-hive-features

https://docs.databricks.com/spark/latest/spark-sql/language-manual/alter-table-or-view.html#replace-columns


问:
How to move a button background?
I'm having trouble moving a button background. I've identified the class which enables me to move the button text anywhere I like, but I want the  button background to move with it.

Html:

```<code><li class="location"><a class="google_map_link"
href="http://maps.google.com/maps?
q=London&zoom=14&size=512x512&
maptype=roadmap&sensor=false">London</a></li>
</code>```

Tried css:

```<code>.google_map_link {margin-top: 10px;}
</code>```

This works for the text but background and fafa stay in same place??

https://adsler.co.uk/job/holland-and-barratt-london-4-store-colleague

答:
You can use background-position to rearrange a background image</p>

```<code>.google_map_link {
   background-position:0 10px;
}
</code>```

Title: How to move a button background?

Body:
I'm having trouble moving a button background. I've identified the class which enables me to move the button text anywhere I like, but I want the  button background to move with it.

Html:

London

Tried css:

.google_map_link {margin-top: 10px;}

This works for the text but background and fafa stay in same place??

https://adsler.co.uk/job/holland-and-barratt-london-4-store-colleague

Body:
You can use background-position to rearrange a background image

.google_map_link {
   background-position:0 10px;
}


问:
How to find the furthest point from other given points in Java
I have a given S point (red on the graph) and n other points (black on the graph). I want to find a point P, in a distance of 1 from S, which is the furthest from all the black points (in this case - the sum of distances between P and each point should is the highest).

As P is 1 away from S, we can tell that y = √(1 - x^2).

The analitical way I would personally use would be to:

Calculate the sum of the distances

Q - P = √((Qx - Sx - x)^2 + (Qy - Sy - √(1 - x^2))^2) (repeat of all n points and sum up),

Calculate the derivative of the obtained expression,

Calculate roots of the derivative and find maximums (in the domain),

Calculate values at the ends of the intervals in the domain,

Choose the correct X.

What would be the most efficient way to do this in Java and what libraries could be used? I heard about libraries allowing to do this analyticaly, but it sounds complicated and slow so I was searching for any numerical ideas, but couldn't find any.

答:
Follow the path of the circle in SMALL incrementials. Calculate the sum of distances for each point along the circle. Find the position where the sum of distances are the maximum. Done.
java.lang.Math is enough for this. No need of extra libraries. Look up trigonometry.

SP segment's angle is phi. You go from 0 to 2*pi (remember it uses radians). Increment phi with a small number in your loop.

Something like:

phi=0.0;

maxSumDistance = 0.0;

phiAtMaxValue = 0.0;

do a loop: phi goes from 0.0 to 2*pi adding a small number to phi each time

Inside the loop:  if (currentSumDistance > maxSumDistance) then
maxSumDistance = currentSumDistance; and
phiAtMaxValue = current value of phi (the loop variable);

At the end of the loop You will have the phi angle's value where the sum of distances was the biggest. Then you recalculate the coordinates of P from phi, and the distance of SP.

This might be a bruteforce approach, but calculating derivatives for this seems overkill, and too complicated.


问:
Trying to understand why there are extra brackets at the end of a call
Possibly a silly question, I am trying to work through an example for OAuth and want to understand exactly what is happening before I add to my own code.

Sample is node, express using passport-azure-ad

The route is being defined and a call to passport.authenticate is made.

```<code>app.get('/login',
  (req, res, next) => {
      passport.authenticate('azuread-openidconnect',
      {
        response: res,
        resourceURL: config.resourceURL,
        failureRedirect: '/'
      })(req, res, next); // <-- Here is what I am stuck on.
   },
   (req, res) => {
       log.info('Login was called in the Sample');
       res.redirect('/');
});
</code>```

I am trying to understand the (req, res, next); that follows directly after the authenticate.

Appreciate any help, or a link to the theory/documentation on this syntax.

答:
That's because passport.authenticate returns a function (middleware) to handle the request, so you're passing the request to the actual handler here

like this:

```<code>function authenticate(someArg) {
    return function (req, res, next) {
        // the handler
    }
}
</code>```

And this is a simplified version of the example you provided, without the extra explicit pass of the parameters

```<code>app.get('/login', passport.authenticate('azuread-openidconnect', {
    response: res,
    resourceURL: config.resourceURL,
    failureRedirect: '/'
}), (req, res) => {
    log.info('Login was called in the Sample');
    res.redirect('/');
});
</code>```

Body:
Possibly a silly question, I am trying to work through an example for OAuth and want to understand exactly what is happening before I add to my own code.

Sample is node, express using passport-azure-ad

The route is being defined and a call to passport.authenticate is made.

app.get('/login',
  (req, res, next) => {
      passport.authenticate('azuread-openidconnect',
      {
        response: res,
        resourceURL: config.resourceURL,
        failureRedirect: '/'
      })(req, res, next); // <-- Here is what I am stuck on.
   },
   (req, res) => {
       log.info('Login was called in the Sample');
       res.redirect('/');
});

I am trying to understand the (req, res, next); that follows directly after the authenticate.

Appreciate any help, or a link to the theory/documentation on this syntax.

Body:
That's because passport.authenticate returns a function (middleware) to handle the request, so you're passing the request to the actual handler here

like this:

function authenticate(someArg) {
    return function (req, res, next) {
        // the handler
    }
}

And this is a simplified version of the example you provided, without the extra explicit pass of the parameters

app.get('/login', passport.authenticate('azuread-openidconnect', {
    response: res,
    resourceURL: config.resourceURL,
    failureRedirect: '/'
}), (req, res) => {
    log.info('Login was called in the Sample');
    res.redirect('/');
});


问:
Pandas group a column by another column
I have a pandas dataframe that looks like:

```<code>A B
1 a
1 b
1 c
2 d
2 e
2 f
</code>```

I want to get a list of values for column 'B' by column 'A', so the final product would look like:

```<code>list_one = [a, b, c]
list_two = [d, e, f]
</code>```

I've tried:

```<code>df.groupby(['A','B'])
</code>```

But, this doesn't do what I want it to do.

What would be an elegant pythonic way to achieve this?

Title: Pandas group a column by another column

Body:
I have a pandas dataframe that looks like:

A B
1 a
1 b
1 c
2 d
2 e
2 f

I want to get a list of values for column 'B' by column 'A', so the final product would look like:

list_one = [a, b, c]
list_two = [d, e, f]

I've tried:

df.groupby(['A','B'])

But, this doesn't do what I want it to do.

What would be an elegant pythonic way to achieve this?

Body:
import pandas as pd

df = pd.DataFrame([
    {'A':1, 'B': 'a'},
    {'A':1, 'B': 'b'},
    {'A':1, 'B': 'c'},
    {'A':2, 'B': 'd'},
    {'A':2, 'B': 'e'},
    {'A':2, 'B': 'f'}])

list(df.groupby('A')['B'].apply(list).values)

# Output
# [['a', 'b', 'c'], ['d', 'e', 'f']]


问:
Unable to fix "could not obtain transaction-synchronized Session for current thread"
I am new to spring hibernate.
I am using sprin 4.3.8 and Hibernate 5.2.

I tried solutions available on the net and I have all of them in my code, yet I am getting this error please help me resolve this.

error:

```<code>Exception in thread "main" org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:133)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:456)
at com.travello.daoImpl.ActivityDAOImpl.getActivity(ActivityDAOImpl.java:43)
at com.travello.model.SpringMain.main(SpringMain.java:17)
</code>```

Here is the ActivityListDAOImpl:

```<code>@Transactional
public class ActivityDAOImpl implements ActivityDAO {

@Autowired
private SessionFactory sessionfactory;

public SessionFactory getSessionfactory() {
    return sessionfactory;
}

public void setSessionfactory(SessionFactory sessionfactory) {
    this.sessionfactory = sessionfactory;
}

@Override
public ActivityList getActivity(int activity_id) {
    Session session = sessionfactory.getCurrentSession();
    ActivityList activity = session.get(ActivityList.class, activity_id);
    return activity;
    }
}
</code>```

The Main method:

```<code>public class SpringMain {

public static void main(String[] args) {

    @SuppressWarnings("resource")
    ApplicationContext context = new ClassPathXmlApplicationContext         ("spring.xml");
    ActivityDAOImpl dao = (ActivityDAOImpl) context.getBean("activityDao", ActivityDAOImpl.class);

    ActivityList activity = dao.getActivity(1);
    System.out.println(activity.getActivityName());
    System.out.println("Done");

}

}
</code>```

The spring.xml

```<code>    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <context:property-placeholder location="classpath:resources/database.properties" />
    <context:annotation-config/>
    <context:component-scan base-package="com.travello" />

<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${database.driver}" />
        <property name="url" value="${database.url}" />
        <property name="username" value="${database.user}" />
        <property name="password" value="${database.password}" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="hibernate.cfg.xml" />
    </bean>

    <bean id="hibernateTransactionManager"
        class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="activityDao" class="com.travello.daoImpl.ActivityDAOImpl">
        <property name="sessionfactory" ref="sessionFactory" />
    </bean>

    </beans>
</code>```

I have @Transational annotation applied and the bean for the same in the spring.xml yet there's this error.

答:
I have had a similar error, the easiest solution is to add @Transaction with </p>

```<code>@Transactional(propagation = Propagation.REQUIRES_NEW)
</code>```

<p>You will not get this error after that and would work perfectly. </p>

Body:
I am new to spring hibernate.
I am using sprin 4.3.8 and Hibernate 5.2.

I tried solutions available on the net and I have all of them in my code, yet I am getting this error please help me resolve this.

error:

Exception in thread "main" org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:133)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:456)
at com.travello.daoImpl.ActivityDAOImpl.getActivity(ActivityDAOImpl.java:43)
at com.travello.model.SpringMain.main(SpringMain.java:17)

Here is the ActivityListDAOImpl:

@Transactional
public class ActivityDAOImpl implements ActivityDAO {

@Autowired
private SessionFactory sessionfactory;

public SessionFactory getSessionfactory() {
    return sessionfactory;
}

public void setSessionfactory(SessionFactory sessionfactory) {
    this.sessionfactory = sessionfactory;
}

@Override
public ActivityList getActivity(int activity_id) {
    Session session = sessionfactory.getCurrentSession();
    ActivityList activity = session.get(ActivityList.class, activity_id);
    return activity;
    }
}

The Main method:

public class SpringMain {

public static void main(String[] args) {

    @SuppressWarnings("resource")
    ApplicationContext context = new ClassPathXmlApplicationContext         ("spring.xml");
    ActivityDAOImpl dao = (ActivityDAOImpl) context.getBean("activityDao", ActivityDAOImpl.class);

    ActivityList activity = dao.getActivity(1);
    System.out.println(activity.getActivityName());
    System.out.println("Done");

}

}

The spring.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <context:property-placeholder location="classpath:resources/database.properties" />
    <context:annotation-config/>
    <context:component-scan base-package="com.travello" />

<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${database.driver}" />
        <property name="url" value="${database.url}" />
        <property name="username" value="${database.user}" />
        <property name="password" value="${database.password}" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="hibernate.cfg.xml" />
    </bean>

    <bean id="hibernateTransactionManager"
        class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="activityDao" class="com.travello.daoImpl.ActivityDAOImpl">
        <property name="sessionfactory" ref="sessionFactory" />
    </bean>

    </beans>

I have @Transational annotation applied and the bean for the same in the spring.xml yet there's this error.

Body:
I have had a similar error, the easiest solution is to add @Transaction with

@Transactional(propagation = Propagation.REQUIRES_NEW)

You will not get this error after that and would work perfectly.


问:
Spring Cloud Gateway and fault tolerance
I was reading about spring cloud architecture and technologies (like eureka, hystrix circuit breaker) used to prevent your application from downtime because of failure of some of yours microservices. And all in all spring cloud suggests to use Spring Cloud Gateway as an entry point to all the micro services. So I am questioning myself how to provide fault tolerance of spring cloud gateway itself? As I see right now if this entry point will fail then all these technologies like eureka and hystrix circuit breaker will not be available since they are implemented on the level of spring cloud gateway. Now when spring cloud gateway is down - all clients will not be able to reach all services behind spring cloud gateway. So how to deal with such kind of situations? </p>

答:
I don't think this is directly related to Spring Cloud Gateway, to be honest. The question is more "How to deploy highly available Java application?" (SCG is a Spring application).

The answer depends on the platform you use.

Most of IAAS platforms provide their own infrastructure load balancers, like ALB / ELB in AWS.

PAAS platform usually include out of the box LB , e.g. Cloud Foundry or Kubernetes can do that for you.

DNS is probably not the best choice for the reasons you've described - TTL and client caching. Also, DNS doesn't really have a way to do a health check of an upstream service. So using DNS requires client-side load balancing, when the client needs to be smart and invalidate cache / retry if a request failed.


问:
Skip first line of fgetcsv method
I have a CSV file and I read data from CSV file then I want to skip first line of CSV file.Which'll contain any header. I am using this code.

```<code>while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
    // Code to insert into database
}
</code>```

When I insert data into th database then header should not to be saved into the database.

答:
You should use the fseek() method in order to get the desired line, regardless  the current pointer position.

At this example, get the first line after the loop:

```<code>$file = fopen($path, "r");

while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
  // ...
}

fseek($file, 1, SEEK_CUR);
</code>```

You can use the third parameter to position the pointer in the file, as is:

SEEK_SET – It moves file pointer position to the beginning of the file.

SEEK_CUR – It moves file pointer position to given location.

SEEK_END – It moves file pointer position to the end of file.

Title: Skip first line of fgetcsv method

Body:
I have a CSV file and I read data from CSV file then I want to skip first line of CSV file.Which'll contain any header. I am using this code.

while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
    // Code to insert into database
}

When I insert data into th database then header should not to be saved into the database.

Body:
You should use the fseek() method in order to get the desired line, regardless  the current pointer position.

At this example, get the first line after the loop:

$file = fopen($path, "r");

while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
  // ...
}

fseek($file, 1, SEEK_CUR);

You can use the third parameter to position the pointer in the file, as is:

SEEK_SET – It moves file pointer position to the beginning of the file.

SEEK_CUR – It moves file pointer position to given location.

SEEK_END – It moves file pointer position to the end of file.


问:
Why stored procedure result is zero?
Work on C# vs 2008. I have a stored procedure in SQL Server 2005. Using Linq-to-SQL I execute the stored procedure, but the result is zero. When i run the query in Sql server it's work fine

```<code> exec spGetInvoiceByDate '03/01/2011 00:00:00 AM','03/31/2011 11:59:59 PM'
</code>```

above syntax works fine.

Here is my SQL Server stored procedure

```<code>create procedure [spGetInvoiceByDate]
  @Beginning_Date DateTime, @Ending_Date DateTime
as
begin

SELECT * INTO #temp1 FROM (
SELECT     convert(varchar, ManifestPort.StartDate, 1)+'-'+CASE dbo.ManifestPort.EndDate WHEN '1800-01-01 00:00:00.000' THEN 'N/A' ELSE convert(varchar, ManifestPort.EndDate, 1) END AS [Date], Manifest.VesselName, Manifest.VoyageNo, DischargePort.PortName
, ManifestPort.Terminal, COUNT(Seal.ContainerNo) TotalContainers, 0 AS TotalHours, 0 AS TotalFee
FROM ManifestPort
INNER JOIN Manifest ON ManifestPort.ManifestNo = Manifest.ManifestNo
INNER JOIN DischargePort ON ManifestPort.PortCode = DischargePort.PortCode
INNER JOIN Seal ON ManifestPort.ManifestPortNo = Seal.ManifestPortNo
WHERE (StartDate BETWEEN @Beginning_Date AND @Ending_Date)
GROUP BY StartDate,EndDate, VesselName, VoyageNo, PortName, Terminal) AS a

SELECT * INTO #temp2 FROM (
SELECT convert(varchar, ManifestPort.StartDate, 1)+'-'+CASE dbo.ManifestPort.EndDate WHEN '1800-01-01 00:00:00.000' THEN 'N/A' ELSE convert(varchar, ManifestPort.EndDate, 1) END AS [Date], Manifest.VesselName, Manifest.VoyageNo, DischargePort.PortName,
ManifestPort.Terminal, COUNT(Seal.ContainerNo) STotalContainers, 0 AS STotalHours, 0 AS STotalFee
FROM ManifestPort
INNER JOIN Manifest ON ManifestPort.ManifestNo = Manifest.ManifestNo
INNER JOIN DischargePort ON ManifestPort.PortCode = DischargePort.PortCode
INNER JOIN Seal ON ManifestPort.ManifestPortNo = Seal.ManifestPortNo
WHERE (StartDate BETWEEN @Beginning_Date AND @Ending_Date ) AND Line = 'CSAV'
GROUP BY StartDate,EndDate, VesselName, VoyageNo, PortName, Terminal     ) AS b

SELECT  #temp1.Date,
        #temp1.VesselName ,
        #temp1.VoyageNo ,
        #temp1.PortName ,
        #temp1.Terminal ,
        #temp1.TotalContainers ,
        #temp1.TotalHours ,
        #temp1.TotalFee, #temp2.STotalContainers, #temp2.STotalHours, #temp2.STotalFee FROM #temp1 INNER JOIN #temp2
        ON #temp1.Date = #temp2.Date AND #temp1.PortName = #temp2.PortName AND #temp1.Terminal = #temp2.Terminal AND #temp1.VesselName = #temp2.VesselName
        AND #temp1.VoyageNo = #temp2.VoyageNo

        Order BY #temp1.VesselName, #temp1.VoyageNo

DROP TABLE #temp1
DROP TABLE #temp2

end
</code>```

I use this C# Linq syntax to execute the stored procedure:

```<code>DateTime firstDayOfMonth = Convert.ToDateTime("03/01/2011");
DateTime lastDayOfMonth = Convert.ToDateTime("03/31/2011");

var results = ProviderName.spGetInvoiceByDate(firstDayOfMonth,lastDayOfMonth);
</code>```

Why do I always get result is zero?

Can anybody tell me how to reduce the problem?

Thanks in advance, if you have any question, please ask.

答:
As mentioned above by Hans Kesting, you're not using the same date/times in your call to the stored procedure in your SQL query vs. your call via the code.

```<code>exec spGetInvoiceByDate '03/01/2011 00:00:00 AM','03/31/2011 11:59:59 PM'
</code>```

Set the end date in the code to March 31 2011, 11:59:59 PM.

```<code>DateTime firstDayOfMonth = Convert.ToDateTime("03/01/2011");
DateTime lastDayOfMonth = Convert.ToDateTime("03/31/2011 11:59:59 PM");

var results = ProviderName.spGetInvoiceByDate(firstDayOfMonth,lastDayOfMonth);
</code>```

Title: Why stored procedure result is zero?

Body:
Work on C# vs 2008. I have a stored procedure in SQL Server 2005. Using Linq-to-SQL I execute the stored procedure, but the result is zero. When i run the query in Sql server it's work fine

 exec spGetInvoiceByDate '03/01/2011 00:00:00 AM','03/31/2011 11:59:59 PM'

above syntax works fine.

Here is my SQL Server stored procedure

create procedure [spGetInvoiceByDate]
  @Beginning_Date DateTime, @Ending_Date DateTime
as
begin

SELECT * INTO #temp1 FROM (
SELECT     convert(varchar, ManifestPort.StartDate, 1)+'-'+CASE dbo.ManifestPort.EndDate WHEN '1800-01-01 00:00:00.000' THEN 'N/A' ELSE convert(varchar, ManifestPort.EndDate, 1) END AS [Date], Manifest.VesselName, Manifest.VoyageNo, DischargePort.PortName
, ManifestPort.Terminal, COUNT(Seal.ContainerNo) TotalContainers, 0 AS TotalHours, 0 AS TotalFee
FROM ManifestPort
INNER JOIN Manifest ON ManifestPort.ManifestNo = Manifest.ManifestNo
INNER JOIN DischargePort ON ManifestPort.PortCode = DischargePort.PortCode
INNER JOIN Seal ON ManifestPort.ManifestPortNo = Seal.ManifestPortNo
WHERE (StartDate BETWEEN @Beginning_Date AND @Ending_Date)
GROUP BY StartDate,EndDate, VesselName, VoyageNo, PortName, Terminal) AS a

SELECT * INTO #temp2 FROM (
SELECT convert(varchar, ManifestPort.StartDate, 1)+'-'+CASE dbo.ManifestPort.EndDate WHEN '1800-01-01 00:00:00.000' THEN 'N/A' ELSE convert(varchar, ManifestPort.EndDate, 1) END AS [Date], Manifest.VesselName, Manifest.VoyageNo, DischargePort.PortName,
ManifestPort.Terminal, COUNT(Seal.ContainerNo) STotalContainers, 0 AS STotalHours, 0 AS STotalFee
FROM ManifestPort
INNER JOIN Manifest ON ManifestPort.ManifestNo = Manifest.ManifestNo
INNER JOIN DischargePort ON ManifestPort.PortCode = DischargePort.PortCode
INNER JOIN Seal ON ManifestPort.ManifestPortNo = Seal.ManifestPortNo
WHERE (StartDate BETWEEN @Beginning_Date AND @Ending_Date ) AND Line = 'CSAV'
GROUP BY StartDate,EndDate, VesselName, VoyageNo, PortName, Terminal     ) AS b

SELECT  #temp1.Date,
        #temp1.VesselName ,
        #temp1.VoyageNo ,
        #temp1.PortName ,
        #temp1.Terminal ,
        #temp1.TotalContainers ,
        #temp1.TotalHours ,
        #temp1.TotalFee, #temp2.STotalContainers, #temp2.STotalHours, #temp2.STotalFee FROM #temp1 INNER JOIN #temp2
        ON #temp1.Date = #temp2.Date AND #temp1.PortName = #temp2.PortName AND #temp1.Terminal = #temp2.Terminal AND #temp1.VesselName = #temp2.VesselName
        AND #temp1.VoyageNo = #temp2.VoyageNo

        Order BY #temp1.VesselName, #temp1.VoyageNo

DROP TABLE #temp1
DROP TABLE #temp2

end

I use this C# Linq syntax to execute the stored procedure:

DateTime firstDayOfMonth = Convert.ToDateTime("03/01/2011");
DateTime lastDayOfMonth = Convert.ToDateTime("03/31/2011");

var results = ProviderName.spGetInvoiceByDate(firstDayOfMonth,lastDayOfMonth);

Why do I always get result is zero?

Can anybody tell me how to reduce the problem?

Thanks in advance, if you have any question, please ask.

Body:
As mentioned above by Hans Kesting, you're not using the same date/times in your call to the stored procedure in your SQL query vs. your call via the code.

exec spGetInvoiceByDate '03/01/2011 00:00:00 AM','03/31/2011 11:59:59 PM'

Set the end date in the code to March 31 2011, 11:59:59 PM.

DateTime firstDayOfMonth = Convert.ToDateTime("03/01/2011");
DateTime lastDayOfMonth = Convert.ToDateTime("03/31/2011 11:59:59 PM");

var results = ProviderName.spGetInvoiceByDate(firstDayOfMonth,lastDayOfMonth);


问:
Amazon S3 Transferutility use FilePath or Stream?
When uploading a file to S3 using the TransportUtility class, there is an option to either use FilePath or an input stream. I'm using multi-part uploads.

I'm uploading a variety of things, of which some are files on disk and others are raw streams. I'm currently using the InputStream variety for everything, which works OK, but I'm wondering if I should specialize the method further. For the files on disk, I'm basically using File.OpenRead and passing that stream to the InputStream of the transfer request.

Are there any performance gains or otherwise to prefer the FilePath method over the InputStream one where the input is known to be a file.

In short: Is this the same thing

```<code>using (var fs = File.OpenRead("some path"))
{
    var uploadMultipartRequest = new TransferUtilityUploadRequest
    {
        BucketName = "defaultBucket",
        Key = "key",
        InputStream = fs,
        PartSize = partSize
    };

    using (var transferUtility = new TransferUtility(s3Client))
    {
        await transferUtility.UploadAsync(uploadMultipartRequest);
    }
}
</code>```

As:

```<code>    var uploadMultipartRequest = new TransferUtilityUploadRequest
    {
        BucketName = "defaultBucket",
        Key = "key",
        FilePath = "some path",
        PartSize = partSize
    };

    using (var transferUtility = new TransferUtility(s3Client))
    {
        await transferUtility.UploadAsync(uploadMultipartRequest);
    }
</code>```

Or are there any significant difference between the two? I know if files are large or not, and could prefer one method or another based on that.

Edit: I've also done some decompiling of the S3Client, and there does indeed seem to be some difference in regards to the concurrency level of the transfer, as found in MultipartUploadCommand.cs

```<code>private int CalculateConcurrentServiceRequests()
{
  int num = !this._fileTransporterRequest.IsSetFilePath() || this._s3Client is AmazonS3EncryptionClient ? 1 : this._config.ConcurrentServiceRequests;
  if (this._totalNumberOfParts < num)
    num = this._totalNumberOfParts;
  return num;
}
</code>```

答:
I think the difference may be that they both use Multipart Upload API, but using a FilePath allows for concurrent uploads, however,

When you're using a stream for the source of data, the TransferUtility
  class does not do concurrent uploads.

https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingTheMPDotNetAPI.html

Body:
When uploading a file to S3 using the TransportUtility class, there is an option to either use FilePath or an input stream. I'm using multi-part uploads.

I'm uploading a variety of things, of which some are files on disk and others are raw streams. I'm currently using the InputStream variety for everything, which works OK, but I'm wondering if I should specialize the method further. For the files on disk, I'm basically using File.OpenRead and passing that stream to the InputStream of the transfer request.

Are there any performance gains or otherwise to prefer the FilePath method over the InputStream one where the input is known to be a file.

In short: Is this the same thing

using (var fs = File.OpenRead("some path"))
{
    var uploadMultipartRequest = new TransferUtilityUploadRequest
    {
        BucketName = "defaultBucket",
        Key = "key",
        InputStream = fs,
        PartSize = partSize
    };

    using (var transferUtility = new TransferUtility(s3Client))
    {
        await transferUtility.UploadAsync(uploadMultipartRequest);
    }
}

As:

    var uploadMultipartRequest = new TransferUtilityUploadRequest
    {
        BucketName = "defaultBucket",
        Key = "key",
        FilePath = "some path",
        PartSize = partSize
    };

    using (var transferUtility = new TransferUtility(s3Client))
    {
        await transferUtility.UploadAsync(uploadMultipartRequest);
    }

Or are there any significant difference between the two? I know if files are large or not, and could prefer one method or another based on that.

Edit: I've also done some decompiling of the S3Client, and there does indeed seem to be some difference in regards to the concurrency level of the transfer, as found in MultipartUploadCommand.cs

private int CalculateConcurrentServiceRequests()
{
  int num = !this._fileTransporterRequest.IsSetFilePath() || this._s3Client is AmazonS3EncryptionClient ? 1 : this._config.ConcurrentServiceRequests;
  if (this._totalNumberOfParts < num)
    num = this._totalNumberOfParts;
  return num;
}


问:
os.walk without hidden folders
I need to list all files with the containing directory path inside a folder. I tried to use os.walk, which obviously would be the perfect solution.

However, it also lists hidden folders and files. I'd like my application not to list any hidden folders or files. Is there any flag you can use to make it not yield any hidden files?

Cross-platform is not really important to me, it's ok if it only works for linux (.* pattern)

答:
My use-case was similar to that of OP, except I wanted to return a count of the total number of sub-directories inside a certain folder. In my case I wanted to omit any sub-directories named .git (as well as any folders that may be nested inside these .git folders).

In Python 3.6.7, I found that the accepted answer's approach didn't work -- it counted all .git folder and their sub-folders. Here's what did work for me:

```<code>num_local_subdir = 0
for root, dirs, files in os.walk(local_folder_path):
    if '.git' in dirs:
        dirs.remove('.git')
    num_local_subdir += (len(dirs))
</code>```

Title: os.walk without hidden folders

Body:
My use-case was similar to that of OP, except I wanted to return a count of the total number of sub-directories inside a certain folder. In my case I wanted to omit any sub-directories named .git (as well as any folders that may be nested inside these .git folders).

In Python 3.6.7, I found that the accepted answer's approach didn't work -- it counted all .git folder and their sub-folders. Here's what did work for me:

num_local_subdir = 0
for root, dirs, files in os.walk(local_folder_path):
    if '.git' in dirs:
        dirs.remove('.git')
    num_local_subdir += (len(dirs))


问:
Images not loading after Wordpress switch to HTTPS (but image links work fine)
After switching my wordpress site to https the images fail to load on the website, but the images load fine when their URL is pasted directly into the browser.

This is what I did to perform the switch:

Searched and replaced all instances of http://www.mydomain with https://www.mydomain using the WP DB Migrate plugin;

Added redirection code at the top of the htaccess file to redirect http to https;

Modified wp-config.php file to force wordpress admin to load as https;

made the canonical URL https://mydomain in the General settings of wordpress.

When I go to the Media section of Wordpress (where the images are kept), most of them are not visible, but again, when the image URL is copied and pasted directly into the browser, they load fine -- and then they are visible on the webpage too (but only to me -- not to other users on other machines).

The SSL itself works fine, and there are no mixed content errors.

答:
I suspected it might be an anti-hotlinking code issue, so I deleted this line from the htaccess file:

```<code>RewriteRule .*\.(jpg|jpeg|gif|png|bmp)$ - [F,NC]
</code>```

Now, images load correctly.

Body:
I suspected it might be an anti-hotlinking code issue, so I deleted this line from the htaccess file:

RewriteRule .*\.(jpg|jpeg|gif|png|bmp)$ - [F,NC]

Now, images load correctly.


问:
What does the pipe character (|) mean when part of a purescript type signature?
I've been unable to figure this out exactly from reading the available docs.

On the record section of the Type docs, it seems to have to do with Row Polymorphism, but I don't understand it's general usage. What does it mean when there is a type signature with a | symbol?

For example:

```<code>class Monad m <= MonadTell w m | m -> w where
  tell :: w -> m Unit
</code>```

答:
The pipe in PureScript is not used "generally". There are multiple uses of it depending on the context. One, as you mentioned, is for type row combinations. Another is for function guards.

The specific syntax you're quoting is called "functional dependency". It is a property of a multi-parameter type class, and it specifies that some variables must be unambiguously determined by others.

In this particular case, the syntax means "for every m there can be only one w".
Or, in plainer language, a given m cannot be MonadTell for several different ws.

Functional dependencies show up in many other places. For example:

```<code>-- For every type `a` there is only one generic representation `rep`
class Generic a rep | a -> rep where

-- Every newtype `t` wraps only one unique inner type `a`
class Newtype t a | t -> a where
</code>```

Body:
I've been unable to figure this out exactly from reading the available docs.

On the record section of the Type docs, it seems to have to do with Row Polymorphism, but I don't understand it's general usage. What does it mean when there is a type signature with a | symbol?

For example:

class Monad m <= MonadTell w m | m -> w where
  tell :: w -> m Unit

Body:
The pipe in PureScript is not used "generally". There are multiple uses of it depending on the context. One, as you mentioned, is for type row combinations. Another is for function guards.

The specific syntax you're quoting is called "functional dependency". It is a property of a multi-parameter type class, and it specifies that some variables must be unambiguously determined by others.

In this particular case, the syntax means "for every m there can be only one w".
Or, in plainer language, a given m cannot be MonadTell for several different ws.

Functional dependencies show up in many other places. For example:

-- For every type `a` there is only one generic representation `rep`
class Generic a rep | a -> rep where

-- Every newtype `t` wraps only one unique inner type `a`
class Newtype t a | t -> a where


Title: Pandas group a column by another column

Body:
[x['B'].values.tolist() for _,x in df.groupby('A')]

Output

[['a', 'b', 'c'], ['d', 'e', 'f']]