问:
Java Date Validator with Time Zone
Do we have any API's to validate if a date is valid or not when date is having EDT/EST in it. I have tried with Joda, Java SimpleDateFormat but i am not able to parse the date.

Below is the sample format i am getting "2017/09/25 16:18:15.099 -0400 EDT".

Any help is appreciated.

Thanks,
sk

答:
Did you try reading the documentation?

From the documentation of DateTimeFormatter:

```<code> z     time-zone name   zone-name     Pacific Standard Time; PST
 x     zone-offset      offset-x      +0000; -08; -0830; -08:30; -083015; -08:30:15;
</code>```

Zone names: This outputs the display name of the time-zone ID. If the count of letters is one, two or three, then the short name is
  output. …

Offset X and x: This formats the offset based on the number of pattern letters. … Two letters outputs the hour and minute, without a
  colon, such as '+0130'. …

So let’s try that:

```<code>    ZonedDateTime zdt = ZonedDateTime.parse("2017/09/25 16:18:15.099 -0400 EDT",
            DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss.SSS xx zzz", Locale.ENGLISH));
</code>```

This produces a ZonedDateTime of 2017-09-25T16:18:15.099-04:00[America/New_York].

Validation

In the code above ZonedDateTime picks up the time zone from your string and ignores the offset. To validate that the two agree, we can parse the same string both into a ZonedDateTime and into an OffsetDateTime and compare. The latter picks up the offset and ignores the time zone abbreviation, so this will work:

```<code>    String inputDateTimeWithZone = "2017/09/25 16:18:15.099 -0400 EDT";
    DateTimeFormatter formatterWithOffsetAndZone
            = DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss.SSS xx zzz", Locale.ENGLISH);
    ZonedDateTime zdt = ZonedDateTime.parse(inputDateTimeWithZone,
            formatterWithOffsetAndZone);
    OffsetDateTime odt = OffsetDateTime.parse(inputDateTimeWithZone,
            formatterWithOffsetAndZone);
    if (! zdt.toOffsetDateTime().equals(odt)) {
        System.err.println("Offset does not match: is " + odt.getOffset()
                + ", but time zone " + zdt.getZone() + " implies offset " + zdt.getOffset());
    }
</code>```

Avoid the three letter time zone abbreviations where you can

EST and EDT may also be used about Australian Eastern Standard and Daylight Time, respectively. Three letter time zone abbreviations are not standardized and are often ambiguous. It would be safer if you either could get a string with a time zone ID in the region/city format (like America/New_York) or you simply stripped off the abbreviation and relied on the offset alone, since this is unambiguous.

The modern Java date and time API

Today I recommend java.time, AKA JSR-310, over Joda-Time and certainly over the long outdated classes SimpleDateFormat and Date. To me it’s proven very nice to work with, and it certainly doesn’t come with the surprises of the old classes. It’s built-in with Java 8 and later. If using Java 6 or 7, you may be tempted to consider Joda-Time at first, but if you’re ready to accept an external dependency, why not take the ThreeTen Backport, the backport of java.time to Java 6 and 7?

Title: Java Date Validator with Time Zone

Body:
Did you try reading the documentation?

From the documentation of DateTimeFormatter:

 z     time-zone name   zone-name     Pacific Standard Time; PST
 x     zone-offset      offset-x      +0000; -08; -0830; -08:30; -083015; -08:30:15;

Zone names: This outputs the display name of the time-zone ID. If the count of letters is one, two or three, then the short name is
  output. …

Offset X and x: This formats the offset based on the number of pattern letters. … Two letters outputs the hour and minute, without a
  colon, such as '+0130'. …

