问:
Only include grouped observations where event order is valid
I have a table of dates for eye exams and eye wear purchases for individuals. I only want to keep instances where individuals bought their eye wear following an eye exam. In the example below, I would want to keep person 1, events 2 and 3 for person 2, person 3, but not person 4. How can I do this in SQL server?

```<code>| Person | Event  | Order |
|    1   |  Exam  |    1  |
|    1   | Eyewear|    2  |
|    2   | Eyewear|    1  |
|    2   | Exam   |    2  |
|    2   | Eyewear|    3  |
|    3   | Exam   |    1  |
|    3   | Eyewear|    2  |
|    4   | Eyewear|    1  |
|    4   | Exam   |    2  |
</code>```

The final result would look like

```<code>| Person | Event  | Order |
|    1   |  Exam  |    1  |
|    1   | Eyewear|    2  |
|    2   | Exam   |    2  |
|    2   | Eyewear|    3  |
|    3   | Exam   |    1  |
|    3   | Eyewear|    2  |
</code>```

答:
I haven't tried to optimize it but this seems to work:</p>

```<code>create table t(
  person varchar(10),
  event varchar(10),
  [order] varchar(10)
);
insert into t values
('1','Exam','1'),
('1','Eyewear','2'),
('2','Eyewear','1'),
('2','Exam','2'),
('2','Eyewear','3'),
('3','Exam','1'),
('3','Eyewear','2'),
('4','Eyewear','1'),
('4','Exam','2');

with xxx(person,event_a,seq_a,event_b,seq_b) as (
  select a.person,a.event,a.[order],b.event,b.[order]
    from t a join t b
      on a.person = b.person
      and a.[order] < b.[order]
      and a.event like 'exam'
      and b.event like 'eyewear'
  )
select person,event_a event,seq_a [order] from xxx
union
select person,event_b event,seq_b [order] from xxx
  order by 1,3
</code>```

Body:
I have a table of dates for eye exams and eye wear purchases for individuals. I only want to keep instances where individuals bought their eye wear following an eye exam. In the example below, I would want to keep person 1, events 2 and 3 for person 2, person 3, but not person 4. How can I do this in SQL server?

| Person | Event  | Order |
|    1   |  Exam  |    1  |
|    1   | Eyewear|    2  |
|    2   | Eyewear|    1  |
|    2   | Exam   |    2  |
|    2   | Eyewear|    3  |
|    3   | Exam   |    1  |
|    3   | Eyewear|    2  |
|    4   | Eyewear|    1  |
|    4   | Exam   |    2  |

The final result would look like

| Person | Event  | Order |
|    1   |  Exam  |    1  |
|    1   | Eyewear|    2  |
|    2   | Exam   |    2  |
|    2   | Eyewear|    3  |
|    3   | Exam   |    1  |
|    3   | Eyewear|    2  |

Body:
I haven't tried to optimize it but this seems to work:

create table t(
  person varchar(10),
  event varchar(10),
  [order] varchar(10)
);
insert into t values
('1','Exam','1'),
('1','Eyewear','2'),
('2','Eyewear','1'),
('2','Exam','2'),
('2','Eyewear','3'),
('3','Exam','1'),
('3','Eyewear','2'),
('4','Eyewear','1'),
('4','Exam','2');

with xxx(person,event_a,seq_a,event_b,seq_b) as (
  select a.person,a.event,a.[order],b.event,b.[order]
    from t a join t b
      on a.person = b.person
      and a.[order] < b.[order]
      and a.event like 'exam'
      and b.event like 'eyewear'
  )
select person,event_a event,seq_a [order] from xxx
union
select person,event_b event,seq_b [order] from xxx
  order by 1,3


来源: stackexchange

问:
How to run a specific junit test in ant with parameter?
First, I have searched in stackoverflow, the following questions are related to mine, but not exactly what I wanted:

How to run only specific JUnit tests in Ant?

How to run JUnit test cases from the command line

Use Ant for running program with command line arguments

Suppose I have more than 100 test cases: A1Test... A100Test. I can make bachtest of junit in ant to run all of them. But I only want to run, say, A50Test. How I config my build.xml, so that I can run:

```<code>ant test A50Test
</code>```

I don't want to create 100 targets for each of the test.

答:
Introduce property which defines test name you want to execute:

```<code><property name="unit.test" value="*.java" />
</code>```

Use this property in your batchtest:

```<code><batchtest fork="yes" todir="${output.test.dir}">
    <fileset dir="${source.test.dir}" includes="**/${unit.test}"/>
</batchtest>
</code>```

Pass value for this property to ant:

```<code>ant test -Dunit.test=A50Test
</code>```

ContentLicense: CC BY-SA 3.0

Body:
First, I have searched in stackoverflow, the following questions are related to mine, but not exactly what I wanted:

How to run only specific JUnit tests in Ant?

How to run JUnit test cases from the command line

Use Ant for running program with command line arguments

Suppose I have more than 100 test cases: A1Test... A100Test. I can make bachtest of junit in ant to run all of them. But I only want to run, say, A50Test. How I config my build.xml, so that I can run:

ant test A50Test

I don't want to create 100 targets for each of the test.

Body:
Introduce property which defines test name you want to execute:

<property name="unit.test" value="*.java" />

Use this property in your batchtest:

<batchtest fork="yes" todir="${output.test.dir}">
    <fileset dir="${source.test.dir}" includes="**/${unit.test}"/>
</batchtest>

Pass value for this property to ant:

ant test -Dunit.test=A50Test


问:
Is there a way to read a file one line at a time using a different delimiter than VBA's default (vbCr/vbCrLf)?
I am trying to read a multi-line .csv file and put each token inside its own cell within Excel. The issue is that I have no control over the incoming .csv files.

