问:
Google container connect to service
I'm following a course on PluralSight where the course author puts a docker image onto kubernetes and then access it via his browser. I'm trying to replicate what he does but I cannot manage to reach the website. I believe I might be connecting to the wrong IP.

I have a ReplicationController that's running 10 pods:

rc.yml

```<code>apiVersion: v1
kind: ReplicationController
metadata:
          name: hello-rc
spec:
        replicas: 10
        selector:
                app: hello-world
        template:
             metadata:
                labels:
                        app: hello-world
             spec:
                     containers:
                             - name: hello-pod
                               image: nigelpoulton/pluralsight-docker-ci:latest
                               ports:
                                       - containerPort: 8080
</code>```

I then  tried to expose the rc:

```<code>kubectl expose rc hello-rc --name=hello-svc --target-port=8080 --type=NodePort

$ kubectl get services
NAME         CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
hello-svc    10.27.254.160   <nodes>       8080:30488/TCP   30s
kubernetes   10.27.240.1     <none>        443/TCP          1h
</code>```

My google container endpoint is : 35.xxx.xx.xxx and when running kubectl describe svc hello-svc the NodePort is 30488

Thus I try to access the app at 35.xxx.xx.xxx:30488 but the site can’t be reached.

答:
If you want to access your service via the NodePort port, you need to open your firewall for that port (and that instance).

A better way is to create a service of type LoadBalancer (--type=LoadBalancer) and access it on the IP Google will give you.

Do not forget to delete the load balancer when you are done.

Title: Google container connect to service

Body:
I'm following a course on PluralSight where the course author puts a docker image onto kubernetes and then access it via his browser. I'm trying to replicate what he does but I cannot manage to reach the website. I believe I might be connecting to the wrong IP.

I have a ReplicationController that's running 10 pods:

rc.yml

apiVersion: v1
kind: ReplicationController
metadata:
          name: hello-rc
spec:
        replicas: 10
        selector:
                app: hello-world
        template:
             metadata:
                labels:
                        app: hello-world
             spec:
                     containers:
                             - name: hello-pod
                               image: nigelpoulton/pluralsight-docker-ci:latest
                               ports:
                                       - containerPort: 8080

I then  tried to expose the rc:

kubectl expose rc hello-rc --name=hello-svc --target-port=8080 --type=NodePort

$ kubectl get services
NAME         CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
hello-svc    10.27.254.160   <nodes>       8080:30488/TCP   30s
kubernetes   10.27.240.1     <none>        443/TCP          1h

My google container endpoint is : 35.xxx.xx.xxx and when running kubectl describe svc hello-svc the NodePort is 30488

Thus I try to access the app at 35.xxx.xx.xxx:30488 but the site can’t be reached.


来源: stackexchange

问:
Plotly: how to specify symbol and color based on value?
When plotting with plotly in R, how does one specify a color and a symbol based on a value? For example with the mtcars example dataset, how to plot as a red square if mtcars$mpg is greater or less than 18?

For example:

```<code>library(plotly)

p <- plot_ly(type = "scatter", data = mtcars, x = rownames(mtcars), y = mtcars$mpg,
             mode = "markers" )
</code>```

How to get all points above 20 as yellow squares?

答:
you could do something like this:

```<code>plot_ly(type = "scatter", data = mtcars, x = rownames(mtcars), y = mtcars$mpg,
        mode = "markers", symbol = ~mpg > 20, symbols = c(16,15),
        color = ~mpg > 20, colors = c("blue", "yellow"))
</code>```

https://plot.ly/r/line-and-scatter/#mapping-data-to-symbols

yes it's possible, I'd make all of your grouping and shape/color specification outside of plot_ly() with cut() first. And then take advantage of the literal I() syntax inside of plot_ly() when referencing your new color and shape vars:

```<code>data(mtcars)

mtcars$shape <- cut(mtcars$mpg,
                    breaks = c(0,18, 26, 100),
                    labels = c("square", "circle", "diamond"))
mtcars$color <- cut(mtcars$mpg,
                    breaks = c(0,18, 26, 100),
                    labels = c("red", "yellow", "green"))

plot_ly(type = "scatter", data = mtcars, x = rownames(mtcars), y = mtcars$mpg,
        mode = "markers", symbol = ~I(shape), color = ~I(color))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When plotting with plotly in R, how does one specify a color and a symbol based on a value? For example with the mtcars example dataset, how to plot as a red square if mtcars$mpg is greater or less than 18?

For example:

library(plotly)

p <- plot_ly(type = "scatter", data = mtcars, x = rownames(mtcars), y = mtcars$mpg,
             mode = "markers" )

How to get all points above 20 as yellow squares?

Body:
you could do something like this:

plot_ly(type = "scatter", data = mtcars, x = rownames(mtcars), y = mtcars$mpg,
        mode = "markers", symbol = ~mpg > 20, symbols = c(16,15),
        color = ~mpg > 20, colors = c("blue", "yellow"))

https://plot.ly/r/line-and-scatter/#mapping-data-to-symbols

yes it's possible, I'd make all of your grouping and shape/color specification outside of plot_ly() with cut() first. And then take advantage of the literal I() syntax inside of plot_ly() when referencing your new color and shape vars:

data(mtcars)

mtcars$shape <- cut(mtcars$mpg,
                    breaks = c(0,18, 26, 100),
                    labels = c("square", "circle", "diamond"))
mtcars$color <- cut(mtcars$mpg,
                    breaks = c(0,18, 26, 100),
                    labels = c("red", "yellow", "green"))

plot_ly(type = "scatter", data = mtcars, x = rownames(mtcars), y = mtcars$mpg,
        mode = "markers", symbol = ~I(shape), color = ~I(color))


问:
ASP.NET MVC2: EF4 + POCO + Repository pattern for beginner?
There are a lot articles introduced these technologies, but looks hard for beginners. Do you know any easy-beginning materials that fit newbies?</p>

答: asp.net/mvc is a great place for beginners to start. It contains many tutorials and videos.</p>

ContentLicense: CC BY-SA 2.5


问:
Is there a page maintained on Jose4J vulnerabilities if any posted on bitbucket?
I am looking for a vulnerabilities list for JOSE4J if any. We want to apply the library in our product to validate Azure AD tokens and generate so called entitlement tokens which contain more product related data, we like the library a lot, but the question from the security team came up if there are any vulnerabilities identified for JOSE4J and if any where are they posted, and how bug fixes are communicated in case of a discovered vulnerability

Thanks

Jan

答: The Release Notes of the project lists the changes made including anything security related.  </p>


问:
Determine if Python is running inside virtualenv
Is it possible to determine if the current script is running inside a virtualenv environment?</p>

答:
In windows OS you see something like this:

```<code>C:\Users\yourusername\virtualEnvName\Scripts>activate
(virtualEnvName) C:\Users\yourusername\virtualEnvName\Scripts>
</code>```

Parentheses mean that you are actually in the virtual environment called "virtualEnvName".

Body:
In windows OS you see something like this:

C:\Users\yourusername\virtualEnvName\Scripts>activate
(virtualEnvName) C:\Users\yourusername\virtualEnvName\Scripts>

Parentheses mean that you are actually in the virtual environment called "virtualEnvName".


问:
NSubstitute Argument Matcher Errors only in TFS Build
I'm experiencing an issue where tests are succeeding on my local machine using visual studio but they will fail when my CI Build runs them on my TFS server.

Here's the line that is failing and the preceding line for context.

```<code>var mockEventRepository = Substitute.For<IEventRepository>();
mockEventRepository.GetAll().ReturnsForAnyArgs(r => new List<Event>().AsQueryable());
</code>```

Note that there are NO ARGUMENT MATCHERS!  Not a single one in the entire test.

TFS will give the error:

NSubstitute.Exceptions.UnexpectedArgumentMatcherException : Argument matchers (Arg.Is, Arg.Any) should only be used in place of member arguments. Do not use in a Returns() statement or anywhere else outside of a member call.

In a nutshell the errors seem to be consistent (the same error) when they're occurring, but they also will seemingly randomly occur or not occur.

For instance... It just succeeded after queuing a subsequent identical build after the original one failed.  That time however it failed when it tried the same build with a different configuration with a different but similar and erroneous error:

NSubstitute.Exceptions.AmbiguousArgumentsException : Cannot determine argument specifications to use.

FYI Using TFS 2015 and VS 2015.

答:
I was seeing this issue when using NSubstitute with xunit which by default runs test classes in parallel.  There must be threading issues with NSubstitute because turning off parallelization fixed it for us. In your Test project AssemblyInfo.cs add

[assembly: CollectionBehavior(DisableTestParallelization = true)]

https://stackoverflow.com/a/34876963/1128742

Body:
I'm experiencing an issue where tests are succeeding on my local machine using visual studio but they will fail when my CI Build runs them on my TFS server.

Here's the line that is failing and the preceding line for context.

var mockEventRepository = Substitute.For<IEventRepository>();
mockEventRepository.GetAll().ReturnsForAnyArgs(r => new List<Event>().AsQueryable());

Note that there are NO ARGUMENT MATCHERS!  Not a single one in the entire test.

TFS will give the error:

NSubstitute.Exceptions.UnexpectedArgumentMatcherException : Argument matchers (Arg.Is, Arg.Any) should only be used in place of member arguments. Do not use in a Returns() statement or anywhere else outside of a member call.

In a nutshell the errors seem to be consistent (the same error) when they're occurring, but they also will seemingly randomly occur or not occur.

For instance... It just succeeded after queuing a subsequent identical build after the original one failed.  That time however it failed when it tried the same build with a different configuration with a different but similar and erroneous error:

NSubstitute.Exceptions.AmbiguousArgumentsException : Cannot determine argument specifications to use.

FYI Using TFS 2015 and VS 2015.


问:
Combine two regex together
I have this expression from a ps ax list that I want to parse:

```<code>183838 ? myprocess -uuid 0f6309e3-bee2-4747-b76d-7aaf4d0f074e serial=802e7fd9-a2ab-e411-8000-001e67ca95b2
</code>```

I want to match the process id (183838) AND the uuid expression (0f6309e3-bee2-4747-b76d-7aaf4d0f074e).

I have the two regexes that match each of them:

```<code># PID
([0-9]*)
# UUID
(?<=uuid).([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})
</code>```

But I can't find how to combine them together to have this as result with sed:

```<code>183838 0f6309e3-bee2-4747-b76d-7aaf4d0f074e
</code>```

awk is not an option since it must be column number independent.

答:
Bash uses POSIX ERE, and you have a PCRE with a lookbehind. If you need PCRE, grep -P is an option, combined with -o, an option to pring only matched parts of the matched line:

```<code>$ ps ax | grep -oP '(^[0-9]+)|(?<=uuid )([-0-9a-f]{36})' | paste -sd' '
183838 0f6309e3-bee2-4747-b76d-7aaf4d0f074e
</code>```

(We combine multiple lines here with paste.)

Title: Combine two regex together

Body:
I have this expression from a ps ax list that I want to parse:

183838 ? myprocess -uuid 0f6309e3-bee2-4747-b76d-7aaf4d0f074e serial=802e7fd9-a2ab-e411-8000-001e67ca95b2

I want to match the process id (183838) AND the uuid expression (0f6309e3-bee2-4747-b76d-7aaf4d0f074e).

I have the two regexes that match each of them:

# PID
([0-9]*)
# UUID
(?<=uuid).([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})

But I can't find how to combine them together to have this as result with sed:

183838 0f6309e3-bee2-4747-b76d-7aaf4d0f074e

awk is not an option since it must be column number independent.

Body:
Bash uses POSIX ERE, and you have a PCRE with a lookbehind. If you need PCRE, grep -P is an option, combined with -o, an option to pring only matched parts of the matched line:

$ ps ax | grep -oP '(^[0-9]+)|(?<=uuid )([-0-9a-f]{36})' | paste -sd' '
183838 0f6309e3-bee2-4747-b76d-7aaf4d0f074e

(We combine multiple lines here with paste.)


问:
Ansible role does not add missing defaults
If I add any part of a var dict in the playbook...it won't fill in the rest of the dict from the role defaults. Is that normal? It's very confusing.

Playbook snippet:

```<code>- role: nvm
    nvm:
      node_version: '6.11.0'
