问:
Android screen sharing using WebRTC
I have heard about screen sharing on desktop using WebRTC. But for the Android, it seems not to have much information.

My question is:

Is it possible to use WebRTC for screen sharing on android?. I mean I can cast the current screen to the other phone's screen.

If 1 is Yes, How can I achieve this?

Thanks.

答:
It is possible!

It can be done using the directions below.

I've used ScreenShareRTC in conjunction with ProjectRTC to stream the contents of the screen to a browser with decent quality and fairly low latency ~100ms.

I've added an example below that shows how to configure a screen share as a video source and add it as a track on a stream.

Get the VideoCapturer

```<code>@TargetApi(21)
private VideoCapturer createScreenCapturer() {
    if (mMediaProjectionPermissionResultCode != Activity.RESULT_OK) {
        report("User didn't give permission to capture the screen.");
        return null;
    }
    return new ScreenCapturerAndroid(
            mMediaProjectionPermissionResultData, new MediaProjection.Callback() {
        @Override
        public void onStop() {
            report("User revoked permission to capture the screen.");
        }
    });
}
</code>```

Initialize the capturer and add the tracks to the local media stream

```<code>private void initScreenCapturStream() {
    mLocalMediaStream = factory.createLocalMediaStream("ARDAMS");
    MediaConstraints videoConstraints = new MediaConstraints();
    videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxHeight", Integer.toString(mPeerConnParams.videoHeight)));
    videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxWidth", Integer.toString(mPeerConnParams.videoWidth)));
    videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxFrameRate", Integer.toString(mPeerConnParams.videoFps)));
    videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("minFrameRate", Integer.toString(mPeerConnParams.videoFps)));

    mVideoSource = factory.createVideoSource(videoCapturer);
    videoCapturer.startCapture(mPeerConnParams.videoWidth, mPeerConnParams.videoHeight, mPeerConnParams.videoFps);
    VideoTrack localVideoTrack = factory.createVideoTrack(VIDEO_TRACK_ID, mVideoSource);
    localVideoTrack.setEnabled(true);
    mLocalMediaStream.addTrack(factory.createVideoTrack("ARDAMSv0", mVideoSource));
    AudioSource audioSource = factory.createAudioSource(new MediaConstraints());
    mLocalMediaStream.addTrack(factory.createAudioTrack("ARDAMSa0", audioSource));

    mListener.onStatusChanged("STREAMING");
}
</code>```

For more information this might be a good place to start.  Its a Android project that connects to a ProjectRTC signalling server and shares the screen as video.  I found it very helpful!

Android screen sharing project(Android client - Java)
https://github.com/Jeffiano/ScreenShareRTC

ProjectRTC(Node server)
https://github.com/pchab/ProjectRTC

Title: Android screen sharing using WebRTC

Body:
It is possible!

It can be done using the directions below.

I've used ScreenShareRTC in conjunction with ProjectRTC to stream the contents of the screen to a browser with decent quality and fairly low latency ~100ms.

I've added an example below that shows how to configure a screen share as a video source and add it as a track on a stream.

Get the VideoCapturer

@TargetApi(21)
private VideoCapturer createScreenCapturer() {
    if (mMediaProjectionPermissionResultCode != Activity.RESULT_OK) {
        report("User didn't give permission to capture the screen.");
        return null;
    }
    return new ScreenCapturerAndroid(
            mMediaProjectionPermissionResultData, new MediaProjection.Callback() {
        @Override
        public void onStop() {
            report("User revoked permission to capture the screen.");
        }
    });
}

Initialize the capturer and add the tracks to the local media stream

private void initScreenCapturStream() {
    mLocalMediaStream = factory.createLocalMediaStream("ARDAMS");
    MediaConstraints videoConstraints = new MediaConstraints();
    videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxHeight", Integer.toString(mPeerConnParams.videoHeight)));
    videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxWidth", Integer.toString(mPeerConnParams.videoWidth)));
    videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxFrameRate", Integer.toString(mPeerConnParams.videoFps)));
    videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("minFrameRate", Integer.toString(mPeerConnParams.videoFps)));

    mVideoSource = factory.createVideoSource(videoCapturer);
    videoCapturer.startCapture(mPeerConnParams.videoWidth, mPeerConnParams.videoHeight, mPeerConnParams.videoFps);
    VideoTrack localVideoTrack = factory.createVideoTrack(VIDEO_TRACK_ID, mVideoSource);
    localVideoTrack.setEnabled(true);
    mLocalMediaStream.addTrack(factory.createVideoTrack("ARDAMSv0", mVideoSource));
    AudioSource audioSource = factory.createAudioSource(new MediaConstraints());
    mLocalMediaStream.addTrack(factory.createAudioTrack("ARDAMSa0", audioSource));

    mListener.onStatusChanged("STREAMING");
}

For more information this might be a good place to start.  Its a Android project that connects to a ProjectRTC signalling server and shares the screen as video.  I found it very helpful!

Android screen sharing project(Android client - Java)
https://github.com/Jeffiano/ScreenShareRTC

ProjectRTC(Node server)
https://github.com/pchab/ProjectRTC


来源: stackexchange

问:
Awk printing only strings before variables and strings
I'm trying to turn data from the last command into epoch time using the awk print. the code works on 10.14.5 all the time, and works on 10.13.6 some of the time. When I came into work this morning it worked fine, then around 11 started giving me errors.

Basically, awk is printing literal strings, then a newline character, then the literal strings and the variables as it should. for example,
if $1="Hello", then:

awk '{print $1,"World"}'
```

<p>is actually printing "World
Hello World"</p>

<p>the actual line of code giving the error is this:</p>

<pre class="lang-sh prettyprint-override"><code>x=$(last -1 $a | awk '{print $3 " "$4 " " $5  " " $6 ":00 EDT "}')
</code>```

where it should be setting x to "Fri May 31 12:43:00 EDT " for example, it is setting x to " :00 EDT
Fri May 31 12:43:00 EDT "

EDIT: I should say that the $a in the line of code would be set to a username on the computer

答:
On my High Sierra system, last -1 barmar doesn't print any useful information. My Mac has been up for 9 days (since I installed the most recent security update). It takes 8 seconds to run, and just prints:

```<code>
wtmp begins Fri May 31 12:53
</code>```

So there's a blank line and then the line saying where wtmp begins, which always seems to be the current time.

So the awk script is working correctly. The first line doesn't have any fields, so all the $n values will be empty, and you get just :00 EDT. The second line contains the wtmp begins line, and that creates Fri May 31 12:48:00 EDT in the output (even though you used -1, it still produces two lines of output). When you combine them, you get

```<code>$ echo "$x"
   :00 EDT
Fri May 31 12:48:00 EDT
</code>```

Terminal 'last' command doesn't display login history claims that sudo last should work, but it doesn't for me.

How do you stop wtmp from erasing? suggests getting the information you want from /var/log/monthly.out.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to turn data from the last command into epoch time using the awk print. the code works on 10.14.5 all the time, and works on 10.13.6 some of the time. When I came into work this morning it worked fine, then around 11 started giving me errors.

Basically, awk is printing literal strings, then a newline character, then the literal strings and the variables as it should. for example,
if $1="Hello", then:

awk '{print $1,"World"}'

is actually printing "World
Hello World"

the actual line of code giving the error is this:

x=$(last -1 $a | awk '{print $3 " "$4 " " $5  " " $6 ":00 EDT "}')

where it should be setting x to "Fri May 31 12:43:00 EDT " for example, it is setting x to " :00 EDT
Fri May 31 12:43:00 EDT "

EDIT: I should say that the $a in the line of code would be set to a username on the computer

Body:
On my High Sierra system, last -1 barmar doesn't print any useful information. My Mac has been up for 9 days (since I installed the most recent security update). It takes 8 seconds to run, and just prints:

wtmp begins Fri May 31 12:53

So there's a blank line and then the line saying where wtmp begins, which always seems to be the current time.

So the awk script is working correctly. The first line doesn't have any fields, so all the $n values will be empty, and you get just :00 EDT. The second line contains the wtmp begins line, and that creates Fri May 31 12:48:00 EDT in the output (even though you used -1, it still produces two lines of output). When you combine them, you get

$ echo "$x"
   :00 EDT
Fri May 31 12:48:00 EDT

Terminal 'last' command doesn't display login history claims that sudo last should work, but it doesn't for me.

How do you stop wtmp from erasing? suggests getting the information you want from /var/log/monthly.out.


问:
Add page numbers to the bottom of Word document in the format X of Y
I am trying to add the X of Y page numbers to the bottom right of a Word document. X being the current page number and Y being the total number of pages in the document.

I recorded a macro.

```<code>Sub InsertPageLabelsXofY()

    If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
        ActiveWindow.Panes(2).Close
    End If
    If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
        ActivePane.View.Type = wdOutlineView Then
        ActiveWindow.ActivePane.View.Type = wdPrintView
    End If
    ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter

    Application.Templates( _
        "C:\Users\jhandler\AppData\Roaming\Microsoft\Document Building Blocks\1033\16\Built-In Building Blocks.dotx" _
        ).BuildingBlockEntries("Bold Numbers 3").Insert Where:=Selection.Range, _
        RichText:=True

    ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument

End Sub
</code>```

This works initially, but after a day or so it gives me an error.

Run-time error '5941': The requested member of the collection does not exist

The line that generates the error is:

```<code>Application.Templates( _
    "C:\Users\jhandler\AppData\Roaming\Microsoft\Document Building Blocks\1033\16\Built-In Building Blocks.dotx" _
    ).BuildingBlockEntries("Bold Numbers 3").Insert Where:=Selection.Range, _
    RichText:=True
</code>```

Also, I would like for other people to use the macro. Is there some way to save the template in a public area?

答:
To make your routine work, change the "Application.Templates ..." line to:

```<code> Templates(1).BuildingBlockEntries("Bold Numbers 3").Insert Selection.Range, True
</code>```

Word's building blocks template is always available as a global template, and the Built-in version is always the first template, so it has an index of 1.

Trying to specify the path to this template is what is causing the error. Yes, it might work sometimes but at other times it doesn't, so it is best to just use the index level and it has the added benefit of allowing your code to be transportable to other systems. If you tried to execute your existing code on a system that does not have your Home directory, "handler" then it will fail.

Body:
I am trying to add the X of Y page numbers to the bottom right of a Word document. X being the current page number and Y being the total number of pages in the document.

I recorded a macro.

Sub InsertPageLabelsXofY()

    If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
        ActiveWindow.Panes(2).Close
    End If
    If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
        ActivePane.View.Type = wdOutlineView Then
        ActiveWindow.ActivePane.View.Type = wdPrintView
    End If
    ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter

    Application.Templates( _
        "C:\Users\jhandler\AppData\Roaming\Microsoft\Document Building Blocks\1033\16\Built-In Building Blocks.dotx" _
        ).BuildingBlockEntries("Bold Numbers 3").Insert Where:=Selection.Range, _
        RichText:=True

    ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument

End Sub

This works initially, but after a day or so it gives me an error.

Run-time error '5941': The requested member of the collection does not exist

The line that generates the error is:

Application.Templates( _
    "C:\Users\jhandler\AppData\Roaming\Microsoft\Document Building Blocks\1033\16\Built-In Building Blocks.dotx" _
    ).BuildingBlockEntries("Bold Numbers 3").Insert Where:=Selection.Range, _
    RichText:=True

Also, I would like for other people to use the macro. Is there some way to save the template in a public area?

Body:
To make your routine work, change the "Application.Templates ..." line to:

 Templates(1).BuildingBlockEntries("Bold Numbers 3").Insert Selection.Range, True

Word's building blocks template is always available as a global template, and the Built-in version is always the first template, so it has an index of 1.

Trying to specify the path to this template is what is causing the error. Yes, it might work sometimes but at other times it doesn't, so it is best to just use the index level and it has the added benefit of allowing your code to be transportable to other systems. If you tried to execute your existing code on a system that does not have your Home directory, "handler" then it will fail.


问:
Modify CucumberOptions tags when running Cucumber in Java
I was wondering if there was a way to modify CucumberOptions tags while Cucumber is running?

I'm not sure if this is possible or not but I was wondering if there was a way to modify tags while Cucumber is running. In my example code, I would like to add another tag "@Login" once Cucumber runs. I am trying to setup a configuration where I can select which feature I want to run without going into the Runner class.

Settings Class

```<code> String AddTags = "@Login";
          set = new HashMap<String, String>(){
            {put("Tags", AddTags);
</code>```

Runner

```<code>import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions (features="src/test/cucumber/features",
tags = "@Smoke",  //For instance, once cucumber runs I want to add
tag "@Login". //So something like adding Settings.set.get("Tags");
plugin = {"pretty", "html:target/cucumber-
htmlreport","json:target/cucumber-report.json"}
)
public class Runner {

}
</code>```

Not sure if this is possible with Cucumber but wanted to ask.

答:
What about using a list of tags?</p>

```<code>tags = "@Smoke,@Login"
</code>```

Body:
I was wondering if there was a way to modify CucumberOptions tags while Cucumber is running?

I'm not sure if this is possible or not but I was wondering if there was a way to modify tags while Cucumber is running. In my example code, I would like to add another tag "@Login" once Cucumber runs. I am trying to setup a configuration where I can select which feature I want to run without going into the Runner class.