They are all the same in terms of number of columns (variable number of rows, though, but that's easy to account for). However, for whatever reason the source of the .csv files sometimes puts a CRLF at the end of the header line and sometimes it puts only an LF. Again, I have no control over this so I must code around the variability.

As far as I understand, the VBA line Line Input #1, strLine uses either CR or CRLF to delimit lines, which makes sense. I have attempted to place the entire .csv file's contents into a single string and then use Replace strFileContents, vbCr, "" to eliminate all CR characters, but it seems as though this got rid of all later occurrences of CRLF as well and leaves me where I started.

So, is there a way for me to accept one line at a time using Line Input #1, strLine but a LF delimiter? Or is there another way I can manipulate the entire contents of a string (i.e. getting rid of only CR and not the instances of CRLF) and Split() the string from there?

Here is a shortened version of my code:

```<code>Dim Column, Row As Integer 'used Sheets().Input(Row, Column).Value to insert strings
Open strFilePath For Input Access Read As #1
Do Until EOF(1)
    Line Input #1, strLine
    strLine = Split(strLine, vbLf)(1)
    arr = Split(strLine, ",")
    For Column = 1 to 8
        'insert stuff
    Next Column
    Row = Row + 1
Loop
</code>```

However this doesn't quite work for me, and I believe if it did I would still have to deal with the extra CR chars.

Thank you.

答:
```<code>asc(vbLF)=10
asc(vbCR)=13
asc(vbCRLF)=13
</code>```

So Replace vbLF only.

Example

```<code>Sub test()

    Dim strTest  As String

    strTest = "First Line " & vbLf & "Second Line" & vbCrLf & "Third Line" & vbCr & "Fourth Line"
     strTest = Replace(strTest, vbCrLf, vbCr) '/ Gets rid of double line breaks caused by next replacement
    strTest = Replace(strTest, vbLf, vbCr)

    MsgBox strTest

End Sub
</code>```

Body:
I am trying to read a multi-line .csv file and put each token inside its own cell within Excel. The issue is that I have no control over the incoming .csv files.

They are all the same in terms of number of columns (variable number of rows, though, but that's easy to account for). However, for whatever reason the source of the .csv files sometimes puts a CRLF at the end of the header line and sometimes it puts only an LF. Again, I have no control over this so I must code around the variability.

As far as I understand, the VBA line Line Input #1, strLine uses either CR or CRLF to delimit lines, which makes sense. I have attempted to place the entire .csv file's contents into a single string and then use Replace strFileContents, vbCr, "" to eliminate all CR characters, but it seems as though this got rid of all later occurrences of CRLF as well and leaves me where I started.

So, is there a way for me to accept one line at a time using Line Input #1, strLine but a LF delimiter? Or is there another way I can manipulate the entire contents of a string (i.e. getting rid of only CR and not the instances of CRLF) and Split() the string from there?

Here is a shortened version of my code:

Dim Column, Row As Integer 'used Sheets().Input(Row, Column).Value to insert strings
Open strFilePath For Input Access Read As #1
Do Until EOF(1)
    Line Input #1, strLine
    strLine = Split(strLine, vbLf)(1)
    arr = Split(strLine, ",")
    For Column = 1 to 8
        'insert stuff
    Next Column
    Row = Row + 1
Loop

However this doesn't quite work for me, and I believe if it did I would still have to deal with the extra CR chars.

Thank you.

Body:
asc(vbLF)=10
asc(vbCR)=13
asc(vbCRLF)=13

So Replace vbLF only.

Example

Sub test()

    Dim strTest  As String

    strTest = "First Line " & vbLf & "Second Line" & vbCrLf & "Third Line" & vbCr & "Fourth Line"
     strTest = Replace(strTest, vbCrLf, vbCr) '/ Gets rid of double line breaks caused by next replacement
    strTest = Replace(strTest, vbLf, vbCr)

    MsgBox strTest

End Sub


问:
Permanent services on android oreo
Android 8's battery consumption improvements are nice to the user but I am a bit afraid if my service will work as expected.

First of all: Thank you for any suggestions but I cannot just schedule my service. I want to make a OK Google-like keyword listener running in the background all the time. It will be based on the open source pocketsphinx-android library. I know that this will consume much battery power and I will inform the user about this.

Can we create a permanent background service on android 8+ ? I need to target android 8 in gradle because I was expecting some bugs with older targets. I also don't want to annoy a user with a foreground service which permanently shows a notification in the status bar.

[https://developer.android.com/about/versions/oreo/background.html] - Is there really no way of making permanent background services for my use-case (but preferably for all use-cases) possible?

答:
Unfortunately, it's not possible to use a background service and don't show a foreground notification on Android 8.0 and higher.

The only one way that it might work is if you stick your app to Google APIs such as Voice Actions API.

As far as I know there is no a good work around and most apps like WhatsApp are still targetting Android API 24.

Title: Permanent services on android oreo


问:
Spreadsheet Authentication in GData API
I'm trying to edit a gdocs spreadsheet using the GData API. I have the following code:

```<code>    _service = new DocsService("attask-gdocsintegration-1.0");
    _service.setUserCredentials(username, password);

    String feedUrl = "https://docs.google.com/feeds/default/private/full";

    SpreadsheetQuery query = new SpreadsheetQuery(new URL(feedUrl));
    query.setMaxResults(1);
    query.setTitleExact(true);
    query.setTitleQuery(title);
    SpreadsheetFeed feed = _service.getFeed(query, SpreadsheetFeed.class);

    if(feed.getEntries().size() != 1) {
        throw new FileNotFoundException("'"+title+"' not a spreadsheet");
    }
    _entry = feed.getEntries().get(0);
    List<WorksheetEntry> worksheets = _entry.getWorksheets();
</code>```

however, on the last line of that block, it throws an exception:

```<code>Exception in thread "main" com.google.gdata.util.AuthenticationException: Unauthorized
<HTML>
<HEAD>
<TITLE>Unauthorized</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Unauthorized</H1>
<H2>Error 401</H2>
</BODY>
</HTML>

    at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:600)
    ...
</code>```

The username/password are correct, and seems to authenticate fine to query my documents, but soon as I try to get the worksheet it fails. Any ideas of what I'm missing here?

答:
after some more trial and error I found that the feed URL was incorrect. Here's what I had to change:

changed:

```<code>String feedUrl = "https://docs.google.com/feeds/default/private/full";
</code>```

to:

```<code>String feedUrl = "https://spreadsheets.google.com/feeds/spreadsheets/private/full";
</code>```

and it worked.

ContentLicense: CC BY-SA 2.5

Title: Spreadsheet Authentication in GData API

Body:
I'm trying to edit a gdocs spreadsheet using the GData API. I have the following code:

    _service = new DocsService("attask-gdocsintegration-1.0");
    _service.setUserCredentials(username, password);

    String feedUrl = "https://docs.google.com/feeds/default/private/full";

    SpreadsheetQuery query = new SpreadsheetQuery(new URL(feedUrl));
    query.setMaxResults(1);
    query.setTitleExact(true);
    query.setTitleQuery(title);
    SpreadsheetFeed feed = _service.getFeed(query, SpreadsheetFeed.class);

    if(feed.getEntries().size() != 1) {
        throw new FileNotFoundException("'"+title+"' not a spreadsheet");
    }
    _entry = feed.getEntries().get(0);
    List<WorksheetEntry> worksheets = _entry.getWorksheets();

however, on the last line of that block, it throws an exception:

Exception in thread "main" com.google.gdata.util.AuthenticationException: Unauthorized

<TITLE>Unauthorized</TITLE>

Unauthorized

Error 401

    at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:600)
    ...

The username/password are correct, and seems to authenticate fine to query my documents, but soon as I try to get the worksheet it fails. Any ideas of what I'm missing here?

Body:
after some more trial and error I found that the feed URL was incorrect. Here's what I had to change:

changed:

String feedUrl = "https://docs.google.com/feeds/default/private/full";

to:

String feedUrl = "https://spreadsheets.google.com/feeds/spreadsheets/private/full";

and it worked.


问:
When appending a python variable to a list I am getting object values
```<code>print("Device discovered: %s" % remote)
m.append(remote)
print(m)
</code>```

I am getting the following result. How Can I get same value is the list names m

```<code>Device discovered: 0013A20041481642 - REMOTE
[<digi.xbee.devices.RemoteZigBeeDevice object at 0x7f42c312ceb8>]
</code>```

答:
List contents use the repr() result of the objects contained, which in turn uses the __repr__ method on an object.

print() converts objects with str(), which will use a __str__ method, if present, __repr__ otherwise.

You remote object (a digi.xbee.devices.RemoteZigBeeDevice instance) only has a __str__ method, and no __repr__ method. Implement the latter to customise how your object is shown in a list.

Alternatively, print all individual values in the list with:

```<code>print(*m)
</code>```

These are then space separated, use sep='...' to specify a different separator.

Or you could convert all the objects in the list to a string before printing:

```<code>print([str(obj) for obj in m])
</code>```

and print the list of strings.

Body:
print("Device discovered: %s" % remote)
m.append(remote)
print(m)

I am getting the following result. How Can I get same value is the list names m

Device discovered: 0013A20041481642 - REMOTE
[<digi.xbee.devices.RemoteZigBeeDevice object at 0x7f42c312ceb8>]

Body:
List contents use the repr() result of the objects contained, which in turn uses the __repr__ method on an object.

print() converts objects with str(), which will use a __str__ method, if present, __repr__ otherwise.

You remote object (a digi.xbee.devices.RemoteZigBeeDevice instance) only has a __str__ method, and no __repr__ method. Implement the latter to customise how your object is shown in a list.

Alternatively, print all individual values in the list with:

print(*m)

These are then space separated, use sep='...' to specify a different separator.

Or you could convert all the objects in the list to a string before printing:

print([str(obj) for obj in m])

and print the list of strings.


问:
Standardization before or after categorical encoding?
I'm working on a regression algorithm, in this case k-NearestNeighbors to predict a certain price of a product.

So I have a Training set which has only one categorical feature with 4 possible values. I've dealt with it using a one-to-k categorical encoding scheme which means now I have 3 more columns in my Pandas DataFrame with a 0/1 depending the value present.

The other features in the DataFrame are mostly distances like latitud - longitude for locations and prices, all numerical.

Should I standardize (Gaussian distribution with zero mean and unit variance) and normalize before or after the categorical encoding?

I'm thinking it might be benefitial to normalize after encoding so that every feature is to the estimator as important as every other when measuring distances between neighbors but I'm not really sure.

答: You generally want to standardize all your features so it would be done after the encoding (that is assuming that you want to standardize to begin with, considering that there are some machine learning algorithms that do not need features to be standardized to work well).</p>


问:
eval $(docker-machine env myvm1) does not switch to shell to talk to myvm1
Folks,

I'm following the Docker tutorial here: https://docs.docker.com/get-started/part4/#configure-a-docker-machine-shell-to-the-swarm-manager and coming up against resistance when running this particular command:

```<code>eval $(docker-machine env myvm1)
</code>```

I'm actually running (as above but with addition of sudo).

```<code>eval $(sudo docker-machine env myvm1)
</code>```

I get no output from the command line to tell me anything has been done and when I run:

```<code>sudo docker-machine ls
</code>```

I see that myvm1 does not have an active state as expected. I do know that this step isn't necessary but I'd like to understand why the command is not working and try to fix it.

I am running docker 17.09.0-ce

On Ubuntu 16.04 LTS

zsh shell (have tried switching to bash)

This is just on my local machine by the way, not a server.

Any help would be much appreciated.

答:
There's less to go wrong if you run the eval on the far side of sudo:

```<code>sudo sh -c 'eval "$(docker-machine env myvm1)"; docker-machine ls'
</code>```

Otherwise, the environment variables set by evaling the output of docker-machine env aren't necessarily (barring some very specific /etc/sudoers configuration) propagated through to the future docker-machine invocation.

If you wanted to automate this with a shell function, that can be done:

```<code># docker-env sudo; usage: desudo vm-name command-to-run
desudo() {
  local cmd1 cmd2
  printf -v cmd1 'eval "$(docker-machine env %q)"' "$1"; shift
  printf -v cmd2 '%q ' "$@"
  sudo bash -c "${cmd1} && exec ${cmd2}"
}
</code>```

...used as:

```<code>desudo vm1 docker-machine ls
</code>```

Body:
Folks,

I'm following the Docker tutorial here: https://docs.docker.com/get-started/part4/#configure-a-docker-machine-shell-to-the-swarm-manager and coming up against resistance when running this particular command:

eval $(docker-machine env myvm1)

I'm actually running (as above but with addition of sudo).

eval $(sudo docker-machine env myvm1)

I get no output from the command line to tell me anything has been done and when I run:

sudo docker-machine ls

I see that myvm1 does not have an active state as expected. I do know that this step isn't necessary but I'd like to understand why the command is not working and try to fix it.

I am running docker 17.09.0-ce

On Ubuntu 16.04 LTS

zsh shell (have tried switching to bash)

This is just on my local machine by the way, not a server.

Any help would be much appreciated.

Body:
There's less to go wrong if you run the eval on the far side of sudo:

sudo sh -c 'eval "$(docker-machine env myvm1)"; docker-machine ls'

Otherwise, the environment variables set by evaling the output of docker-machine env aren't necessarily (barring some very specific /etc/sudoers configuration) propagated through to the future docker-machine invocation.

If you wanted to automate this with a shell function, that can be done:

# docker-env sudo; usage: desudo vm-name command-to-run
desudo() {
  local cmd1 cmd2
  printf -v cmd1 'eval "$(docker-machine env %q)"' "$1"; shift
  printf -v cmd2 '%q ' "$@"
  sudo bash -c "${cmd1} && exec ${cmd2}"
}

...used as:

desudo vm1 docker-machine ls


问:
making a constant heading - css issue
I have an AJAX application which has used CSS divs to create panels on the screen, which are loaded separately and in succession, depending on what was loaded before it. The bottom "panel" is a table showing a list or records from a database. At the top of the database is the name of the table, and I would like a way to have it be always above the list of records. I am unsure of how to do this, if it is with Javascript, or PHP, or css and html.

edit: I tried wrapping the table header in a div and setting the css for this purpose, but the table header does not seem to be in its own header and does not stay on screen separate from the records.

```<code>.tableheader {
    position: absolute;
}
</code>```

and

```<code>$table = 'AUCTIONS';

$rows = getRowsByArticleSearch($query, $table);

echo '<div id="tableheader" class="tableheader">';

echo "<h1>{$query} Auctions</h1>" . "\n";
echo "</div>";
</code>```

Have I missed something fundamental here?

答:
I assume you mean to be able to scroll the table without moving the header?

I think your easiest option is the CSS overflow property.

```<code><style type="text/css">
  div#dblist {
    overflow: scroll;
    height: 400px;
  }
</style>

<!-- ... -->

<div>Database Title</div>
<div id="dblist">
  <table>
    <!-- ... -->
  </table>
</div>
</code>```

@Joshxtothe4: It sounds like you've got scrolling set to the wrong element:

```<code><div> <!-- sounds like you have it set here -->
  <div><h1>Query Archive</h1></div>
  <div> <!-- and want it set here -->
    <table>
      <!-- ... -->
    </table>
  </div>
</div>
</code>```

You shouldn't need absolute positioning for this.

Title: making a constant heading - css issue

Body:
I have an AJAX application which has used CSS divs to create panels on the screen, which are loaded separately and in succession, depending on what was loaded before it. The bottom "panel" is a table showing a list or records from a database. At the top of the database is the name of the table, and I would like a way to have it be always above the list of records. I am unsure of how to do this, if it is with Javascript, or PHP, or css and html.

edit: I tried wrapping the table header in a div and setting the css for this purpose, but the table header does not seem to be in its own header and does not stay on screen separate from the records.

.tableheader {
    position: absolute;
}

and

$table = 'AUCTIONS';

$rows = getRowsByArticleSearch($query, $table);

echo '
';

echo "
{$query} Auctions
" . "\n";
echo "
";

Have I missed something fundamental here?

Body:
I assume you mean to be able to scroll the table without moving the header?

I think your easiest option is the CSS overflow property.

<style type="text/css">
  div#dblist {
    overflow: scroll;
    height: 400px;
  }
</style>

<!-- ... -->

<div>Database Title</div>
<div id="dblist">
  <table>
    <!-- ... -->
  </table>
</div>

@Joshxtothe4: It sounds like you've got scrolling set to the wrong element:

<div> <!-- sounds like you have it set here -->
  <div><h1>Query Archive</h1></div>
  <div> <!-- and want it set here -->
    <table>
      <!-- ... -->
    </table>
  </div>
</div>

You shouldn't need absolute positioning for this.

OwnerDisplayName: Jonathan Lonowski

LastEditorDisplayName: Jonathan Lonowski


问:
How do I simulate drag and drop in enzyme testcase?
I am trying to create a test for simulating a dragging of an image into a div. I am clueless on how to achieve this. Any help is much appreciated.

```<code>it('test drag and drop', () => {
    const app = mount(<App />);
    const loco = app.find('.app img');
    const dropTarget = app.find('.drop-target');
    let mockEvent = { dataTransfer: { type: 'test' } };
    loco.simulate('drag', mockEvent);
    //loco.simulate('dragover', dropTarget, mockEvent);
    //loco.simulate('drop', dropTarget, mockEvent);
});
</code>```

I am trying to simulate the drop event, not sure how to do as 2 elements are involved in it.

Thanks,
Saud

答:
What DnD Component do you use? React-Dnd?
Maybe this issue on Github can help you.
Or maybe this article about testing Drag&Drop via Jest.</p>

Body:
I am trying to create a test for simulating a dragging of an image into a div. I am clueless on how to achieve this. Any help is much appreciated.

it('test drag and drop', () => {
    const app = mount(<App />);
    const loco = app.find('.app img');
    const dropTarget = app.find('.drop-target');
    let mockEvent = { dataTransfer: { type: 'test' } };
    loco.simulate('drag', mockEvent);
    //loco.simulate('dragover', dropTarget, mockEvent);
    //loco.simulate('drop', dropTarget, mockEvent);
});

I am trying to simulate the drop event, not sure how to do as 2 elements are involved in it.

Thanks,
Saud


问:
Converting a String to DateTime with new format
How do you convert a string such as 13.11.2017 into a DateTime with that format 13/11/2017

I tried several ways but i didn't get solution  .

```<code>string Arrival = Request.QueryString["Arrival"];//13.11.2017
DateTime datee = DateTime.ParseExact(Arrival , "dd/MM/yyyy", null);
</code>```

here is updated code i split the string :

```<code>            string Arrival = Request.QueryString["Arrival"];//13.11.2017
      string year = Arrival.Split('.')[2];
                   string month = Arrival.Split('.')[1];
                        string day = Arrival.Split('.')[0];
                        string date = day + "/" + month + "/" + year;
                        DateTime datee = DateTime.ParseExact(date, "dd/MM/yyyy", null);
</code>```

答:
Observe:

```<code>// the input string
string inputString = "13.11.2017";

// parse the input string with a specific format to create a DateTime
DateTime dt = DateTime.ParseExact(inputString, "dd.MM.yyyy", CultureInfo.InvariantCulture);

// create a string from the DateTime using a different specific format
string outputString = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

// output the string
Console.WriteLine(outputString);  // "13/11/2017"
</code>```

Note that a DateTime itself does not have any particular format.  A format only comes into play when going to or from a string.

Also note that by using the invariant culture here, we are avoiding any issues that may arise if the current culture was one that used different date separators or a different calendar system.

Body:
How do you convert a string such as 13.11.2017 into a DateTime with that format 13/11/2017

I tried several ways but i didn't get solution  .

string Arrival = Request.QueryString["Arrival"];//13.11.2017
DateTime datee = DateTime.ParseExact(Arrival , "dd/MM/yyyy", null);

here is updated code i split the string :

            string Arrival = Request.QueryString["Arrival"];//13.11.2017
      string year = Arrival.Split('.')[2];
                   string month = Arrival.Split('.')[1];
                        string day = Arrival.Split('.')[0];
                        string date = day + "/" + month + "/" + year;
                        DateTime datee = DateTime.ParseExact(date, "dd/MM/yyyy", null);

Body:
Observe:

// the input string
string inputString = "13.11.2017";

// parse the input string with a specific format to create a DateTime
DateTime dt = DateTime.ParseExact(inputString, "dd.MM.yyyy", CultureInfo.InvariantCulture);

// create a string from the DateTime using a different specific format
string outputString = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);