</code>```

All of defaults/main.yml

```<code>---
nvm:
  user: "{{ ansible_user_id | default('goats') }}"
  version: v0.4.0

  node_version: '0.10'
</code>```

gets ignored, and the nvm object only contains node_version

Am I being unreasonable to expect it would have added the missing values, or is this a bug?

答:
The default behavior of ansible when you define the same variable is to replace it, with precedence defined in "Variable Precedence: Where Should I Put A Variable?"

You can change this behavior by setting the configuration hash_behaviour to merge

Body:
If I add any part of a var dict in the playbook...it won't fill in the rest of the dict from the role defaults. Is that normal? It's very confusing.

Playbook snippet:

- role: nvm
    nvm:
      node_version: '6.11.0'

All of defaults/main.yml

---
nvm:
  user: "{{ ansible_user_id | default('goats') }}"
  version: v0.4.0

  node_version: '0.10'

gets ignored, and the nvm object only contains node_version

Am I being unreasonable to expect it would have added the missing values, or is this a bug?


问:
How to Join In LiteDb
How can i join between two table in LiteDb Like SQL
Example : I Have Two table User and ActivityLog

Here is the Model

```<code>public class ActivityLog
{
    [BsonId]
    public int Id { get; set; }
    public string UserId { get; set; }
    public string Action { get; set; }
    public DateTime ActionDateTime { get; set; }
}

public class User
{
    [BsonId]
    public int Id { get; set; }
    public string UserId { get; set; }
    public string UserName { get; set; }
    public DateTime LoginDate { get; set; }

}
</code>```

I need to join Activity.UserID = User.UserId.
Is there any way to join like sql

答:
From official documentation

LiteDB is a document database, so there is no JOIN between
  collections. If you need reference a document in another document you
  can use DbRef. This document reference can be loaded when the
  database is initialized or when a query is run, or after a query is
  finished.

In your case, you can do smth like

```<code>public class ActivityLog
{
    [BsonId]
    public int Id { get; set; }
    public DbRef<User> User { get; set; }
    public string Action { get; set; }
    public DateTime ActionDateTime { get; set; }
}

public class User
{
    [BsonId]
    public int Id { get; set; }
    public string UserId { get; set; }
    public string UserName { get; set; }
    public DateTime LoginDate { get; set; }

}

//usage
// Getting user and activityLog collections
var usersCollection = db.GetCollection<User>("Users");
var activityLogsCollection = db.GetCollection<ActivityLog>("ActivityLogs");

// Creating a new User instance
var user = new User { UserId = 5, ...};
usersCollection.Insert(user);

// Create a instance of ActivityLog and reference to User John
var activityLog = new ActivityLog
{
    OrderNumber = 1,
    OrderDate = DateTime.Now,
    //Add it by DbRef
    User = new DbRef<User>(usersCollection, user.UserId)
};
activityLogsCollection.Insert(activityLog)
</code>```

See the documentation for more details.

Title: How to Join In LiteDb

Body:
How can i join between two table in LiteDb Like SQL
Example : I Have Two table User and ActivityLog

Here is the Model

public class ActivityLog
{
    [BsonId]
    public int Id { get; set; }
    public string UserId { get; set; }
    public string Action { get; set; }
    public DateTime ActionDateTime { get; set; }
}

public class User
{
    [BsonId]
    public int Id { get; set; }
    public string UserId { get; set; }
    public string UserName { get; set; }
    public DateTime LoginDate { get; set; }

}

I need to join Activity.UserID = User.UserId.
Is there any way to join like sql

Body:
From official documentation

LiteDB is a document database, so there is no JOIN between
  collections. If you need reference a document in another document you
  can use DbRef. This document reference can be loaded when the
  database is initialized or when a query is run, or after a query is
  finished.

In your case, you can do smth like

public class ActivityLog
{
    [BsonId]
    public int Id { get; set; }
    public DbRef<User> User { get; set; }
    public string Action { get; set; }
    public DateTime ActionDateTime { get; set; }
}

public class User
{
    [BsonId]
    public int Id { get; set; }
    public string UserId { get; set; }
    public string UserName { get; set; }
    public DateTime LoginDate { get; set; }

}

//usage
// Getting user and activityLog collections
var usersCollection = db.GetCollection<User>("Users");
var activityLogsCollection = db.GetCollection<ActivityLog>("ActivityLogs");

// Creating a new User instance
var user = new User { UserId = 5, ...};
usersCollection.Insert(user);

// Create a instance of ActivityLog and reference to User John
var activityLog = new ActivityLog
{
    OrderNumber = 1,
    OrderDate = DateTime.Now,
    //Add it by DbRef
    User = new DbRef<User>(usersCollection, user.UserId)
};
activityLogsCollection.Insert(activityLog)

See the documentation for more details.


问:
handling exceptions in ML
everyone, I'm trying to understand how exceptions work in ML, but I have strange error, and I can't figure out what is wrong:

```<code>exception Factorial