Settings Class

 String AddTags = "@Login";
          set = new HashMap<String, String>(){
            {put("Tags", AddTags);

Runner

import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions (features="src/test/cucumber/features",
tags = "@Smoke",  //For instance, once cucumber runs I want to add
tag "@Login". //So something like adding Settings.set.get("Tags");
plugin = {"pretty", "html:target/cucumber-
htmlreport","json:target/cucumber-report.json"}
)
public class Runner {

}

Not sure if this is possible with Cucumber but wanted to ask.

Body:
What about using a list of tags?

tags = "@Smoke,@Login"


问:
7z get total size of uncompress contents?
How might i get the size of the contents of a zip/rar/7z file after full extraction? Under both windows and linux. I thought about using 7z l filename command but i dont like the idea of the filename interfering with the code counting the size of each file.</p>

答:
This doesn't solve your filename problem, but may be good enough for others and myself (in cygwin):</p>

```<code>/cygdrive/c/Program\ Files/7-Zip/7z.exe l filename.zip | grep -e "files,.*folders" | awk '{printf $1}'
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This doesn't solve your filename problem, but may be good enough for others and myself (in cygwin):

/cygdrive/c/Program\ Files/7-Zip/7z.exe l filename.zip | grep -e "files,.*folders" | awk '{printf $1}'

ContentLicense: CC BY-SA 3.0


问:
Skip Current Migrations but Apply Future Ones
QUESTION:
Is there any way I can avoid running current migrations on a remote database already configured correctly,  while ALSO being allowed to apply future migrations to it?

Context:

I have an existing rails app with plenty of migrations, that, up until now, has been using a local postgres database. A remote postgres database which SHOULD mostly match up to the structure of my local database exists.

When I try to connect to it, I get a "pending migrations" error.  Attempting to run my migrations gets errors about tables already existing.

I want to skip all current migrations, but UNLIKE a lot of similar questions I'm seeing, I want to make sure my future migrations will work on this remote database.

Edit:

I followed this answer:

Rails 4 how to ignore pending migrations

And inserted my own current scheme version number into the remove database's schema_migrations table. But the pending migration remains.

I can confirm trying to run the migration gets me an error of a table already existing. This table is the FIRST migration past the remote databases previously most recent version in the schema table. It appears to be ignoring my inserted current most recent version.

答:
You have to add all migration version numbers that you want to ignore to schema_migrations

Other technique that may be also applicable - migration squashing with something like squasher or manually. Point is in combining all old migrations that are not to be rolled back into one.


问:
Pandas - group by one column, sort by another, get value from the third column
I would like to take pandas dataframe, group it by one column, sort it by another column and take first element from third column and populate original dataframe.

Here is my original df. I would to group by col_1, sort by col_2 (ascending) and take first element from col_3 and populate col_4 with results.

```<code>df_in = pd.DataFrame({'col_1':['A', 'A', 'A', 'B', 'B', 'B'], 'col_2': [5,9,2, 3,7,1],
                   'col_3': ['c','d','k','n','l','f']})
</code>```

[

Here is how output df should look like:

```<code>df_out = pd.DataFrame({'col_1':['A', 'A', 'A', 'B', 'B', 'B'], 'col_2': [5,9,2, 3,7,1],
                   'col_3': ['c','d','k','n','l','f'], 'col_4': ['k','k','k','f','f','f'], })
</code>```

I can accomplish grouping and sorting with group and transform, but how to extract first element is not clear.

Sorry SO does not display images correctly ;-(

Body:
I would like to take pandas dataframe, group it by one column, sort it by another column and take first element from third column and populate original dataframe.

Here is my original df. I would to group by col_1, sort by col_2 (ascending) and take first element from col_3 and populate col_4 with results.

df_in = pd.DataFrame({'col_1':['A', 'A', 'A', 'B', 'B', 'B'], 'col_2': [5,9,2, 3,7,1],
                   'col_3': ['c','d','k','n','l','f']})

[

Here is how output df should look like:

df_out = pd.DataFrame({'col_1':['A', 'A', 'A', 'B', 'B', 'B'], 'col_2': [5,9,2, 3,7,1],
                   'col_3': ['c','d','k','n','l','f'], 'col_4': ['k','k','k','f','f','f'], })

I can accomplish grouping and sorting with group and transform, but how to extract first element is not clear.

Sorry SO does not display images correctly ;-(

Body:
Try, given your index is as shown,

df_in.sort_values('col_2',  inplace=True)
df_in['col_4'] = df_in.groupby('col_1').col_3.transform('first')

df_in.sort_index(inplace=True)

Output:

+----+---------+---------+---------+---------+
|    | col_1   |   col_2 | col_3   | col_4   |
|----+---------+---------+---------+---------|
|  0 | A       |       5 | c       | k       |
|  1 | A       |       9 | d       | k       |
|  2 | A       |       2 | k       | k       |
|  3 | B       |       3 | n       | f       |
|  4 | B       |       7 | l       | f       |
|  5 | B       |       1 | f       | f       |
+----+---------+---------+---------+---------+


问:
How do I check if a MediaWiki extension is installed from within another extension?
I am currently working on a MediaWiki extension that requires the "Arrays" extension for some features. If the array extension is not installed, my extension should give a friendly warning when trying to use said features.

How do I check if an extension is installed from within another extension?

答: The nice way is ExtensionRegistry::getInstance()->isLoaded( 'Arrays' ). This only works for extensions which use extension registration (which Arrays does). Otherwise, you can just check if some class from that extension can be loaded.


问:
Can I add a curved trend line to a ggplot with only one data point per column?
I have used ggplot2 to create a line graph for a soil water release curve. However, because I only have one data point at each pressure value (the x axis), the lines are connected directly from point to point. I would like to keep the points but have a curve that shows the trend of the points. This is the typical style for soil water release curves.

Data:

```<code>> dput(head(sub2018))
structure(list(Year = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label =
c("2018",
"2019"), class = "factor"), Pressure = structure(1:6, .Label = c("-1",
"-0.5", "-0.25", "-0.2", "-0.1", "-0.05", "-0.02", "-0.01", "0"
), class = "factor"), meanVWC = c(0.291819594, 0.308328767666667,
0.318496127666667, 0.323671866333333, 0.349356212666667,
0.374201803666667
)), row.names = c(NA, -6L), class = c("grouped_df", "tbl_df",
"tbl", "data.frame"), vars = "Year", drop = TRUE, indices = list(
0:5), group_sizes = 6L, biggest_group_size = 6L, labels = structure(list(
Year = structure(1L, .Label = c("2018", "2019"), class = "factor")),
row.names = c(NA,
-1L), class = "data.frame", vars = "Year", drop = TRUE))
</code>```

ggplot:

```<code>GGplot2018 <- ggplot(sub2018, aes(x=Pressure, y=meanVWC, group=1)) +
  geom_line() +
  geom_point() + labs(y= "Volumetric Water Content")
GGplot2018
</code>```

Does anyone know if/how I can add this curve?

Thanks very much for any help!

答:
I believe this is what you are looking for:</p>

```<code>GGplot2018 <- ggplot(sub2018, aes(x=Pressure, y=meanVWC, group=1)) +
  geom_line()+
  geom_point() + labs(y= "Volumetric Water Content")+
  geom_smooth(method = "lm",se = FALSE)
GGplot2018
</code>```

Body:
I have used ggplot2 to create a line graph for a soil water release curve. However, because I only have one data point at each pressure value (the x axis), the lines are connected directly from point to point. I would like to keep the points but have a curve that shows the trend of the points. This is the typical style for soil water release curves.

Data:

> dput(head(sub2018))
structure(list(Year = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label =
c("2018",
"2019"), class = "factor"), Pressure = structure(1:6, .Label = c("-1",
"-0.5", "-0.25", "-0.2", "-0.1", "-0.05", "-0.02", "-0.01", "0"
), class = "factor"), meanVWC = c(0.291819594, 0.308328767666667,
0.318496127666667, 0.323671866333333, 0.349356212666667,
0.374201803666667
)), row.names = c(NA, -6L), class = c("grouped_df", "tbl_df",
"tbl", "data.frame"), vars = "Year", drop = TRUE, indices = list(
0:5), group_sizes = 6L, biggest_group_size = 6L, labels = structure(list(
Year = structure(1L, .Label = c("2018", "2019"), class = "factor")),
row.names = c(NA,
-1L), class = "data.frame", vars = "Year", drop = TRUE))

ggplot:

GGplot2018 <- ggplot(sub2018, aes(x=Pressure, y=meanVWC, group=1)) +
  geom_line() +
  geom_point() + labs(y= "Volumetric Water Content")
GGplot2018

Does anyone know if/how I can add this curve?

Thanks very much for any help!

Body:
I believe this is what you are looking for:

GGplot2018 <- ggplot(sub2018, aes(x=Pressure, y=meanVWC, group=1)) +
  geom_line()+
  geom_point() + labs(y= "Volumetric Water Content")+
  geom_smooth(method = "lm",se = FALSE)
GGplot2018


问:
MVC Policy Override in Integration Tests
I am in the process of adding integration tests at work for an MVC app. Many of our endpoints have policies applied to them, e.g.

```<code>namespace WorkProject
{
  [Route("A/Route")]
  public class WorkController : Controller
  {
    [HttpPost("DoStuff")]
    [Authorize(Policy = "CanDoStuff")]
    public IActionResult DoStuff(){/* */}
  }
}
</code>```

For our integration tests, I have overridden the WebApplicationFactory like it is suggested in the ASP .NET Core documentation. My goal was to overload the authentication step and to bypass the policy by making a class which allows all parties through the authorization policy.

```<code>namespace WorkApp.Tests
{
    public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup: class
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            base.ConfigureWebHost(builder);
            builder.ConfigureServices(services =>
            {
                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = "Test Scheme"; // has to match scheme in TestAuthenticationExtensions
                    options.DefaultChallengeScheme = "Test Scheme";
                }).AddTestAuth(o => { });

                services.AddAuthorization(options =>
                {
                    options.AddPolicy("CanDoStuff", policy =>
                        policy.Requirements.Add(new CanDoStuffRequirement()));
                });

             // I've also tried the line below, but neither worked
             // I figured that maybe the services in Startup were added before these
             // and that a replacement was necessary
             // services.AddTransient<IAuthorizationHandler, CanDoStuffActionHandler>();
             services.Replace(ServiceDescriptor.Transient<IAuthorizationHandler, CanDoStuffActionHandler>());
            });
        }
    }

    internal class CanDoStuffActionHandler : AuthorizationHandler<CanDoStuffActionRequirement>
    {
        public CanDoStuffActionHandler()
        {
        }

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CanDoStuffActionRequirement requirement)
        {
            context.Succeed(requirement);

            return Task.CompletedTask;
        }
    }

    internal class CanDoStuffRequirement : IAuthorizationRequirement
    {
    }
}
</code>```

The first thing that I do to the services is override the authentication as suggested here (without the bit about overriding Startup since that didn't seem to work for me). I am inclined to believe that this authentication override works. When I run my tests, I receive an HTTP 403 from within the xUnit testing framework. If I hit the route that I am testing from PostMan I receive an HTTP 401. I have also made a class that lives in the custom web application factory that allows all requests for the CanDoStuff authorization handler. I thought this would allow the integration tests through the authorization policy, but, as stated above, I receive an HTTP 403. I know that a 403 will be returned if the app doesn't know where certain files are. However, this is a post route strictly for receiving and processing data and this route does not attempt to return any views so this 403 is most likely related to the authorization policy which, for some reason, is not being overridden.

I'm clearly doing something wrong. When I run the test under debug mode and set a breakpoint in the HandleRequirementsAsync function, the application never breaks. Is there a different way that I should be attempting to override the authorization policies?

答:
Here is what I did.

Override the WebApplicationFactory with my own. Note, I still added my application's startup as the template parameter

Create my on startup function which overrides the ConfigureAuthServices function that I added.

Tell the builder in the ConfigureWebHost function to use my custom startup class.

Override the authentication step in the ConfigureWebHost function via builder.ConfigureServices.

Add an assembly reference to the controller whose endpoint I am trying to hit at the end of builder.ConfigureServices in the ConfigureWebHost function.

Write my own IAuthorizationHandler for the policy that allows all requests to succeed.

I hope I have done a decent job at explaining what I did. If not, hopefully the sample code below is easy enough to follow.

YourController.cs

```<code>namespace YourApplication
{
  [Route("A/Route")]
  public class WorkController : Controller
  {
    [HttpPost("DoStuff")]
    [Authorize(Policy = "CanDoStuff")]
    public IActionResult DoStuff(){/* */}
  }
}
</code>```

Test.cs

```<code>namespace YourApplication.Tests
{
    public class Tests
        : IClassFixture<CustomWebApplicationFactory<YourApplication.Startup>>
    {
        private readonly CustomWebApplicationFactory<YourApplication.Startup> _factory;

        public Tests(CustomWebApplicationFactory<YourApplication.Startup> factory)
        {
            _factory = factory;
        }

        [Fact]
        public async Task SomeTest()
        {
            var client = _factory.CreateClient();
            var response = await client.PostAsync("/YourEndpoint");
            response.EnsureSuccessStatusCode();

            Assert.Equal(/* whatever your condition is */);
        }
    }
}
</code>```

CustomWebApplicationFactory.cs

```<code>namespace YourApplication.Tests
{
    public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup: class
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            base.ConfigureWebHost(builder);
            builder.ConfigureServices(services =>
            {
                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = "Test Scheme"; // has to match scheme in TestAuthenticationExtensions
                    options.DefaultChallengeScheme = "Test Scheme";
                }).AddTestAuth(o => { });

                services.AddAuthorization(options =>
                {
                    options.AddPolicy("CanDoStuff", policy =>
                        policy.Requirements.Add(new CanDoStuffRequirement()));
                });

             services.AddMvc().AddApplicationPart(typeof(YourApplication.Controllers.YourController).Assembly);
             services.AddTransient<IAuthorizationHandler, CanDoStuffActionHandler>();
            });
            builder.UseStartup<TestStartup>();
        }
    }

    internal class CanDoStuffActionHandler : AuthorizationHandler<CanDoStuffActionRequirement>
    {
        public CanDoStuffActionHandler()
        {
        }

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CanDoStuffActionRequirement requirement)
        {
            context.Succeed(requirement);

            return Task.CompletedTask;
        }
    }

    internal class CanDoStuffRequirement : IAuthorizationRequirement
    {
    }
}
</code>```

TestStartup.cs

```<code>namespace YourApplication.Tests
{
    public class TestStartup : YourApplication.Startup
    {
        public TestStartup(IConfiguration configuration) : base(configuration)
        {

        }

        protected override void ConfigureAuthServices(IServiceCollection services)
        {
        }
    }
}
</code>```

Body:
I am in the process of adding integration tests at work for an MVC app. Many of our endpoints have policies applied to them, e.g.

namespace WorkProject
{
  [Route("A/Route")]
  public class WorkController : Controller
  {
    [HttpPost("DoStuff")]
    [Authorize(Policy = "CanDoStuff")]
    public IActionResult DoStuff(){/* */}
  }
}

For our integration tests, I have overridden the WebApplicationFactory like it is suggested in the ASP .NET Core documentation. My goal was to overload the authentication step and to bypass the policy by making a class which allows all parties through the authorization policy.

namespace WorkApp.Tests
{
    public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup: class
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            base.ConfigureWebHost(builder);
            builder.ConfigureServices(services =>
            {
                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = "Test Scheme"; // has to match scheme in TestAuthenticationExtensions
                    options.DefaultChallengeScheme = "Test Scheme";
                }).AddTestAuth(o => { });

                services.AddAuthorization(options =>
                {
                    options.AddPolicy("CanDoStuff", policy =>
                        policy.Requirements.Add(new CanDoStuffRequirement()));
                });

             // I've also tried the line below, but neither worked
             // I figured that maybe the services in Startup were added before these
             // and that a replacement was necessary
             // services.AddTransient<IAuthorizationHandler, CanDoStuffActionHandler>();
             services.Replace(ServiceDescriptor.Transient<IAuthorizationHandler, CanDoStuffActionHandler>());
            });
        }
    }

    internal class CanDoStuffActionHandler : AuthorizationHandler<CanDoStuffActionRequirement>
    {
        public CanDoStuffActionHandler()
        {
        }

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CanDoStuffActionRequirement requirement)
        {
            context.Succeed(requirement);

            return Task.CompletedTask;
        }
    }

    internal class CanDoStuffRequirement : IAuthorizationRequirement
    {
    }
}

The first thing that I do to the services is override the authentication as suggested here (without the bit about overriding Startup since that didn't seem to work for me). I am inclined to believe that this authentication override works. When I run my tests, I receive an HTTP 403 from within the xUnit testing framework. If I hit the route that I am testing from PostMan I receive an HTTP 401. I have also made a class that lives in the custom web application factory that allows all requests for the CanDoStuff authorization handler. I thought this would allow the integration tests through the authorization policy, but, as stated above, I receive an HTTP 403. I know that a 403 will be returned if the app doesn't know where certain files are. However, this is a post route strictly for receiving and processing data and this route does not attempt to return any views so this 403 is most likely related to the authorization policy which, for some reason, is not being overridden.

I'm clearly doing something wrong. When I run the test under debug mode and set a breakpoint in the HandleRequirementsAsync function, the application never breaks. Is there a different way that I should be attempting to override the authorization policies?

Body:
Here is what I did.

Override the WebApplicationFactory with my own. Note, I still added my application's startup as the template parameter

Create my on startup function which overrides the ConfigureAuthServices function that I added.

Tell the builder in the ConfigureWebHost function to use my custom startup class.

Override the authentication step in the ConfigureWebHost function via builder.ConfigureServices.

Add an assembly reference to the controller whose endpoint I am trying to hit at the end of builder.ConfigureServices in the ConfigureWebHost function.

Write my own IAuthorizationHandler for the policy that allows all requests to succeed.

I hope I have done a decent job at explaining what I did. If not, hopefully the sample code below is easy enough to follow.

YourController.cs

namespace YourApplication
{
  [Route("A/Route")]
  public class WorkController : Controller
  {
    [HttpPost("DoStuff")]
    [Authorize(Policy = "CanDoStuff")]
    public IActionResult DoStuff(){/* */}
  }
}

Test.cs

namespace YourApplication.Tests
{
    public class Tests
        : IClassFixture<CustomWebApplicationFactory<YourApplication.Startup>>
    {
        private readonly CustomWebApplicationFactory<YourApplication.Startup> _factory;

        public Tests(CustomWebApplicationFactory<YourApplication.Startup> factory)
        {
            _factory = factory;
        }

        [Fact]
        public async Task SomeTest()
        {
            var client = _factory.CreateClient();
            var response = await client.PostAsync("/YourEndpoint");
            response.EnsureSuccessStatusCode();

            Assert.Equal(/* whatever your condition is */);
        }
    }
}

CustomWebApplicationFactory.cs

namespace YourApplication.Tests
{
    public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup: class
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            base.ConfigureWebHost(builder);
            builder.ConfigureServices(services =>
            {
                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = "Test Scheme"; // has to match scheme in TestAuthenticationExtensions
                    options.DefaultChallengeScheme = "Test Scheme";
                }).AddTestAuth(o => { });

                services.AddAuthorization(options =>
                {
                    options.AddPolicy("CanDoStuff", policy =>
                        policy.Requirements.Add(new CanDoStuffRequirement()));
                });

             services.AddMvc().AddApplicationPart(typeof(YourApplication.Controllers.YourController).Assembly);
             services.AddTransient<IAuthorizationHandler, CanDoStuffActionHandler>();
            });
            builder.UseStartup<TestStartup>();
        }
    }

    internal class CanDoStuffActionHandler : AuthorizationHandler<CanDoStuffActionRequirement>
    {
        public CanDoStuffActionHandler()
        {
        }

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CanDoStuffActionRequirement requirement)
        {
            context.Succeed(requirement);

            return Task.CompletedTask;
        }
    }

    internal class CanDoStuffRequirement : IAuthorizationRequirement
    {
    }
}

TestStartup.cs

namespace YourApplication.Tests
{
    public class TestStartup : YourApplication.Startup
    {
        public TestStartup(IConfiguration configuration) : base(configuration)
        {

        }

        protected override void ConfigureAuthServices(IServiceCollection services)
        {
        }
    }
}


问:
Android: How to create my own cursor class?
I'm using Sqlite in Android and to get a value from the database I use something like this:

```<code>Cursor cursor = sqliteDatabase.rawQuery("select title,category from table", null);