// output the string
Console.WriteLine(outputString);  // "13/11/2017"

Note that a DateTime itself does not have any particular format.  A format only comes into play when going to or from a string.

Also note that by using the invariant culture here, we are avoiding any issues that may arise if the current culture was one that used different date separators or a different calendar system.


问:
Using JS or AJAX to live search filter through JSON object on page (laravel)
I'm new to AJAX and a lot of JS, but I need to replace some old angular functionality on our Laravel site.

We simply have a page with a static/sticky header search bar, but no submit button. It needs to do a live filter upon search input. i.e. if I type sofa, it should hide anything from the page without the word sofa.

The Laravel blade/HTML is built with foreach loops from controller data, but more importantly, the data is stored in a JSON object called orderFormData, shown below.

I need a simple and effective live search filter to hide anything that doesn't match between the JSON and the search bar. The page is built with multiple HTML tables so I don't want to filter by the table and I think that's too complicated and convoluted. It should suffice to do it by JSON, possibly with AJAX. However, I'm a total novice here and I'm desperate for a solution.

Here's the search html:

```<code><div class="md-input-wrapper search-form">
            <form class="uk-search" id="searchProducts">
                <input type="text" class="md-input label-fixed" name="srch-term" id="srch-term" autofocus placeholder="Search Products"/>
                <span class="md-input-bar"></span>

            </form>
        </div>
</code>```

Here's the JSON object and some JS that I was playing with, but it doesn't work:

```<code><script type = "text/javascript">
var orderFormData = <?php echo json_encode ($tempdata);?>;

$(document).ready(function(){
$('#srch-term').on('keyup',function(){
    var searchTerm = $(this).val().toLowerCase();
    $('.uk-table tbody tr').each(function(){
        var lineStr = $(this).text().toLowerCase();
        if(lineStr.indexOf(searchTerm) === -1){
            $(this).hide();
        }else{
            $(this).show();
        }
      });
  });
});
</script>
</code>```

This is just a pure JS idea, but I'm interested in AJAX as well if it will work better for this scenario. How can I properly filter items on the page by tying the search bar and JSON object?

答:
You don't need of Ajax to do a search function with hide and show, this is simply manipulating DOM, instead ajax can calls the json from the php and with jquery you can simple loop your td on keypress and use :contains of jquery, onkeypress you call a function and in this function you do show and hide if contains "search" show otherwise hide.
Here a simple example in one of my old project #tabellaWebLog was the id of the table ricercaUser was the id of the input search and trTabellaWebLog was the id of the row where i wanted the search instead .ricUser was the class of the table column to loop the search inside the table...Bye </p>

```<code>user = $('#ricercaUser').val();
$('#tabellaWebLog').find("#TrTabellaWebLogRiga:not(:contains('"+ user +"'))").hide();
$(".ricUser:contains('" + user + "')").parent().show();
$(".ricUser:not(:contains('" + user + "'))").parent().hide();
</code>```

Body:
I'm new to AJAX and a lot of JS, but I need to replace some old angular functionality on our Laravel site.

We simply have a page with a static/sticky header search bar, but no submit button. It needs to do a live filter upon search input. i.e. if I type sofa, it should hide anything from the page without the word sofa.

The Laravel blade/HTML is built with foreach loops from controller data, but more importantly, the data is stored in a JSON object called orderFormData, shown below.

I need a simple and effective live search filter to hide anything that doesn't match between the JSON and the search bar. The page is built with multiple HTML tables so I don't want to filter by the table and I think that's too complicated and convoluted. It should suffice to do it by JSON, possibly with AJAX. However, I'm a total novice here and I'm desperate for a solution.

Here's the search html:

            <form class="uk-search" id="searchProducts">
                <input type="text" class="md-input label-fixed" name="srch-term" id="srch-term" autofocus placeholder="Search Products"/>

            </form>

Here's the JSON object and some JS that I was playing with, but it doesn't work:

This is just a pure JS idea, but I'm interested in AJAX as well if it will work better for this scenario. How can I properly filter items on the page by tying the search bar and JSON object?

Body:
You don't need of Ajax to do a search function with hide and show, this is simply manipulating DOM, instead ajax can calls the json from the php and with jquery you can simple loop your td on keypress and use :contains of jquery, onkeypress you call a function and in this function you do show and hide if contains "search" show otherwise hide.
Here a simple example in one of my old project #tabellaWebLog was the id of the table ricercaUser was the id of the input search and trTabellaWebLog was the id of the row where i wanted the search instead .ricUser was the class of the table column to loop the search inside the table...Bye

user = $('#ricercaUser').val();
$('#tabellaWebLog').find("#TrTabellaWebLogRiga:not(:contains('"+ user +"'))").hide();
$(".ricUser:contains('" + user + "')").parent().show();
$(".ricUser:not(:contains('" + user + "'))").parent().hide();


问:
SQL Server - Get the Latest Date With Grouping
I am running a problem with SQL Server query that I couldn't figure out how to get it works correctly. I try to get the MAX date based on the Category grouped. I know it sounds confused, so let me explain what the result I want.

Let's say I have this table:

```<code>Table1
Category    Value   UpdatedDateTime
Cat1        5       2017-11-12 10:46
Cat1        2       2017-11-13 11:46
Cat1        4       2017-11-13 10:46
Cat2        5       2017-11-12 10:46
Cat2        7       2017-11-12 11:46
Cat2        3       2017-11-13 09:46
Cat3        1       2017-11-12 10:46
Cat3        2       2017-11-12 11:46
Cat3        7       2017-11-13 11:46
Cat3        8       2017-11-13 10:46
Cat3        3       2017-11-10 10:46
Cat4        4       2017-11-13 10:46
Cat4        4       2017-11-12 10:46
</code>```

I want the UpdatedDateTime in the result to pick the latest date by the Category grouping like this:

```<code>Category    Value   UpdatedDateTime
Cat1        5       2017-11-13 11:46
Cat1        2       2017-11-13 11:46
Cat1        4       2017-11-13 11:46
Cat2        5       2017-11-13 09:46
Cat2        7       2017-11-13 09:46
Cat2        3       2017-11-13 09:46
Cat3        1       2017-11-13 11:46
Cat3        2       2017-11-13 11:46
Cat3        7       2017-11-13 11:46
Cat3        8       2017-11-13 11:46
Cat3        3       2017-11-13 11:46
Cat4        4       2017-11-13 10:46
Cat4        4       2017-11-13 10:46
</code>```

I tried this query, but of course it doesn't work because I was looking for the Max(UpdatedDate) for the entire table, not by Category.  Then I got stuck.

```<code>With cte AS
(
    Select Category, Value, UpdatedDateTime FROM Table1
)
Select Category, Sum(Value)
, (Select Top 1 Max(UpdatedDateTime) FORM cte) AS UpdatedDateTime
FROM cte
Group By Category
</code>```

Please help, thanks in advance.

答:
Try this, you always get the latest row in each Category</p>

```<code>SELECT * FROM
    (SELECT ROW_NUMBER()
       OVER (PARTITION BY Category ORDER BY UpdatedDateTime DESC) AS RowNum,
    * FROM Table1) AS Table2 WHERE RowNum = 1
</code>```

Body:
I am running a problem with SQL Server query that I couldn't figure out how to get it works correctly. I try to get the MAX date based on the Category grouped. I know it sounds confused, so let me explain what the result I want.

Let's say I have this table:

Table1
Category    Value   UpdatedDateTime
Cat1        5       2017-11-12 10:46
Cat1        2       2017-11-13 11:46
Cat1        4       2017-11-13 10:46
Cat2        5       2017-11-12 10:46
Cat2        7       2017-11-12 11:46
Cat2        3       2017-11-13 09:46
Cat3        1       2017-11-12 10:46
Cat3        2       2017-11-12 11:46
Cat3        7       2017-11-13 11:46
Cat3        8       2017-11-13 10:46
Cat3        3       2017-11-10 10:46
Cat4        4       2017-11-13 10:46
Cat4        4       2017-11-12 10:46

I want the UpdatedDateTime in the result to pick the latest date by the Category grouping like this:

Category    Value   UpdatedDateTime
Cat1        5       2017-11-13 11:46
Cat1        2       2017-11-13 11:46
Cat1        4       2017-11-13 11:46
Cat2        5       2017-11-13 09:46
Cat2        7       2017-11-13 09:46
Cat2        3       2017-11-13 09:46
Cat3        1       2017-11-13 11:46
Cat3        2       2017-11-13 11:46
Cat3        7       2017-11-13 11:46
Cat3        8       2017-11-13 11:46
Cat3        3       2017-11-13 11:46
Cat4        4       2017-11-13 10:46
Cat4        4       2017-11-13 10:46

I tried this query, but of course it doesn't work because I was looking for the Max(UpdatedDate) for the entire table, not by Category.  Then I got stuck.

With cte AS
(
    Select Category, Value, UpdatedDateTime FROM Table1
)
Select Category, Sum(Value)
, (Select Top 1 Max(UpdatedDateTime) FORM cte) AS UpdatedDateTime
FROM cte
Group By Category

Please help, thanks in advance.

Body:
Try this, you always get the latest row in each Category

SELECT * FROM
    (SELECT ROW_NUMBER()
       OVER (PARTITION BY Category ORDER BY UpdatedDateTime DESC) AS RowNum,
    * FROM Table1) AS Table2 WHERE RowNum = 1


问:
Make sure GtkWindow fits all children
How do I make sure my GtkWindow fits all children?

As you can see, currently my GtkWindow can shrink to the point the children do not fit in it.

I have been browsing the documentation, but there doesn't even seem to be a way to hard-code the minimum size, let alone let it dynamically depend on the size of my children.

The UI is written in XML and loaded using GtkBuilder.

答:
As @JoséFonte pointed out in the comments, I had to disable shrinking for all children of my GtkPaned.

To achieve this I used Glade, and then for each child opened its properties, went to the packing tab, and disabled Shrink.

Title: Make sure GtkWindow fits all children


问:
fitting geom_smooth() to multiple categories in ggplot2
I have some data which looks like:

```<code>sample  diff    chromosome  haploid coverage
B   90.9963099631   7   b   0.513
A   91.7019475021   12  a   8.234
C   90.3855783676   14  a   6.211
D   91.3407821229   17  b   4.321
E   91.5740740741   11  b   0.213
F   90.9963099631   7   b   0.513
G   91.7019475021   12  a   8.234
H   90.3855783676   14  a   6.211
I   91.3407821229   17  b   4.321
J   91.5740740741   11  b   0.213
</code>```

And I want to visualise the change for 'diff' for different coverage value, across different chromosomes, so I did this:

```<code>plot = ggplot(dat, aes(x = coverage, y = diff, group  = chromosome, colour = chromosome, ylim(0, 100)) ) + geom_point(colour = chromosome) + stat_smooth(se=FALSE) + ylim(0, 100)

`geom_smooth()` using method = 'loess'
</code>```

Now I think this isn't the best way to draw mutliple trendlines, but I produced this:

Which is kind of what I'm after. But I think in reality, all the curves shouldn't be exactly the same shape given my data, but the shape of all of them is basically identical. So has geom_smooth() plot a single LOWESS curve for all categories and then just shifted the same curve up and down for different categories?

If so, is there a way to make it plot independent lines for each category?

答:
Cannot replicate your plot with the code you have provided.
However, the correct syntax to obtain what you're looking for is the following, using the mtcars dataset.

```<code>library(ggplot2)

df = mtcars

df$cyl = factor(df$cyl)

ggplot(df, aes(x = mpg, y = disp, colour = cyl, group = cyl)) +
  geom_point() +
  geom_smooth(se=F)
</code>```

Try to adjust your example / dataset on this code.

Body:
I have some data which looks like:

sample  diff    chromosome  haploid coverage
B   90.9963099631   7   b   0.513
A   91.7019475021   12  a   8.234
C   90.3855783676   14  a   6.211
D   91.3407821229   17  b   4.321
E   91.5740740741   11  b   0.213
F   90.9963099631   7   b   0.513
G   91.7019475021   12  a   8.234
H   90.3855783676   14  a   6.211
I   91.3407821229   17  b   4.321
J   91.5740740741   11  b   0.213

And I want to visualise the change for 'diff' for different coverage value, across different chromosomes, so I did this:

plot = ggplot(dat, aes(x = coverage, y = diff, group  = chromosome, colour = chromosome, ylim(0, 100)) ) + geom_point(colour = chromosome) + stat_smooth(se=FALSE) + ylim(0, 100)

`geom_smooth()` using method = 'loess'

Now I think this isn't the best way to draw mutliple trendlines, but I produced this:

Which is kind of what I'm after. But I think in reality, all the curves shouldn't be exactly the same shape given my data, but the shape of all of them is basically identical. So has geom_smooth() plot a single LOWESS curve for all categories and then just shifted the same curve up and down for different categories?

If so, is there a way to make it plot independent lines for each category?

Body:
Cannot replicate your plot with the code you have provided.
However, the correct syntax to obtain what you're looking for is the following, using the mtcars dataset.

library(ggplot2)

df = mtcars

df$cyl = factor(df$cyl)

ggplot(df, aes(x = mpg, y = disp, colour = cyl, group = cyl)) +
  geom_point() +
  geom_smooth(se=F)

Try to adjust your example / dataset on this code.


问:
C# Date Converter Program
This will be a noobish question but I am currently working on a program that will take in a user input in the format of DD/MM/YYYY and the output it in the format 1st of May 2017, for example.

But whenever the use string.substring (UserInput.substring in my case) it does not separate the values correctly. For example, when I input the date as 21/05/2001 it displays 215 2001. I have no idea why this is happening.