fun checked_factorial n =
  if n < 0 then
    raise Factorial
  else n;

fun factorial_driver () =
    checked_factorial(~4)
  handle
    Factorial => print "Out of range.";
</code>```

what may be wrong? thanks in advance for any help.

答:
You need to make sure that factorial_driver has a consistent type.  The non-exceptional case returns int, so ML infers the function to be of type unit -> int, but the exceptional case (that is, the print expression) returns unit, not int.

Generally, you basically need to return a value of the same type in all cases.

Title: handling exceptions in ML

Body:
everyone, I'm trying to understand how exceptions work in ML, but I have strange error, and I can't figure out what is wrong:

exception Factorial

fun checked_factorial n =
  if n < 0 then
    raise Factorial
  else n;

fun factorial_driver () =
    checked_factorial(~4)
  handle
    Factorial => print "Out of range.";

what may be wrong? thanks in advance for any help.


答:
You can do this sort of matching with capturing groups. These are enclosed by \( and \) in sed. In the replacement, \1 is replaced by whatever matched the content of the first capturing group, and so on.

So to translate your input string:

```<code>$ ps ax | grep -- '-uuid' | sed 's/\([0-9]*\).* -uuid \([0-9a-f-]*\).*/\1 \2/'
183838 0f6309e3-bee2-4747-b76d-7aaf4d0f074
</code>```

I've used the "-uuid" as an anchor to locate the right part of the string, allowing a shorter and more relaxed pattern for the uuid itself. But you can adapt this to your own requirements.

Title: Combine two regex together

Body:
You can do this sort of matching with capturing groups. These are enclosed by \( and \) in sed. In the replacement, \1 is replaced by whatever matched the content of the first capturing group, and so on.

So to translate your input string:

$ ps ax | grep -- '-uuid' | sed 's/\([0-9]*\).* -uuid \([0-9a-f-]*\).*/\1 \2/'
183838 0f6309e3-bee2-4747-b76d-7aaf4d0f074

I've used the "-uuid" as an anchor to locate the right part of the string, allowing a shorter and more relaxed pattern for the uuid itself. But you can adapt this to your own requirements.


问:
Android emulator doesn't work
I am new to Xamarin and trying to run the 'Hello, Android' application found in the introductory chapter of the official on-line Xamarin guide (link here). I use Visual Studio Community 2017 (VS).

I've created an Android Virtual Device (AVD) using Visual Studio's Android Emulator Manager tool. Here's a screenshot of the settings of the AVD I've set up:

My hardware specs are: Intel Core2 Duo 8400, 5GB of DDR2 667MHz RAM. I also use Win10 Enterprise.

Now, when try to run my application I initiate the AVD from within VS and after waiting for at least 5 minutes get the following screenshot from the Android Emulator:

How can I troubleshoot this error? As it is right now I simply cannot debug any Android application using Visual Studio and the specs described above.

Update:

I installed the exact same software on my laptop. The hardware specs of the laptop are: Core I5 4210U, 12GB DDR3 1600MHz.

Now the emulator runs smoothly, but, although I installed the same software I get a different GUI for the AVD. Anyway, problem solved. It seems the low hardware specifications was the issue.

Update 2:

It seems the AVD has problems. The build process intermittently halts at this point:

1 >  Processing: obj\Debug\res\layout\main.xml

1 >  Processing: obj\Debug\res\values\strings.xml

Also the sample application I tried to deploy (when the AVD starts) doesn't work.

答: Genymotion is an Android emulator that is free for personal use. It is what I use and it works very well. I would recommend trying that.</p>

Title: Android emulator doesn't work


问:
concate or segregate strings based on requirement
```<code>USER_ID     COLUMN1       COLUMN2

JOHN          24           CA
JOHN          24           LA
JOHN          63           CA
JOHN          63           LA
JOHN          66           CA
JOHN          66           LA
JOHN           9           AF
JOHN           9           AL
JOHN           9           AW
JOHN           9           DF
</code>```

Required output:

```<code>USER_ID          RESULT

JOHN             24~CA-LA  +  63~CA-LA  + 66~CA-LA +  9~AF-AL-AW-DF
</code>```

This is my requirement. I am trying listagg():

```<code>select USER_ID,
   (listagg(case when seqnum_p = 1 then COLUMN1 end, '-') within group (order by COLUMN1) ||
    '~' ||
    listagg(case when seqnum_b = 1 then COLUMN2 end, '-') within group (order by COLUMN2)
   ) as result
from (select TABLE.*,
         row_number() over (partition by USER_ID, COLUMN1 order by COLUMN1) as seqnum_p,
         row_number() over (partition by USER_ID, COLUMN2 order by COLUMN2) as seqnum_b
  from TABLE
 )
group by USER_ID;
</code>```

Current output:

```<code>JOHN         ||       AF-AL-AW-CA-DF-LA~24-63-66-9
</code>```

答:
You can do two levels of aggregation instead of dealing with the row numbers:

```<code>select user_id,
  listagg(tmp, ' + ') within group (order by tmp) as result
from (
  select user_id,
    column1 ||'~'|| listagg(column2, '-') within group (order by column2) as tmp
  from your_table
  group by user_id, column1
)
group by user_id
order by user_id;

USER RESULT
---- --------------------------------------------------
JOHN 24~CA-LA + 63~CA-LA + 66~CA-LA + 9~AF-AL-AW-DF
</code>```

The inner query gives you the first level:

```<code>USER TMP
---- --------------------------------------------------
JOHN 9~AF-AL-AW-DF
JOHN 24~CA-LA
JOHN 63~CA-LA
JOHN 66~CA-LA
</code>```

and the outer level further aggregates those into a single string per user.

The order-by in the outer query aggregation is of a string starting with a number, which puts '9~...' after '24~...', which would normally be odd but seems to be what you expect.

If you actually wanted them in numerical column-1-order you can include that in the subquery and use it for ordering:

```<code>select user_id,
  listagg(tmp, ' + ') within group (order by column1) as result
from (
  select user_id, column1,
    column1 ||'~'|| listagg(column2, '-') within group (order by column2) as tmp
  from your_table
  group by user_id, column1
)
group by user_id
order by user_id;