int columnIndexTitle = cursor.getColumnIndex("title");
iny columnIndexCategory = cursor.getColumnIndex("category");

cursor.moveToFirst();
while (cursor.moveToNext()) {
    String title = cursor.getString(columnIndexTitle);
    String category = cursor.getString(columnIndexCategory);
}
cursor.close();
</code>```

I want to create my own Cursor so that I can do getColumnIndex() and getString() with one method. Something like this:

```<code>String title = cursor.getString("title");
</code>```

I want to create my own class that extends the cursor that I get from sqliteDatabase.rawQuery, but I'm not sure how to accomplish this. Should I extend SQLiteCursor or how should I do this? Is it even a possible and is it a good idea?

答:
I wouldn't extend it, I'd make a helper:

```<code>class MartinCursor {
    private Cursor cursor;

    MartinCursor(Cursor cursor) {
        this.cursor = cursor;
    }

    String getString(String column) {
        ....
    }
}
</code>```

or

```<code>class MartinCursorHelper {
    static String getString(Cursor cursor, String column) {
        ....
    }
}
</code>```

Personally, I'd do the latter, unless you hate providing this extra argument all the time.

EDIT: I forgot to mention pydave's important point: If you call this in a loop, you're setting yourself up for a noticeable performance impact. The preferred way is to lookup the index once, cache it, and use that instead.

Body:
I'm using Sqlite in Android and to get a value from the database I use something like this:

Cursor cursor = sqliteDatabase.rawQuery("select title,category from table", null);

int columnIndexTitle = cursor.getColumnIndex("title");
iny columnIndexCategory = cursor.getColumnIndex("category");

cursor.moveToFirst();
while (cursor.moveToNext()) {
    String title = cursor.getString(columnIndexTitle);
    String category = cursor.getString(columnIndexCategory);
}
cursor.close();

I want to create my own Cursor so that I can do getColumnIndex() and getString() with one method. Something like this:

String title = cursor.getString("title");

I want to create my own class that extends the cursor that I get from sqliteDatabase.rawQuery, but I'm not sure how to accomplish this. Should I extend SQLiteCursor or how should I do this? Is it even a possible and is it a good idea?

Body:
I wouldn't extend it, I'd make a helper:

class MartinCursor {
    private Cursor cursor;

    MartinCursor(Cursor cursor) {
        this.cursor = cursor;
    }

    String getString(String column) {
        ....
    }
}

or

class MartinCursorHelper {
    static String getString(Cursor cursor, String column) {
        ....
    }
}

Personally, I'd do the latter, unless you hate providing this extra argument all the time.

EDIT: I forgot to mention pydave's important point: If you call this in a loop, you're setting yourself up for a noticeable performance impact. The preferred way is to lookup the index once, cache it, and use that instead.


问:
Sorting Child Elements Based on 'h2' Tag
I have an an example page containing several categories. Each category is wrapped in a .items class which contains an h2 title tag and several links. My goal is to sort each of those categories alphabetically based on the h2 tag.

I found several examples on how to do this, but they were in jquery. I want to do this only in javascript. I found some code that will sort divs but not by the divs's h2 tag.

HTML

Testimonials

    Testimonial slider

Directories

     Staff Directory

FAQ

Forms

      Simple contact form - WIP
      Online payment form using Network Merchants - WIP
      Form with attachment

```

<p><strong>JavaScript</strong></p>

```sortCategory('#mainContainer');
function sortCategory(s) {
  Array.prototype.slice.call(document.body.querySelectorAll(s)).sort(function sort (ea, eb) {
    var a = ea.textContent.trim();
    var b = eb.textContent.trim();
    if (a  b) return 1;
    return 0;
  }).forEach(function(div) {
    div.parentElement.appendChild(div);
  });
}
```

<p>How can I modify the javascipt code to sort each <code>.item</code> by the h2 tag?</p>

<h2>Solution</h2>

<p>With the help of others I figured it out and wanted to share the code. I also formatted the code to be easily read.</p>

```//****************************************
// Sort Categories Alphabetically
//****************************************

function sortCategory(elementContainer)
{
  var allElements = document.body.querySelectorAll(elementContainer);
  Array.prototype.slice.call(allElements).sort(byAlphabet).forEach(function(div)
  {
    div.parentElement.appendChild(div);
  });
}

function byAlphabet(first, second)
{
  var order = 0;
  var first = first.querySelector('h2').textContent.trim();
  var second = second.querySelector('h2').textContent.trim();

  first > second ? order = 1 : order = -1;

  return order;
}

//Call sortCategory function and pass in the container you want sorted
sortCategory('#mainContainer>.item');
```

答:
Change ea.textContent.trim() to ea.querySelector('h2').textContent.trim()

and

change eb.textContent.trim() to eb.querySelector('h2').textContent.trim()

This will basically say check each div's first H2 element, rather than the div.

Hope I was helpful!

Body:
I have an an example page containing several categories. Each category is wrapped in a .items class which contains an h2 title tag and several links. My goal is to sort each of those categories alphabetically based on the h2 tag.

I found several examples on how to do this, but they were in jquery. I want to do this only in javascript. I found some code that will sort divs but not by the divs's h2 tag.

HTML

Testimonials

    Testimonial slider

Directories

     Staff Directory

FAQ

Forms

      Simple contact form - WIP
      Online payment form using Network Merchants - WIP
      Form with attachment

JavaScript

sortCategory('#mainContainer');
function sortCategory(s) {
  Array.prototype.slice.call(document.body.querySelectorAll(s)).sort(function sort (ea, eb) {
    var a = ea.textContent.trim();
    var b = eb.textContent.trim();
    if (a  b) return 1;
    return 0;
  }).forEach(function(div) {
    div.parentElement.appendChild(div);
  });
}

How can I modify the javascipt code to sort each .item by the h2 tag?

Solution

With the help of others I figured it out and wanted to share the code. I also formatted the code to be easily read.

//****************************************
// Sort Categories Alphabetically
//****************************************

function sortCategory(elementContainer)
{
  var allElements = document.body.querySelectorAll(elementContainer);
  Array.prototype.slice.call(allElements).sort(byAlphabet).forEach(function(div)
  {
    div.parentElement.appendChild(div);
  });
}

function byAlphabet(first, second)
{
  var order = 0;
  var first = first.querySelector('h2').textContent.trim();
  var second = second.querySelector('h2').textContent.trim();

  first > second ? order = 1 : order = -1;

  return order;
}

//Call sortCategory function and pass in the container you want sorted
sortCategory('#mainContainer>.item');


问:
Making a property deserialize but not serialize with json.net
We have some configuration files which were generated by serializing C# objects with Json.net.

We'd like to migrate one property of the serialised class away from being a simple enum property into a class property.

One easy way to do this, would be to leave the old enum property on the class, and arrange for Json.net to read this property when we load the config, but not to save it again when we next serialize the object.   We'll deal with generating the new class from the old enum separately.

Is there any simple way to mark (e.g. with attributes) a property of a C# object, so that Json.net will ignore it ONLY when serializing, but attend to it when deserializing?

答:
Depending on where in the application this takes place and if it's just one property, one manual way you can do this is by setting the property value to null and then on the model you can specify that the property be ignored if the value is null:

```<code>[JsonProperty(NullValueHandling = NullValue.Ignore)]
public string MyProperty { get; set; }
</code>```

If you are working on an ASP.NET Core web app, you can globally set this for all properties in all models by setting this in your Startup.cs file:

```<code>public void ConfigureServices(IServiceCollection services) {
    // other configuration here
    services.AddMvc()
        .AddJsonOptions(options => options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore);
}
</code>```

Body:
Depending on where in the application this takes place and if it's just one property, one manual way you can do this is by setting the property value to null and then on the model you can specify that the property be ignored if the value is null:

[JsonProperty(NullValueHandling = NullValue.Ignore)]
public string MyProperty { get; set; }

If you are working on an ASP.NET Core web app, you can globally set this for all properties in all models by setting this in your Startup.cs file:

public void ConfigureServices(IServiceCollection services) {
    // other configuration here
    services.AddMvc()
        .AddJsonOptions(options => options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore);
}


问:
How to manually add an error bar (95% CI) to a barplot
I drew a cumulative barplot with ggplot2:

```<code>a <- ggplot(datasilice2) +
  aes(x = Duree_exposition_4gpes, fill = factor(Antinucléaires_sup_ou_egal_200)) +
  geom_bar(position = "fill", show.legend = F, colour = "NA", alpha = 0.4) +
  scale_fill_manual(values=c(NA, "red")) +
  scale_y_continuous(name = "Yes", limits=c(0,0.5),oob = rescale_none, breaks = seq(0,0.5,0.05), labels = percent_format(suffix = "%", accuracy = 1))
</code>```

It looks like this:

I want to add an error bar for each column.

So first, I manually calculated each 95% CI :

```<code>binom.test(2,45)$conf.int*100
binom.test(3,10)$conf.int*100
binom.test(5,18)$conf.int*100
binom.test(12,27)$conf.int*100
</code>```

Then, I use the geom_errorbar function:

```<code>a + geom_errorbar(ymin=0.2, ymax=0.4,width = 0.2, size=1)
</code>```

It does draw an error bar, but every error bars is the same:

Right now I am stuck: I was not able to find the solution for setting every error bar manually. I imagined something like this, but it won't work:

```<code>a + geom_errorbar(ymin=c(0.2,0.22,0.23,0.30), ymax=c(0.4,0.43,0.35,0.50))
#random number, I will put CI here
</code>```

Here is the error I get:

```<code>Aesthetics must be either length 1 or the same as the data (100): ymin, ymax
</code>```

Any ideas of what to do to get something like this?
Thanks!

EDIT:
Here is the 10 first rows of my database (datasilice2):

```<code>> dput(head(datasilice2, 10))
structure(list(Duree_exposition_4gpes = c(3, 3, 0, 1, 0, 1, 2,
2, 1, 3), Antinucléaires_sup_ou_egal_200 = c(1, 0, 0, 1, 1, 1,
0, 0, 1, 1)), row.names = c(NA, -10L), class = c("tbl_df", "tbl",
"data.frame"))
</code>```

As suggested, I created a new dataframe and tried to feed that into the geom_errorbar:

```<code>a <- ggplot(datasilice2) +
  aes(x = Duree_exposition_4gpes, fill = factor(Antinucléaires_sup_ou_egal_200)) +
  geom_bar(position = "fill", show.legend = F, colour = "NA", alpha = 0.4) +
  scale_fill_manual(values=c(NA, "red")) +
  scale_y_continuous(name = "Yes", limits=c(0,0.5),oob = rescale_none, breaks = seq(0,0.5,0.05), labels = percent_format(suffix = "%", accuracy = 1))

newdf <- data.frame(xcol=c(0,1,2,3),ymincol=c(0.2,0.3,0.4,0.5),ymaxcol=c(0.25,0.30,0.45,0.5))
a + geom_errorbar(data=newdf,aes(x=xcol,ymin=ymincol,ymax=ymaxcol))
</code>```

But here is a new error:

```<code>Error in factor(Antinucléaires_sup_ou_egal_200) :
  object 'Antinucléaires_sup_ou_egal_200' not found
</code>```

答: You need to put your manually calculated data into a data frame and feed that into the geom_errorbar.  I don't think ggplot accepts vectors. So your new data frame, say newdf, should have columns for the x value, the y min value, and the ymax value.  Then something like this should work: a + geom_errorbar(data=newdf,aes(x=xcol,ymin=ymincol,ymax=ymaxcol)) (the column names need to match whatever you decide to name them in the dataframe).

Body:
I drew a cumulative barplot with ggplot2:

a <- ggplot(datasilice2) +
  aes(x = Duree_exposition_4gpes, fill = factor(Antinucléaires_sup_ou_egal_200)) +
  geom_bar(position = "fill", show.legend = F, colour = "NA", alpha = 0.4) +
  scale_fill_manual(values=c(NA, "red")) +
  scale_y_continuous(name = "Yes", limits=c(0,0.5),oob = rescale_none, breaks = seq(0,0.5,0.05), labels = percent_format(suffix = "%", accuracy = 1))

It looks like this:

I want to add an error bar for each column.

So first, I manually calculated each 95% CI :

binom.test(2,45)$conf.int*100
binom.test(3,10)$conf.int*100
binom.test(5,18)$conf.int*100
binom.test(12,27)$conf.int*100

Then, I use the geom_errorbar function:

a + geom_errorbar(ymin=0.2, ymax=0.4,width = 0.2, size=1)

It does draw an error bar, but every error bars is the same:

Right now I am stuck: I was not able to find the solution for setting every error bar manually. I imagined something like this, but it won't work:

a + geom_errorbar(ymin=c(0.2,0.22,0.23,0.30), ymax=c(0.4,0.43,0.35,0.50))
#random number, I will put CI here

Here is the error I get:

Aesthetics must be either length 1 or the same as the data (100): ymin, ymax

Any ideas of what to do to get something like this?
Thanks!

EDIT:
Here is the 10 first rows of my database (datasilice2):

> dput(head(datasilice2, 10))
structure(list(Duree_exposition_4gpes = c(3, 3, 0, 1, 0, 1, 2,
2, 1, 3), Antinucléaires_sup_ou_egal_200 = c(1, 0, 0, 1, 1, 1,
0, 0, 1, 1)), row.names = c(NA, -10L), class = c("tbl_df", "tbl",
"data.frame"))

As suggested, I created a new dataframe and tried to feed that into the geom_errorbar:

a <- ggplot(datasilice2) +
  aes(x = Duree_exposition_4gpes, fill = factor(Antinucléaires_sup_ou_egal_200)) +
  geom_bar(position = "fill", show.legend = F, colour = "NA", alpha = 0.4) +
  scale_fill_manual(values=c(NA, "red")) +
  scale_y_continuous(name = "Yes", limits=c(0,0.5),oob = rescale_none, breaks = seq(0,0.5,0.05), labels = percent_format(suffix = "%", accuracy = 1))

newdf <- data.frame(xcol=c(0,1,2,3),ymincol=c(0.2,0.3,0.4,0.5),ymaxcol=c(0.25,0.30,0.45,0.5))
a + geom_errorbar(data=newdf,aes(x=xcol,ymin=ymincol,ymax=ymaxcol))

But here is a new error:

Error in factor(Antinucléaires_sup_ou_egal_200) :
  object 'Antinucléaires_sup_ou_egal_200' not found