Im sorry as this is very noobish but I am new to using .substring and I'm sure the problem will seem obvious when someone points it out xD

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            /// Define Varibles

            string UserIntput;
            int Day;
            int Month;
            int year;

            ///Gathering UserInput

            Console.Write("Please enter the date in the format dd/mm/yyyy");
            UserIntput = Console.ReadLine();

            ///Validations

            try
            {
                while(UserIntput.Substring(2,1) != "/" || UserIntput.Substring(5,1) != "/" || UserIntput.Length != 10)
                {
                    Console.WriteLine("Invalid Input");
                    Console.Write("Please enter the date in the format dd/mm/yyyy");
                    UserIntput = Console.ReadLine();

                }

            }
            catch
            {
                Console.WriteLine("Invalid Input");
            }

            /// Defining to Variables

            Day = Convert.ToInt32(UserIntput.Substring(0, 2));

            Month = Convert.ToInt32(UserIntput.Substring(3, 2));

            year = Convert.ToInt32(UserIntput.Substring(6, 4));

            Console.WriteLine(Day + "" + Month + " " + year);
            Console.ReadLine();
        }
    }
}
</code>```

答:
Assuming you want to keep your current approach (instead of using any of the built-in functions provided in the other answers), your problem is just a typo.

Change this:

```<code>Console.WriteLine(Day + "" + Month + " " + year);
</code>```

To this:

```<code>Console.WriteLine(Day + " " + Month + " " + year);  //Notice the space
</code>```

In the future, you can avoid this sort of problem by using a constant:

```<code>const string space = " ";
Console.WriteLine(Day + space + Month + space + year);
</code>```

Title: C# Date Converter Program

Body:
This will be a noobish question but I am currently working on a program that will take in a user input in the format of DD/MM/YYYY and the output it in the format 1st of May 2017, for example.

But whenever the use string.substring (UserInput.substring in my case) it does not separate the values correctly. For example, when I input the date as 21/05/2001 it displays 215 2001. I have no idea why this is happening.

Im sorry as this is very noobish but I am new to using .substring and I'm sure the problem will seem obvious when someone points it out xD

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            /// Define Varibles

            string UserIntput;
            int Day;
            int Month;
            int year;

            ///Gathering UserInput

            Console.Write("Please enter the date in the format dd/mm/yyyy");
            UserIntput = Console.ReadLine();

            ///Validations

            try
            {
                while(UserIntput.Substring(2,1) != "/" || UserIntput.Substring(5,1) != "/" || UserIntput.Length != 10)
                {
                    Console.WriteLine("Invalid Input");
                    Console.Write("Please enter the date in the format dd/mm/yyyy");
                    UserIntput = Console.ReadLine();

                }

            }
            catch
            {
                Console.WriteLine("Invalid Input");
            }

            /// Defining to Variables

            Day = Convert.ToInt32(UserIntput.Substring(0, 2));

            Month = Convert.ToInt32(UserIntput.Substring(3, 2));

            year = Convert.ToInt32(UserIntput.Substring(6, 4));

            Console.WriteLine(Day + "" + Month + " " + year);
            Console.ReadLine();
        }
    }
}

Body:
Assuming you want to keep your current approach (instead of using any of the built-in functions provided in the other answers), your problem is just a typo.

Change this:

Console.WriteLine(Day + "" + Month + " " + year);

To this:

Console.WriteLine(Day + " " + Month + " " + year);  //Notice the space

In the future, you can avoid this sort of problem by using a constant:

const string space = " ";
Console.WriteLine(Day + space + Month + space + year);


问:
How to update foreign key referenced table using trigger, in SQL Server?
Say I have these tables:

```<code>CREATE TABLE person
(
    person_id INT NOT NULL PRIMARY KEY,
    name VARCHAR NOT NULL,
    phone INT,
);

CREATE TABLE volunteers
(
    person_id INT NOT NULL PRIMARY KEY,
    skill VARCHAR,
    FOREIGN KEY (person_id) REFERENCES person(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);
</code>```

Could I create a trigger on volunteers that could insert into person table when I insert a new record in volunteers table.

Like this:

```<code>INSERT INTO volunteers (person_id, name, skill)
VALUES (12345, 'abc xyz', 'cooking');
</code>```

If not using trigger, is there any alternatives?

答:
I'm not going to write the code for you, but you can do the following:

Create a view with all the columns you want, joining the tables.

Write an instead of trigger to update the view

The use of such triggers on views is defined in the documentation.

The view would look like:

```<code>create view v_volunteers as
    select v.person_id, p.name, v.skill
    from volunteers v join
         people p
         on p.person_id = v.person_id;
</code>```

Body:
Say I have these tables:

CREATE TABLE person
(
    person_id INT NOT NULL PRIMARY KEY,
    name VARCHAR NOT NULL,
    phone INT,
);

CREATE TABLE volunteers
(
    person_id INT NOT NULL PRIMARY KEY,
    skill VARCHAR,
    FOREIGN KEY (person_id) REFERENCES person(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

Could I create a trigger on volunteers that could insert into person table when I insert a new record in volunteers table.

Like this:

INSERT INTO volunteers (person_id, name, skill)
VALUES (12345, 'abc xyz', 'cooking');

If not using trigger, is there any alternatives?

Body:
I'm not going to write the code for you, but you can do the following:

Create a view with all the columns you want, joining the tables.

Write an instead of trigger to update the view

The use of such triggers on views is defined in the documentation.

The view would look like:

create view v_volunteers as
    select v.person_id, p.name, v.skill
    from volunteers v join
         people p
         on p.person_id = v.person_id;


问:
Unable to dismiss keyboard with UITextField
I cannot get textFieldShouldEndEditing to call. I have re created the links in interface builder and tried, but nothing seems to work. Any idea why this would not be called?

Edit

I am implementing both -textFieldShouldEndEditing and -textFieldDidFinishEditing. Adding the delegate for the textField didnt help either. The code I am using below is not triggering the log messages.

```<code>-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    NSLog(@"Done editing...");
    [textField resignFirstResponder];
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    NSLog(@"Done editing...");
}
</code>```

答:
Don't use -textFieldDidEndEditing. That gets called after the text field resigns first responder... which it hasn't yet because you haven't told it to because that method hasn't been called yet because first responder hasn't been resigned because you haven't told it to yet. Circular, chicken-and-egg sort of problem.

The delegate method you want is -textFieldShouldReturn. That gets called when the "return" key is pressed. Inside that, tell the text field to resign first responder, then return YES.

Also put a big clear custom button behind your form, and hook its touch-up-inside to a method that goes through all the text fields in the form and resigns first responder on each of them. So a background touch releases the keyboard too.

Body:
I cannot get textFieldShouldEndEditing to call. I have re created the links in interface builder and tried, but nothing seems to work. Any idea why this would not be called?

Edit

I am implementing both -textFieldShouldEndEditing and -textFieldDidFinishEditing. Adding the delegate for the textField didnt help either. The code I am using below is not triggering the log messages.

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    NSLog(@"Done editing...");
    [textField resignFirstResponder];
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    NSLog(@"Done editing...");
}


问:
Tomcat session timeout in 1 minute
I have a web application that has a timeout of 1 minute in its web.xml but it never times out for this value.It does timeout for other values such as 5,9,10 or 25 minutes but never for 1 minute. Is this a minimum session timeout restriction on Tomcat 8?</p>

```<code>    <!-- Session Configuration --> <session-config>
    <session-timeout>1</session-timeout> </session-config>
</code>```

答: It works for me, in my case is a global configuration, try to change it TOMCAT_HOME/conf/web.xml</p>

Title: Tomcat session timeout in 1 minute

Body:
I have a web application that has a timeout of 1 minute in its web.xml but it never times out for this value.It does timeout for other values such as 5,9,10 or 25 minutes but never for 1 minute. Is this a minimum session timeout restriction on Tomcat 8?

     <session-config>
    <session-timeout>1</session-timeout> </session-config>


问:
making the following VBA code more efficient
I'm trying to delete rows that include any of the values specified. The below code worked in a sheet with ~200k rows but excel crashes when I try to run it in a sheet with 350k rows. How to make it more efficient?</p>

```<code>    Sub MultiDelete()

    With Application
    .ScreenUpdating = False
    .DisplayAlerts = False
    End With

    Range("A1").Activate 'change to suit the column containing the names
    Dim MultiDelete
    MultiDelete = Array("Name1", "Name2", "Name3") 'put as many names as you like in the array
    Dim G As Variant
    While ActiveCell.Value <> ""
    G = Filter(MultiDelete, ActiveCell.Value)
    If UBound(G) <> -1 Then
        Selection.EntireRow.Delete
    Else
        ActiveCell.Offset(1, 0).Activate
   End If
    Wend
    With Application
    .ScreenUpdating = True
    .DisplayAlerts = True
    End With
    End Sub
</code>```

答:
Your current code is pretty much doing the most inefficient thing possible: selecting and filtering 350k rows one at a time to see if they match items in an array.

Instead, add an autofilter (or convert the range into an Excel Table/ListObject, as this has built in filters) then fire up the macro recorder, manually filter on your three terms, delete the results, clear the filter, stop the macro recorder, then go look at the code it generated.

The Macro Recorder should be your first port of call when working out how to go about something. It doesn't always generate elegant/efficient code and you'll often have to clean it up, but in this case you will go from glacial to warp speed.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to delete rows that include any of the values specified. The below code worked in a sheet with ~200k rows but excel crashes when I try to run it in a sheet with 350k rows. How to make it more efficient?

    Sub MultiDelete()

    With Application
    .ScreenUpdating = False
    .DisplayAlerts = False
    End With

    Range("A1").Activate 'change to suit the column containing the names
    Dim MultiDelete
    MultiDelete = Array("Name1", "Name2", "Name3") 'put as many names as you like in the array
    Dim G As Variant
    While ActiveCell.Value <> ""
    G = Filter(MultiDelete, ActiveCell.Value)
    If UBound(G) <> -1 Then
        Selection.EntireRow.Delete
    Else
        ActiveCell.Offset(1, 0).Activate
   End If
    Wend
    With Application
    .ScreenUpdating = True
    .DisplayAlerts = True
    End With
    End Sub


问:
How to wrap a video on a monitor?
If I have a video file that defines a video image that is 6144 pixels long (x) by 64 pixels high (y) and I want to display that video so that it wraps at the end of the monitor. In other words I want to display the first 1024 pixels of the video starting at position 0,0 on the monitor, then video pixels 1024 to 2047 starting at position 0,64, and repeat this until all 6144 pixels are shown on the monitor. That would mean the video needs to wrap around on a 1024x768 monitor 6 times.

What is the best way to do this? Can DirectX, DirectShow, Media Foundation, or Windows Media Player ActiveX Control handle this wrapping for you automatically? I need to do this preferably in C#, but not opposed to dropping in to C++ native. Or is the only way to do this, is to split the video into 6 separate sections and play them in separate window? If splitting them into 6 separate videos and playing them in 6 separate windows is the only reasonable way, how do you make certain they start at the same time so they are sync'd?

Just thinking about something per comment below could ffmpeg and/or C# transform this 6144 x 64 pixel video file into something like this:

```<code>6144 x 64  --->  0-1023 x 64
                 1024-2047 x 64
                 2048-3071 x 64
                 3072-4095 x 64
                 4096-5119 x 64
                 5120-6143 x 64