USER RESULT
---- --------------------------------------------------
JOHN 9~AF-AL-AW-DF + 24~CA-LA + 63~CA-LA + 66~CA-LA
</code>```

Body:
USER_ID     COLUMN1       COLUMN2

JOHN          24           CA
JOHN          24           LA
JOHN          63           CA
JOHN          63           LA
JOHN          66           CA
JOHN          66           LA
JOHN           9           AF
JOHN           9           AL
JOHN           9           AW
JOHN           9           DF

Required output:

USER_ID          RESULT

JOHN             24~CA-LA  +  63~CA-LA  + 66~CA-LA +  9~AF-AL-AW-DF

This is my requirement. I am trying listagg():

select USER_ID,
   (listagg(case when seqnum_p = 1 then COLUMN1 end, '-') within group (order by COLUMN1) ||
    '~' ||
    listagg(case when seqnum_b = 1 then COLUMN2 end, '-') within group (order by COLUMN2)
   ) as result
from (select TABLE.*,
         row_number() over (partition by USER_ID, COLUMN1 order by COLUMN1) as seqnum_p,
         row_number() over (partition by USER_ID, COLUMN2 order by COLUMN2) as seqnum_b
  from TABLE
 )
group by USER_ID;

Current output:

JOHN         ||       AF-AL-AW-CA-DF-LA~24-63-66-9

Body:
You can do two levels of aggregation instead of dealing with the row numbers:

select user_id,
  listagg(tmp, ' + ') within group (order by tmp) as result
from (
  select user_id,
    column1 ||'~'|| listagg(column2, '-') within group (order by column2) as tmp
  from your_table
  group by user_id, column1
)
group by user_id
order by user_id;

USER RESULT
---- --------------------------------------------------
JOHN 24~CA-LA + 63~CA-LA + 66~CA-LA + 9~AF-AL-AW-DF

The inner query gives you the first level:

USER TMP
---- --------------------------------------------------
JOHN 9~AF-AL-AW-DF
JOHN 24~CA-LA
JOHN 63~CA-LA
JOHN 66~CA-LA

and the outer level further aggregates those into a single string per user.

The order-by in the outer query aggregation is of a string starting with a number, which puts '9~...' after '24~...', which would normally be odd but seems to be what you expect.

If you actually wanted them in numerical column-1-order you can include that in the subquery and use it for ordering:

select user_id,
  listagg(tmp, ' + ') within group (order by column1) as result
from (
  select user_id, column1,
    column1 ||'~'|| listagg(column2, '-') within group (order by column2) as tmp
  from your_table
  group by user_id, column1
)
group by user_id
order by user_id;

USER RESULT
---- --------------------------------------------------
JOHN 9~AF-AL-AW-DF + 24~CA-LA + 63~CA-LA + 66~CA-LA


问:
Why does contentEditable element reject the Enter key?
I'm using an application that embeds IE control to show content. I change that content to contain a
Hello World
 element. This works well and I can edit the content of this div, but pressing Enter is rejected with a beep.

When I add a textarea element to that page the Enter key works and I can add lines, but not in the contentEditable element.

When I attach event to that element I see that pressing the Enter key triggers a keyDown event, but not a keyPress.

Anyone has an idea what might cause it?

Thanks,
splintor

答: I have checked it in IE and Firefox it worked perfectly</p>


问:
Is there an equivalent to Chrome developer tools (ctrl+shift+I) for Safari running on a mobile device
(I have Googled a lot but either I do not understand the info or ...?)

So on the desktop I can debug my site using Chrome Dev. Tools. All good.

But a small part of my site does not run correctly on my new iPad Pro with iOS 10 (it seems to be OK with iOS 9, 8)

Can someone please point me down the right path.

Thanks

答: If the suggestion from @w0xxOm is no good for you on Windows, Browserstack is a great alternative.</p>


问:
What is state Id that xtext uses while saving the resource
I am hosting xtext's orion editor using iframe in my angular application. I need to save the content written from my angular application side to a backend (Java application). Can anyone help me with what API calls or approach should I make from my angular side so that I can save the content written in the editor.

What I have already done :

1 .I tried extracting the content from the iframe from my angular side , but the data so extracted is partial as it only extracts data what is only visible through the iframe at once and not the whole content which one has to scroll to view .

2 . I tried making 'save' API calls that the xtext makes while saving, but it requires some stateId as its request body . I need to understand what is this state Id and how is it evaluated ?

I am making this call from my angular application

```<code>        _this.saveEditor = function(args) {
        var params = {
            requiredStateId: args.stateId
        }
        _this.saveUrl = XTEXT_URL + '/save?resource=' + args.resourceId;
        return $http({
            method: 'POST',
            url: _this.saveUrl,
            data: params
        });
    };