问:
Learning neural network and saving the result
I think this is a simple question, but not for me( There is a table in df:

```<code>Date        X1  X2  Y1
07.02.2019  5   1   1
08.02.2019  6   2   1
09.02.2019  1   3   0
10.02.2019  4   4   1
11.02.2019  1   1   0
12.02.2019  4   2   1
13.02.2019  5   5   1
14.02.2019  6   5   1
15.02.2019  1   1   0
16.02.2019  4   5   1
17.02.2019  1   2   0
18.02.2019  1   1
19.02.2019  2   1
20.02.2019  3   2
21.02.2019  4   14
</code>```

I need to build a neural network for Y1 from the parameters X1 and X2 and then apply it to the lines with a date greater than 17.02.2019, And save the network prediction result in a separate df2

```<code> import pandas as pd
    import numpy as np
    import re
    from sklearn.neural_network import MLPClassifier

    df = pd.read_csv("ob.csv", encoding = 'cp1251', sep = ';')
    df['Date'] = pd.to_datetime(df['Date'], format='%d.%m.%Y')
    startdate = pd.to_datetime('2019-02-17')

    X = ['X1', 'X2'] ????
    y = ['Y1'] ????
    clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1)
    clf.fit(x, y)
    clf.predict(???????)  ????? df2 = ????
</code>```

Where ???? - I do not know how to set the conditions correctly

答:
```<code>import pandas as pd
import numpy as np
import re
from sklearn.neural_network import MLPClassifier

df = pd.read_csv("ob.csv", encoding = 'cp1251', sep = ';')
df['Date'] = pd.to_datetime(df['Date'], format='%d.%m.%Y')
startdate = pd.to_datetime('2019-02-17')

train = df[df['Date'] <= '2019-02-17']
test = df[df['Date'] > '2019-02-17']

X_train = train[['X1', 'X2']]
y_train = train[['Y1']]

X_test = test[['X1', 'X2']]
y_test = test[['Y1']]

clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1)
clf.fit(X_train, y_train)
df2 = pd.DataFrame(clf.predict(X_test))
df2.to_csv('prediction.csv')
</code>```

Body:
I think this is a simple question, but not for me( There is a table in df:

Date        X1  X2  Y1
07.02.2019  5   1   1
08.02.2019  6   2   1
09.02.2019  1   3   0
10.02.2019  4   4   1
11.02.2019  1   1   0
12.02.2019  4   2   1
13.02.2019  5   5   1
14.02.2019  6   5   1
15.02.2019  1   1   0
16.02.2019  4   5   1
17.02.2019  1   2   0
18.02.2019  1   1
19.02.2019  2   1
20.02.2019  3   2
21.02.2019  4   14

I need to build a neural network for Y1 from the parameters X1 and X2 and then apply it to the lines with a date greater than 17.02.2019, And save the network prediction result in a separate df2

 import pandas as pd
    import numpy as np
    import re
    from sklearn.neural_network import MLPClassifier

    df = pd.read_csv("ob.csv", encoding = 'cp1251', sep = ';')
    df['Date'] = pd.to_datetime(df['Date'], format='%d.%m.%Y')
    startdate = pd.to_datetime('2019-02-17')

    X = ['X1', 'X2'] ????
    y = ['Y1'] ????
    clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1)
    clf.fit(x, y)
    clf.predict(???????)  ????? df2 = ????

Where ???? - I do not know how to set the conditions correctly


问:
How to fix binary operator
Error C2676 binary '[': 'collection::item' does not define this operator or a conversion to a type acceptable to the predefined operator

I read few posts and Microsoft VS site, but cannot understand how to fix the problem

template<typename T1, typename T2>
class collection {
private:
    class item {
    public:
        T1 item; T2 key;
    };
    unsigned int top;
    item array = new item[top];
public:
    collection& operator[](unsigned int i) {
        return array[i];
    }
    collection(int top) {
        this->top = top;
    }
    void coutarr() {
        for (int i = 0; array[i] != 0; i++) {
            cout << array[i].item << endl;
        }
    }
    void extendarray() {
        item x = new item[top*2];
        for (int i = 0; i < top; i++) {
            x[i] = array[i];
        }
        delete []array;
        swap(array, x);
        top = top*2;

    }
    void addvar(int i, T1 item, T2 key) {
        array[i].item = item; array[i].key = key; //Here 2 Errors
    }
};
```

If someone can explain what shall I do, I'd be very grateful. Thanks.

答:
Error C2676 binary '[': 'collection::item' does not define this operator or a conversion to a type acceptable to the predefined operator

this is because

```<code>item array = new item[top];
</code>```

must be

```<code>item * array = new item[top];
</code>```

but you also have to move the initialization in the constructor when top has a value

Out of that is was better that the constructor collection(int top) get an unsigned value being collection(unsigned top) or better collection(size_t top)

Copy contructor, operator= ... are missing while an attribute is a pointer

What about to check the validity of i in collection& operator[](unsigned int i) and void addvar(int i, T1 item, T2 key) to produce an exception when it is invalid ? addvar is also a strange name because it is a set, a add means the size is increased. You cannot access to an element on a const instance, add const collection& operator[](unsigned int i) const

In void extendarray() to double the size will not do a lot if the initial size is 0 ;-)

Title: How to fix binary operator

Body:
Error C2676 binary '[': 'collection::item' does not define this operator or a conversion to a type acceptable to the predefined operator

I read few posts and Microsoft VS site, but cannot understand how to fix the problem

template<typename T1, typename T2>
class collection {
private:
    class item {
    public:
        T1 item; T2 key;
    };
    unsigned int top;
    item array = new item[top];
public:
    collection& operator[](unsigned int i) {
        return array[i];
    }
    collection(int top) {
        this->top = top;
    }
    void coutarr() {
        for (int i = 0; array[i] != 0; i++) {
            cout << array[i].item << endl;
        }
    }
    void extendarray() {
        item x = new item[top*2];
        for (int i = 0; i < top; i++) {
            x[i] = array[i];
        }
        delete []array;
        swap(array, x);
        top = top*2;

    }
    void addvar(int i, T1 item, T2 key) {
        array[i].item = item; array[i].key = key; //Here 2 Errors
    }
};

If someone can explain what shall I do, I'd be very grateful. Thanks.

Body:
Error C2676 binary '[': 'collection::item' does not define this operator or a conversion to a type acceptable to the predefined operator

this is because

item array = new item[top];

must be

item * array = new item[top];

but you also have to move the initialization in the constructor when top has a value

Out of that is was better that the constructor collection(int top) get an unsigned value being collection(unsigned top) or better collection(size_t top)

Copy contructor, operator= ... are missing while an attribute is a pointer

What about to check the validity of i in collection& operator[](unsigned int i) and void addvar(int i, T1 item, T2 key) to produce an exception when it is invalid ? addvar is also a strange name because it is a set, a add means the size is increased. You cannot access to an element on a const instance, add const collection& operator[](unsigned int i) const

In void extendarray() to double the size will not do a lot if the initial size is 0 ;-)


问:
OutlineShowAllTasks generating runtime error 1100 VBA MS Project
I'm helping my dad out with some of his work on an MS project plan and I've written this macro which will refresh all tasks in an MS project plan to their needed value. Apparently recently the Project plan started acting up and giving a runtime error 1100 on OutlineShowAllTasks (this hasn't happened before). Do you think this is a problem in the logic of the code or could it be due to the volume of the project plan? Code is below. Thanks again for any help in advance. </p>

```<code>Sub RefreshTaskStatus()
Dim tsks As Tasks
Dim t As Task
Dim rgbColor As Long
Dim predCount As Integer
Dim predComplete As Integer
Dim time As Date

time = Now()

OutlineShowAllTasks
FilterApply "All Tasks"

Set tsks = ActiveProject.Tasks

For Each t In tsks
    ' We do not need to worry about the summary tasks
    If (Not t Is Nothing) And (t.Summary) Then
        SelectRow Row:=t.ID, RowRelative:=False
        Font32Ex CellColor:=&HFFFFFF
    End If

    If t.PercentComplete = "100" Then
        'Font32Ex CellColor:=&HCCFFCC
        SetTaskField Field:="Text11", Value:="Completed", TaskID:=t.ID
    End If

    ready = False

    If (Not t Is Nothing) And (Not t.Summary) And (t.PercentComplete <> "100") Then
        SelectTaskField Row:=t.ID, Column:="Name", RowRelative:=False
        rgbColor = ActiveCell.CellColorEx
        pcount = 0
        pcompl = 0

        For Each tPred In t.PredecessorTasks  'looping through the predecessor tasks
                pcount = pcount + 1
                percomp = tPred.PercentComplete
                If percomp = "100" Then pcompl = pcompl + 1
        Next tPred

            If pcount = 0 Then
                    ready = True
            Else
                If pcompl = pcount Then
                    ready = True
                 Else
                    ready = False
                 End If
            End If
            If (ready) Then
                'Font32Ex CellColor:=&HF0D9C6
                SetTaskField Field:="Text11", Value:="Ready", TaskID:=t.ID
                If (t.Text12 = "Yes") Then
                    SetTaskField Field:="Text11", Value:="In Progress", TaskID:=t.ID
                End If

                If t.Text11 = "In Progress" And t.Finish < time Then
                    SetTaskField Field:="Text11", Value:="Late / Overdue", TaskID:=t.ID
                End If

            Else

                'Font32Ex CellColor:=&HFFFFFF
                SetTaskField Field:="Text11", Value:="Not Ready",      TaskID:=t.ID
            End If
        End If
    Next t

End Sub
</code>```

答: OutlineShowAllTasks also will crash if the file is not sorted by ID first. A simple work-around is to add a line that sorts the project by ID number.

Body:
I'm helping my dad out with some of his work on an MS project plan and I've written this macro which will refresh all tasks in an MS project plan to their needed value. Apparently recently the Project plan started acting up and giving a runtime error 1100 on OutlineShowAllTasks (this hasn't happened before). Do you think this is a problem in the logic of the code or could it be due to the volume of the project plan? Code is below. Thanks again for any help in advance.

Sub RefreshTaskStatus()
Dim tsks As Tasks
Dim t As Task
Dim rgbColor As Long
Dim predCount As Integer
Dim predComplete As Integer
Dim time As Date

time = Now()

OutlineShowAllTasks
FilterApply "All Tasks"

Set tsks = ActiveProject.Tasks

For Each t In tsks
    ' We do not need to worry about the summary tasks
    If (Not t Is Nothing) And (t.Summary) Then
        SelectRow Row:=t.ID, RowRelative:=False
        Font32Ex CellColor:=&HFFFFFF
    End If

    If t.PercentComplete = "100" Then
        'Font32Ex CellColor:=&HCCFFCC
        SetTaskField Field:="Text11", Value:="Completed", TaskID:=t.ID
    End If

    ready = False

    If (Not t Is Nothing) And (Not t.Summary) And (t.PercentComplete <> "100") Then
        SelectTaskField Row:=t.ID, Column:="Name", RowRelative:=False
        rgbColor = ActiveCell.CellColorEx
        pcount = 0
        pcompl = 0

        For Each tPred In t.PredecessorTasks  'looping through the predecessor tasks
                pcount = pcount + 1
                percomp = tPred.PercentComplete
                If percomp = "100" Then pcompl = pcompl + 1
        Next tPred

            If pcount = 0 Then
                    ready = True
            Else
                If pcompl = pcount Then
                    ready = True
                 Else
                    ready = False
                 End If
            End If
            If (ready) Then
                'Font32Ex CellColor:=&HF0D9C6
                SetTaskField Field:="Text11", Value:="Ready", TaskID:=t.ID
                If (t.Text12 = "Yes") Then
                    SetTaskField Field:="Text11", Value:="In Progress", TaskID:=t.ID
                End If

                If t.Text11 = "In Progress" And t.Finish < time Then
                    SetTaskField Field:="Text11", Value:="Late / Overdue", TaskID:=t.ID
                End If

            Else

                'Font32Ex CellColor:=&HFFFFFF
                SetTaskField Field:="Text11", Value:="Not Ready",      TaskID:=t.ID
            End If
        End If
    Next t

End Sub


问:
Led matrix row bits don't shift
I am new to VHDL and I am trying to do a simple application with a led matrix (8x8). My goal is to turn on the leds of the matrix so I can see a smiley face. For some reason none of the leds turn on.

In order to see what's wrong I tried to turn on all leds on each line at a time by commenting the case statement and giving cols<="00000000" before the statement, the result is that the only line that turns on is the first, it keeps turning on and off each second.

I made the frequency divider for 1 second just to see if the code works correctly.

```<code>use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
use IEEE.std_logic_unsigned.all;

entity main is
    Port ( clk : in STD_LOGIC;
           rows : out STD_LOGIC_VECTOR (7 downto 0);
           cols : out STD_LOGIC_VECTOR (7 downto 0));
end main;

architecture Behavioral of main is

signal count: std_logic_vector(7 downto 0):= "00000001";
signal clk1Hz: std_logic_vector(26 downto 0);

begin

process(clk)
begin
    if rising_edge(clk) then
        if clk1Hz = X"5F5E0FF" then
            clk1Hz <= "000" & X"000000";
        else
            clk1Hz <= clk1Hz + 1;
        end if;

        if clk1Hz(26) = '1' then
            if count = "10000000" then
                count <= "00000001";
             else
                count(7 downto 1) <= count(6 downto 0);
                count(0) <= '0';
            end if;

         rows <= count;

        case count is
            when "00000001" => cols <= "11111111";
            when "00000010" => cols <= "11011011";
            when "00000100" => cols <= "11011011";
            when "00001000" => cols <= "11111111";
            when "00010000" => cols <= "00111100";
            when "00100000" => cols <= "10000001";
            when "01000000" => cols <= "11000011";
            when "10000000" => cols <= "11111111";
            when others => cols <= "11111111";
         end case;
     end if;

    end if;

end process;
end Behavioral;
</code>```

答:
Do you realize that if clk1Hz(26) = '1' then stays true from X"4000000" to X"5F5E0FF"?

You most likely want to change count only on the exact X"4000000" value, no? And not continuously for 1/3rd of the time...

Title: Led matrix row bits don't shift

Body:
I am new to VHDL and I am trying to do a simple application with a led matrix (8x8). My goal is to turn on the leds of the matrix so I can see a smiley face. For some reason none of the leds turn on.

In order to see what's wrong I tried to turn on all leds on each line at a time by commenting the case statement and giving cols<="00000000" before the statement, the result is that the only line that turns on is the first, it keeps turning on and off each second.

I made the frequency divider for 1 second just to see if the code works correctly.

use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
use IEEE.std_logic_unsigned.all;

entity main is
    Port ( clk : in STD_LOGIC;
           rows : out STD_LOGIC_VECTOR (7 downto 0);
           cols : out STD_LOGIC_VECTOR (7 downto 0));
end main;

architecture Behavioral of main is

signal count: std_logic_vector(7 downto 0):= "00000001";
signal clk1Hz: std_logic_vector(26 downto 0);

begin

process(clk)
begin
    if rising_edge(clk) then
        if clk1Hz = X"5F5E0FF" then
            clk1Hz <= "000" & X"000000";
        else
            clk1Hz <= clk1Hz + 1;
        end if;

        if clk1Hz(26) = '1' then
            if count = "10000000" then
                count <= "00000001";
             else
                count(7 downto 1) <= count(6 downto 0);
                count(0) <= '0';
            end if;

         rows <= count;

        case count is
            when "00000001" => cols <= "11111111";
            when "00000010" => cols <= "11011011";
            when "00000100" => cols <= "11011011";
            when "00001000" => cols <= "11111111";
            when "00010000" => cols <= "00111100";
            when "00100000" => cols <= "10000001";
            when "01000000" => cols <= "11000011";
            when "10000000" => cols <= "11111111";
            when others => cols <= "11111111";
         end case;
     end if;

    end if;

end process;
end Behavioral;


答: Just a guess: top is unititialized. That makes array an array with zero length at best (which is really bad) and invokes undefined behavior at worst.

Title: How to fix binary operator


问:
Passion in CouchBase Programming
I would like to get the single element in the Couchbase document that is in the array of objects, but i am able to fetch the array of objects

i tried to fetch the array using the following query, 'select countryDetails from test';

```<code>{
   "type":"countries",
   "docName":"CountryData",
   "countryDetails":[
      {
         "name":"US",
         "code":"+1",
         "stateInfo":[
            {
               "name":"Florida",
               "id":"1212"
            },
            {
               "name":"NewYork",
               "id":"1214"
            }
         ]
      },
       {
         "name":"France",
         "code":"+33",
         "stateInfo":[
            {
               "name":"Grand Est",
               "id":"5212"
            },
            {
               "name":"Brittany",
               "id":"5214"
            }
         ]
      }
   ]
}
</code>```

i tried fetching array using, select countryDetails from test;

i like to fetch the result as [ {"name" : "US", "code" : "+1" }, {"name" : "France", "code" : "+33"}]

答:
What you are trying to do does not seem to be possible. You can get closer to what you want with a query like this:

```<code>select raw countryDetails from test
</code>```

But the results of this query still have the result wrapped in an extra level of array.

Title: Passion in CouchBase Programming

Body:
I would like to get the single element in the Couchbase document that is in the array of objects, but i am able to fetch the array of objects

i tried to fetch the array using the following query, 'select countryDetails from test';

{
   "type":"countries",
   "docName":"CountryData",
   "countryDetails":[
      {
         "name":"US",
         "code":"+1",
         "stateInfo":[
            {
               "name":"Florida",
               "id":"1212"
            },
            {
               "name":"NewYork",
               "id":"1214"
            }
         ]
      },
       {
         "name":"France",
         "code":"+33",
         "stateInfo":[
            {
               "name":"Grand Est",
               "id":"5212"
            },
            {
               "name":"Brittany",
               "id":"5214"
            }
         ]
      }
   ]
}

i tried fetching array using, select countryDetails from test;

i like to fetch the result as [ {"name" : "US", "code" : "+1" }, {"name" : "France", "code" : "+33"}]

Body:
What you are trying to do does not seem to be possible. You can get closer to what you want with a query like this:

select raw countryDetails from test

But the results of this query still have the result wrapped in an extra level of array.


问:
How to see what git merge has done before commit?
Say you've done a merge:

```<code>git checkout mybranch
git merge master
</code>```

then edited some files manually to deal with merge conflits.

git status will show all the files which have been modified, but git diff only appears to show changes in the files you've edited for merge conflicts. How can you see the changes relative to mybranch which the merge has introduced, before you commit the whole lot (after which I think you can just do git diff HEAD^ HEAD).

Coming from a mercurial background here so I am probably missing some concepts ...

答:
The usual way to see diffs of staged files is

```<code>git diff --cached
</code>```

It should work here as well

Body:
Say you've done a merge:

git checkout mybranch
git merge master

then edited some files manually to deal with merge conflits.

git status will show all the files which have been modified, but git diff only appears to show changes in the files you've edited for merge conflicts. How can you see the changes relative to mybranch which the merge has introduced, before you commit the whole lot (after which I think you can just do git diff HEAD^ HEAD).

Coming from a mercurial background here so I am probably missing some concepts ...

Body:
The usual way to see diffs of staged files is

git diff --cached

It should work here as well


问:
ServiceStack Dump() of base class
I use ServiceStack's Dump() in logs to dump whole object to the console, however I just noticed that when the object in question is cast to a base class then only those class properties will be serialized. Is there any way to to serialize the full class? I looked for an overload with a type parameter which would allow me to do something like obj.Dump(obj.GetType()) but it doesn't exist.

Is there a way to serialize that object? I know there a lot of different options to log to console but I used this primarily for the simplicity and ease of use.

答:
You can down cast it to an object where it will use the runtime type instead:</p>

```<code>((object)obj).Dump();
</code>```

Title: ServiceStack Dump() of base class

Body:
You can down cast it to an object where it will use the runtime type instead:

((object)obj).Dump();


问:
Jenkins working directories vocabulary misundertanding [agent configuration]
In the agent configuration screens, Jenkins is talking about:

Remote root directory

Custom WorkDir path (when you choose Java web Start JNLP)

Agent Root Directory (when you choose Java web Start JNLP)

I'm living a bad user experience, because I don't understand what I'm able to set.

What are this 3 directories? What will happen to it?

答:
Remote Root Directory - "An agent needs to have a directory dedicated to Jenkins. Specify the path to this directory on the agent. It is best to use an absolute path, such as /var/jenkins" The directory that you set here will become the Jenkins directory on the new agent that you are creating.

Custom WorkDir path - If defined, this will be a custom remoting work directory that will be used instead of the remote root directory defined above. Recommended to use absolute paths in this case.

Agent Root Directory - I believe that this is the same as the Remote root directory, I don't see it when I go to Java web Start JNLP. So definition wise I think it's the same as the Remote Root Directory.


问:
How can I enable mail in Wordpress?
I'm using Apache 2.2.25 and PHP 5.3.28 in my Windows 8 desktop. Once when I was recovering my wordpress password, I got this error:

The e-mail could not be sent. Possible reason: your host may have disabled the mail() function.

I googled it that how can I enable mail() function, found that I need to configure a mail server with my server. I downloaded hMailServer, but it didn't work... Please help me how can I enable mail() function? Which mail server will I have to download?

答:
it called -Manage Registered Email-Ids For Sending Mails via Scripts(Wordpress)

Login your Cpanel.

Go to Email Section > then Click Registered Email IDs.

then add (wordpress@yourdomain.com) or where your wordpress hosted. ie (wordpress@blog.yourdomain.com) . then submit, it takes few minute to activate wait 15minute to 1 hour depending to your hosting provider, then it will work.

Title: How can I enable mail in Wordpress?


问:
How to configure GlobalChannelInterceptor for spring-cloud-stream?
I have a spring-cloud-stream worker which is using kafka bindings

```<code>@Slf4j
@EnableBinding(KafkaStreamsProcessor.class)
@RequiredArgsConstructor
public class SomeWorker {

    @StreamListener(Sink.INPUT)
    @SendTo(Source.OUTPUT)
    public KStream<?, Obj> process(KStream<?, Obj> objStream) {
        return objStream.something();
    }
}

</code>```

And a global-interceptor

```<code>@Component
@Slf4j
@GlobalChannelInterceptor
public class StreamInterceptor implements ChannelInterceptor {

    @Override
    public Message<?> preSend(Message<?> msg, MessageChannel mc) {
        log.info("In preSend");
        return msg;
    }

    @Override
    public void postSend(Message<?> msg, MessageChannel mc, boolean bln) {
        log.info("In postSend");
    }

    @Override
    public void afterSendCompletion(Message<?> msg, MessageChannel mc, boolean bln, Exception excptn) {
        log.info("In afterSendCompletion");
    }

    @Override
    public boolean preReceive(MessageChannel mc) {
        log.info("In preReceive");
        return true;
    }

    @Override
    public Message<?> postReceive(Message<?> msg, MessageChannel mc) {
        log.info("In postReceive");
        return msg;
    }

}
</code>```

On receiving any message on stream, the GlobalChannelInterceptor is not called.

What am I missing ?

ps: I am following this test https://github.com/spring-cloud/spring-cloud-stream/blob/master/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/interceptor/BoundChannelsInterceptedTest.java#L67

答: The Kafka Streams binder is not based on MessageChannels so there is no channel to intercept.

Body:
I have a spring-cloud-stream worker which is using kafka bindings

@Slf4j
@EnableBinding(KafkaStreamsProcessor.class)
@RequiredArgsConstructor
public class SomeWorker {

    @StreamListener(Sink.INPUT)
    @SendTo(Source.OUTPUT)
    public KStream<?, Obj> process(KStream<?, Obj> objStream) {
        return objStream.something();
    }
}

And a global-interceptor

@Component
@Slf4j
@GlobalChannelInterceptor
public class StreamInterceptor implements ChannelInterceptor {

    @Override
    public Message<?> preSend(Message<?> msg, MessageChannel mc) {
        log.info("In preSend");
        return msg;
    }

    @Override
    public void postSend(Message<?> msg, MessageChannel mc, boolean bln) {
        log.info("In postSend");
    }

    @Override
    public void afterSendCompletion(Message<?> msg, MessageChannel mc, boolean bln, Exception excptn) {
        log.info("In afterSendCompletion");
    }

    @Override
    public boolean preReceive(MessageChannel mc) {
        log.info("In preReceive");
        return true;
    }

    @Override
    public Message<?> postReceive(Message<?> msg, MessageChannel mc) {
        log.info("In postReceive");
        return msg;
    }

}

On receiving any message on stream, the GlobalChannelInterceptor is not called.

What am I missing ?

ps: I am following this test https://github.com/spring-cloud/spring-cloud-stream/blob/master/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/interceptor/BoundChannelsInterceptedTest.java#L67


问:
Why is Kendo UI DatePicker not passing value to JSP on form submit via POST?
I'm building a JSP Form that includes a Kendo UI DatePicker on it.  For some reason the date is not getting to the JSP controller with the request.getParameter function.  It only comes across as null.  How do I fix this issue?

I've searched Stackoverflow, Kendo UI support and Google.  I've tried a few variations, but without success.  I've tried different browsers and dev environments.

The form section that includes datePicker:

```<code><table class="vipTable">
    <tr>
        <th class="strong" colspan="3">Time Frame</th>
    </tr>
    <tr>
        <td>Date Req <input type="text" name="dateReq" id="dateReq" size="10" value=""/><BR>(mm/dd/yyyy)</td>
        <td>Expected Start Time <input id="startTime" name="startTime" title="startTime" value="8:00 AM"/></td>
        <td>Expected Completion Time <input id="endTime" name="endTime" title="endTime" value="10:00 AM"/></td>
    </tr>
</table>
</code>```

The JS used to setup the datePicker so that:
- Only Sundays are active and only future Sundays are selectable
- Disable keyboard input; force use of datepicker calendar

```<code>// create DatePicker but ensure that only Sundays can be selected - present and future Sundays).
//That is, if today is Sunday, it is selectable in addition to future Sundays.
    var presentDate = new Date();
    var dayOfWeek = presentDate.getDay();

    if(dayOfWeek != 0) {
      // day of week is not Sunday
      presentDate.setDate(presentDate.getDate() + ( 7 - dayOfWeek));

    }

    var dd = presentDate.getDate();
    var mm = presentDate.getMonth() + 1; //January is 0!
    var yyyy = presentDate.getFullYear();

    if (mm < 10) {
      mm = '0' + mm;
    }
    var closestSunday = mm + '/' + dd + '/' + yyyy;

    $('#dateReq').attr("value", closestSunday);

    $('#dateReq').kendoDatePicker({
        value: presentDate,
        min: presentDate,
        disableDates: ["mo", "tu", "we", "th", "fr", "sa"],
        change: function() {
            var value = this.value();
            $("#dateReq").attr("value", kendo.toString(new Date(value), "d"));

        }
    }).data('kendoDatePicker');

    // Disable manual input on this field, force use of calendar.
    $("#dateReq").attr("disabled","disabled");

</code>```

JSP Code trying to get the datepicker value

```<code>String dateReqString = request.getParameter("dateReq");

            if (MY_LOG.isDebugEnabled()) {
                MY_LOG.debug("formattedDate: dateReqString = " + dateReqString);
            }
</code>```

Error message in the log

```<code>[WebContainer : 7] DEBUG {} ITOutageSubmitController - formattedDate: dateReqString = null

 java.lang.NullPointerException
    at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1450)
    at java.text.DateFormat.parse(DateFormat.java:375)
    at com.kmbs.itsform.portlet.controller.ITOutageSubmitController.handleActionRequest(ITOutageSubmitController.java:57)