</code>```

In other words what looks like it's wrapped but really just one video that's 1024 x 384 ??

答:
You need to develop a transformation which converts your 6144x64 video to resolution in question (1024x768 or different) and integrate it with one of the player pipelines. When you convert the video frames to required resolution, the frames can be presented as usual video playback, esp. fullscreen in you need to span in across the entire monitor, and such playback on its presentation end will not differ from play back a regular video file meaning that you can use standard components and APIs.

All video APIs are native: in most, if not all, cases you would be better off implementing the transformation in C++ rather than C#.

With DirectShow you typically develop a transform filter which accept the video frames and rearranges the pixel data respectively to your requirements. With Media Foundation the similar task is achieved by developing a Media Foundation Transform (with the data processing in CPU or GPU domain). In both cases you are packing your transformation step into API defined form factor and extending the standard pipeline.

Otherwise you can also prepare the frames outside of the playback pipelines and inject them already prepared. Even though possible, it is perhaps a more complicated way but it can be preferred by those who are not well familiar with the mentioned APIs.

When you prepare a re-arranged frame for presentation at once you don't need to do additional presentation synchronization. Presumably, this is the way to achieve the mentioned task as the splitting into parts and managing synchronized presentation is a more complicated for now reason alternative.

DirectShow vs. Media Foundation - both APIs let you play video with the same quality and performance (exception might be that you need GPU only processing, in which case Media Foundation might be a better choice, but in your case it's unlikely that you can leverage this advantage).

DirectShow is older and near stop of its development but offers much more online tutorials, discussions, materials, helpers and samples. Windows SDK 7.1 EzRGB24 Filter Sample is a good start point for a transform filter.

Media Foundation is newer and "current" API, presumably a more reasonable choice. Windows SDK 7.1 offers MFT_Grayscale Sample for a starting development point. It is generally possible to implement a C# MFT for Media Foundation (there are good reasons to not do it - 1, 2). Even though DirectShow is notorious for being an API with a step learning curve, for the video effect developer Media Foundation is even a more complicated API.

Generally speaking the API choice should take into consideration, if not even be defined by, your preference for playback pipeline.

Title: How to wrap a video on a monitor?

Body:
If I have a video file that defines a video image that is 6144 pixels long (x) by 64 pixels high (y) and I want to display that video so that it wraps at the end of the monitor. In other words I want to display the first 1024 pixels of the video starting at position 0,0 on the monitor, then video pixels 1024 to 2047 starting at position 0,64, and repeat this until all 6144 pixels are shown on the monitor. That would mean the video needs to wrap around on a 1024x768 monitor 6 times.

What is the best way to do this? Can DirectX, DirectShow, Media Foundation, or Windows Media Player ActiveX Control handle this wrapping for you automatically? I need to do this preferably in C#, but not opposed to dropping in to C++ native. Or is the only way to do this, is to split the video into 6 separate sections and play them in separate window? If splitting them into 6 separate videos and playing them in 6 separate windows is the only reasonable way, how do you make certain they start at the same time so they are sync'd?

Just thinking about something per comment below could ffmpeg and/or C# transform this 6144 x 64 pixel video file into something like this:

6144 x 64  --->  0-1023 x 64
                 1024-2047 x 64
                 2048-3071 x 64
                 3072-4095 x 64
                 4096-5119 x 64
                 5120-6143 x 64

In other words what looks like it's wrapped but really just one video that's 1024 x 384 ??


问:
Problems with SHA 2 Hashing and Java
I am working on following the SHA-2 cryptographically functions as stated in https://en.wikipedia.org/wiki/SHA-2.

I am examining the lines that say:

begin with the original message of length L bits append a single '1' bit;

append K '0' bits, where K is the minimum number >= 0 such that L + 1 + K + 64 is a multiple of 512

append L as a 64-bit big-endian integer, making the total post-processed length a multiple of 512 bits.

I do not understand the last two lines. If my string is short can its length after adding K '0' bits be 512. How should I implement this in Java code?

答:
First of all, it should be made clear that the "string" that is talked about is not a Java String but a bit string. These algorithms are binary/bit based. The implementation will generally not handle bits but bytes. So there is a translation phase where you should see bytes instead of bits.

SHA-512 is operated on in blocks of 512 bits (SHA-224/256) or 1024 bits (SHA-384/512). So basically you have a 64 or 128 byte buffer that you are filling before operating on it. You could also directly cache the data in 32 bit int fields (SHA-224/256) or 64 bit long fields, as that is the word size that is operated on.

Now the padding is relatively simple procedure. The padding is called bit-padding. As it is used in big-endian mode (SHA-2 fortunately uses this instead of the braindead little endian mode in SHA-3) the padding consists of a single bit set on the highest order bit in a byte, with the rest filled by zero's. That makes for a value of (byte) 0x80 which must be put in the buffer.

If you cannot create this padding because the buffer is full then you will have to process the previous block, and then set the first bit of the now available buffer to (byte) 0x80. In the newer Java you can also use (byte) 0b1_0000000 byte the way, which is more explicit.

Now you simply add zero's until you have 8 to 16 bytes left, again depending on the hash output size used. If there aren't enough bytes then fill till the end, process the block, and re-start filling with zero bytes until you have 8 or 16 bytes left again.

Now finally you have to encode the number of bits in those 8 or 16 bytes you've left. So multiply your input by eight, and make sure you encode those bytes in the same way as you'd expect in Java with the least significant bits as much to the right as possible. You might want to use https://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#putLong-long- for this if you don't want to program it yourself. You may probably forget about anything over 2^56 bytes anyway, so if you have SHA-384/SHA-512 then simply set the first eight bytes to zero.

And that's it, except that you still need to process that last block and then use as many bytes from the left as required for your particular output size.

Title: Problems with SHA 2 Hashing and Java


问:
Memory Address showing? C++
Not really sure what's going on here, I'm using Clion as my IDE which I don't believe has anything to do with this but I figured I'd add that information. My confusion comes from a function that I wrote

```<code>int Arry()
{

int Mynumbers [5] = {10};

    std::cout << Mynumbers;
}
</code>```

something simple. It should be assigning 5 integers the value of 10. But when I print out Mynumbers I am shown the memory address. Why is this happening, I thought that was what calling pointers was for. Thank you for your time.

Sincerely,
Nicholas

答:
The value of Mynumbers is in fact the adress of the first element in the array.

try the following:

```<code>for(int i=0; i<5;i++) {
    cout << Mynumbers[i];
}
</code>```

Title: Memory Address showing? C++

Body:
Not really sure what's going on here, I'm using Clion as my IDE which I don't believe has anything to do with this but I figured I'd add that information. My confusion comes from a function that I wrote

int Arry()
{

int Mynumbers [5] = {10};

    std::cout << Mynumbers;
}

something simple. It should be assigning 5 integers the value of 10. But when I print out Mynumbers I am shown the memory address. Why is this happening, I thought that was what calling pointers was for. Thank you for your time.

Sincerely,
Nicholas

Body:
The value of Mynumbers is in fact the adress of the first element in the array.

try the following:

for(int i=0; i<5;i++) {
    cout << Mynumbers[i];
}


问:
How to load from Json?
I'am trying to get the information from the web api with Python 3 but it gives me an error. That's my code:

```<code>import json, urllib.request, requests

def findLocation():
"""returns latlng location value in the form of a list."""

    send_url = 'http://freegeoip.net/json'
    r = requests.get(send_url)
    j = json.loads(r.text)
    lat = j['latitude']
    lon = j['longitude']
    return lat, lon

location = findLocation()
print(findLocation()[0])
print(findLocation()[1])

def readJsonUrl(url):
"""reads the Json returned by the google api and converts it into a format
that can be used in python."""
    page = urllib.request.urlopen(url)
    data_bytes = page.read()
    data_str = data_bytes.decode("utf-8")
    page.close()

    return data_str
search =readJsonUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query=indian+restaurantsin+Coventry&location=52.4066,-1.5122&key=AIzaSyCI8n1sI4CDRnsYo3hB_oH1trfxbt2IEaw")

print(search['website'])
</code>```

Error:

```<code>Traceback (most recent call last):
  File "google api.py", line 28, in <module>
    print(search['website'])
TypeError: string indices must be integers
</code>```

Any help is appreciated.

答:
data_str is string ( not dict format ) You should convert data_str to dict! just add this line to your code : convert_to_dict = json.loads(data_str). then return convert_to_dict ... and done.

Try this :

```<code>import json, urllib.request, requests

def findLocation():

    send_url = 'http://freegeoip.net/json'
    r = requests.get(send_url)
    j = json.loads(r.text)
    lat = j['latitude']
    lon = j['longitude']
    return lat, lon

location = findLocation()
print(findLocation()[0])
print(findLocation()[1])

def readJsonUrl(url):

    page = urllib.request.urlopen(url)
    data_bytes = page.read()
    data_str = data_bytes.decode("utf-8")
    page.close()

    convert_to_dict = json.loads(data_str)  # new line

    return convert_to_dict  # updated

search = readJsonUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query=indian+restaurantsin+Coventry&location=52.4066,-1.5122&key=AIzaSyCI8n1sI4CDRnsYo3hB_oH1trfxbt2IEaw")
print(search['your_key']) # now you can call your keys
</code>```

Title: How to load from Json?

Body:
I'am trying to get the information from the web api with Python 3 but it gives me an error. That's my code:

import json, urllib.request, requests

def findLocation():
"""returns latlng location value in the form of a list."""

    send_url = 'http://freegeoip.net/json'
    r = requests.get(send_url)
    j = json.loads(r.text)
    lat = j['latitude']
    lon = j['longitude']
    return lat, lon

location = findLocation()
print(findLocation()[0])
print(findLocation()[1])

def readJsonUrl(url):
"""reads the Json returned by the google api and converts it into a format
that can be used in python."""
    page = urllib.request.urlopen(url)
    data_bytes = page.read()
    data_str = data_bytes.decode("utf-8")
    page.close()

    return data_str
search =readJsonUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query=indian+restaurantsin+Coventry&location=52.4066,-1.5122&key=AIzaSyCI8n1sI4CDRnsYo3hB_oH1trfxbt2IEaw")

print(search['website'])

Error:

Traceback (most recent call last):
  File "google api.py", line 28, in <module>
    print(search['website'])
TypeError: string indices must be integers

Any help is appreciated.

Body:
data_str is string ( not dict format ) You should convert data_str to dict! just add this line to your code : convert_to_dict = json.loads(data_str). then return convert_to_dict ... and done.

Try this :

import json, urllib.request, requests

def findLocation():

    send_url = 'http://freegeoip.net/json'
    r = requests.get(send_url)
    j = json.loads(r.text)
    lat = j['latitude']
    lon = j['longitude']
    return lat, lon

location = findLocation()
print(findLocation()[0])
print(findLocation()[1])

def readJsonUrl(url):

    page = urllib.request.urlopen(url)
    data_bytes = page.read()
    data_str = data_bytes.decode("utf-8")
    page.close()

    convert_to_dict = json.loads(data_str)  # new line

    return convert_to_dict  # updated

search = readJsonUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query=indian+restaurantsin+Coventry&location=52.4066,-1.5122&key=AIzaSyCI8n1sI4CDRnsYo3hB_oH1trfxbt2IEaw")
print(search['your_key']) # now you can call your keys


问:
Angular Material MatTableDataSource with Firestore
I currently have a data table that is being populated with data coming from Firestore. I also used MatTableDataSource to implement pagination, sorting, and filtering.  All 3 work fine but for some reason my data only loads once when the page is refreshed.  If I go to another page and then back to the table the data is gone.  I'm at a loss as to why this is happening. Below is my code.

Service

```<code>import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Account } from './../models/account.model';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AccountService {
  accountsCollection: AngularFirestoreCollection<Account>;
  accounts: Observable<Account[]>;

  constructor(public afs: AngularFirestore) {
    this.accountsCollection = afs.collection('accounts');

    this.accounts = this.accountsCollection.snapshotChanges().map(changes => {
      return changes.map(a => {
        const data = a.payload.doc.data() as Account;
        data.id = a.payload.doc.id;
        return data;
      });
    });

  }

  getAccounts() {
    return this.accounts;
  }

}
</code>```

Component

```<code>import { Account } from './../../../models/account.model';
import { Component, ViewChild, OnInit } from '@angular/core';
import { MatPaginator, MatSort, MatTableDataSource } from '@angular/material';
import { AccountService } from '../../../services/account.service';
import { AfterViewInit } from '@angular/core/src/metadata/lifecycle_hooks';