So let’s try that:

    ZonedDateTime zdt = ZonedDateTime.parse("2017/09/25 16:18:15.099 -0400 EDT",
            DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss.SSS xx zzz", Locale.ENGLISH));

This produces a ZonedDateTime of 2017-09-25T16:18:15.099-04:00[America/New_York].

Validation

In the code above ZonedDateTime picks up the time zone from your string and ignores the offset. To validate that the two agree, we can parse the same string both into a ZonedDateTime and into an OffsetDateTime and compare. The latter picks up the offset and ignores the time zone abbreviation, so this will work:

    String inputDateTimeWithZone = "2017/09/25 16:18:15.099 -0400 EDT";
    DateTimeFormatter formatterWithOffsetAndZone
            = DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss.SSS xx zzz", Locale.ENGLISH);
    ZonedDateTime zdt = ZonedDateTime.parse(inputDateTimeWithZone,
            formatterWithOffsetAndZone);
    OffsetDateTime odt = OffsetDateTime.parse(inputDateTimeWithZone,
            formatterWithOffsetAndZone);
    if (! zdt.toOffsetDateTime().equals(odt)) {
        System.err.println("Offset does not match: is " + odt.getOffset()
                + ", but time zone " + zdt.getZone() + " implies offset " + zdt.getOffset());
    }

Avoid the three letter time zone abbreviations where you can

EST and EDT may also be used about Australian Eastern Standard and Daylight Time, respectively. Three letter time zone abbreviations are not standardized and are often ambiguous. It would be safer if you either could get a string with a time zone ID in the region/city format (like America/New_York) or you simply stripped off the abbreviation and relied on the offset alone, since this is unambiguous.

The modern Java date and time API

Today I recommend java.time, AKA JSR-310, over Joda-Time and certainly over the long outdated classes SimpleDateFormat and Date. To me it’s proven very nice to work with, and it certainly doesn’t come with the surprises of the old classes. It’s built-in with Java 8 and later. If using Java 6 or 7, you may be tempted to consider Joda-Time at first, but if you’re ready to accept an external dependency, why not take the ThreeTen Backport, the backport of java.time to Java 6 and 7?


来源: stackexchange

问:
SQL combine based on common row value
I am attempting to migrate from one help desk software to another, part of that is migrating our ticket history database over, which I exported to a excel spreadsheet and then imported into a SQL Server database.

The current format of the table is as follows:

Column headers:

```<code>Description: Initial ticket text
ticketnum: Ticket number
subject: Ticket subject header
value: ticket comment
</code>```

In case it's needed:

```<code>Description: nvarchar(max)
ticketnum: float
subject: nvarchar(max)
value: nvarchar(max)
</code>```

Edit: Example data as asked:

```<code>Description            TicketNum     Subject                       Value
-------------------------------------------------------------------------
Our computer exploded   10020        CPU Explosion        Our computer exploded
Our computer exploded   10020        CPU Explosion        The computer is a dell
Virus Found             10021        Virus                We need help with a virus
</code>```

I'd want that to become:

```<code>Description            TicketNum     Subject              Value
-------------------------------------------------------------------------
Our computer exploded   10020        CPU Explosion        Our computer exploded; The computer is a dell
Virus Found             10021        Virus                We need help with a virus
</code>```

Every row is a new entry into a ticket, so the value field is always unique, while the description and value stay the same for each ticket number. So I am looking to merge the rows based on the ticket number field, keep/merge ALL the data of the value fields and only keep one value of both the subject and description fields. I have seen a number of questions that come close to my scenario, but none match and sadly I know very little about SQL, and not enough to extrapolate based on what I've seen to figure this out solo.

Thank you so much in advance.

Edit 2: Revised code, runs but doesn't merge, produces an empty table:

```<code>declare @tmpTable table ([Description] nvarchar(max), niceid float,
[Subject] nvarchar(max), [Value] nvarchar(max))

SELECT * INTO tmpTable FROM sheetnew$

declare @newTable table ([Description] nvarchar(max), niceid float,
[Subject] nvarchar(max), [Value] nvarchar(max))

insert into @newTable
select distinct
    x.[Description]
    ,x.niceID
    ,x.[Subject]
   ,[Value] = stuff((
          select '; ' + y.[Value]
          from @tmptable y
          where x.niceid = y.niceid
          for xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
from @tmptable x
</code>```

答:
Here's a way using STUFF

```<code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_WARNINGS ON
GO
SET ANSI_PADDING ON
GO

declare @table table ([Description] varchar(64), TicketNum int, [Subject] varchar(64), [Value] varchar(4000))
insert into @table
values
('Our computer exploded',10020,'CPU Explosion','Our computer exploded'),
('Our computer exploded',10020,'CPU Explosion','The computer is a dell'),
('Virus Found',10021,'Virus','We need help with a virus')

declare @newTable table ([Description] varchar(64), TicketNum int, [Subject] varchar(64), [Value] varchar(4000))
insert into @newTable
select distinct
    x.[Description]
    ,x.TicketNum
    ,x.[Subject]
    ,[Value] = stuff((
          select '; ' + y.[Value]
          from @table y
          where x.TicketNum = y.TicketNum
          for xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
from @table x

select * from @newTable
</code>```

ContentLicense: CC BY-SA 3.0

Title: SQL combine based on common row value

Body:
I am attempting to migrate from one help desk software to another, part of that is migrating our ticket history database over, which I exported to a excel spreadsheet and then imported into a SQL Server database.

The current format of the table is as follows:

Column headers:

Description: Initial ticket text
ticketnum: Ticket number
subject: Ticket subject header
value: ticket comment

In case it's needed:

Description: nvarchar(max)
ticketnum: float
subject: nvarchar(max)
value: nvarchar(max)

Edit: Example data as asked:

Description            TicketNum     Subject                       Value
-------------------------------------------------------------------------
Our computer exploded   10020        CPU Explosion        Our computer exploded
Our computer exploded   10020        CPU Explosion        The computer is a dell
Virus Found             10021        Virus                We need help with a virus

I'd want that to become:

Description            TicketNum     Subject              Value
-------------------------------------------------------------------------
Our computer exploded   10020        CPU Explosion        Our computer exploded; The computer is a dell
Virus Found             10021        Virus                We need help with a virus

Every row is a new entry into a ticket, so the value field is always unique, while the description and value stay the same for each ticket number. So I am looking to merge the rows based on the ticket number field, keep/merge ALL the data of the value fields and only keep one value of both the subject and description fields. I have seen a number of questions that come close to my scenario, but none match and sadly I know very little about SQL, and not enough to extrapolate based on what I've seen to figure this out solo.

Thank you so much in advance.

Edit 2: Revised code, runs but doesn't merge, produces an empty table:

declare @tmpTable table ([Description] nvarchar(max), niceid float,
[Subject] nvarchar(max), [Value] nvarchar(max))

SELECT * INTO tmpTable FROM sheetnew$

declare @newTable table ([Description] nvarchar(max), niceid float,
[Subject] nvarchar(max), [Value] nvarchar(max))

insert into @newTable
select distinct
    x.[Description]
    ,x.niceID
    ,x.[Subject]
   ,[Value] = stuff((
          select '; ' + y.[Value]
          from @tmptable y
          where x.niceid = y.niceid
          for xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
from @tmptable x

Body:
Here's a way using STUFF

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_WARNINGS ON
GO
SET ANSI_PADDING ON
GO

declare @table table ([Description] varchar(64), TicketNum int, [Subject] varchar(64), [Value] varchar(4000))
insert into @table
values
('Our computer exploded',10020,'CPU Explosion','Our computer exploded'),
('Our computer exploded',10020,'CPU Explosion','The computer is a dell'),
('Virus Found',10021,'Virus','We need help with a virus')

declare @newTable table ([Description] varchar(64), TicketNum int, [Subject] varchar(64), [Value] varchar(4000))
insert into @newTable
select distinct
    x.[Description]
    ,x.TicketNum
    ,x.[Subject]
    ,[Value] = stuff((
          select '; ' + y.[Value]
          from @table y
          where x.TicketNum = y.TicketNum
          for xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
from @table x

select * from @newTable


问:
How to set typescript type for matchPath return value
I'm trying to use matchPath to extract a route param from the parent container as described in https://stackoverflow.com/a/45492498/3574819

```<code>const topicMatch = matchPath(history.location.pathname, { path: '/:topic' });
</code>```

When I console.log(topicMatch.params), the object has the topic key set but if I try to access topicMatch.params.topic I get the following error:

error TS2339: Property 'topic' does not exist on type '{}'.

```<code>const RouterApp = withRouter<{}>(
    class App extends React.Component<RouteComponentProps<{}>, AuthState> {
        render() {
            const { history } = this.props;
            const topicMatch = matchPath(history.location.pathname, { path: '/:topic' });

            if (topicMatch) {
                console.log(topicMatch.params); // has topic key
                console.log(topicMatch.params.topic); // causes compile error
            }

            return (
                <div className="App">
                    <div className="App-header">
                        <img src={logo} className="App-logo" alt="logo"/>
                        <h2>Welcome to React</h2>
                    </div>
                </div>
            );
        }
    }
);
</code>```

答:
matchPath is a parameterized function that takes a generic type
 and returns a match with match
. It's up to you to define P; otherwise I'm actually not sure how TypeScript determines the return type.

```<code>matchPath<{topic: "string"}>(...)
</code>```

You could also create your own type if you wish, e.g.

```<code>interface RouteParams {
  topic: string;
}
</code>```

and then do matchPath<RouteParams>(...).

Body:
I'm trying to use matchPath to extract a route param from the parent container as described in https://stackoverflow.com/a/45492498/3574819

const topicMatch = matchPath(history.location.pathname, { path: '/:topic' });

When I console.log(topicMatch.params), the object has the topic key set but if I try to access topicMatch.params.topic I get the following error:

error TS2339: Property 'topic' does not exist on type '{}'.

const RouterApp = withRouter<{}>(
    class App extends React.Component<RouteComponentProps<{}>, AuthState> {
        render() {
            const { history } = this.props;
            const topicMatch = matchPath(history.location.pathname, { path: '/:topic' });

            if (topicMatch) {
                console.log(topicMatch.params); // has topic key
                console.log(topicMatch.params.topic); // causes compile error
            }

            return (

Welcome to React

            );
        }
    }
);

Body:
matchPath is a parameterized function that takes a generic type <P> and returns a match with match<P>. It's up to you to define P; otherwise I'm actually not sure how TypeScript determines the return type.

matchPath<{topic: "string"}>(...)

You could also create your own type if you wish, e.g.

interface RouteParams {
  topic: string;
}

and then do matchPath<RouteParams>(...).


问:
Testing for a deadlock with nUnit
I'm new to unit testing and nUnit (2.48). I'd like to write a test method where the failure case is that it deadlocks. Is this possible? Obviously nUnit doesn't know by default how long the method should take to execute, so would I have to write code to do the work on a separate thread and then abort it and throw and exception if it took longer than some time I define? Is there a better way to do this?

Thank you

答:
It is possible but it might not be the best thing to do. Unit tests aren't really suitable for testing concurrency behaviour, unfortunately there aren't many test-methods that are suitable.

NUnit doesnt do anything with threads. You could write tests that start several threads and then test their interaction. But these would start to look more like integration tests than unit tests.

Another problem is that deadlock behaviour usually depends on the order threads are scheduled in. So it would be hard to write a conclusive test to test a certain deadlock issue because you don't have any control over the thread scheduling, this is done by the OS. You could end up with tests that sometimes fail on multicore processors but always succeed on single core processors.

OwnerDisplayName: frou

ContentLicense: CC BY-SA 2.5

Title: Testing for a deadlock with nUnit

OwnerDisplayName: Mendelt


问:
Word frequency count Java 8
How to count the frequency of words of List in Java 8?

```<code>List <String> wordsList = Lists.newArrayList("hello", "bye", "ciao", "bye", "ciao");
</code>```

The result must be:

```<code>{ciao=2, hello=1, bye=2}
</code>```

答:
Another 2 cent of mine, given an array:</p>

```<code>import static java.util.stream.Collectors.*;

String[] str = {"hello", "bye", "ciao", "bye", "ciao"};
Map<String, Integer> collected
= Arrays.stream(str)
        .collect(groupingBy(Function.identity(),
                    collectingAndThen(counting(), Long::intValue)));
</code>```

Title: Word frequency count Java 8

Body:
How to count the frequency of words of List in Java 8?

List <String> wordsList = Lists.newArrayList("hello", "bye", "ciao", "bye", "ciao");

The result must be:

{ciao=2, hello=1, bye=2}

Body:
Another 2 cent of mine, given an array:

import static java.util.stream.Collectors.*;

String[] str = {"hello", "bye", "ciao", "bye", "ciao"};
Map<String, Integer> collected
= Arrays.stream(str)
        .collect(groupingBy(Function.identity(),
                    collectingAndThen(counting(), Long::intValue)));


问:
Cross-validation for Sklearn 0.20+?
I am trying to do cross validation and I am running into an error that says: 'Found input variables with inconsistent numbers of samples: [18, 1]'

I am using different columns in a pandas data frame (df) as the features, with the last column as the label. This is derived from the machine learning repository for UC Irvine. When importing the cross-validation package that I have used in the past, I am getting an error that it may have depreciated. I am going to be running a decision tree, SVM, and K-NN.

My code is as such:

```<code>feature = [df['age'], df['job'], df['marital'], df['education'], df['default'], df['housing'], df['loan'], df['contact'],
       df['month'], df['day_of_week'], df['campaign'], df['pdays'], df['previous'], df['emp.var.rate'], df['cons.price.idx'],
       df['cons.conf.idx'], df['euribor3m'], df['nr.employed']]
label = [df['y']]

from sklearn.cross_validation import train_test_split
from sklearn.model_selection import cross_val_score
# Model Training
x = feature[:]
y = label
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.5)
</code>```

Any help would be great!

答:
The items in your feature list are pandas Series. You don't need to list out each feature in a list like you have done; you just need to pass them all as a single "table".

For example, this looks like the bank dataset so:

```<code>df = pd.read_csv('bank.csv', sep=';')
#df.shape
#(4521, 17)
#df.columns
#Index(['age', 'job', 'marital', 'education', 'default', 'balance', 'housing',
#       'loan', 'contact', 'day', 'month', 'duration', 'campaign', 'pdays',
#       'previous', 'poutcome', 'y'],
#      dtype='object')

x = df.iloc[:, :-1]
y = df.iloc[:, -1]
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.5)
</code>```

Should work. The only thing to notice here is that xis a DataFrame with 16 columns but its underlying data is a numpy ndarray - not a list of Series but a single "matrix".

Title: Cross-validation for Sklearn 0.20+?

Body:
I am trying to do cross validation and I am running into an error that says: 'Found input variables with inconsistent numbers of samples: [18, 1]'

I am using different columns in a pandas data frame (df) as the features, with the last column as the label. This is derived from the machine learning repository for UC Irvine. When importing the cross-validation package that I have used in the past, I am getting an error that it may have depreciated. I am going to be running a decision tree, SVM, and K-NN.

My code is as such:

feature = [df['age'], df['job'], df['marital'], df['education'], df['default'], df['housing'], df['loan'], df['contact'],
       df['month'], df['day_of_week'], df['campaign'], df['pdays'], df['previous'], df['emp.var.rate'], df['cons.price.idx'],
       df['cons.conf.idx'], df['euribor3m'], df['nr.employed']]
label = [df['y']]

from sklearn.cross_validation import train_test_split
from sklearn.model_selection import cross_val_score
# Model Training
x = feature[:]
y = label
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.5)

Any help would be great!

Body:
The items in your feature list are pandas Series. You don't need to list out each feature in a list like you have done; you just need to pass them all as a single "table".

For example, this looks like the bank dataset so:

df = pd.read_csv('bank.csv', sep=';')
#df.shape
#(4521, 17)
#df.columns
#Index(['age', 'job', 'marital', 'education', 'default', 'balance', 'housing',
#       'loan', 'contact', 'day', 'month', 'duration', 'campaign', 'pdays',
#       'previous', 'poutcome', 'y'],
#      dtype='object')

x = df.iloc[:, :-1]
y = df.iloc[:, -1]
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.5)

Should work. The only thing to notice here is that xis a DataFrame with 16 columns but its underlying data is a numpy ndarray - not a list of Series but a single "matrix".


问:
jsPlumb: fat arrow?
I want a fat arrow in jsPlumb with a pretty tip.

This is what I want:

This is what I get:

How can I change the settings?

Here's what I currently use:

```<code>PaintStyle: { stroke: "#f00", strokeWidth: 20 },
connector: ["Straight"],
connectorOverlays:[["Arrow", { location:1, width:70, length:70 } ]]
</code>```

I have been using arrows in SVG before. There, I could simply change the SVG code of the head to be moved forward so that the end of the line (the coordinates of the line end point) is inside the arrowhead triangle. I don't seem to be able to do this in jsPlumb.

I see it is difficult to convey the problem.

Here's a next try:

答:
This could probably work. Please try it out

```<code>connector: ["StateMachine", {curviness:0.001}],
connectorOverlays:[
  [
    "Arrow",
    { location: [0.5, 0.5], width: 70, length: 70 }
  ]
]
</code>```

Check out the Overlay location section in this webpage https://jsplumbtoolkit.com/community/doc/overlays.html#adding

Title: jsPlumb: fat arrow?

Body:
I want a fat arrow in jsPlumb with a pretty tip.

This is what I want:

This is what I get:

How can I change the settings?

Here's what I currently use:

PaintStyle: { stroke: "#f00", strokeWidth: 20 },
connector: ["Straight"],
connectorOverlays:[["Arrow", { location:1, width:70, length:70 } ]]

I have been using arrows in SVG before. There, I could simply change the SVG code of the head to be moved forward so that the end of the line (the coordinates of the line end point) is inside the arrowhead triangle. I don't seem to be able to do this in jsPlumb.

I see it is difficult to convey the problem.

Here's a next try:

Body:
This could probably work. Please try it out

connector: ["StateMachine", {curviness:0.001}],
connectorOverlays:[
  [
    "Arrow",
    { location: [0.5, 0.5], width: 70, length: 70 }
  ]
]

Check out the Overlay location section in this webpage https://jsplumbtoolkit.com/community/doc/overlays.html#adding


问:
Browser Push notifications for Microsoft Edge server side
From what I read, Microsoft Edge still does not support Web Push (it is still under development, as per site ). So what is the best way to implement browser push notification for Microsoft Edge?

The link - https://learn.microsoft.com/en-us/microsoft-edge/dev-guide/device/web-notifications-api - explains how we can send from a Javascript. But am trying to understand how I can send a notification from a different server side component (Java), to Microsoft Edge browser? Do we get any tokens like how we get when we use FCM in Chrome? Can someone provide me pointers on this? The application running on Microsoft Edge will be an angular 4 app.

答: You need to use the Javascript Fetch API, AJAX, Long Polling, WebSockets or SSE. Once you get the notification on the client side you can use vanilla Javascript and the Notification API to display the notification.</p>


问:
ASPNET Core: Wrong Value for ContentRootPath
I have an ASP.NET core application with the following configurations:

```<code>public Startup(IHostingEnvironment hostingEnvironment)
{
    _configuration = new ConfigurationBuilder()
        .SetBasePath(hostingEnvironment.ContentRootPath)
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{hostingEnvironment.EnvironmentName}.json", true)
        .AddEnvironmentVariables()
        .Build();
}
</code>```

When I publish the application and run it using the dotnet MyApp.dll inside the application directory, it runs with no problems. When I execute the the command dotnet /dir1/dir2/MyApp.dll, it fails to load the appsettings.json file. I did a little digging and found out that the ContentRootPath is set to the directory I'm running the dotnet command from and not the actual directory of the application. Can anyone tell me how to fix this issue?

答:
I have the same problem. I often store my code in a /src folder which contains multiple projects. So from the CLI I would like to do the following:

```<code>cd /c/code/repo
dotnet restore /src/solution.sln
dotnet build /src/solution.sln
dotnet run /src/project/project.csproj
</code>```

The first 2 work no problem but the CLI for .NET Core 2.0 does not recognize .SetBasePath(env.ContentRootPath) as the path where the project is being built to. Instead it uses the current path I am in on the CLI.

This results in:

```<code>Unhandled Exception: System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:\code\repo\appsettings.json'.
</code>```

The only way I can get it to work is if I go the that directory:

```<code>cd /src/project
dotnet run project.csproj
</code>```

Which is fine but if I want to rebuild the solution then I need to navigate back to /src where my .sln is located which is very annoying.

Seems like a bug in the CLI.

Body:
I have an ASP.NET core application with the following configurations:

public Startup(IHostingEnvironment hostingEnvironment)
{
    _configuration = new ConfigurationBuilder()
        .SetBasePath(hostingEnvironment.ContentRootPath)
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{hostingEnvironment.EnvironmentName}.json", true)
        .AddEnvironmentVariables()
        .Build();
}

When I publish the application and run it using the dotnet MyApp.dll inside the application directory, it runs with no problems. When I execute the the command dotnet /dir1/dir2/MyApp.dll, it fails to load the appsettings.json file. I did a little digging and found out that the ContentRootPath is set to the directory I'm running the dotnet command from and not the actual directory of the application. Can anyone tell me how to fix this issue?

Body:
I have the same problem. I often store my code in a /src folder which contains multiple projects. So from the CLI I would like to do the following:

cd /c/code/repo
dotnet restore /src/solution.sln
dotnet build /src/solution.sln
dotnet run /src/project/project.csproj

The first 2 work no problem but the CLI for .NET Core 2.0 does not recognize .SetBasePath(env.ContentRootPath) as the path where the project is being built to. Instead it uses the current path I am in on the CLI.

This results in:

Unhandled Exception: System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:\code\repo\appsettings.json'.

The only way I can get it to work is if I go the that directory:

cd /src/project
dotnet run project.csproj

Which is fine but if I want to rebuild the solution then I need to navigate back to /src where my .sln is located which is very annoying.

Seems like a bug in the CLI.


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

```<code>int Arry()
{

int Mynumbers [5] = {10};

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

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

Sincerely,
Nicholas

答:
Some notes:</p>

```<code>void Arry()                     // use void if nothing is being returned
{
    int Mynumbers[5] = {10};    // first element is 10, the rest are 0
    //std::cout << Mynumbers;   // will print the first address because the array decays to a pointer which is then printed
    for (auto i : Mynumbers)    // range-for takes note of the size of the array (no decay)
        std::cout << i << '\t';
}
</code>```

Title: Memory Address showing? C++

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

int Arry()
{

int Mynumbers [5] = {10};

    std::cout << Mynumbers;
}

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

Sincerely,
Nicholas

Body:
Some notes:

void Arry()                     // use void if nothing is being returned
{
    int Mynumbers[5] = {10};    // first element is 10, the rest are 0
    //std::cout << Mynumbers;   // will print the first address because the array decays to a pointer which is then printed
    for (auto i : Mynumbers)    // range-for takes note of the size of the array (no decay)
        std::cout << i << '\t';
}


问:
Removing a number from a listed created by given numbers
so here's the details.
I'm coding using java - BlueJ, and currently have a main class Auction, and a few other classes: Lot, Person, Bid

The purpose of the program is to enter items into the auction, along with their prices, where the information will be stored according to whether it's price, person, or item name/description.

This is the code for my getLot method - user inputs lot number, and it shows info for the lot, which I assume should also be the starting point for the removeLot method since it should still check if the lot number given is valid first.

I'm trying to figure out how to add a removeLot method so that I can remove an item from the lot by typing in its lot number.

This is the code I have for that section.

```<code>public Lot removeLot(int number)
 {
    if((number >= 1) && (number < nextLotNumber)) {
        // The number seems to be reasonable.
        Lot selectedLot = lots.get(number - 1);
        // Include a confidence check to be sure we have the
        // right lot.
        if(selectedLot.getNumber() != number) {
            System.out.println("Internal error: Lot number " +
                selectedLot.getNumber() +
                " was returned instead of " +
                number);
            // Don't return an invalid lot.
            selectedLot = null;
        }
        **else {
        Lot.removeIf(selectedLot.getNumber() = number);**
        }
        return selectedLot;
</code>```

The else block with the "**" is what I added, wanting to remove the given number. But it's clearly wrong, and I'm not sure what to do.

答:
If the datatype of lots variable is List than you can try below code

```<code>public Lot removeLot(int number)
 {
    Lot selectedLot=null;
    if((number >= 1) && (number < nextLotNumber)) {
        // The number seems to be reasonable.
        selectedLot = lots.get(number - 1);
        // Include a confidence check to be sure we have the
        // right lot.
        if(selectedLot.getNumber() != number) {
            System.out.println("Internal error: Lot number " +
                selectedLot.getNumber() +
                " was returned instead of " +
                number);
            // Don't return an invalid lot.
            selectedLot=null;
        }
        else {

            if(selectedLot.getNumber() = number)
                {
                    lots.remove(number-1);
                }

        }
        return selectedLot;
}
</code>```

Body:
so here's the details.
I'm coding using java - BlueJ, and currently have a main class Auction, and a few other classes: Lot, Person, Bid

The purpose of the program is to enter items into the auction, along with their prices, where the information will be stored according to whether it's price, person, or item name/description.

This is the code for my getLot method - user inputs lot number, and it shows info for the lot, which I assume should also be the starting point for the removeLot method since it should still check if the lot number given is valid first.

I'm trying to figure out how to add a removeLot method so that I can remove an item from the lot by typing in its lot number.

This is the code I have for that section.

public Lot removeLot(int number)
 {
    if((number >= 1) && (number < nextLotNumber)) {
        // The number seems to be reasonable.
        Lot selectedLot = lots.get(number - 1);
        // Include a confidence check to be sure we have the
        // right lot.
        if(selectedLot.getNumber() != number) {
            System.out.println("Internal error: Lot number " +
                selectedLot.getNumber() +
                " was returned instead of " +
                number);
            // Don't return an invalid lot.
            selectedLot = null;
        }
        **else {
        Lot.removeIf(selectedLot.getNumber() = number);**
        }
        return selectedLot;

The else block with the "**" is what I added, wanting to remove the given number. But it's clearly wrong, and I'm not sure what to do.

Body:
If the datatype of lots variable is List than you can try below code

public Lot removeLot(int number)
 {
    Lot selectedLot=null;
    if((number >= 1) && (number < nextLotNumber)) {
        // The number seems to be reasonable.
        selectedLot = lots.get(number - 1);
        // Include a confidence check to be sure we have the
        // right lot.
        if(selectedLot.getNumber() != number) {
            System.out.println("Internal error: Lot number " +
                selectedLot.getNumber() +
                " was returned instead of " +
                number);
            // Don't return an invalid lot.
            selectedLot=null;
        }
        else {

            if(selectedLot.getNumber() = number)
                {
                    lots.remove(number-1);
                }

        }
        return selectedLot;
}


问:
file_get_contents URL returns nothing
I am trying to get site content(JSON reply) with file_get_contents. But it returns blank var. Trying to communicate with google's recaptcha api. When I enter URL by myself, it returns JSON message fine, but file_get_contents returns nothing.. No code, because nothing complex, just file_get_contents("https://....")
openssl is enabled and allow_url_fopen is enabled too by default.

Code added:

```<code>$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$this->settings->captcha_secret_code."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$response = json_decode($response, true);
</code>```

$response returns 1, and if we comment out json_decoding, $response = ""

答:
For some reasons file_get_contents doesn't work with https URL's. Instead you can use cURL:

```<code>$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, "YOUR_URL");
$response = curl_exec($ch);
curl_close($ch);

$response = json_decode($response, true);
</code>```

More complex, but it works :)

Title: file_get_contents URL returns nothing

Body:
I am trying to get site content(JSON reply) with file_get_contents. But it returns blank var. Trying to communicate with google's recaptcha api. When I enter URL by myself, it returns JSON message fine, but file_get_contents returns nothing.. No code, because nothing complex, just file_get_contents("https://....")
openssl is enabled and allow_url_fopen is enabled too by default.

Code added:

$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$this->settings->captcha_secret_code."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$response = json_decode($response, true);

$response returns 1, and if we comment out json_decoding, $response = ""

Body:
For some reasons file_get_contents doesn't work with https URL's. Instead you can use cURL:

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, "YOUR_URL");
$response = curl_exec($ch);
curl_close($ch);

$response = json_decode($response, true);

More complex, but it works :)


问:
Spring boot read and new mail Listener on spring-boot-starter-mail
I want to demonstrate the email application using the spring boot MVC in that web application I follow this tutorial I can easily send the emails using spring boot.

Here my question is

how can I read the emails using spring boot..?

how can I listen for new emails and how to update the inbox on the view..?

please suggest me any solutions for that because I searched a lot but I can find only send email example.please share me if you have any working samples for that using spring boot. Thanks in advance.

答:
You could consider using Spring integration mail support

There is a Java DSL for this purposes.

An example of IMAP config could be found here

The key aspects are like this

```<code>@Configuration
@EnableIntegration
public class IntegrationConfig {
    ...

    @Bean
    public IntegrationFlow imapIdleFlow() {
        return IntegrationFlows
                .from(Mail.imapIdleAdapter("imap://user:pw@localhost:" + imapIdleServer.getPort() + "/INBOX")
                        .autoStartup(true)
                        .searchTermStrategy(this::fromAndNotSeenTerm)
                        .userFlag("testSIUserFlag")
                        .javaMailProperties(p -> p.put("mail.debug", "false")
                                .put("mail.imap.connectionpoolsize", "5"))
                        .shouldReconnectAutomatically(false)
                        .headerMapper(mailHeaderMapper()))
                .channel(MessageChannels.queue("imapIdleChannel"))
                .get();
    }

    @Bean
    public HeaderMapper<MimeMessage> mailHeaderMapper() {
        return new DefaultMailHeaderMapper();
    }

    private SearchTerm fromAndNotSeenTerm(Flags supportedFlags, Folder folder) {
        try {
            FromTerm fromTerm = new FromTerm(new InternetAddress("bar@baz"));
            return new AndTerm(fromTerm, new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        }
        catch (AddressException e) {
            throw new RuntimeException(e);
        }

    }
}
</code>```

Body:
You could consider using Spring integration mail support

There is a Java DSL for this purposes.

An example of IMAP config could be found here

The key aspects are like this

@Configuration
@EnableIntegration
public class IntegrationConfig {
    ...

    @Bean
    public IntegrationFlow imapIdleFlow() {
        return IntegrationFlows
                .from(Mail.imapIdleAdapter("imap://user:pw@localhost:" + imapIdleServer.getPort() + "/INBOX")
                        .autoStartup(true)
                        .searchTermStrategy(this::fromAndNotSeenTerm)
                        .userFlag("testSIUserFlag")
                        .javaMailProperties(p -> p.put("mail.debug", "false")
                                .put("mail.imap.connectionpoolsize", "5"))
                        .shouldReconnectAutomatically(false)
                        .headerMapper(mailHeaderMapper()))
                .channel(MessageChannels.queue("imapIdleChannel"))
                .get();
    }

    @Bean
    public HeaderMapper<MimeMessage> mailHeaderMapper() {
        return new DefaultMailHeaderMapper();
    }

    private SearchTerm fromAndNotSeenTerm(Flags supportedFlags, Folder folder) {
        try {
            FromTerm fromTerm = new FromTerm(new InternetAddress("bar@baz"));
            return new AndTerm(fromTerm, new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        }
        catch (AddressException e) {
            throw new RuntimeException(e);
        }

    }
}


问:
Python | find method
```<code>def count_substring(string, sub_string):
    count = 0
    for i in range(0 , len(string)):
    if ( string[i: ].find(sub_string)) == True:
        count = count +1
    return count

STRING = 'ininini'
SUB_STRING = 'ini'
</code>```

CORRECT OUTPUT : 3

MY OUTPUT : 2

it is not detecting the last substring.

答:
the problem is that

```<code>string[i:].find(sub_string)
</code>```

returns -1 if not found or the position if found. You want to test for 0 you're testing for position 1 (aka True) (https://docs.python.org/3/library/stdtypes.html#str.find).

It's not "not detecting the last substring", it's detecting bogus matches.

You could use startswith instead:

```<code>def count_substring(string, sub_string):
    count = 0
    for i in range(0,len(string)):
      if string[i:].startswith(sub_string):
        count += 1
    return count
</code>```

Note that using find isn't a bad idea at all, since you don't have to slice the string (it's faster), there's a start position parameter which is handy here:

```<code>def count_substring(string, sub_string):
    count = 0
    for i in range(0,len(string)):
      if string.find(sub_string,i) == i:
        count += 1
    return count
</code>```

or in one line:

```<code>def count_substring(string, sub_string):
        return sum(1 for i in range(len(string)) if string.find(sub_string,i) == i)
</code>```

note that string.count(sub_string) doesn't yield the same result because it doesn't consider overlapping strings, like your solution does.

Title: Python | find method

Body:
def count_substring(string, sub_string):
    count = 0
    for i in range(0 , len(string)):
    if ( string[i: ].find(sub_string)) == True:
        count = count +1
    return count

STRING = 'ininini'
SUB_STRING = 'ini'

CORRECT OUTPUT : 3

MY OUTPUT : 2

it is not detecting the last substring.

Body:
the problem is that

string[i:].find(sub_string)

returns -1 if not found or the position if found. You want to test for 0 you're testing for position 1 (aka True) (https://docs.python.org/3/library/stdtypes.html#str.find).

It's not "not detecting the last substring", it's detecting bogus matches.

You could use startswith instead:

def count_substring(string, sub_string):
    count = 0
    for i in range(0,len(string)):
      if string[i:].startswith(sub_string):
        count += 1
    return count

Note that using find isn't a bad idea at all, since you don't have to slice the string (it's faster), there's a start position parameter which is handy here:

def count_substring(string, sub_string):
    count = 0
    for i in range(0,len(string)):
      if string.find(sub_string,i) == i:
        count += 1
    return count

or in one line:

def count_substring(string, sub_string):
        return sum(1 for i in range(len(string)) if string.find(sub_string,i) == i)

note that string.count(sub_string) doesn't yield the same result because it doesn't consider overlapping strings, like your solution does.


问:
How to use filterM with an infinite list
I was trying to find a directory name by appending a number until I found a name that doesn't yet exist:

```<code>head <$> filterM (fmap not . fexists_) [ getDatedDir t d n | n <- [0..] ]
</code>```

The problem with this is that it never returns.  I think the problem is that although IO is a Functor, filterM has to do all the IO before the head effects; that is, it has to evaluate fexists for every n - and that's of course infinite.

Now, I can solve this:

```<code>go t d 0
where go t d n = do
    let dir = getDatedDir t d n
    fexists_ dir >>= \case
        False -> return dir
        True  -> go t d (n+1)
</code>```

But I feel that there ought to be a more elegant approach, using filterM or something similar.

This feels like a common enough pattern that there is probably an extisting function in Control.Monad, I'm just not seeing it.

答:
There's firstM from Control.Monad.Loops:

```<code>firstM :: Monad m => (a -> m Bool) -> [a] -> m (Maybe a)
</code>```

return the first value from a list, if any, satisfying the given
  predicate.

Body:
I was trying to find a directory name by appending a number until I found a name that doesn't yet exist:

head <$> filterM (fmap not . fexists_) [ getDatedDir t d n | n <- [0..] ]

The problem with this is that it never returns.  I think the problem is that although IO is a Functor, filterM has to do all the IO before the head effects; that is, it has to evaluate fexists for every n - and that's of course infinite.

Now, I can solve this:

go t d 0
where go t d n = do
    let dir = getDatedDir t d n
    fexists_ dir >>= \case
        False -> return dir
        True  -> go t d (n+1)

But I feel that there ought to be a more elegant approach, using filterM or something similar.

This feels like a common enough pattern that there is probably an extisting function in Control.Monad, I'm just not seeing it.

Body:
There's firstM from Control.Monad.Loops:

firstM :: Monad m => (a -> m Bool) -> [a] -> m (Maybe a)

return the first value from a list, if any, satisfying the given
  predicate.


问:
ASP.NET membership provider on a different development machine
Is the "asp.net membership provider" portable? Do I have to run the aspnet_regsql.exe to set it up for every new machine?

I imported the membership provider database to Visual Studio Database Edition and checked into my source control, and redeployed it to a different dev machine. From the new machine, I got the following error.  How do I fix this? Thanks!

The
  'System.Web.Security.SqlMembershipProvider'
  requires a database schema compatible
  with schema version '1'.  However, the
  current database schema is not
  compatible with this version.  You may
  need to either install a compatible
  schema with aspnet_regsql.exe
  (available in the framework
  installation directory), or upgrade
  the provider to a newer version.

答:
I had this problem too. For me, I had to explicitly give my application a name (it was "/" on my dev machine).

web.config:

```<code><membership>
  <providers>
    <clear />
    <add name="AspNetSqlMembershipProvider" applicationName="jobs"... />
  </providers>
</membership>
<profile>
  <providers>
    <clear />
    <add name="AspNetSqlProfileProvider" applicationName="jobs" ... />
  </providers>
</profile>
<roleManager enabled="true">
  <providers>
    <clear />
    <add connectionStringName="ApplicationServices" applicationName="jobs" ... />
    <add applicationName="jobs" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" />
  </providers>
</roleManager>
</code>```

And then in my database:

```<code>INSERT INTO [dbo].[aspnet_Applications]([ApplicationName], [LoweredApplicationName], [ApplicationId], [Description]) SELECT N'jobs', N'jobs', N'74b045ce-9c16-4e6a-b1ec-08504600a627', NULL
</code>```

OwnerDisplayName: ycseattle

Body:
I had this problem too. For me, I had to explicitly give my application a name (it was "/" on my dev machine).

web.config:

<membership>
  <providers>
    <clear />
    <add name="AspNetSqlMembershipProvider" applicationName="jobs"... />
  </providers>
</membership>
<profile>
  <providers>
    <clear />
    <add name="AspNetSqlProfileProvider" applicationName="jobs" ... />
  </providers>
</profile>
<roleManager enabled="true">
  <providers>
    <clear />
    <add connectionStringName="ApplicationServices" applicationName="jobs" ... />
    <add applicationName="jobs" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" />
  </providers>
</roleManager>

And then in my database:

INSERT INTO [dbo].[aspnet_Applications]([ApplicationName], [LoweredApplicationName], [ApplicationId], [Description]) SELECT N'jobs', N'jobs', N'74b045ce-9c16-4e6a-b1ec-08504600a627', NULL


问:
Gradle build error in Android Studio 3.0
Can you please help me to resolve the Gradle build issue in Android 3.0 ?

I am new with Android Studio.
Here are my configurations in the AS 3.0:

gradle->wrapper->gradle-wrapper.properties:

```<code>distributionUrl=https\://services.gradle.org/distributions/gradle-4.2.1-all.zip
</code>```

build.gradle dependencies (Android Plugin for Gradle):

```<code>dependencies {classpath 'com.android.tools.build:gradle:3.0.0'}
</code>```

Settings">

Stacktrace from Android Studio:

```<code>D:\AppiumAutomation\MobileTest>gradlew assemble --stacktrace

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'MobileTest'.
> Could not resolve all files for configuration ':classpath'.
   > Could not resolve com.android.tools.build:gradle:3.0.0.
     Required by:
         project :
      > Could not resolve com.android.tools.build:gradle:3.0.0.
         > Could not get resource 'https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom'.
            > Could not GET 'https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom'.
               > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification pat
h to requested target
      > Could not resolve com.android.tools.build:gradle:3.0.0.
         > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom'.
            > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom'.
               > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification pat
h to requested target
</code>```

答:
It's a problem related to Android Studio 3.0 and the corporate networks. I had the same problem.

```<code>Error:Could not resolve all files for configuration ':app:debugAndroidTestRuntimeClasspath'.
    > Could not resolve com.android.support.test:runner:1.0.1.
      Required by:
          project :app
       > Could not resolve com.android.support.test:runner:1.0.1.
          > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/support/test/runner/1.0.1/runner-1.0.1.pom'.
             > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/support/test/runner/1.0.1/runner-1.0.1.pom'.
                > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    > Could not resolve com.android.support.test.espresso:espresso-core:3.0.1.
      Required by:
          project :app
       > Could not resolve com.android.support.test.espresso:espresso-core:3.0.1.
          > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/support/test/espresso/espresso-core/3.0.1/espresso-core-3.0.1.pom'.
             > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/support/test/espresso/espresso-core/3.0.1/espresso-core-3.0.1.pom'.
                > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
</code>```

I leave you 2 solutions:

1rst:
You must add certificates manually to your java security certs (used by Android):

C:\Program Files\Android\Android Studio\jre\jre\lib\security\cacerts

SOLUTION 01 (Didn't work for me):

Go to:

```<code>C:\Program Files\Android\Android Studio\jre\jre\bin
</code>```

Download the Certificate you need (just copy the URL with the problem and paste it into <remote_host_name>):

```<code>keytool -J-Dhttps.proxyHost=<proxy_hostname> -J-Dhttps.proxyPort=<proxy_port> -printcert -rfc -sslserver <remote_host_name:remote_ssl_port> > <name.cer>

Example:
C:\Program Files\Android\Android Studio\jre\jre\bin>keytool -J-Dhttps.proxyHost= proxy.mycompany.com -J-Dhttps.proxyPort=80 -printcert -rfc -sslserver https://dl.google.com/dl/android/maven2/com/android/support/test/runner/1.0.1/runner-1.0.1.pom > maven2.cer
</code>```

And run the command:

```<code>keytool -import -noprompt -trustcacerts -keystore ..\lib\security\cacerts -importcert -alias <AliasName> -file <name.cer> -storepass <cacertsPassword>
</code>```

If you never changed the password of cacerts the default one is changeit:

```<code>Example:
C:\Program Files\Android\Android Studio\jre\jre\bin>keytool -import -noprompt -trustcacerts -keystore ..\lib\security\cacerts -importcert -alias Maven -file maven2.cer -storepass changeit
</code>```

SOLUTION 02 (Worked for me):

Download the pom entering to the URL site and store it in your local repo:

```<code>Ex:
If your missing resoruce is:
https://dl.google.com/dl/android/maven2/com/android/support/test/espresso/espresso-core/3.0.1/espresso-core-3.0.1.pom

Download it and put it in:
C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/support/test/espresso/espresso-core/3.0.1/espresso-core-3.0.1.pom
</code>```

Body:
Can you please help me to resolve the Gradle build issue in Android 3.0 ?

I am new with Android Studio.
Here are my configurations in the AS 3.0:

gradle->wrapper->gradle-wrapper.properties:

distributionUrl=https\://services.gradle.org/distributions/gradle-4.2.1-all.zip

build.gradle dependencies (Android Plugin for Gradle):

dependencies {classpath 'com.android.tools.build:gradle:3.0.0'}

Settings">

Stacktrace from Android Studio:

D:\AppiumAutomation\MobileTest>gradlew assemble --stacktrace

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'MobileTest'.
> Could not resolve all files for configuration ':classpath'.
   > Could not resolve com.android.tools.build:gradle:3.0.0.
     Required by:
         project :
      > Could not resolve com.android.tools.build:gradle:3.0.0.
         > Could not get resource 'https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom'.
            > Could not GET 'https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom'.
               > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification pat
h to requested target
      > Could not resolve com.android.tools.build:gradle:3.0.0.
         > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom'.
            > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom'.
               > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification pat
h to requested target

Body:
It's a problem related to Android Studio 3.0 and the corporate networks. I had the same problem.

Error:Could not resolve all files for configuration ':app:debugAndroidTestRuntimeClasspath'.
    > Could not resolve com.android.support.test:runner:1.0.1.
      Required by:
          project :app
       > Could not resolve com.android.support.test:runner:1.0.1.
          > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/support/test/runner/1.0.1/runner-1.0.1.pom'.
             > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/support/test/runner/1.0.1/runner-1.0.1.pom'.
                > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    > Could not resolve com.android.support.test.espresso:espresso-core:3.0.1.
      Required by:
          project :app
       > Could not resolve com.android.support.test.espresso:espresso-core:3.0.1.
          > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/support/test/espresso/espresso-core/3.0.1/espresso-core-3.0.1.pom'.
             > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/support/test/espresso/espresso-core/3.0.1/espresso-core-3.0.1.pom'.
                > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

I leave you 2 solutions:

1rst:
You must add certificates manually to your java security certs (used by Android):

C:\Program Files\Android\Android Studio\jre\jre\lib\security\cacerts

SOLUTION 01 (Didn't work for me):

Go to:

C:\Program Files\Android\Android Studio\jre\jre\bin

Download the Certificate you need (just copy the URL with the problem and paste it into <remote_host_name>):

keytool -J-Dhttps.proxyHost=<proxy_hostname> -J-Dhttps.proxyPort=<proxy_port> -printcert -rfc -sslserver <remote_host_name:remote_ssl_port> > <name.cer>

Example:
C:\Program Files\Android\Android Studio\jre\jre\bin>keytool -J-Dhttps.proxyHost= proxy.mycompany.com -J-Dhttps.proxyPort=80 -printcert -rfc -sslserver https://dl.google.com/dl/android/maven2/com/android/support/test/runner/1.0.1/runner-1.0.1.pom > maven2.cer

And run the command:

keytool -import -noprompt -trustcacerts -keystore ..\lib\security\cacerts -importcert -alias <AliasName> -file <name.cer> -storepass <cacertsPassword>

If you never changed the password of cacerts the default one is changeit:

Example:
C:\Program Files\Android\Android Studio\jre\jre\bin>keytool -import -noprompt -trustcacerts -keystore ..\lib\security\cacerts -importcert -alias Maven -file maven2.cer -storepass changeit

SOLUTION 02 (Worked for me):

Download the pom entering to the URL site and store it in your local repo:

Ex:
If your missing resoruce is:
https://dl.google.com/dl/android/maven2/com/android/support/test/espresso/espresso-core/3.0.1/espresso-core-3.0.1.pom

Download it and put it in:
C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/support/test/espresso/espresso-core/3.0.1/espresso-core-3.0.1.pom


问:
In WebRTC, which ICE candidate created a successful connection?
I want to know which ICE candidate created a successful connection and is being used to transfer data between peers. I want to be able to differentiate a local (host) connection from a server reflexive to a TURN connection.

I am currently using the WebRTC native API and don't see any public APIs that allow me to know which ICE candidate successfully created a connection.

答: use the getStats API. The process is similar to the one described here</p>


问:
Azure AD B2C with Azure AD - profile edit
If I've successfully configured Azure AD B2C to allow login using Azure AD accounts (per https://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-setup-aad-custom), should I be able to set up custom policies to allow AAD-authenticated users to edit their profiles, overriding the default ProfileEdit policy?  If so, any hints as to how to tackle?  I am pretty sure I need to create a new UserJourney and a new ProfileEdit policy, but I'm not sure of the details.

thanks!

Martin

答:
You can enable an Azure AD-authenticated user to modify their account profile by including the Azure AD claims provider in the profile edit user journey as follows:

<UserJourney Id="ProfileEdit">
  <OrchestrationSteps>
    <OrchestrationStep Order="1" Type="ClaimsProviderSelection" ContentDefinitionReferenceId="api.idpselections">
      <ClaimsProviderSelections>
        <ClaimsProviderSelection TargetClaimsExchangeId="ContosoExchange" />
        <ClaimsProviderSelection TargetClaimsExchangeId="LocalAccountSigninEmailExchange" />
      </ClaimsProviderSelections>
    </OrchestrationStep>
    <OrchestrationStep Order="2" Type="ClaimsExchange">
      <ClaimsExchanges>
        <ClaimsExchange Id="ContosoExchange" TechnicalProfileReferenceId="ContosoProfile" />
        <ClaimsExchange Id="LocalAccountSigninEmailExchange" TechnicalProfileReferenceId="SelfAsserted-LocalAccountSignin-Email" />
      </ClaimsExchanges>
    </OrchestrationStep>
    <OrchestrationStep Order="3" Type="ClaimsExchange">
      <Preconditions>
        <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
          <Value>authenticationSource</Value>
          <Value>localAccountAuthentication</Value>
          <Action>SkipThisOrchestrationStep</Action>
        </Precondition>
      </Preconditions>
      <ClaimsExchanges>
        <ClaimsExchange Id="AADUserRead" TechnicalProfileReferenceId="AAD-UserReadUsingAlternativeSecurityId" />
      </ClaimsExchanges>
    </OrchestrationStep>
    <OrchestrationStep Order="4" Type="ClaimsExchange">
      <Preconditions>
        <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
          <Value>authenticationSource</Value>
          <Value>contosoAuthentication</Value>
          <Action>SkipThisOrchestrationStep</Action>
        </Precondition>
      </Preconditions>
      <ClaimsExchanges>
        <ClaimsExchange Id="AADUserReadWithObjectId" TechnicalProfileReferenceId="AAD-UserReadUsingObjectId" />
      </ClaimsExchanges>
    </OrchestrationStep>
    <OrchestrationStep Order="5" Type="ClaimsExchange">
      <ClaimsExchanges>
        <ClaimsExchange Id="B2CUserProfileUpdateExchange" TechnicalProfileReferenceId="SelfAsserted-ProfileUpdate" />
      </ClaimsExchanges>
    </OrchestrationStep>
    <OrchestrationStep Order="6" Type="SendClaims" CpimIssuerTechnicalProfileReferenceId="JwtIssuer" />
  </OrchestrationSteps>
  <ClientDefinition ReferenceId="DefaultWeb" />
</UserJourney>
```

This user journey prompts the end user to log in with either their local account or their Azure AD account and then, after reading the user object by either the object identifier (for the local account) or the alternative security identifier (for the Azure AD account), shows the profile editing page.

Body:
You can enable an Azure AD-authenticated user to modify their account profile by including the Azure AD claims provider in the profile edit user journey as follows:

<UserJourney Id="ProfileEdit">
  <OrchestrationSteps>
    <OrchestrationStep Order="1" Type="ClaimsProviderSelection" ContentDefinitionReferenceId="api.idpselections">
      <ClaimsProviderSelections>
        <ClaimsProviderSelection TargetClaimsExchangeId="ContosoExchange" />
        <ClaimsProviderSelection TargetClaimsExchangeId="LocalAccountSigninEmailExchange" />
      </ClaimsProviderSelections>
    </OrchestrationStep>
    <OrchestrationStep Order="2" Type="ClaimsExchange">
      <ClaimsExchanges>
        <ClaimsExchange Id="ContosoExchange" TechnicalProfileReferenceId="ContosoProfile" />
        <ClaimsExchange Id="LocalAccountSigninEmailExchange" TechnicalProfileReferenceId="SelfAsserted-LocalAccountSignin-Email" />
      </ClaimsExchanges>
    </OrchestrationStep>
    <OrchestrationStep Order="3" Type="ClaimsExchange">
      <Preconditions>
        <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
          <Value>authenticationSource</Value>
          <Value>localAccountAuthentication</Value>
          <Action>SkipThisOrchestrationStep</Action>
        </Precondition>
      </Preconditions>
      <ClaimsExchanges>
        <ClaimsExchange Id="AADUserRead" TechnicalProfileReferenceId="AAD-UserReadUsingAlternativeSecurityId" />
      </ClaimsExchanges>
    </OrchestrationStep>
    <OrchestrationStep Order="4" Type="ClaimsExchange">
      <Preconditions>
        <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
          <Value>authenticationSource</Value>
          <Value>contosoAuthentication</Value>
          <Action>SkipThisOrchestrationStep</Action>
        </Precondition>
      </Preconditions>
      <ClaimsExchanges>
        <ClaimsExchange Id="AADUserReadWithObjectId" TechnicalProfileReferenceId="AAD-UserReadUsingObjectId" />
      </ClaimsExchanges>
    </OrchestrationStep>
    <OrchestrationStep Order="5" Type="ClaimsExchange">
      <ClaimsExchanges>
        <ClaimsExchange Id="B2CUserProfileUpdateExchange" TechnicalProfileReferenceId="SelfAsserted-ProfileUpdate" />
      </ClaimsExchanges>
    </OrchestrationStep>
    <OrchestrationStep Order="6" Type="SendClaims" CpimIssuerTechnicalProfileReferenceId="JwtIssuer" />
  </OrchestrationSteps>
  <ClientDefinition ReferenceId="DefaultWeb" />
</UserJourney>

This user journey prompts the end user to log in with either their local account or their Azure AD account and then, after reading the user object by either the object identifier (for the local account) or the alternative security identifier (for the Azure AD account), shows the profile editing page.


问:
Extension Methods vs. Regular Methods - Best Practice Ideas
I'm having a bit of a difficult time determining when to implement a method as an extension method and when to implement a method as a stand-alone method. What are some best practices people follow in determining this?</p>

答:
Use an extension method if any of the following conditions are true:

You need a method on a type and you don't own the source.

You need a method on a type, you do own the source, and the type is an interface.

You need a method on a type, you do own the source, but adding the method creates undesired coupling.*

Otherwise, you should use a real method on the actual type itself.

I don't think it makes a whole lot of sense to create an extension method for a class or struct that you own the source for - why confuse readers with an extension method when a regular method will suffice?

Suggested reading: Framework Design Guidelines: Extension Methods

* Imagine that you wanted to add convenience methods to a type but don't want to create dependencies to assemblies or types that shouldn't be part of the API.  You could use extension methods to manage this.


问:
Boxing, unboxing and type erasure
I have come across the terms boxing, unboxing, and type erasure a few times. I am reading the Scala puzzler book (Puzzler 22, Cast Away) and found a few statements which have confused me. For example:

Scala collections, like Java collections (except for arrays), cannot store Java primitive types directly. Because collections are generic, and generic classes are subject to type erasure, the type of collection elements is erased to AnyRef (java.lang.Object). All Scala’s value types, including Int, are AnyVals and thus need to be boxed into AnyRef wrapper types when stored in a collection. So every Scala Map[String, Int] actually contains Integer values under the covers. Reading Integer values out of a Map[String, Int] is thus what the compiler does all the time.

Question 1 - Does the above statement mean that Map[Int, String] is actually Map[Integer, String]?

Question 2 - Why are arrays different with regard to their ability to store Java primitives?

Question 3 - Does type erasure affect boxing and unboxing?

答:
Question 1. No in both senses. It's Map[Int, String] at compile-time, but just Map at runtime. The keys in this runtime Map are Integers... unless your program "cheats" in some way.

Question 2. Because JVM type system treats arrays specially and did long before generics existed. The quote doesn't mention this, but Array[File] and Array[String] are also different types at runtime (as opposed to List and all other collections).

Question 3. They happen at the same compilation stage (as you can see at https://typelevel.org/scala/docs/phases.html), and they certainly interact.

Title: Boxing, unboxing and type erasure


问:
sequelize sync is not a function
I am trying to set up a test using mocha with sequelize. I'd like to truncate all the table and create new ones before and after each test. I thought I could just use sequelize.sync.

Here is my test:

```<code>import chai from "chai";
import assert from "assert";
import app from "../../src/app";
import chaiHttp from "chai-http";
import factories from "../factories";
import Sequelize from "sequelize";

// import dotenv from "dotenv";
// dotenv.config({path: ".env.test"});
chai.use(chaiHttp);

describe("'regions'service", () => {
  beforeEach(async () => {
    await Sequelize.sync({ force: true });
  });

  it("should POST area", async () => {
    const region = await factories.create("region");
    const dummy = {
      name: "New area",
      open: true,
      description: "This is a cool area!",
      gps: "122.123, 123.4123",
      regionId: region.dataValues.id
    };
    const res = await chai
      .request(app)
      .post("/api/areas")
      .send(dummy);
    assert.equal(res.body.name, dummy.name);
  });
});
</code>```

My error message:

```<code> TypeError: _sequelize2.default.sync is not a function
</code>```

答:
I guess I understood sequelize all wrong. I have to use sequelize to make the connection everytime when trying to use it.

so change the file to :

```<code>import chai from "chai";
import assert from "assert";
import app from "../../src/app";
import chaiHttp from "chai-http";
import factories from "../factories";
import db from "../../src/models";

// import dotenv from "dotenv";
// dotenv.config({path: ".env.test"});
chai.use(chaiHttp);

describe("'regions'service", () => {
  beforeEach(async () => {
    await db.sequelize.sync({ force: true, logging: false });
  });

  it("should POST area", async () => {
    const region = await factories.create("region");
    const dummy = {
      name: "New area",
      open: true,
      description: "This is a cool area!",
      gps: "122.123, 123.4123",
      regionId: region.dataValues.id
    };
    const res = await chai
      .request(app)
      .post("/api/areas")
      .send(dummy);
    assert.equal(res.body.name, dummy.name);
  });
});
</code>```

Where my db file looks like the following:

```<code>"use strict";

const fs = require("fs");
const path = require("path");
const Sequelize = require("sequelize");
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || "development";
const config = require(__dirname + "/../config/config.json")[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  sequelize = new Sequelize(
    config.database,
    config.username,
    config.password,
    config
  );
}

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (
      file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js"
    );
  })
  .forEach(file => {
    var model = sequelize["import"](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
</code>```

Title: sequelize sync is not a function

Body:
I am trying to set up a test using mocha with sequelize. I'd like to truncate all the table and create new ones before and after each test. I thought I could just use sequelize.sync.

Here is my test:

import chai from "chai";
import assert from "assert";
import app from "../../src/app";
import chaiHttp from "chai-http";
import factories from "../factories";
import Sequelize from "sequelize";

// import dotenv from "dotenv";
// dotenv.config({path: ".env.test"});
chai.use(chaiHttp);

describe("'regions'service", () => {
  beforeEach(async () => {
    await Sequelize.sync({ force: true });
  });

  it("should POST area", async () => {
    const region = await factories.create("region");
    const dummy = {
      name: "New area",
      open: true,
      description: "This is a cool area!",
      gps: "122.123, 123.4123",
      regionId: region.dataValues.id
    };
    const res = await chai
      .request(app)
      .post("/api/areas")
      .send(dummy);
    assert.equal(res.body.name, dummy.name);
  });
});

My error message:

 TypeError: _sequelize2.default.sync is not a function

Body:
I guess I understood sequelize all wrong. I have to use sequelize to make the connection everytime when trying to use it.

so change the file to :

import chai from "chai";
import assert from "assert";
import app from "../../src/app";
import chaiHttp from "chai-http";
import factories from "../factories";
import db from "../../src/models";

// import dotenv from "dotenv";
// dotenv.config({path: ".env.test"});
chai.use(chaiHttp);

describe("'regions'service", () => {
  beforeEach(async () => {
    await db.sequelize.sync({ force: true, logging: false });
  });

  it("should POST area", async () => {
    const region = await factories.create("region");
    const dummy = {
      name: "New area",
      open: true,
      description: "This is a cool area!",
      gps: "122.123, 123.4123",
      regionId: region.dataValues.id
    };
    const res = await chai
      .request(app)
      .post("/api/areas")
      .send(dummy);
    assert.equal(res.body.name, dummy.name);
  });
});

Where my db file looks like the following:

"use strict";

const fs = require("fs");
const path = require("path");
const Sequelize = require("sequelize");
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || "development";
const config = require(__dirname + "/../config/config.json")[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  sequelize = new Sequelize(
    config.database,
    config.username,
    config.password,
    config
  );
}

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (
      file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js"
    );
  })
  .forEach(file => {
    var model = sequelize["import"](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;


问:
Can 'attributes' change its value after setting value to a property?
Consider this code:

```<code>Public Class SomeViewModel
    <Custom>
    Public Property myData As String
End Class
</code>```

I want the Custom attribute to have capability to change myData after it set to some data.

ie. trim myData or omit extra chars from it or ...  it doesn't matter now.

I know I can use set and get statement, but those make my code look like not good, and also I want to repeat this CustomAttribute many times is same class or elsewhere.

UPDATE

Ok, if there is no way else, can I use some customAttribute and before my 'insert to SQL logic' call a function say: for all property that has this customAttribute do this thing? How can I implement that?

答:
You should use setters and getters, that's what they are for.

Attributes mark parts of your code, such that reflection can be used on this code - it is a rather heavy weight approach just because you don't like the look of property setters and getters.

Body:
Consider this code:

Public Class SomeViewModel
    <Custom>
    Public Property myData As String
End Class

I want the Custom attribute to have capability to change myData after it set to some data.

ie. trim myData or omit extra chars from it or ...  it doesn't matter now.

I know I can use set and get statement, but those make my code look like not good, and also I want to repeat this CustomAttribute many times is same class or elsewhere.

UPDATE

Ok, if there is no way else, can I use some customAttribute and before my 'insert to SQL logic' call a function say: for all property that has this customAttribute do this thing? How can I implement that?


答:
IIUC, (without accounting for anomalies) you can use diff + cumsum to get distinct groups and groupby on those:

```<code>for _, g in df.groupby((~df['Op.progressPercentage']\
                          .diff().fillna(0).ge(0)).cumsum()):
     print(g, '\n')
</code>```

Details

The groups are found like this:

```<code>(~df['Op.progressPercentage'].diff().fillna(0).ge(0)).cumsum()

0     0
1     0
2     0
3     0
4     0
5     0
6     0
7     0
8     1
9     1
10    1
11    1
12    1
13    1
14    1
15    1
16    1
17    1
18    1
19    1
20    1
21    1
22    1
Name: Op.progressPercentage, dtype: int64
</code>```

Title: Splitting a pandas Dataframe into separate groups

Body:
Given the following dataset DF:

uuid,eventTime,Op.progress,Op.progressPercentage, AnotherAttribute
C0972765-8436-0000-0000-000000000000,2017-08-19T12:52:39,P,3.0,01:57:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:52:49,P,3.0,01:56:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:18,P,4.0,01:55:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:49,P,5.0,01:55:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:54:27,P,5.0,01:54:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:07,P,6.0,01:54:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:27,P,6.0,01:53:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:33:46,W,40.0,01:13:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:10,N,1.0,02:00:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:16,N,1.0,02:00:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:18,N,1.0,02:00:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:55,P,1.0,02:00:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:41:15,P,1.0,01:59:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:41:31,P,3.0,01:57:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:41:51,P,3.0,01:56:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:42:22,P,4.0,01:56:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:42:51,P,4.0,01:55:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:29:22,S,98.0,00:04:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:29:27,S,98.0,00:03:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:30:27,S,99.0,00:02:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:31:27,S,100.0,00:01:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:33:01,F,100.0,00:01:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:33:01,F,100.0,00:01:00

I would like to split into two:

df1:

uuid,eventTime,Op.progress,Op.progressPercentage, AnotherAttribute
C0972765-8436-0000-0000-000000000000,2017-08-19T12:52:39,P,3.0,01:57:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:52:49,P,3.0,01:56:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:18,P,4.0,01:55:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:53:49,P,5.0,01:55:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:54:27,P,5.0,01:54:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:07,P,6.0,01:54:00
C0972765-8436-0000-0000-000000000000,2017-08-19T12:55:27,P,6.0,01:53:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:33:46,W,40.0,01:13:00

df2:

uuid,eventTime,Op.progress,Op.progressPercentage, AnotherAttribute
C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:10,N,1.0,02:00:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:16,N,1.0,02:00:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:18,N,1.0,02:00:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:40:55,P,1.0,02:00:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:41:15,P,1.0,01:59:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:41:31,P,3.0,01:57:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:41:51,P,3.0,01:56:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:42:22,P,4.0,01:56:00
C0972765-8436-0000-0000-000000000000,2017-08-19T13:42:51,P,4.0,01:55:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:29:22,S,98.0,00:04:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:29:27,S,98.0,00:03:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:30:27,S,99.0,00:02:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:31:27,S,100.0,00:01:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:33:01,F,100.0,00:01:00
C0972765-8436-0000-0000-000000000000,2017-08-19T15:33:01,F,100.0,00:01:00

The split should be based on the Op.progressPercentage attribute which can assume value from 1 to 100.

When I try to apply the solution provided at splitting a pandas Dataframe as shown below, I do not get the right and expected result.

df_dataset = pd.read_csv(filepath) #your input data saved here
wash_list = []
shifted = df_dataset['Op.progressPercentage'].shift()
m = shifted.diff(-1).ne(0) & shifted.eq(100)
a = m.cumsum()
aa = df_dataset.groupby([df_dataset.uuid,a])
for k, gp in aa:
    wash_list.append(gp.sort_values(['uuid', 'eventTime'], ascending=[1, 1]))

for wash in wash_list :
    print("")
    print(wash.to_string())
    print("")

Please, any help would be very appreciated.
Thank you very much in advance,
Best Regards,
Carlo

Body:
IIUC, (without accounting for anomalies) you can use diff + cumsum to get distinct groups and groupby on those:

for _, g in df.groupby((~df['Op.progressPercentage']\
                          .diff().fillna(0).ge(0)).cumsum()):
     print(g, '\n')

Details

The groups are found like this:

(~df['Op.progressPercentage'].diff().fillna(0).ge(0)).cumsum()

0     0
1     0
2     0
3     0
4     0
5     0
6     0
7     0
8     1
9     1
10    1
11    1
12    1
13    1
14    1
15    1
16    1
17    1
18    1
19    1
20    1
21    1
22    1
Name: Op.progressPercentage, dtype: int64


问:
Multiple values in one parameter field in MS Access
Is there a way to use a parameter query to search for multiple values in text format in the same field? Ideally the parameter box would pop up and I can put in any number of values separate by commas.For example i would be putting in values like CAR1074,19-2140-4-0001 from the field 'CPN' in the parameter box. I tried the below query but it did not come up with any result. (Got a blank result sheet)</p>

```<code>PARAMETERS [Enter CPN/M&E] Text (255);

SELECT PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.CPN,
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.MPN,
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.KEYWORD,
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[PO NUMBER],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[PO LINE NUMBER],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[PO RECEIVED DATE],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[PO SUPPLIER CODE],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[PO SUPPLIER NAME],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[PO RECEIPT STATION],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[PO SYSTEM],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[RO NUMBER],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[RO LINE NUMBER],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[RO RECEIVED DATE],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[RO SUPPLIER CODE],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[RO SUPPLIER NAME],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[RO RECEIPT STATION],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[RO SYSTEM]
FROM PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE
WHERE (((PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.CPN)=Instr("," & [CPN] & ",","," & [CPN] & ",")));
</code>```

答:
So search for the CPN within the input string and if found the position is greater than 0.

WHERE InStr([Enter CPN/M&E, separate multiple values by comma], [CPN])>0

Body:
Is there a way to use a parameter query to search for multiple values in text format in the same field? Ideally the parameter box would pop up and I can put in any number of values separate by commas.For example i would be putting in values like CAR1074,19-2140-4-0001 from the field 'CPN' in the parameter box. I tried the below query but it did not come up with any result. (Got a blank result sheet)

PARAMETERS [Enter CPN/M&E] Text (255);

SELECT PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.CPN,
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.MPN,
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.KEYWORD,
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[PO NUMBER],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[PO LINE NUMBER],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[PO RECEIVED DATE],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[PO SUPPLIER CODE],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[PO SUPPLIER NAME],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[PO RECEIPT STATION],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[PO SYSTEM],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[RO NUMBER],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[RO LINE NUMBER],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[RO RECEIVED DATE],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[RO SUPPLIER CODE],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[RO SUPPLIER NAME],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[RO RECEIPT STATION],
       PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.[RO SYSTEM]
FROM PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE
WHERE (((PROD_SUPLR_MGMT_SNBX_DB_CUSTOMS_DATABASE.CPN)=Instr("," & [CPN] & ",","," & [CPN] & ",")));


问:
Haskell couldn't match expected type float with actual type 'a'
I have run into a problem when trying to add 2 parts of a tuple together

Function Type:

```<code>close :: (Floating a, Ord a) => (a,a) -> (a,a) -> Float
</code>```

Function definition:

```<code>close y x = sqrt (((fromIntegral(snd x) - fromIntegral(snd y))^2) + ((fromIntegral(fst x) - fromIntegral(fst y)^2)))
</code>```

On feeding the function a y tuple of format ( , ) and a x tuple of format ( , ) it should calculate the distance between two coordinates.
However on launch I get an error of:

```<code>Couldn't match expected type 'Float' with actual type 'a'
a is a rigid type variable bound by...
</code>```

I do understand why the problem is arising, but I have no idea how to fix it

答:
Your type is wrong. As Redu mentions in the comments, you have a type under typeclass Floating and are calling fromIntegral on it.

```<code>Prelude> :t fromIntegral
fromIntegral :: (Num b, Integral a) => a -> b
</code>```

You can't have a Floating Integral, so this fails. Your type instead should be:

```<code>close :: Integral a => (a, a) -> (a, a) -> Float
</code>```

Note that you also don't need as many fromIntegral calls, since (^) operates on (Num a, Integral b) => a -> b -> a, any number can be the base. The only operation that matters is sqrt which requires a Floating a.

```<code>close :: Integral a => (a, a) -> (a, a) -> Float
close (x1, y1) (x2, y2) = sqrt . fromIntegral $ squaredDistance where
  squaredDistance = (x1 - x2) ^ 2 + (y1 - y2) ^ 2
</code>```

Body:
I have run into a problem when trying to add 2 parts of a tuple together

Function Type:

close :: (Floating a, Ord a) => (a,a) -> (a,a) -> Float

Function definition:

close y x = sqrt (((fromIntegral(snd x) - fromIntegral(snd y))^2) + ((fromIntegral(fst x) - fromIntegral(fst y)^2)))

On feeding the function a y tuple of format ( , ) and a x tuple of format ( , ) it should calculate the distance between two coordinates.
However on launch I get an error of:

Couldn't match expected type 'Float' with actual type 'a'
a is a rigid type variable bound by...

I do understand why the problem is arising, but I have no idea how to fix it

Body:
Your type is wrong. As Redu mentions in the comments, you have a type under typeclass Floating and are calling fromIntegral on it.

Prelude> :t fromIntegral
fromIntegral :: (Num b, Integral a) => a -> b

You can't have a Floating Integral, so this fails. Your type instead should be:

close :: Integral a => (a, a) -> (a, a) -> Float

Note that you also don't need as many fromIntegral calls, since (^) operates on (Num a, Integral b) => a -> b -> a, any number can be the base. The only operation that matters is sqrt which requires a Floating a.

close :: Integral a => (a, a) -> (a, a) -> Float
close (x1, y1) (x2, y2) = sqrt . fromIntegral $ squaredDistance where
  squaredDistance = (x1 - x2) ^ 2 + (y1 - y2) ^ 2


问:
Removing duplicated from sorted list (OCaml)
I'm trying to remove duplicate items from already sorted list in OCaml. This is my code:

```<code>let rec remove_dup = function
    | [] -> []
    | hd :: [] -> hd :: []
    | hd :: hd2 :: tl -> if (hd == hd2) (remove_dup tl) :: hd else (remove_dup (h2 :: tl) :: hd;;
</code>```

I'm getting a syntax error.

答:
The OCaml if looks like if expr1 then expr2 else expr3. You're missing the keyword then.

You also have unbalanced parentheses. It looks like you need a right parenthesis at the very end.

After these fixes you have some type errors that you should look at.

As a side comment, don't use == to test for equality. It's a special-purpose operator for advanced uses. The day-to-day equality operator is =.

Body:
I'm trying to remove duplicate items from already sorted list in OCaml. This is my code:

let rec remove_dup = function
    | [] -> []
    | hd :: [] -> hd :: []
    | hd :: hd2 :: tl -> if (hd == hd2) (remove_dup tl) :: hd else (remove_dup (h2 :: tl) :: hd;;

I'm getting a syntax error.


问:
add subtitle in navigation bar
I want to add subtitle in navigation bar. How can i do this?

Here is image of what i want =>

http://img189.imageshack.us/img189/6373/80160929.jpg

Let say this is my navigation bar . so how can add sub title which is smaller than title in size?
thanks in advance

答: You can set your own view as the navigationControllers titleView.  Here you will need to make a view that contains 2 UILabels, size them properly, and set that as the titleView.

Title: add subtitle in navigation bar


问:
Collatz - maximum number of steps and the corresponding number
I am trying to write a Scala function that takes an upper bound as argument and calculates the steps for the numbers in a range from 1 up to this bound. It had to return the maximum number of steps and the corresponding number that needs that many steps. (as a pair - first element is the number of steps and second is the corresponding index)

I already have created a function called "collatz" which computes the number of steps. I am very new with Scala and I am a bit stuck because of the limitations. Here's how I thought to start the function:

```<code>def max(x:Int):Int = {
  for (i<-(1 to x).toList) yield collatz(i)
</code>```

the way I think to solve this problem is to: 1. iterate through the range and apply collatz to all elements while putting them in a new list which stores the number of steps. 2. find the maximum of the new list by using List.max 3. Use List.IndexOf to find the index. However, I'm really stuck since I don't know how to do this without using var (and only using val). Thanks!

答:
Something like this:

```<code>def collatzMax(n: Long): (Long, Long) = {
  require(n > 0, "Collatz function is not defined for n <= 0")

  def collatz(n: Long, steps: Long): Long = n match {
    case n if (n <= 1)     => steps
    case n if (n % 2 == 0) => collatz(n / 2, steps + 1)
    case n if (n % 2 == 1) => collatz(3 * n + 1, steps + 1)
  }

  def loop(n: Long, current: Long, acc: List[(Long, Long)]): List[(Long, Long)] =
    if (current > n) acc
    else {
      loop(n, current + 1, collatz(current, 0) -> current :: acc)
    }

  loop(n, 1, Nil).sortBy(-_._1).head
}
</code>```

Example:

```<code>collatzMax(12)
result: (Long, Long) = (19,9) // 19 steps for collatz(9)
</code>```

Using for:

```<code>def collatzMax(n: Long) =
  (for(i <- 1L to n) yield collatz(i) -> i).sortBy(-_._1).head
</code>```

Or(continuing your idea):

```<code>def maximum(x: Long): (Long, Long) = {
  val lst = for (i <- 1L to x) yield collatz(i)
  val maxValue = lst.max
  (maxValue, lst.indexOf(maxValue) + 1)
}
</code>```

Body:
I am trying to write a Scala function that takes an upper bound as argument and calculates the steps for the numbers in a range from 1 up to this bound. It had to return the maximum number of steps and the corresponding number that needs that many steps. (as a pair - first element is the number of steps and second is the corresponding index)

I already have created a function called "collatz" which computes the number of steps. I am very new with Scala and I am a bit stuck because of the limitations. Here's how I thought to start the function:

def max(x:Int):Int = {
  for (i<-(1 to x).toList) yield collatz(i)

the way I think to solve this problem is to: 1. iterate through the range and apply collatz to all elements while putting them in a new list which stores the number of steps. 2. find the maximum of the new list by using List.max 3. Use List.IndexOf to find the index. However, I'm really stuck since I don't know how to do this without using var (and only using val). Thanks!

Body:
Something like this:

def collatzMax(n: Long): (Long, Long) = {
  require(n > 0, "Collatz function is not defined for n <= 0")

  def collatz(n: Long, steps: Long): Long = n match {
    case n if (n <= 1)     => steps
    case n if (n % 2 == 0) => collatz(n / 2, steps + 1)
    case n if (n % 2 == 1) => collatz(3 * n + 1, steps + 1)
  }

  def loop(n: Long, current: Long, acc: List[(Long, Long)]): List[(Long, Long)] =
    if (current > n) acc
    else {
      loop(n, current + 1, collatz(current, 0) -> current :: acc)
    }

  loop(n, 1, Nil).sortBy(-_._1).head
}

Example:

collatzMax(12)
result: (Long, Long) = (19,9) // 19 steps for collatz(9)

Using for:

def collatzMax(n: Long) =
  (for(i <- 1L to n) yield collatz(i) -> i).sortBy(-_._1).head

Or(continuing your idea):

def maximum(x: Long): (Long, Long) = {
  val lst = for (i <- 1L to x) yield collatz(i)
  val maxValue = lst.max
  (maxValue, lst.indexOf(maxValue) + 1)
}


问:
how to hide column in django form and set foreign key value
I want to hide the column bh in the html page so I am hiding it by exclude in forms.py and trying to set foreign key column bh with request.user.username in the views but it is giving me this error:
Cannot assign "]>": "Bed.bh" must be a "Hospital" instance.

Is there any way to resolve the issue. Please help!

```<code>`#forms.py

class BedForm(forms.ModelForm):
class Meta:
    model=Bed
    fields = ('bed_id','bed_type','created_date','bh',)
    exclude=('bh',)

if request.method == "POST":
    form = BedForm(request.POST)
    if form.is_valid():
            bed = form.save(commit=False)
            bed.created_date = timezone.now()
            hh = Hospital.objects.filter(hospital_id=request.user.username)
            bed.bh=hh
            bed.save()
            b = Bed.objects.filter(bh=request.user.username)
</code>```

`

答:
This is because Hospital.objects.filter() is returning a QuerySet, not an instance of Hospital.

You want something like:

```<code>hh = Hospital.objects.filter(hospital_id=request.user.username)[0]
</code>```

or

```<code>hh = Hospital.objects.get(hospital_id=request.user.username)
</code>```

In both cases, however you will have to either check that the object exists before retrieving it, or catch the exception, then figure out what to do next.

Body:
I want to hide the column bh in the html page so I am hiding it by exclude in forms.py and trying to set foreign key column bh with request.user.username in the views but it is giving me this error:
Cannot assign "]>": "Bed.bh" must be a "Hospital" instance.

Is there any way to resolve the issue. Please help!

`#forms.py

class BedForm(forms.ModelForm):
class Meta:
    model=Bed
    fields = ('bed_id','bed_type','created_date','bh',)
    exclude=('bh',)

if request.method == "POST":
    form = BedForm(request.POST)
    if form.is_valid():
            bed = form.save(commit=False)
            bed.created_date = timezone.now()
            hh = Hospital.objects.filter(hospital_id=request.user.username)
            bed.bh=hh
            bed.save()
            b = Bed.objects.filter(bh=request.user.username)

`

Body:
This is because Hospital.objects.filter() is returning a QuerySet, not an instance of Hospital.

You want something like:

hh = Hospital.objects.filter(hospital_id=request.user.username)[0]

or

hh = Hospital.objects.get(hospital_id=request.user.username)

In both cases, however you will have to either check that the object exists before retrieving it, or catch the exception, then figure out what to do next.