</code>```

Note, line 57 in ITOutageSubmitController is trying to use the dateReqString value from the dateReq parameter, but it is null.

Thanks.

答: Ok, this was an embarrassingly simple fix.  Disabled inputs do not get submitted.  Commenting out the line that disabled it fixed the issue.  However, I do want the input field disabled, so I created a new hidden input field which gets the datepicker's date value on change and the controller grabs that value instead.

Body:
I'm building a JSP Form that includes a Kendo UI DatePicker on it.  For some reason the date is not getting to the JSP controller with the request.getParameter function.  It only comes across as null.  How do I fix this issue?

I've searched Stackoverflow, Kendo UI support and Google.  I've tried a few variations, but without success.  I've tried different browsers and dev environments.

The form section that includes datePicker:

        Time Frame

        Date Req <input type="text" name="dateReq" id="dateReq" size="10" value=""/>
(mm/dd/yyyy)
        Expected Start Time <input id="startTime" name="startTime" title="startTime" value="8:00 AM"/>
        Expected Completion Time <input id="endTime" name="endTime" title="endTime" value="10:00 AM"/>

The JS used to setup the datePicker so that:
- Only Sundays are active and only future Sundays are selectable
- Disable keyboard input; force use of datepicker calendar

// create DatePicker but ensure that only Sundays can be selected - present and future Sundays).
//That is, if today is Sunday, it is selectable in addition to future Sundays.
    var presentDate = new Date();
    var dayOfWeek = presentDate.getDay();

    if(dayOfWeek != 0) {
      // day of week is not Sunday
      presentDate.setDate(presentDate.getDate() + ( 7 - dayOfWeek));

    }

    var dd = presentDate.getDate();
    var mm = presentDate.getMonth() + 1; //January is 0!
    var yyyy = presentDate.getFullYear();

    if (mm < 10) {
      mm = '0' + mm;
    }
    var closestSunday = mm + '/' + dd + '/' + yyyy;

    $('#dateReq').attr("value", closestSunday);

    $('#dateReq').kendoDatePicker({
        value: presentDate,
        min: presentDate,
        disableDates: ["mo", "tu", "we", "th", "fr", "sa"],
        change: function() {
            var value = this.value();
            $("#dateReq").attr("value", kendo.toString(new Date(value), "d"));

        }
    }).data('kendoDatePicker');

    // Disable manual input on this field, force use of calendar.
    $("#dateReq").attr("disabled","disabled");

JSP Code trying to get the datepicker value

String dateReqString = request.getParameter("dateReq");

            if (MY_LOG.isDebugEnabled()) {
                MY_LOG.debug("formattedDate: dateReqString = " + dateReqString);
            }

Error message in the log

[WebContainer : 7] DEBUG {} ITOutageSubmitController - formattedDate: dateReqString = null

 java.lang.NullPointerException
    at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1450)
    at java.text.DateFormat.parse(DateFormat.java:375)
    at com.kmbs.itsform.portlet.controller.ITOutageSubmitController.handleActionRequest(ITOutageSubmitController.java:57)

Note, line 57 in ITOutageSubmitController is trying to use the dateReqString value from the dateReq parameter, but it is null.

Thanks.


问:
Laravel - alphabetical order
I would like to make an alphabetical sort in my function index().

I think I should use the Order By clause?

I am stuck in my code below:

```<code>public function index(Request $req)
    {
    if ($req->has('search') && !empty($req->search)) {

        $validated = $req->validate([
            'search' => 'alpha',
        ]);

        $auteurs = Auteur::where('nom', 'LIKE', '%' . $validated['search'] . '%')->paginate(5);
        $auteurs->appends($req->only('search'));
        return view('admin.auteurs.index', compact('auteurs'));
    }

    $auteurs = Auteur::paginate(5);
    return view('admin.auteurs.index', compact('auteurs'));
    }