@Component({
  selector: 'app-account-table',
  templateUrl: './account-table.component.html',
  styleUrls: ['./account-table.component.css']
})
export class AccountTableComponent implements AfterViewInit {
  dataSource = new MatTableDataSource<Account>();
  displayedColumns = [
    'salesStep',
    'status',
    'idn',
    'hospital',
    'state',
    'regionalManager',
    'accountExecutive',
    'clientLiaison',
    'gpo'
  ];

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor(private accountService: AccountService) {}

  ngAfterViewInit() {
    this.accountService.getAccounts().subscribe(data => {
      this.dataSource.data = data;
      console.log(this.dataSource.data);
    });
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  }

}
</code>```

HTML

```<code><div class="example-header">
  <mat-form-field>
    <input matInput #filter (keyup)="applyFilter($event.target.value)" placeholder="Search">
  </mat-form-field>
</div>

<mat-card class="example-container">

  <mat-table #table [dataSource]="dataSource" matSort>

    <!--- Note that these columns can be defined in any order.
          The actual rendered columns are set as a property on the row definition" -->

    <!-- Sales Step Column -->
    <ng-container matColumnDef="salesStep">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Sales Step </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.salesStep}} </mat-cell>
    </ng-container>

    <!-- Status Column -->
    <ng-container matColumnDef="status">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Status </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.status}} </mat-cell>
    </ng-container>

    <!-- IDN Column -->
    <ng-container matColumnDef="idn">
      <mat-header-cell *matHeaderCellDef mat-sort-header> IDN </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.idn}} </mat-cell>
    </ng-container>

    <!-- Hospital Column -->
    <ng-container matColumnDef="hospital">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Hospital </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.hospital}} </mat-cell>
    </ng-container>

    <!-- State Column -->
    <ng-container matColumnDef="state">
      <mat-header-cell *matHeaderCellDef mat-sort-header> State </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.state}} </mat-cell>
    </ng-container>

    <!-- Regional Manager Column -->
    <ng-container matColumnDef="regionalManager">
      <mat-header-cell *matHeaderCellDef mat-sort-header> RM </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.regionalManager}} </mat-cell>
    </ng-container>

    <!-- Account Executive Column -->
    <ng-container matColumnDef="accountExecutive">
      <mat-header-cell *matHeaderCellDef mat-sort-header> AE </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.accountExecutive}} </mat-cell>
    </ng-container>

    <!-- Client Liaison Column -->
    <ng-container matColumnDef="clientLiaison">
      <mat-header-cell *matHeaderCellDef mat-sort-header> CL </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.clientLiaison}} </mat-cell>
    </ng-container>

    <!-- GPO Column -->
    <ng-container matColumnDef="gpo">
      <mat-header-cell *matHeaderCellDef mat-sort-header> GPO </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.gpo}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;">
    </mat-row>
  </mat-table>

  <!-- <div class="example-no-results"
       [style.display]="(accountService.accounts | async)?.length">
    No accounts found matching filter.
  </div> -->

  <mat-paginator #paginator
                [pageSize]="10"
                [pageSizeOptions]="[5, 10, 20]">
  </mat-paginator>
</mat-card>
</code>```

答: Save the subscription you get from getAccounts().subscribe and call unsubscribe() to it in ngOnDestroy. I didn't test but it might help if af2 caches the subscriptions, as the observable never completes on it's own. Necessary and good practice for avoiding memory leaks anyway.</p>

Body:
I currently have a data table that is being populated with data coming from Firestore. I also used MatTableDataSource to implement pagination, sorting, and filtering.  All 3 work fine but for some reason my data only loads once when the page is refreshed.  If I go to another page and then back to the table the data is gone.  I'm at a loss as to why this is happening. Below is my code.

Service

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Account } from './../models/account.model';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AccountService {
  accountsCollection: AngularFirestoreCollection<Account>;
  accounts: Observable<Account[]>;

  constructor(public afs: AngularFirestore) {
    this.accountsCollection = afs.collection('accounts');

    this.accounts = this.accountsCollection.snapshotChanges().map(changes => {
      return changes.map(a => {
        const data = a.payload.doc.data() as Account;
        data.id = a.payload.doc.id;
        return data;
      });
    });

  }

  getAccounts() {
    return this.accounts;
  }

}

Component

import { Account } from './../../../models/account.model';
import { Component, ViewChild, OnInit } from '@angular/core';
import { MatPaginator, MatSort, MatTableDataSource } from '@angular/material';
import { AccountService } from '../../../services/account.service';
import { AfterViewInit } from '@angular/core/src/metadata/lifecycle_hooks';

@Component({
  selector: 'app-account-table',
  templateUrl: './account-table.component.html',
  styleUrls: ['./account-table.component.css']
})
export class AccountTableComponent implements AfterViewInit {
  dataSource = new MatTableDataSource<Account>();
  displayedColumns = [
    'salesStep',
    'status',
    'idn',
    'hospital',
    'state',
    'regionalManager',
    'accountExecutive',
    'clientLiaison',
    'gpo'
  ];

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor(private accountService: AccountService) {}

  ngAfterViewInit() {
    this.accountService.getAccounts().subscribe(data => {
      this.dataSource.data = data;
      console.log(this.dataSource.data);
    });
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  }

}

HTML

  <mat-form-field>
    <input matInput #filter (keyup)="applyFilter($event.target.value)" placeholder="Search">
  </mat-form-field>

<mat-card class="example-container">

  <mat-table #table [dataSource]="dataSource" matSort>

    <ng-container matColumnDef="salesStep">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Sales Step </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.salesStep}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="status">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Status </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.status}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="idn">
      <mat-header-cell *matHeaderCellDef mat-sort-header> IDN </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.idn}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="hospital">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Hospital </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.hospital}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="state">
      <mat-header-cell *matHeaderCellDef mat-sort-header> State </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.state}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="regionalManager">
      <mat-header-cell *matHeaderCellDef mat-sort-header> RM </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.regionalManager}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="accountExecutive">
      <mat-header-cell *matHeaderCellDef mat-sort-header> AE </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.accountExecutive}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="clientLiaison">
      <mat-header-cell *matHeaderCellDef mat-sort-header> CL </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.clientLiaison}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="gpo">
      <mat-header-cell *matHeaderCellDef mat-sort-header> GPO </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.gpo}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;">
    </mat-row>
  </mat-table>

  <mat-paginator #paginator
                [pageSize]="10"
                [pageSizeOptions]="[5, 10, 20]">
  </mat-paginator>
</mat-card>


问:
Use void pointer to store float numbers into array
I'm new to pointers and this may be a silly question.
Not able to store float numbers into float array using void pointer. Below is the code and the output:

Code:

```<code>int main()
{
int size=5;
float f_array[size];
populate(f_array, size);
// printing array below
}
void populate(void *p, int size)
{
    int i;
    for(i=0; i<size; i++)
    {
        scanf("%f", (((float *)p)+i));
    }
}
</code>```

Output:

//Entering five float numbers to be stored in array

1.2   // not able to enter other numbers and gives the below output

```<code>a[0] = 1
a[1] = garbage value
a[2] = garbage value
a[3] = garbage value
a[4] = 0
</code>```

答:
```<code>#include <stdio.h>
#define SIZE 5
void populate(void *p, int size)
{
    int i;
    float *array = (float*)p;
    for (i = 0; i < size; i++)
    {
        scanf("%f", &array[i]);
    }
}

int main()
{

    int i;
    float f_array[SIZE];
    populate(f_array, SIZE);
    //print array
}
</code>```

Body:
I'm new to pointers and this may be a silly question.
Not able to store float numbers into float array using void pointer. Below is the code and the output:

Code:

int main()
{
int size=5;
float f_array[size];
populate(f_array, size);
// printing array below
}
void populate(void *p, int size)
{
    int i;
    for(i=0; i<size; i++)
    {
        scanf("%f", (((float *)p)+i));
    }
}

Output:

//Entering five float numbers to be stored in array

1.2   // not able to enter other numbers and gives the below output

a[0] = 1
a[1] = garbage value
a[2] = garbage value
a[3] = garbage value
a[4] = 0


问:
IdentityServer 4 - invaid_client error
I am new to Identity Server. I haven't configured it before. But I need it for a Project I am working on.
The API will be serving an Angular JS Client, iOS App and an Android App. We need to implement authentication and authorisation and custmer grant

Note: I am trying to configure Identity Server and my API in the same Web API project.

I have followed the documentation and configured Identity Server as the following:

In startup.cs, in ConfigureServices()

```<code>    private readonly IConfiguration config;

    private const string DEFAULT_CORS_POLICY = "localhost";

    public Startup (IConfiguration config) => this.config = config;

    public void ConfigureServices (IServiceCollection services) {
        services.AddIdentityServer ()
            .AddDeveloperSigningCredential ()
            //.AddInMemoryApiResources(config.GetSection("ApiResources"))
            .AddInMemoryApiResources (Config.GetApis ())
            //.AddInMemoryClients(config.GetSection("Clients"))
            .AddInMemoryClients (Config.GetClients ())
            .AddInMemoryIdentityResources (Config.GetIdentityResources ())
            //.AddInMemoryIdentityResources(config.GetSection("IdentityResources"))
            .AddExtensionGrantValidator<WechatGrantValidator> ();

        services.AddTransient<IUserCodeValidator, UserCodeValidator> ();

        services.AddCors (options => {
            options.AddPolicy (DEFAULT_CORS_POLICY, builder => {
                builder.WithOrigins ("http://localhost:5202");
                builder.AllowAnyHeader ();
                builder.AllowAnyMethod ();
            });
        });
    }