</code>```

my request body is :

```<code>{"requiredStateId":"-80000000"}
</code>```

And this is the state Id i am obtaining by  making a prior load api call which.returns state Id in its response.

答:
may this snipped can help you, i dont know how you can wire this up with your stuff though

```<code>require(["orion/code_edit/built-codeEdit-amd"], function() {
        require(["xtext/xtext-orion"], function(xtext) {
            var editors = xtext.createEditor({
                baseUrl: baseUrl,
                syntaxDefinition: "xtext-resources/generated/mydsl-syntax"
            }).done(function(editorViewer) {
                $("#save-button").click(function() {
                    editorViewer.xtextServices.saveResource();
                });
                $("#log-button").click(function() {
                    console.log(editorViewer.xtextServices.editorContext.getServerState());
                });
            });

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

where i do the simple log you can query and then call save manually.

Body:
I am hosting xtext's orion editor using iframe in my angular application. I need to save the content written from my angular application side to a backend (Java application). Can anyone help me with what API calls or approach should I make from my angular side so that I can save the content written in the editor.

What I have already done :

1 .I tried extracting the content from the iframe from my angular side , but the data so extracted is partial as it only extracts data what is only visible through the iframe at once and not the whole content which one has to scroll to view .

2 . I tried making 'save' API calls that the xtext makes while saving, but it requires some stateId as its request body . I need to understand what is this state Id and how is it evaluated ?

I am making this call from my angular application

        _this.saveEditor = function(args) {
        var params = {
            requiredStateId: args.stateId
        }
        _this.saveUrl = XTEXT_URL + '/save?resource=' + args.resourceId;
        return $http({
            method: 'POST',
            url: _this.saveUrl,
            data: params
        });
    };

my request body is :

{"requiredStateId":"-80000000"}

And this is the state Id i am obtaining by  making a prior load api call which.returns state Id in its response.

Body:
may this snipped can help you, i dont know how you can wire this up with your stuff though

require(["orion/code_edit/built-codeEdit-amd"], function() {
        require(["xtext/xtext-orion"], function(xtext) {
            var editors = xtext.createEditor({
                baseUrl: baseUrl,
                syntaxDefinition: "xtext-resources/generated/mydsl-syntax"
            }).done(function(editorViewer) {
                $("#save-button").click(function() {
                    editorViewer.xtextServices.saveResource();
                });
                $("#log-button").click(function() {
                    console.log(editorViewer.xtextServices.editorContext.getServerState());
                });
            });

        });
    });

where i do the simple log you can query and then call save manually.


问:
Automating file generation
I am curious to see how can we automate file/directory creation in WebStorm. For example, to create a component, right click on Component folder and run some macro/command and it will create folders for action creators, dispatchers, containers, reducers etc, with some code files to begin with.

Further, we may change what exactly is being generated to meet future requirements.

答:
Not currently possible, please vote for IDEA-141225 and IDEA-91565.

You can try a custom plugin (http://ceh9.github.io/PackageTemplates/), or develop your own one

Title: Automating file generation


问:
How to split string into equal-length substrings?
Im looking for an elegant way in Scala to split a given string into substrings of fixed size (the last string in the sequence might be shorter).

So

```<code>split("Thequickbrownfoxjumps", 4)
</code>```

should yield

```<code>["Theq","uick","brow","nfox","jump","s"]
</code>```

Of course I could simply use a loop but there has to be a more elegant (functional style) solution.

答:
Like this:

```<code>def splitString(xs: String, n: Int): List[String] = {
  if (xs.isEmpty) Nil
  else {
    val (ys, zs) = xs.splitAt(n)
    ys :: splitString(zs, n)
  }
}
</code>```

```<code>splitString("Thequickbrownfoxjumps", 4)
/************************************Executing-Process**********************************\
(   ys     ,      zs          )
  Theq      uickbrownfoxjumps
  uick      brownfoxjumps
  brow      nfoxjumps
  nfox      jumps
  jump      s
  s         ""                  ("".isEmpty // true)

 "" :: Nil                    ==>    List("s")
 "jump" :: List("s")          ==>    List("jump", "s")
 "nfox" :: List("jump", "s")  ==>    List("nfox", "jump", "s")
 "brow" :: List("nfox", "jump", "s") ==> List("brow", "nfox", "jump", "s")
 "uick" :: List("brow", "nfox", "jump", "s") ==> List("uick", "brow", "nfox", "jump", "s")
 "Theq" :: List("uick", "brow", "nfox", "jump", "s") ==> List("Theq", "uick", "brow", "nfox", "jump", "s")

\***************************************************************************/
</code>```

Body:
Im looking for an elegant way in Scala to split a given string into substrings of fixed size (the last string in the sequence might be shorter).

So

split("Thequickbrownfoxjumps", 4)

should yield

["Theq","uick","brow","nfox","jump","s"]

Of course I could simply use a loop but there has to be a more elegant (functional style) solution.

Body:
Like this:

def splitString(xs: String, n: Int): List[String] = {
  if (xs.isEmpty) Nil
  else {
    val (ys, zs) = xs.splitAt(n)
    ys :: splitString(zs, n)
  }
}

splitString("Thequickbrownfoxjumps", 4)
/************************************Executing-Process**********************************\
(   ys     ,      zs          )
  Theq      uickbrownfoxjumps
  uick      brownfoxjumps
  brow      nfoxjumps
  nfox      jumps
  jump      s
  s         ""                  ("".isEmpty // true)

 "" :: Nil                    ==>    List("s")
 "jump" :: List("s")          ==>    List("jump", "s")
 "nfox" :: List("jump", "s")  ==>    List("nfox", "jump", "s")
 "brow" :: List("nfox", "jump", "s") ==> List("brow", "nfox", "jump", "s")
 "uick" :: List("brow", "nfox", "jump", "s") ==> List("uick", "brow", "nfox", "jump", "s")
 "Theq" :: List("uick", "brow", "nfox", "jump", "s") ==> List("Theq", "uick", "brow", "nfox", "jump", "s")

\***************************************************************************/


问:
Add user to a Json list #PHP #JS
We are trying to add some new user to a Json file from a frontend form.

We pass the code taken from the form via Js, after that we are trying (Via PHP) to pass the value inserted by the user in a json file.

Extract from HTML

```<code>  <div class="log">
                    <p>Username Nuovo Utente</p>
                    <input class="nome" id="nuovoUtente" placeholder="inserisci il nome"><br>
                    <p>Password Password Nuovo Utente</p>
                    <input type="password" id="nuovaPsw" class="psw"> <br>
                    <button type="submit" class="lo" id="aggiunto">Aggiungi Nuovo Utente</button>
                </div>
</code>```

Extract from the js file

```<code> let newNom = document.getElementById('nuovoUtente');
   let newPass = document.getElementById('nuovaPsw');

   aggiunto.onclick=function(){
       $.get("utenti.php", { nome: newNom.value , pw: newPass.value });
   }
</code>```

Php file

```<code>  <?php
    $data[] = $_GET['data'];
    console.log($data[]);
    $inp = file_get_contents('pindex.json');
    $tempArray = json_decode($inp);
    array_push($tempArray, $data);
    $jsonData = json_encode($tempArray);
    file_put_contents('pindex.json', $jsonData);
    ?>
</code>```

答:
First php does not have console.log(); Might want to try print_r() or var_dump()

Next for the

```<code>$tempArray = json_decode($inp);
</code>```

this will return a stdObject for some reason. To get an array you need to do

```<code>$tempArray = json_decode($inp,TRUE);
</code>```

with an array you should just need to do:

```<code>$tempArray[] = $data;
</code>```

Title: Add user to a Json list #PHP #JS

Body:
We are trying to add some new user to a Json file from a frontend form.

We pass the code taken from the form via Js, after that we are trying (Via PHP) to pass the value inserted by the user in a json file.

Extract from HTML

Username Nuovo Utente

                    <input class="nome" id="nuovoUtente" placeholder="inserisci il nome">

Password Password Nuovo Utente

                    <input type="password" id="nuovaPsw" class="psw">

                    <button type="submit" class="lo" id="aggiunto">Aggiungi Nuovo Utente</button>

Extract from the js file

 let newNom = document.getElementById('nuovoUtente');
   let newPass = document.getElementById('nuovaPsw');

   aggiunto.onclick=function(){
       $.get("utenti.php", { nome: newNom.value , pw: newPass.value });
   }

Php file

  <?php
    $data[] = $_GET['data'];
    console.log($data[]);
    $inp = file_get_contents('pindex.json');
    $tempArray = json_decode($inp);
    array_push($tempArray, $data);
    $jsonData = json_encode($tempArray);
    file_put_contents('pindex.json', $jsonData);
    ?>

Body:
First php does not have console.log(); Might want to try print_r() or var_dump()

Next for the

$tempArray = json_decode($inp);

this will return a stdObject for some reason. To get an array you need to do

$tempArray = json_decode($inp,TRUE);

with an array you should just need to do:

$tempArray[] = $data;

ContentLicense: CC BY-SA 4.0


问:
Is there a client library that implements Hybrid workflow for Node.js for IdentityServer4?
I know that there is a JavaScript client called oidc-client.js for IdentityServer4, but it implements the Implicit flow.  I need something that can implement the Hybrid or Hybrid+PKSE flow.  First, is there a client library out there that implements this flow (given that Node.js is at the server level running on the Google V8 engine and not in a browser)?  Second, is the Node.js server limited to just the Implicit flow?  Third, does it even matter since we're talking about server-to-server which doesn't require a "back channel" to be created to get the access token?

答: It turns out there's a dedicated IdentityServer4 library for Node.js called "openid-connect.js" that can be obtained here:  https://www.npmjs.com/package/openid-client</p>


问:
mapView:didDeselectAnnotationView: delegate method getting called before the annotation view is actually deselected
I am working with a map view populated with custom pins.  When the user taps somewhere on the map to deselect a pin, I want to implement the map such that the pin does not become deselected (i.e. users are not able to deselect pins without selecting other pins, so at least one pin will always be selected).  Here is my implementation of the didDeselectAnnotationView method:

```<code>-(void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view
{
    [mapView selectAnnotation:view.annotation animated:NO];
}
</code>```

Essentially, I'm trying to reselect the annotation.  However, after some debugging and printing to console, I realized that the annotation view isn't actually being deselected until after the method didDeselectAnnotationView: finishes running (that is, the order of events goes: user taps somewhere on map, didDeselectAnnotationView: is called and finishes executing, the annotation view is actually deselected).  Has anyone else experienced this problem, or does anyone know another way to enforce the behavior for the map such that users are unable to deselect pins without selecting other pins, so that one pin will always be selected?

Thanks for the help.

答:
Awesome answer from Anna.
Here the answer in Swift 3 or 4 :D</p>

```<code>func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
    perform(#selector(MyViewController.reSelectAnnotationIfNoneSelected(_:)), with: view.annotation, afterDelay: 0)
}

func reSelectAnnotationIfNoneSelected(_ annotation: MKAnnotation) {
    if mapView.selectedAnnotations.count == 0 {
        mapView.selectAnnotation(annotation, animated: false)
    }
}
</code>```

Body:
I am working with a map view populated with custom pins.  When the user taps somewhere on the map to deselect a pin, I want to implement the map such that the pin does not become deselected (i.e. users are not able to deselect pins without selecting other pins, so at least one pin will always be selected).  Here is my implementation of the didDeselectAnnotationView method:

-(void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view
{
    [mapView selectAnnotation:view.annotation animated:NO];
}

Essentially, I'm trying to reselect the annotation.  However, after some debugging and printing to console, I realized that the annotation view isn't actually being deselected until after the method didDeselectAnnotationView: finishes running (that is, the order of events goes: user taps somewhere on map, didDeselectAnnotationView: is called and finishes executing, the annotation view is actually deselected).  Has anyone else experienced this problem, or does anyone know another way to enforce the behavior for the map such that users are unable to deselect pins without selecting other pins, so that one pin will always be selected?

Thanks for the help.

Body:
Awesome answer from Anna.
Here the answer in Swift 3 or 4 :D

func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
    perform(#selector(MyViewController.reSelectAnnotationIfNoneSelected(_:)), with: view.annotation, afterDelay: 0)
}

func reSelectAnnotationIfNoneSelected(_ annotation: MKAnnotation) {
    if mapView.selectedAnnotations.count == 0 {
        mapView.selectAnnotation(annotation, animated: false)
    }
}


问:
Is adding routes thread-safe in Spark framework?
The SimpleRouteMatcher stores added routes in an ArrayList.

```<code>public SimpleRouteMatcher() {
    routes = new ArrayList<RouteEntry>();
}
</code>```

There doesn't seem to be any synchronization surrounding the access of these routes. Since they are accessed from a separate server thread, are updates to the list of routes guaranteed to be visible?

答:
You answered the question yourself - it seems it is not. Probably, there was the assumption: adding routes will only happen in the main thread on application startup, from the main method, so this might be implemented non-thread safe on purpose.

If you need to modify routes safely from multiple threads, you can create wrapper methods for these operations which are synchronized.

In my opinion, this operation should have been thread safe out-of-the-box.

Body:
The SimpleRouteMatcher stores added routes in an ArrayList.

public SimpleRouteMatcher() {
    routes = new ArrayList<RouteEntry>();
}

There doesn't seem to be any synchronization surrounding the access of these routes. Since they are accessed from a separate server thread, are updates to the list of routes guaranteed to be visible?


问:
Scoop with agents
I'm trying to use an agent callback concurrently. Unfortunately, no matter what I do it always seems to run sequentially instead of parallel. (without the agent it doesn't)

main class(APPLICATION):

```<code>class
    APPLICATION

inherit
    ARGUMENTS

create
    make

feature {NONE} -- Initialization

    make
            -- Run application.
        local
            a1 : separate PROCEDURE
            a2 : separate PROCEDURE
        do
            create my_counter.make (1, 100_000_000)
            create my_counter2.make (2, 100_000_000)

            launch_counter(my_counter)
            launch_counter(my_counter2)

        end

feature -- Launch

    launch_counter(c: separate COUNTER)
        do
            c.run (5, agent print_hello)
        end

    print_hello
        do
            print("Hello!%N")
        end

feature -- Access

    my_counter : separate COUNTER
    my_counter2 : separate COUNTER

end
</code>```

counter class:

```<code>class
    COUNTER

inherit
    EXECUTION_ENVIRONMENT

create
    make

feature -- Initilzation
    make (i: INTEGER; delay: INTEGER)
        do
            id := i
            delay_time := delay
        end

feature -- Stuff

    run (times: INTEGER; p: separate PROCEDURE)
    local
        c : INTEGER
    do
        from
            c := times
        until
            c = 0
        loop
            print("COUNTER: " + id.out)
            p.call
            sleep(delay_time)
            c := c - 1

        end

    end

feature {NONE} -- Access

    delay_time : INTEGER
    id: INTEGER

end
</code>```

expected output:

```<code>COUNTER: 1Hello!
COUNTER: 2Hello!
COUNTER: 1Hello!
etc.
</code>```

actual output:

```<code>COUNTER: 1Hello!
COUNTER: 1Hello!
COUNTER: 1Hello!
COUNTER: 1Hello!
COUNTER: 1Hello!
COUNTER: 2Hello!
COUNTER: 2Hello!
COUNTER: 2Hello!
COUNTER: 2Hello!
COUNTER: 2Hello!
</code>```

What would I have to change to make this run as expected?

答:
The agent object keeps a reference to the target, in your example to the root object of type APPLICAITON, therefore all calls to print_hello get synchronized. To avoid that, the objects on which the agent is called should be recorded in a COUNTER object and used from there.

This can be achieved by adding an attribute action to the class COUNTER and updating its creation procedure

```<code>make (i: INTEGER; delay: INTEGER; a: separate PROCEDURE)
    do
        id := i
        delay_time := delay
        action := a
    end
...
action: separate PROCEDURE
</code>```

Then instead of p.call in COUNTER.run the following code will be used (the feature run has no argument p anymore):

```<code>        separate action as p do
            p.call
        end
</code>```

Now p is not locked on entry to the feature run and therefore callbacks can be executed alternately by different processors.

Title: Scoop with agents

Body:
I'm trying to use an agent callback concurrently. Unfortunately, no matter what I do it always seems to run sequentially instead of parallel. (without the agent it doesn't)

main class(APPLICATION):

class
    APPLICATION

inherit
    ARGUMENTS

create
    make

feature {NONE} -- Initialization

    make
            -- Run application.
        local
            a1 : separate PROCEDURE
            a2 : separate PROCEDURE
        do
            create my_counter.make (1, 100_000_000)
            create my_counter2.make (2, 100_000_000)

            launch_counter(my_counter)
            launch_counter(my_counter2)

        end

feature -- Launch

    launch_counter(c: separate COUNTER)
        do
            c.run (5, agent print_hello)
        end

    print_hello
        do
            print("Hello!%N")
        end

feature -- Access

    my_counter : separate COUNTER
    my_counter2 : separate COUNTER

end

counter class:

class
    COUNTER

inherit
    EXECUTION_ENVIRONMENT

create
    make

feature -- Initilzation
    make (i: INTEGER; delay: INTEGER)
        do
            id := i
            delay_time := delay
        end

feature -- Stuff

    run (times: INTEGER; p: separate PROCEDURE)
    local
        c : INTEGER
    do
        from
            c := times
        until
            c = 0
        loop
            print("COUNTER: " + id.out)
            p.call
            sleep(delay_time)
            c := c - 1

        end

    end

feature {NONE} -- Access

    delay_time : INTEGER
    id: INTEGER

end

expected output:

COUNTER: 1Hello!
COUNTER: 2Hello!
COUNTER: 1Hello!
etc.

actual output:

COUNTER: 1Hello!
COUNTER: 1Hello!
COUNTER: 1Hello!
COUNTER: 1Hello!
COUNTER: 1Hello!
COUNTER: 2Hello!
COUNTER: 2Hello!
COUNTER: 2Hello!
COUNTER: 2Hello!
COUNTER: 2Hello!

What would I have to change to make this run as expected?

Body:
The agent object keeps a reference to the target, in your example to the root object of type APPLICAITON, therefore all calls to print_hello get synchronized. To avoid that, the objects on which the agent is called should be recorded in a COUNTER object and used from there.

This can be achieved by adding an attribute action to the class COUNTER and updating its creation procedure

make (i: INTEGER; delay: INTEGER; a: separate PROCEDURE)
    do
        id := i
        delay_time := delay
        action := a
    end
...
action: separate PROCEDURE

Then instead of p.call in COUNTER.run the following code will be used (the feature run has no argument p anymore):

        separate action as p do
            p.call
        end

Now p is not locked on entry to the feature run and therefore callbacks can be executed alternately by different processors.


问:
Using ServiceLoader for log4j-jcl brigde in OSGi environment
I am trying to use the log4j-jcl bridge in osgi mode and found that the java.util.ServiceLoader should be used to get the LogFactoryImpl from the bridge jar. I am new to OSGi and so tried it after referring to a few tutorials but it doesn't seem to work. The bundle is in RESOLVED state.

LoggingActivator.java

```<code>import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import java.util.ServiceLoader;

public class LoggingActivator  implements BundleActivator{

private static Log log;
ServiceLoader<LogFactory> serviceLoader = ServiceLoader.load(LogFactory.class);
LogFactory service = serviceLoader.iterator().next();

public LoggingActivator(){
    if (service != null){
        log = service.getLog(LoggingActivator.class);
    }
}

@Override
public void start(BundleContext bundleContext) throws Exception {
    log.info("Activated Logging");
}

@Override
public void stop(BundleContext bundleContext) throws Exception {
    log.info("Deactivated Logging");
}

}
</code>```

pom.xml

```<code>    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
    </dependency>

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.8.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-jcl</artifactId>
        <version>2.8.2</version>
    </dependency>
</code>```

```<code>    <Export-Package>
        org.apache.logging.log4j.*,
        org.apache.commons.logging.*
    </Export-Package>
    <Import-Package>
        !org.apache.logging.log4j.*,
        !org.apache.commons.logging.*,
        *;resolution:=optional
    </Import-Package>
</code>```

答:
If you want to make use of ServiceLoader then you should probably take a look at the Service Loader Mediator specification (chapter 133 of the OSGi compendium). There is an implementation called SPI Fly hosted at Apache Aries.

The idea is that the Service Loader mediator extends your bundle's classes at runtime, making sure that it has the Thread Context ClassLoader set correctly for your uses of ServiceLoader to find implementations. The Service Loader Mediator also registers OSGi services for each registered implementation that it finds, so you can avoid using ServiceLoader completely by using the OSGi service registry if you choose.

Body:
I am trying to use the log4j-jcl bridge in osgi mode and found that the java.util.ServiceLoader should be used to get the LogFactoryImpl from the bridge jar. I am new to OSGi and so tried it after referring to a few tutorials but it doesn't seem to work. The bundle is in RESOLVED state.

LoggingActivator.java

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import java.util.ServiceLoader;

public class LoggingActivator  implements BundleActivator{

private static Log log;
ServiceLoader<LogFactory> serviceLoader = ServiceLoader.load(LogFactory.class);
LogFactory service = serviceLoader.iterator().next();

public LoggingActivator(){
    if (service != null){
        log = service.getLog(LoggingActivator.class);
    }
}

@Override
public void start(BundleContext bundleContext) throws Exception {
    log.info("Activated Logging");
}

@Override
public void stop(BundleContext bundleContext) throws Exception {
    log.info("Deactivated Logging");
}

}

pom.xml

    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
    </dependency>

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.8.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-jcl</artifactId>
        <version>2.8.2</version>
    </dependency>

    <Export-Package>
        org.apache.logging.log4j.*,
        org.apache.commons.logging.*
    </Export-Package>
    <Import-Package>
        !org.apache.logging.log4j.*,
        !org.apache.commons.logging.*,
        *;resolution:=optional
    </Import-Package>


问:
How do I interpret the results of the ANTS Memory Profiler?
I've been profiling my ASP.NET application with ANTS Memory Profiler 6, and have seen indications of memory leaks. However, I don't know whether or not the growths I'm seeing are supposed to be there or not (for instance, System.String grows a lot each snapshot. Should it?)

I don't understand the whole memory processso I don't know if I am interpreting the results correctly or not. How do I interpret the results of the ANTS Memory Profiler?

答:
I have kind of been able to answer my own question while solving my memory issue. Although String may be on the top of the list most of the time, I shouldn't see the instance count just keep growing and growing. It turns out in my applcation that an Object I thought was being free'd actually wasn't which held a reference to some XML files which were of course held in Strings.

My test was to go to the home page of the web site -> Click to another page -> Back to the home page. Doing this should mean no new references should have been created (instance count should remain 0 (no growth)).

Hope this can help someone else.


问:
How can I remove these parts of my filenames?
I have some files I need to rename in bulk.   For example:

```<code>Jul-0961_S7_R2_001.fastq.gz
Jul-0967_S22_rep1_R1.fastq.gz
Jul-0974_S32_R2_001.fastq.gz
</code>```

I need to remove the S* part of the filename but I don't know the right regular regex to use.

Specifically:

```<code>Jul-0961_S7_R2_001.fastq.gz --> Jul-0961_R2_001.fastq.gz
</code>```

Something like, rename 's/S*//' *.gz is what I'm looking for.

Is there a regex wizard out there who can show me the way?  Thanks in advance.

答: You should be able to use something like this: s/_S[0-9]+_/_/

Body:
I have some files I need to rename in bulk.   For example:

Jul-0961_S7_R2_001.fastq.gz
Jul-0967_S22_rep1_R1.fastq.gz
Jul-0974_S32_R2_001.fastq.gz

I need to remove the S* part of the filename but I don't know the right regular regex to use.

Specifically:

Jul-0961_S7_R2_001.fastq.gz --> Jul-0961_R2_001.fastq.gz

Something like, rename 's/S*//' *.gz is what I'm looking for.

Is there a regex wizard out there who can show me the way?  Thanks in advance.


问:
Why remove dependency from java.awt?
In Selenium's Point class Javadocs, it states that it is:

A copy of java.awt.Point, to remove dependency on awt.

What is gained by this?

答:
Well, if you wanted to import the entire selenium class, you'd do something like this:

```<code>import org.openqa.selenium.*;
</code>```

If you wanted to use point, then you'd also have to do:

```<code>import java.awt.point;
</code>```

even if you weren't going to use any other part of the java.awt package.

So, by doing this, you never have to include java.awt unless explicitly using it- hence, no dependency on java.awt.

This was probably done because AWT is known to run differently on different platforms, which defeats one of the key philosophies of Java- WORA (Write Once Run Anywhere). You don't want something that's supposed to be platform independent like Selenium to depend on something heavyweight like AWT.

Title: Why remove dependency from java.awt?

Body:
Well, if you wanted to import the entire selenium class, you'd do something like this:

import org.openqa.selenium.*;

If you wanted to use point, then you'd also have to do:

import java.awt.point;

even if you weren't going to use any other part of the java.awt package.

So, by doing this, you never have to include java.awt unless explicitly using it- hence, no dependency on java.awt.

This was probably done because AWT is known to run differently on different platforms, which defeats one of the key philosophies of Java- WORA (Write Once Run Anywhere). You don't want something that's supposed to be platform independent like Selenium to depend on something heavyweight like AWT.


问:
Programming & Software Development News / Newsletters
I currently subscribe to MSDN Flash and Red Gate's developer newsletter, which is great. I'd like to find more sources. Where/Who else sends or posts news or articles about software development?</p>

答:
I don't know if these are the best but they're my favorites:

http://www.reddit.com/r/programming

http://devlinks.tumblr.com

http://sidebar.io

http://www.hackernewsletter.com


问:
How to exclude traffic in Google Analytics from Dynamic IP addresses?
Google's detection of Unusual traffic is nice. But how is it handling Dynamic IP addresses?

For example,I do not have ranges of IPs and my ISP provides Dynamic IP which may change everytime my router reboots and it changes everyday. So here, when I get some IP address I see  notification w/o captcha. After several reboots I seem to get an IP which was not blocked!

How to solve this type of issues in Google Analytics. Also I know very well how to exclude traffic from single IP and with ranges of IPs but I do not know how to block internal traffic whose IPs changes everyday?

答:
We had the task to exclude a whole company from Analytics. The internet router got IP renewed circa once a day. Turned out that this router like nearly all common routers nowadays offered some options to enable dynamic IP services. Like noip.com for example.

You register at noip.com and choose some static domain name of your choice.

Then select that service (noip.com) in your router's dynamic IP options section.

Enter your credentials from noip.com.

And what happens now is, that the router everyday automatically pushes its new IP to noip.com, where it gets associated to the domain name you registered before. Now on your page you can dynamically check that domain's IP and if it matches the client's (browser's) IP you exclude the Analytics scripts from being printed to the page.

In my case I was on PHP and something along the lines of the following snippet worked out fine. See gethostbyname().

$print_tracking_scripts = TRUE;

if (gethostbyname('my-unique-name.ddns.net') === $_SERVER['REMOTE_ADDR']) {
  $print_tracking_scripts = FALSE;
}

if ($print_tracking_scripts) {
  // Print or include tracking scripts however you like.
}
```


问:
undefined method `Then' for #<Object:0x000000073e1be0> (NoMethodError)
I am trying to add test step in a feature , step is as follows:
Then I scroll until I see the "item 2" text

and corresponding step definition is as follows:

```<code>Then(/^I scroll until I see the "([^\"]*)" text$/) do |text|
  q = query("text:'#{item 2}'")
  while q.empty?
    scroll_down
    q = query("text:'#{item 2}'")
  end
end
</code>```

and i am getting following error :
undefined method `Then' for # (NoMethodError)

Then(/^I scroll until I see the "([^\"]*)" text$/) do |text|

can some one  fix this step defination?, also if some one can give me a solution to pass multiple amount of data in same method will be appreciated.. i need to verify 20-30 different item on same page, i tried using perform_action('drag',16,18,30,16,5) function but it drags to diffrent level everytime.. and elements could not be located

I have almost fixed this ... :) the issue was i have entered two methods for same step ... and now new issue .. i am unable to break the statement .. and test do not end after reaching end of the page ,,can some fix this? where should i enter break statement

```<code>itemlistelements = ['item 1','item 2','item 3']
Then(/^I scroll until I see the "([^"]*)" text$/) do |arg1|
  q = query("* text:'#{itemlistelements}'")
  while q.empty?
    perform_action('drag',16,18,40,16,5)
    q = query("* text:'#{itemlistelements}'")
    end
end
</code>```

答:
You can write that loop multiple ways, for example:

```<code>while query("* text:'#{text}'").empty?
  perform_action('drag', 16, 18, 40, 16, 5)
end
</code>```

or you can use 'element_exists' like this:

```<code>until element_exists("* text:'#{text}'")
  perform_action('drag', 16, 18, 40, 16, 5)
end
</code>```

I would go for the second one.

You can refer to this link for more information on style guide and try using rubocop in your IDE

Body:
I am trying to add test step in a feature , step is as follows:
Then I scroll until I see the "item 2" text

and corresponding step definition is as follows:

Then(/^I scroll until I see the "([^\"]*)" text$/) do |text|
  q = query("text:'#{item 2}'")
  while q.empty?
    scroll_down
    q = query("text:'#{item 2}'")
  end
end

and i am getting following error :
undefined method `Then' for # (NoMethodError)

Then(/^I scroll until I see the "([^\"]*)" text$/) do |text|

can some one  fix this step defination?, also if some one can give me a solution to pass multiple amount of data in same method will be appreciated.. i need to verify 20-30 different item on same page, i tried using perform_action('drag',16,18,30,16,5) function but it drags to diffrent level everytime.. and elements could not be located

I have almost fixed this ... :) the issue was i have entered two methods for same step ... and now new issue .. i am unable to break the statement .. and test do not end after reaching end of the page ,,can some fix this? where should i enter break statement

itemlistelements = ['item 1','item 2','item 3']
Then(/^I scroll until I see the "([^"]*)" text$/) do |arg1|
  q = query("* text:'#{itemlistelements}'")
  while q.empty?
    perform_action('drag',16,18,40,16,5)
    q = query("* text:'#{itemlistelements}'")
    end
end

Body:
You can write that loop multiple ways, for example:

while query("* text:'#{text}'").empty?
  perform_action('drag', 16, 18, 40, 16, 5)
end

or you can use 'element_exists' like this:

until element_exists("* text:'#{text}'")
  perform_action('drag', 16, 18, 40, 16, 5)
end

I would go for the second one.

You can refer to this link for more information on style guide and try using rubocop in your IDE


问:
onReceive() of Alarm BroadcastReceiver called during setAlarm method is called
Newbie here, I have this function setAlarm:

```<code> public void setAlarm(){

        SharedPreferences sa=PreferenceManager.getDefaultSharedPreferences(getBaseContext());

        int hr=sa.getInt("alarmhour", 6);
        int mn=sa.getInt("alarmminute", 0);
        String st1=sa.getString("alarmstatus", "Alarm Disabled");

        if(st1.equals("Alarm Enabled"))
        {

        AlarmManager ala = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        Intent inte = new Intent(this, epicalarm.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, inte, 0);

        Calendar time = Calendar.getInstance();
        time.set(Calendar.HOUR_OF_DAY, hr);
        time.set(Calendar.MINUTE, mn);
        time.set(Calendar.SECOND, 0);

        ala.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pi);
        }

 }
</code>```

Each time I call the function setAlarm , the onReceive method gets called and displays the alarm . Why?

答:
```<code>Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, h);
calendar.set(Calendar.MINUTE, m);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND,0);
// if values of h and m are less than current time
//then 'if' block will executes and adds the amount of days as 1 to your calendar object.
if (calendar.before(Calendar.getInstance()))
{
     calendar.add(Calendar.DATE, 1);
}

//you will get an alarm` after a day instead of now

ala.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi);
</code>```

Body:
Newbie here, I have this function setAlarm:

 public void setAlarm(){

        SharedPreferences sa=PreferenceManager.getDefaultSharedPreferences(getBaseContext());

        int hr=sa.getInt("alarmhour", 6);
        int mn=sa.getInt("alarmminute", 0);
        String st1=sa.getString("alarmstatus", "Alarm Disabled");

        if(st1.equals("Alarm Enabled"))
        {

        AlarmManager ala = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        Intent inte = new Intent(this, epicalarm.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, inte, 0);

        Calendar time = Calendar.getInstance();
        time.set(Calendar.HOUR_OF_DAY, hr);
        time.set(Calendar.MINUTE, mn);
        time.set(Calendar.SECOND, 0);

        ala.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pi);
        }

 }

Each time I call the function setAlarm , the onReceive method gets called and displays the alarm . Why?


问:
what is the role of ob_start() in here
```<code>session_start();
ob_start();
$hasDB = false;
$server = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'acl_test';
$link = mysql_connect($server,$user,$pass);
if (!is_resource($link)) {
    $hasDB = false;
    die("Could not connect to the MySQL server at localhost.");
} else {
    $hasDB = true;
    mysql_select_db($db);
}
</code>```

a) what does ob_start() exactly do.? i got to understand it will turn output buffering on. with reference to the above code what will be the benefit if i use ob_start() while trying to establish the connection with the database. what output data it will buffer?

thank you..

答: first of all buffering is usefull for putting http-headers (header function) at any line of code. eg - session cookies. without ob_start you would not be able to add any http-header to response if you already sent some data, e.g. with echo or print functions</p>

Title: what is the role of ob_start() in here

Body:
session_start();
ob_start();
$hasDB = false;
$server = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'acl_test';
$link = mysql_connect($server,$user,$pass);
if (!is_resource($link)) {
    $hasDB = false;
    die("Could not connect to the MySQL server at localhost.");
} else {
    $hasDB = true;
    mysql_select_db($db);
}

a) what does ob_start() exactly do.? i got to understand it will turn output buffering on. with reference to the above code what will be the benefit if i use ob_start() while trying to establish the connection with the database. what output data it will buffer?

thank you..


问:
Loading UIViewController inside an UIScrollView Swift3
I have 2 UIViewControllers.
One UIViewController has a view with many buttons and is +2000 points high.
Another UIViewController has a UIScrollView.

This is my code:

```<code>import UIKit

 class ViewController: UIViewController {

@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    scrollView.contentSize = CGSize(width: 375, height: 2884)

    DispatchQueue.main.async {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let thumb_vc = storyboard.instantiateViewController(withIdentifier: "thumb") as! ThumbsViewController
        //self.present(vc, animated: true, completion: nil)

    self.addChildViewController(thumb_vc)
    self.scrollView.addSubview(thumb_vc.view)
   }
 }
</code>```

and although the thumbs UIViewController get loaded to UIScrollView, the size is wrong and does not scroll.

Any help appreciated

答: You must specify your child's frame too. Also there is no need to dispatch your UI changes to main queue in the viewDidLoad method. And you must call your child view controller's didMove(toParentViewController:) method after adding it's view as your subview. You can read more about container view controllers and their children here.

Body:
I have 2 UIViewControllers.
One UIViewController has a view with many buttons and is +2000 points high.
Another UIViewController has a UIScrollView.

This is my code:

import UIKit

 class ViewController: UIViewController {

@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    scrollView.contentSize = CGSize(width: 375, height: 2884)

    DispatchQueue.main.async {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let thumb_vc = storyboard.instantiateViewController(withIdentifier: "thumb") as! ThumbsViewController
        //self.present(vc, animated: true, completion: nil)

    self.addChildViewController(thumb_vc)
    self.scrollView.addSubview(thumb_vc.view)
   }
 }

and although the thumbs UIViewController get loaded to UIScrollView, the size is wrong and does not scroll.

Any help appreciated


问:
Object Detection API error: "ImportError: cannot import name anchor_generator_pb2"
I'm trying to get Tensorflow's new Object Detection API working. I've followed the installation instructions, but when running the command

```<code>python object_detection/builders/model_builder_test.py
</code>```

I get the following error

```<code>from object_detection.protos import anchor_generator_pb2
ImportError: cannot import name anchor_generator_pb2
</code>```

I've looked inside object_detection.protos, and there doesn't seem to be anything named anchor_generator_pb2. Has anyone else managed to get this command to run, or solved this issue?

答:
Missed a step in the installation instructions, where the following needs to be run from models/research:

```<code>protoc object_detection/protos/*.proto --python_out=.
</code>```

You need to rerun the below command after that:

```<code>pip install .
</code>```

Body:
I'm trying to get Tensorflow's new Object Detection API working. I've followed the installation instructions, but when running the command

python object_detection/builders/model_builder_test.py

I get the following error

from object_detection.protos import anchor_generator_pb2
ImportError: cannot import name anchor_generator_pb2

I've looked inside object_detection.protos, and there doesn't seem to be anything named anchor_generator_pb2. Has anyone else managed to get this command to run, or solved this issue?

Body:
Missed a step in the installation instructions, where the following needs to be run from models/research:

protoc object_detection/protos/*.proto --python_out=.

You need to rerun the below command after that:

pip install .


问:
Are parameters Thread Safe?
I have read a number of posts on this subject, but I'm still just a little fuzzy how C# handles parameters in methods when called from multiple threads.

I have a series of utility methods that need to be called from about 60+ threads.  It's a process that downloads patient data for roughly 20,000-30,000 patients every day.  For the most part, the methods look like this.

```<code>
    Public Static SomeClass
    {
        public static string StringToSQLBool(string s)
        {
           if (s.Trim() == "")
           {
              return "Null";
           }
           else
           {
              if (s.ToLower() == "true")
              {
                 return "1";
              }
              {
                 return "0";
              }
           }
        }

        public static string DateToSQLAnsiStr(string ADate)
        {
            try
            {
               if (ADate.Trim() != "")
               {
                  DateTime d = Convert.ToDateTime(ADate);
                  return "{d '" + d.Year.ToString() + "-" +
                          d.Month.ToString().PadLeft(2, '0') + "-" +
                          d.Day.ToString().PadLeft(2, '0') + "'}";
               }
               else
               {
                  return "Null";
               }
            }
            catch
            {
               return "Null";
            }
        }
    }
</code>
```

As I understand it, as long as the parameters are used in the method that are singular to the calling thread, then it would be considered safe.

Are these thread-safe without locking?

答:
The answer to the question in your title is "maybe; it depends on their type."

Value types: yes

Reference types:

Immutable objects: yes

Normal objects: no

Title: Are parameters Thread Safe?

Body:
I have read a number of posts on this subject, but I'm still just a little fuzzy how C# handles parameters in methods when called from multiple threads.

I have a series of utility methods that need to be called from about 60+ threads.  It's a process that downloads patient data for roughly 20,000-30,000 patients every day.  For the most part, the methods look like this.

    Public Static SomeClass
    {
        public static string StringToSQLBool(string s)
        {
           if (s.Trim() == "")
           {
              return "Null";
           }
           else
           {
              if (s.ToLower() == "true")
              {
                 return "1";
              }
              {
                 return "0";
              }
           }
        }

        public static string DateToSQLAnsiStr(string ADate)
        {
            try
            {
               if (ADate.Trim() != "")
               {
                  DateTime d = Convert.ToDateTime(ADate);
                  return "{d '" + d.Year.ToString() + "-" +
                          d.Month.ToString().PadLeft(2, '0') + "-" +
                          d.Day.ToString().PadLeft(2, '0') + "'}";
               }
               else
               {
                  return "Null";
               }
            }
            catch
            {
               return "Null";
            }
        }
    }

As I understand it, as long as the parameters are used in the method that are singular to the calling thread, then it would be considered safe.

Are these thread-safe without locking?