</code>```

答:
Yes use orderBy like this:</p>

```<code>public function index(Request $req)
{
if ($req->has('search') && !empty($req->search)) {

    $validated = $req->validate([
        'search' => 'alpha',
    ]);

    $auteurs = Auteur::where('nom', 'LIKE', '%' . $validated['search'] . '%')->orderBy('nom', 'ASC')->paginate(5);
    $auteurs->appends($req->only('search'));
    return view('admin.auteurs.index', compact('auteurs'));
}

$auteurs = Auteur::orderBy('nom', 'ASC')->paginate(5);
return view('admin.auteurs.index', compact('auteurs'));
}
</code>```

Title: Laravel - alphabetical order

Body:
I would like to make an alphabetical sort in my function index().

I think I should use the Order By clause?

I am stuck in my code below:

public function index(Request $req)
    {
    if ($req->has('search') && !empty($req->search)) {

        $validated = $req->validate([
            'search' => 'alpha',
        ]);

        $auteurs = Auteur::where('nom', 'LIKE', '%' . $validated['search'] . '%')->paginate(5);
        $auteurs->appends($req->only('search'));
        return view('admin.auteurs.index', compact('auteurs'));
    }

    $auteurs = Auteur::paginate(5);
    return view('admin.auteurs.index', compact('auteurs'));
    }

Body:
Yes use orderBy like this:

public function index(Request $req)
{
if ($req->has('search') && !empty($req->search)) {

    $validated = $req->validate([
        'search' => 'alpha',
    ]);

    $auteurs = Auteur::where('nom', 'LIKE', '%' . $validated['search'] . '%')->orderBy('nom', 'ASC')->paginate(5);
    $auteurs->appends($req->only('search'));
    return view('admin.auteurs.index', compact('auteurs'));
}

$auteurs = Auteur::orderBy('nom', 'ASC')->paginate(5);
return view('admin.auteurs.index', compact('auteurs'));
}


问:
Problem sending mail with javamail
I'm trying to send an email to myself using the javamail api.  I've followed the code correctly that I found online but I can't seem to get it to work.  The error I'm getting is:

```<code>Exception in thread "main" javax.mail.AuthenticationFailedException: No authentication mechansims supported by both server and client
</code>```

Does that mean my computer doesn't support authentication?

```<code>public class Emails
{
    public static void main(String[] args) throws MessagingException
    {
        Emails e = new Emails();
        e.sendMail();
    }

    public void sendMail() throws MessagingException
    {
        boolean debug = false;
        String subject = "Testing";
        String message = "Testing Message";
        String from = "myemail@email.com";
        String[] recipients = {"myemail@email.com"};

        // create some properties and get the default Session
        Session session = getSession();
        session.setDebug(debug);

        // create a message
        Message msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++)
        {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Optional : You can also set your custom headers in the Email if you Want
        msg.addHeader("MyHeaderName", "myHeaderValue");

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");
        Transport.send(msg);
    }

    private Session getSession()
    {
        Authenticator authenticator = new Authenticator();

        Properties properties = new Properties();
        properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
        properties.setProperty("mail.smtp.auth", "true");

        properties.setProperty("mail.smtp.host", "smtp.examplehost.com");
        properties.setProperty("mail.smtp.port", "25");

        return Session.getInstance(properties, authenticator);
    }

    private class Authenticator extends javax.mail.Authenticator
    {
        private PasswordAuthentication authentication;

        public Authenticator()
        {
            String username = "myusername";
            String password = "mypassword";
            authentication = new PasswordAuthentication(username, password);
        }

        protected PasswordAuthentication getPasswordAuthentication()
        {
            return authentication;
        }
    }
}
</code>```

When I send emails from this server, what I have to do is, login via ssh to the server (login.server.com etc.) then I can send emails from the mail server (smtp.server.com etc.).  I need to mimic this in java

RESOLVED:  Use the SMTPSSLTransport class

答:
Make sure you have an smtp server (smtp.examplehost.com) to actually send the email.
Make sure your smtp server allows "myemail@email.com" to send out emails.

These are some of the security checks put in place by standard smtp servers.

Title: Problem sending mail with javamail

Body:
I'm trying to send an email to myself using the javamail api.  I've followed the code correctly that I found online but I can't seem to get it to work.  The error I'm getting is:

Exception in thread "main" javax.mail.AuthenticationFailedException: No authentication mechansims supported by both server and client

Does that mean my computer doesn't support authentication?

public class Emails
{
    public static void main(String[] args) throws MessagingException
    {
        Emails e = new Emails();
        e.sendMail();
    }

    public void sendMail() throws MessagingException
    {
        boolean debug = false;
        String subject = "Testing";
        String message = "Testing Message";
        String from = "myemail@email.com";
        String[] recipients = {"myemail@email.com"};

        // create some properties and get the default Session
        Session session = getSession();
        session.setDebug(debug);

        // create a message
        Message msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++)
        {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Optional : You can also set your custom headers in the Email if you Want
        msg.addHeader("MyHeaderName", "myHeaderValue");

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");
        Transport.send(msg);
    }

    private Session getSession()
    {
        Authenticator authenticator = new Authenticator();

        Properties properties = new Properties();
        properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
        properties.setProperty("mail.smtp.auth", "true");

        properties.setProperty("mail.smtp.host", "smtp.examplehost.com");
        properties.setProperty("mail.smtp.port", "25");

        return Session.getInstance(properties, authenticator);
    }

    private class Authenticator extends javax.mail.Authenticator
    {
        private PasswordAuthentication authentication;

        public Authenticator()
        {
            String username = "myusername";
            String password = "mypassword";
            authentication = new PasswordAuthentication(username, password);
        }

        protected PasswordAuthentication getPasswordAuthentication()
        {
            return authentication;
        }
    }
}

When I send emails from this server, what I have to do is, login via ssh to the server (login.server.com etc.) then I can send emails from the mail server (smtp.server.com etc.).  I need to mimic this in java

RESOLVED:  Use the SMTPSSLTransport class


问:
Pandas - group by one column, sort by another, get value from the third column
I would like to take pandas dataframe, group it by one column, sort it by another column and take first element from third column and populate original dataframe.

Here is my original df. I would to group by col_1, sort by col_2 (ascending) and take first element from col_3 and populate col_4 with results.

```<code>df_in = pd.DataFrame({'col_1':['A', 'A', 'A', 'B', 'B', 'B'], 'col_2': [5,9,2, 3,7,1],
                   'col_3': ['c','d','k','n','l','f']})
</code>```

[

Here is how output df should look like:

```<code>df_out = pd.DataFrame({'col_1':['A', 'A', 'A', 'B', 'B', 'B'], 'col_2': [5,9,2, 3,7,1],
                   'col_3': ['c','d','k','n','l','f'], 'col_4': ['k','k','k','f','f','f'], })
</code>```

I can accomplish grouping and sorting with group and transform, but how to extract first element is not clear.

Sorry SO does not display images correctly ;-(

答:
You can use

```<code>first_values = df_in.sort_values(['col_1','col_2']).groupby('col_1')['col_3'].first().rename('col_4')
df_in = df_in.join(first_values, on='col_1')
</code>```

Output:

```<code>  col_1  col_2 col_3 col_4
0     A      5     c     k
1     A      9     d     k
2     A      2     k     k
3     B      3     n     f
4     B      7     l     f
5     B      1     f     f
</code>```

Body:
I would like to take pandas dataframe, group it by one column, sort it by another column and take first element from third column and populate original dataframe.

Here is my original df. I would to group by col_1, sort by col_2 (ascending) and take first element from col_3 and populate col_4 with results.

df_in = pd.DataFrame({'col_1':['A', 'A', 'A', 'B', 'B', 'B'], 'col_2': [5,9,2, 3,7,1],
                   'col_3': ['c','d','k','n','l','f']})

[

Here is how output df should look like:

df_out = pd.DataFrame({'col_1':['A', 'A', 'A', 'B', 'B', 'B'], 'col_2': [5,9,2, 3,7,1],
                   'col_3': ['c','d','k','n','l','f'], 'col_4': ['k','k','k','f','f','f'], })

I can accomplish grouping and sorting with group and transform, but how to extract first element is not clear.

Sorry SO does not display images correctly ;-(

Body:
You can use

first_values = df_in.sort_values(['col_1','col_2']).groupby('col_1')['col_3'].first().rename('col_4')
df_in = df_in.join(first_values, on='col_1')

Output:

  col_1  col_2 col_3 col_4
0     A      5     c     k
1     A      9     d     k
2     A      2     k     k
3     B      3     n     f
4     B      7     l     f
5     B      1     f     f