</code>```

I implemented the interface IExtensionGrantValidator and register the extension grant

```<code>    public class WechatGrantValidator : IExtensionGrantValidator {

    private IUserCodeValidator validator;

    public WechatGrantValidator (IUserCodeValidator validator) {
        this.validator = validator;
    }
    public string GrantType => "wechat_grant";

    public async Task ValidateAsync (ExtensionGrantValidationContext context) {
        string userCode = context.Request.Raw.Get ("userCode");
        var result = await validator.ValidateAsync (userCode);
        if (result.IsError) {
            context.Result = new GrantValidationResult (TokenRequestErrors.InvalidGrant);
            return;
        }
        context.Result = new GrantValidationResult (result.UserId, GrantType);
        return;
    }
}
</code>```

I have followed the documentation and configured client infos as the following

```<code>        public static IEnumerable<Client> GetClients () {
        return new Client[] {
                    new Client {
                    ClientId = "javascritpClient",
                    ClientName = "JavaScript Client",
                    AllowedGrantTypes = { "wechat_grant" },
                    AllowAccessTokensViaBrowser = true,
                    AllowedCorsOrigins = { "http://localhost:5202" },
                    AllowedScopes = { "api1" },
                    ClientSecrets = { new Secret ("secret".Sha256 ()) }
                    }
        };
    }
</code>```

Now because I want to use it Angular JS, iOS and Android I want to just get the Access Token from the IdentityServer, and then use the Access Token for Authentication and Authorisation.

for this I am trying to access the /connect/token from a JS client

But I am getting an invalid_client error.

```<code>@Injectable()
export class OauthService {
  private http: Http;
  public constructor(http: Http) {
    this.http = http;
  }

  public async getDiscoveryInfos(issuer: string): Promise<DiscoveryInfos> {
    if (!issuer.endsWith('/')) {
      issuer += '/';
    }
    issuer += '.well-known/openid-configuration';
    return this.http.get(issuer).map(response => {
      return response.json();
    }).toPromise();
  }

  public async getToken(): Promise<any> {
    const headers = new Headers({ "Content-Type": "application/x-www-form-urlencoded" });
    const discovery = await this.getDiscoveryInfos('http://localhost:5200');
    return this.http.post(discovery.token_endpoint, {
      grant_type: 'wechat_grant',
      userCode: 'userCodeAA',
      client_id: 'javascritpClient',
      client_secret: 'secret',
      scope:'api1'
    }, { headers: headers }).map(response => response.json()).toPromise();
  }

}
</code>```

http response infos

The server response "error":"invalid_client"

log infos

The error I get on the server side is 'No client identifier found':

1 - Why am I getting this error?

2 - As I need to get the Token programmatically in JS, I need to use /connect/token, am I correct on this? Am I on the correct path?

答:
in ng2 use  a method like bellow:</p>

```<code>public Token(data: SigninModel): Observable<any> {
    this.options = new RequestOptions({ headers: this.headers });
    this.headers.append('Content-Type', 'application/x-www-form-urlencoded');
    const url = this.urlBase + `connect/token`;
    const param = new URLSearchParams();
    param.set('grant_type', 'password');
    param.set('client_Id', 'javascritpClient');
    param.set('client_secret', 'secret');
    param.set('scope', 'offline_access');
    param.set('username', data.username);
    param.set('password', data.password);
    return this.http.post(url, `${param.toString()}`, this.options)
        .map((response: Response) => {
            return (response.json());
        })
        .catch(this.handleError);
}
</code>```

Title: IdentityServer 4 - invaid_client error

Body:
I am new to Identity Server. I haven't configured it before. But I need it for a Project I am working on.
The API will be serving an Angular JS Client, iOS App and an Android App. We need to implement authentication and authorisation and custmer grant

Note: I am trying to configure Identity Server and my API in the same Web API project.

I have followed the documentation and configured Identity Server as the following:

In startup.cs, in ConfigureServices()

    private readonly IConfiguration config;

    private const string DEFAULT_CORS_POLICY = "localhost";

    public Startup (IConfiguration config) => this.config = config;

    public void ConfigureServices (IServiceCollection services) {
        services.AddIdentityServer ()
            .AddDeveloperSigningCredential ()
            //.AddInMemoryApiResources(config.GetSection("ApiResources"))
            .AddInMemoryApiResources (Config.GetApis ())
            //.AddInMemoryClients(config.GetSection("Clients"))
            .AddInMemoryClients (Config.GetClients ())
            .AddInMemoryIdentityResources (Config.GetIdentityResources ())
            //.AddInMemoryIdentityResources(config.GetSection("IdentityResources"))
            .AddExtensionGrantValidator<WechatGrantValidator> ();

        services.AddTransient<IUserCodeValidator, UserCodeValidator> ();

        services.AddCors (options => {
            options.AddPolicy (DEFAULT_CORS_POLICY, builder => {
                builder.WithOrigins ("http://localhost:5202");
                builder.AllowAnyHeader ();
                builder.AllowAnyMethod ();
            });
        });
    }

I implemented the interface IExtensionGrantValidator and register the extension grant

    public class WechatGrantValidator : IExtensionGrantValidator {

    private IUserCodeValidator validator;

    public WechatGrantValidator (IUserCodeValidator validator) {
        this.validator = validator;
    }
    public string GrantType => "wechat_grant";

    public async Task ValidateAsync (ExtensionGrantValidationContext context) {
        string userCode = context.Request.Raw.Get ("userCode");
        var result = await validator.ValidateAsync (userCode);
        if (result.IsError) {
            context.Result = new GrantValidationResult (TokenRequestErrors.InvalidGrant);
            return;
        }
        context.Result = new GrantValidationResult (result.UserId, GrantType);
        return;
    }
}

I have followed the documentation and configured client infos as the following

        public static IEnumerable<Client> GetClients () {
        return new Client[] {
                    new Client {
                    ClientId = "javascritpClient",
                    ClientName = "JavaScript Client",
                    AllowedGrantTypes = { "wechat_grant" },
                    AllowAccessTokensViaBrowser = true,
                    AllowedCorsOrigins = { "http://localhost:5202" },
                    AllowedScopes = { "api1" },
                    ClientSecrets = { new Secret ("secret".Sha256 ()) }
                    }
        };
    }

Now because I want to use it Angular JS, iOS and Android I want to just get the Access Token from the IdentityServer, and then use the Access Token for Authentication and Authorisation.

for this I am trying to access the /connect/token from a JS client

But I am getting an invalid_client error.

@Injectable()
export class OauthService {
  private http: Http;
  public constructor(http: Http) {
    this.http = http;
  }

  public async getDiscoveryInfos(issuer: string): Promise<DiscoveryInfos> {
    if (!issuer.endsWith('/')) {
      issuer += '/';
    }
    issuer += '.well-known/openid-configuration';
    return this.http.get(issuer).map(response => {
      return response.json();
    }).toPromise();
  }

  public async getToken(): Promise<any> {
    const headers = new Headers({ "Content-Type": "application/x-www-form-urlencoded" });
    const discovery = await this.getDiscoveryInfos('http://localhost:5200');
    return this.http.post(discovery.token_endpoint, {
      grant_type: 'wechat_grant',
      userCode: 'userCodeAA',
      client_id: 'javascritpClient',
      client_secret: 'secret',
      scope:'api1'
    }, { headers: headers }).map(response => response.json()).toPromise();
  }

}

http response infos

The server response "error":"invalid_client"

log infos

The error I get on the server side is 'No client identifier found':

1 - Why am I getting this error?

2 - As I need to get the Token programmatically in JS, I need to use /connect/token, am I correct on this? Am I on the correct path?

Body:
in ng2 use  a method like bellow:

public Token(data: SigninModel): Observable<any> {
    this.options = new RequestOptions({ headers: this.headers });
    this.headers.append('Content-Type', 'application/x-www-form-urlencoded');
    const url = this.urlBase + `connect/token`;
    const param = new URLSearchParams();
    param.set('grant_type', 'password');
    param.set('client_Id', 'javascritpClient');
    param.set('client_secret', 'secret');
    param.set('scope', 'offline_access');
    param.set('username', data.username);
    param.set('password', data.password);
    return this.http.post(url, `${param.toString()}`, this.options)
        .map((response: Response) => {
            return (response.json());
        })
        .catch(this.handleError);
}


问:
Preg_replace and preg_match to get and replace HTML / PHP content
I need to extract some HTML / PHP content and put it into an array.

Here is what I have

The code below is within a string called $string for example.

```<code><html>
<?php myclass->my_function('First', 'Last'); ?>
<p>Some other content</p>
<?php myclass->my_function(1, 2, 3); ?>
</html>
</code>```

I want to find all the values from the functions and sum them into an array with preg_match. Only myclass->my_function function values should be found.

The array should look like this

```<code>$array = array(
   1 => array('First', 'Last'),
   2 => array(1,2,3),
);
</code>```

Then I want preg_replace to replace all the rows with [explode_id] and the result should be:

```<code><html>
[explode_1]
<p>Some other content</p>
[explode_2]
</html>
</code>```

Thanks!

答:
```<code>$match_array = preg_match('/<\?php myclass->my_function\((.+?)\); \?>/', $input_string, $matches);
$output_arrays = array();
$output_arrays[] = eval('array('.$matches[0][1].')';
$output_arrays[] = eval('array('.$matches[1][1].')';

echo '<html>';
echo implode(' ', $output_arrays[0]);
echo '<p>Some other content</p>';
echo implode(' ', $output_arrays[1]);
echo '</html>';
</code>```

Body:
I need to extract some HTML / PHP content and put it into an array.

Here is what I have

The code below is within a string called $string for example.

<?php myclass->my_function('First', 'Last'); ?>

Some other content

<?php myclass->my_function(1, 2, 3); ?>

I want to find all the values from the functions and sum them into an array with preg_match. Only myclass->my_function function values should be found.

The array should look like this

$array = array(
   1 => array('First', 'Last'),
   2 => array(1,2,3),
);

Then I want preg_replace to replace all the rows with [explode_id] and the result should be:

[explode_1]

Some other content

[explode_2]

Thanks!