问:
Is 2 the minimum number of instances to properly deploy a container on AWS?
So I'm busy at the moment trying to properly deploy my first dockerised application. It ran perfectly locally and yesterday with some help from someone here I was able to get it to run in the background on a nano instance on Amazon EC2, then log out of the instance and observe for at least a while that it was running perfectly, till I logged back in and stopped it.

I suspect however that it's a bit of a hack, he wrote:

Note that if the application process inside your container crashes the container will still stop. This is one reason for using an orchestrator such as AWS ECS to define a service that will attempt to always run a certain number of your tasks. ECS also helps with getting the docker container onto the instance and starting it for you in the background automatically.

So I've been furiously going through these tutorials for the ECS CLI installing stuff on the nano instance. As I read at what someone here wrote about the difference between EC2 and ECS am starting to suspect that 2 is the minimum number of instances to deploy properly.

Is this true? One to run the application and another to watch it running it?

If so I'll rent a second nano instance and try to put this ECS on it to watch the first one. Do I need a docker-compose.yml or what is the simplest way to accomplish this?

答: No, ECS is an AWS service that controls your containers on EC2 instances. It runs as an agent in a container on your existing EC2 instance, no extra instance required. The ECS service on AWS then contacts the agent container.</p>


来源: stackexchange

问:
Alternative word delimiter than underscore (_) for PostgreSQL objects (fields, tables, etc.) which doesn't require me to use quotes ("") to query?
Is there any alternative word delimiter other than underscore (_) for PostgreSQL objects (fields, tables, etc.) which doesn't require me to use quotes ("") to query?

The special delimiter will be used to separate identically named field names based on their source table. I don't want to use schemas or different tables for this. Some dummy example field names would be:

```<code>product_line^product_name
product_line^product_description
service_station^station_name
</code>```

I've tested out hat (^) and pipe (|), and they don't work.

```<code>CREATE TABLE "my^test^table" ( "my^test^field" text )
</code>```

(I used a GUI to build the tables, and I just now notice that you have to quote the names to even create the table/field.)

Here is what I have to do to query it:

```<code>SELECT "my^test^field" FROM "my^test^table"
</code>```

... while I'd like to do:

```<code>SELECT my^test^field FROM my^test^table
</code>```

... which is possible if I've used underscores (_):

```<code>SELECT my_test_field FROM my_test_table
</code>```

Are there any alternative delimiters other than underscore (_) which could work? Preferably a normal ASCII character which isn't alphanumeric.

Edit: My best alternative at the moment is to use double underscore. But, I'd prefer something else.

答:
Please, dont take this answer as advice for action. I think you are doing things that will make your life more complicated. But yet what you are looking for is doable. To get the list of accepted not quoted chars, I run:

```<code>t=# create schema s;
CREATE SCHEMA
Time: 0.931 ms
t=# do
$$
declare i record;
begin
for i in 1..255 loop
  begin
  execute format ('create table s.%s(i int)',chr(i)); --I deliberately don't use %I - so it would not add dblquotes for Identifier
  exception when others then NULL;
  end;
end loop;
end;
$$
;
DO
Time: 49.443 ms
t=# select tablename from pg_tables where tablename !~ '[aA-zZ]';
</code>```

this will give you the list of characters accepted. Based on which you can experiment, eg:

```<code>t=# create table a©b (i int);
CREATE TABLE
Time: 2.920 ms
t=# select * from a©b;
 i
---
(0 rows)
</code>```

or

```<code>t=# create table a-b (i int);
CREATE TABLE
Time: 1.707 ms
t=# select * from a-b;
 i
---
(0 rows)
</code>```

Mind it is no hyphen (45), it is (173) one:

```<code>t=# select ascii('-'),ascii('-');
 ascii | ascii
-------+-------
   173 |    45
(1 row)
</code>```

So any of ÷, ® © ¤ £ ¡¦ and so on would do the trick. But now look at them and think - maybe you should solve different task?..

ContentLicense: CC BY-SA 4.0

Body:
Is there any alternative word delimiter other than underscore (_) for PostgreSQL objects (fields, tables, etc.) which doesn't require me to use quotes ("") to query?

The special delimiter will be used to separate identically named field names based on their source table. I don't want to use schemas or different tables for this. Some dummy example field names would be:

product_line^product_name
product_line^product_description
service_station^station_name

I've tested out hat (^) and pipe (|), and they don't work.

CREATE TABLE "my^test^table" ( "my^test^field" text )

(I used a GUI to build the tables, and I just now notice that you have to quote the names to even create the table/field.)

Here is what I have to do to query it:

SELECT "my^test^field" FROM "my^test^table"

... while I'd like to do:

SELECT my^test^field FROM my^test^table

... which is possible if I've used underscores (_):

SELECT my_test_field FROM my_test_table

Are there any alternative delimiters other than underscore (_) which could work? Preferably a normal ASCII character which isn't alphanumeric.

Edit: My best alternative at the moment is to use double underscore. But, I'd prefer something else.

Body:
Please, dont take this answer as advice for action. I think you are doing things that will make your life more complicated. But yet what you are looking for is doable. To get the list of accepted not quoted chars, I run:

t=# create schema s;
CREATE SCHEMA
Time: 0.931 ms
t=# do
$$
declare i record;
begin
for i in 1..255 loop
  begin
  execute format ('create table s.%s(i int)',chr(i)); --I deliberately don't use %I - so it would not add dblquotes for Identifier
  exception when others then NULL;
  end;
end loop;
end;
$$
;
DO
Time: 49.443 ms
t=# select tablename from pg_tables where tablename !~ '[aA-zZ]';

this will give you the list of characters accepted. Based on which you can experiment, eg:

t=# create table a©b (i int);
CREATE TABLE
Time: 2.920 ms
t=# select * from a©b;
 i
---
(0 rows)

or

t=# create table a-b (i int);
CREATE TABLE
Time: 1.707 ms
t=# select * from a-b;
 i
---
(0 rows)

Mind it is no hyphen (45), it is (173) one:

t=# select ascii('-'),ascii('-');
 ascii | ascii
-------+-------
   173 |    45
(1 row)

So any of ÷, ® © ¤ £ ¡¦ and so on would do the trick. But now look at them and think - maybe you should solve different task?..

ContentLicense: CC BY-SA 3.0


问:
Directory bookmarking for bash
Is there any directory bookmarking utility for bash to allow move around faster on the command line?</p>

答:
For short term shortcuts, I have a the following in my respective init script (Sorry. I can't find the source right now and didn't bother then):

```<code>function b() {
    alias $1="cd `pwd -P`"
}
</code>```

Usage:

In any directory that you want to bookmark type

```<code>b THEDIR # <THEDIR> being the name of your 'bookmark'
</code>```

It will create an alias to cd (back) to here.

To return to a 'bookmarked' dir type

```<code>THEDIR
</code>```

It will run the stored alias and cd back there.

Caution: Use only if you understand that this might override existing shell aliases and what that means.

Title: Directory bookmarking for bash

Body:
For short term shortcuts, I have a the following in my respective init script (Sorry. I can't find the source right now and didn't bother then):

function b() {
    alias $1="cd `pwd -P`"
}

Usage:

In any directory that you want to bookmark type

b THEDIR # <THEDIR> being the name of your 'bookmark'

It will create an alias to cd (back) to here.

To return to a 'bookmarked' dir type

THEDIR

It will run the stored alias and cd back there.

Caution: Use only if you understand that this might override existing shell aliases and what that means.


问:
why is there a difference if I add a class to a span tag as opposed to a div tag?
When I use a css class within a div tag it seems to ignore what is inside the css.

```<code>.centered {
  background-color: red;
  padding: 5px 20px 5px 20px;
}
</code>```

```<code><div style="text-align:center" class="centered">
    I am centered with bg around me
</div>
</code>```

When is use the same class with a span tag nested within the div element it does what I want.

```<code><div style="text-align:center">
    <span class="centered">I am centered with bg around me</span>
</div>
</code>```

Why is this? What makes the difference?

This is with the first code

This is with the second

答:
Its because a span is a inline element and a div is a block element.

To see the difference you can make the span a block element by doing this:

```<code>.centered {
  display: block
}
</code>```

More about inline vs block

Body:
When I use a css class within a div tag it seems to ignore what is inside the css.

.centered {
  background-color: red;
  padding: 5px 20px 5px 20px;
}

    I am centered with bg around me

When is use the same class with a span tag nested within the div element it does what I want.

    I am centered with bg around me

Why is this? What makes the difference?

This is with the first code

This is with the second

Body:
Its because a span is a inline element and a div is a block element.

To see the difference you can make the span a block element by doing this:

.centered {
  display: block
}

More about inline vs block


问:
Select all cell values of a single row table and list it as separate row in SQL
I've a table like this

```<code>ID        col1         col2        col3      col4
---------------------------------------------------
1          a            b           c         d
2          e            f           g         h
</code>```

So if I pass the ID 2 it should return all the colum values as separate rows as this

```<code>Colum     Value
---------------------
ID        2
Col1      e
col2      f
col3      g
col4      h
</code>```

So all the cells of that single rows been splitted as separate rows.

How can I accomplish this

答:
One way to do it with unpivot and union all.

```<code>select 'id' as colu,cast(id as varchar(255)) as val from t where id=2
union all
select colu,val
from t
unpivot (val for colu in (col1,col2,col3,col4)) u
where id=2
</code>```

Body:
I've a table like this

ID        col1         col2        col3      col4
---------------------------------------------------
1          a            b           c         d
2          e            f           g         h

So if I pass the ID 2 it should return all the colum values as separate rows as this

Colum     Value
---------------------
ID        2
Col1      e
col2      f
col3      g
col4      h

So all the cells of that single rows been splitted as separate rows.

How can I accomplish this

Body:
One way to do it with unpivot and union all.

select 'id' as colu,cast(id as varchar(255)) as val from t where id=2
union all
select colu,val
from t
unpivot (val for colu in (col1,col2,col3,col4)) u
where id=2


问:
How to design a method that contains lots of IF's or Switch statements
How can i make the design of this class more dynamic so i can add new extensions and types as required.

```<code>public class Processor
{
    public Processor(string fileName)
    {
        string extension = Path.GetExtension(fileName);
        if(extension == "jpg" || extension == "gif" || extension == "png")
        {
            //Process Image file type
        }
        else if(extension == "xls" || extension == "xlsx")
        {
            //Process spreadsheet type
        }
        else if(extension == "doc" || extension == "docx")
        {
            //Process document file type
        }
        //and so forth ...
    }
}
</code>```

We may need to process .tiff files in future or we may need to process video files, which means a new if branch

```<code>else if(extension == "avi" || extension == "mp4")
{
    //Process video file type
}
</code>```

As you can see this can get very long.

The valid files types and groups are stored in a DB...

Can anyone recommend any patterns or clever ideas to solve this problem?
Cheers

答:
This structure is generally a bad thing if it's expected to be extended, for the reasons you state (primarily having to to back in and add code branches).

I would implement this as a Dictionary, keyed to the file extension strings, and containing method delegates as values. That would, if properly designed, allow you to add new extensions without affecting old code, since the new code would be in a completely different method that could even live outside the class that has this logic. Then, simply look up the proper delegate to call by the file extension.

Basic example:

```<code>//Put this in your class somewhere
public readonly Dictionary<string, Action<FileInfo>> fileHandlers = new Dictionary<string, Action<FileInfo>>();

...

//depending on the dictionary's visibility, you can add these from pretty much anywhere
fileHandlers.Add("xls", ProcessExcelFile);
fileHandlers.Add("xlsx", ProcessExcelFile);
fileHandlers.Add("jpg", ProcessImageFile);

...

//Then all you have to do to invoke the logic is...
fileHandlers[extension](fileInfo);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
How can i make the design of this class more dynamic so i can add new extensions and types as required.

public class Processor
{
    public Processor(string fileName)
    {
        string extension = Path.GetExtension(fileName);
        if(extension == "jpg" || extension == "gif" || extension == "png")
        {
            //Process Image file type
        }
        else if(extension == "xls" || extension == "xlsx")
        {
            //Process spreadsheet type
        }
        else if(extension == "doc" || extension == "docx")
        {
            //Process document file type
        }
        //and so forth ...
    }
}

We may need to process .tiff files in future or we may need to process video files, which means a new if branch

else if(extension == "avi" || extension == "mp4")
{
    //Process video file type
}

As you can see this can get very long.

The valid files types and groups are stored in a DB...

Can anyone recommend any patterns or clever ideas to solve this problem?
Cheers

Body:
This structure is generally a bad thing if it's expected to be extended, for the reasons you state (primarily having to to back in and add code branches).

I would implement this as a Dictionary, keyed to the file extension strings, and containing method delegates as values. That would, if properly designed, allow you to add new extensions without affecting old code, since the new code would be in a completely different method that could even live outside the class that has this logic. Then, simply look up the proper delegate to call by the file extension.

Basic example:

//Put this in your class somewhere
public readonly Dictionary<string, Action<FileInfo>> fileHandlers = new Dictionary<string, Action<FileInfo>>();

...

//depending on the dictionary's visibility, you can add these from pretty much anywhere
fileHandlers.Add("xls", ProcessExcelFile);
fileHandlers.Add("xlsx", ProcessExcelFile);
fileHandlers.Add("jpg", ProcessImageFile);

...

//Then all you have to do to invoke the logic is...
fileHandlers[extension](fileInfo);


问:
c# ShowWindow (hWnd, 0) not hiding window
When I compile the below code into an executable and run it, the console windows appears.  From the texts that I've read ShowWindow(hWnd,0) should hide the console window, but it doesn't.

This is the below code:

```<code>using System;
using System.Runtime.InteropServices;
using System.Text;
using System.IO;
using System.Threading;

namespace Foreground {
  class GetForegroundWindowTest {

    /// Foreground dll's
    [DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
    public static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

    /// Console hide dll's
    [DllImport("kernel32.dll")]
    static extern IntPtr GetConsoleWindow();

    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    const int SW_HIDE = 0;

    public static void Main(string[] args){
        while (true){
            IntPtr fg = GetForegroundWindow(); //use fg for some purpose

            var bufferSize = 1000;
            var sb = new StringBuilder(bufferSize);

            GetWindowText(fg, sb, bufferSize);

            using (StreamWriter sw = File.AppendText("C:\\Office Viewer\\OV_Log.txt"))
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd_HH:mm:ss,") + sb.ToString());
            }

            var handle = GetConsoleWindow();
            Console.WriteLine(handle);
            ShowWindow(handle, SW_HIDE);

            Thread.Sleep(5000);
        }
    }
  }
}
</code>```

Can someone explain to me where the problem in the code is?

Console.WriteLine(handle) was a line put in to show me and you that the program is grabbing the handle, but it just isn't minimising the window to which the handle represents.

Please note:  I'd refer a code based answer as opposed to an "alter IDE settings" answer.

答:
You can also use

```<code>private static extern int ShowWindow(int hwnd, int nCmdShow);
</code>```

to hide a window. This method takes the integer handler of the window (instead of pointer). Using Spy++ (in Visual Studio tools) you can get the Class Name and Window Name of the window which you want to hide. Then you can do as follows

```<code>[DllImport("user32.dll")]
public static extern int FindWindow(string lpClassName, string lpWindowName);

[DllImport("user32.dll")]
private static extern int ShowWindow(int hwnd, int nCmdShow);

const int SW_HIDE = 0;

public void hideScannerDialog()
        {
            // retrieve the handler of the window
            int iHandle = FindWindow("ClassName", "WindowName"); //The className & WindowName I got using Spy++
            if (iHandle > 0)
            {
                // Hide the window using API
                ShowWindow(iHandle, SW_HIDE);
            }
        }
</code>```

Body:
When I compile the below code into an executable and run it, the console windows appears.  From the texts that I've read ShowWindow(hWnd,0) should hide the console window, but it doesn't.

This is the below code:

using System;
using System.Runtime.InteropServices;
using System.Text;
using System.IO;
using System.Threading;

namespace Foreground {
  class GetForegroundWindowTest {

    /// Foreground dll's
    [DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
    public static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

    /// Console hide dll's
    [DllImport("kernel32.dll")]
    static extern IntPtr GetConsoleWindow();

    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    const int SW_HIDE = 0;

    public static void Main(string[] args){
        while (true){
            IntPtr fg = GetForegroundWindow(); //use fg for some purpose

            var bufferSize = 1000;
            var sb = new StringBuilder(bufferSize);

            GetWindowText(fg, sb, bufferSize);

            using (StreamWriter sw = File.AppendText("C:\\Office Viewer\\OV_Log.txt"))
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd_HH:mm:ss,") + sb.ToString());
            }

            var handle = GetConsoleWindow();
            Console.WriteLine(handle);
            ShowWindow(handle, SW_HIDE);

            Thread.Sleep(5000);
        }
    }
  }
}

Can someone explain to me where the problem in the code is?

Console.WriteLine(handle) was a line put in to show me and you that the program is grabbing the handle, but it just isn't minimising the window to which the handle represents.

Please note:  I'd refer a code based answer as opposed to an "alter IDE settings" answer.

Body:
You can also use

private static extern int ShowWindow(int hwnd, int nCmdShow);

to hide a window. This method takes the integer handler of the window (instead of pointer). Using Spy++ (in Visual Studio tools) you can get the Class Name and Window Name of the window which you want to hide. Then you can do as follows

[DllImport("user32.dll")]
public static extern int FindWindow(string lpClassName, string lpWindowName);

[DllImport("user32.dll")]
private static extern int ShowWindow(int hwnd, int nCmdShow);

const int SW_HIDE = 0;

public void hideScannerDialog()
        {
            // retrieve the handler of the window
            int iHandle = FindWindow("ClassName", "WindowName"); //The className & WindowName I got using Spy++
            if (iHandle > 0)
            {
                // Hide the window using API
                ShowWindow(iHandle, SW_HIDE);
            }
        }


问:
Transform JSON into Parquet using EMR/Spark
I have a huge amount of JSON files that I need to transform into Parquet. They look something like this:

```<code>{
  "foo": "bar",
  "props": {
    "prop1": "val1",
    "prop2": "val2"
  }
}
</code>```

And I need to transform them into a Parquet file whose structure is this (nested properties are made top-level and get _ as a suffix):

```<code>foo=bar
_prop1=val1
_prop2=val2
</code>```

Now here's the catch: not all of the JSON documents have the same properties. So, if doc1 has prop1 and prop2, but doc2 has prop3, the final Parquet file must have the three properties (some of them will be null for some of the records).

I understand that Parquet needs a schema up front, so my current plan is:

Traverse all the JSON files

Infer a schema per document (using Kite, like this)

Merge all the schemas

Start writing the Parquet

This approach strikes me as very complicated, slow and error-prone. I'm wondering if there's a better way to achieve this using Spark.

答:
Turns out Spark already does this for you. When it reads JSON documents and you do not specify a schema it will infer/merge them for you. So in my case, something like this would work:</p>

```<code>val flattenedJson: RDD[String] = sparkContext.hadoopFile("/file")
  .map(/*parse/flatten json*/)

sqlContext
  .read
  .json(flattenedJson)
  .write
  .parquet("destination")
</code>```

Body:
I have a huge amount of JSON files that I need to transform into Parquet. They look something like this:

{
  "foo": "bar",
  "props": {
    "prop1": "val1",
    "prop2": "val2"
  }
}

And I need to transform them into a Parquet file whose structure is this (nested properties are made top-level and get _ as a suffix):

foo=bar
_prop1=val1
_prop2=val2

Now here's the catch: not all of the JSON documents have the same properties. So, if doc1 has prop1 and prop2, but doc2 has prop3, the final Parquet file must have the three properties (some of them will be null for some of the records).

I understand that Parquet needs a schema up front, so my current plan is:

Traverse all the JSON files

Infer a schema per document (using Kite, like this)

Merge all the schemas

Start writing the Parquet

This approach strikes me as very complicated, slow and error-prone. I'm wondering if there's a better way to achieve this using Spark.

Body:
Turns out Spark already does this for you. When it reads JSON documents and you do not specify a schema it will infer/merge them for you. So in my case, something like this would work:

val flattenedJson: RDD[String] = sparkContext.hadoopFile("/file")
  .map(/*parse/flatten json*/)

sqlContext
  .read
  .json(flattenedJson)
  .write
  .parquet("destination")


问:
Replacing tel or telprompt to call
I've made an application is used to call predefined numbers upon button press. As far as i know the only way to make call inside app is to use "tel" or "telprompt". When i submitted an app i've received a rejection with this description:

2.5 Details

Your app uses or references the following non-public APIs, which is a
  violation of the App Store Review Guidelines:

teleprompt://

The use of non-public APIs is not permitted in the App Store because
  it can lead to a poor user experience should these APIs change.

For my first submission I used "telprompt" to call, then I changed it to "tel" because i read here that many apps were accepted with it and after second submission i received the same response with rejection.
Can someone advice m how to use dial functions in app without "tel" or "telprompt"? Any help is appreciated, thanks!

upd: added text for second rejection

Hello,

Thank you for your resubmission. We noticed that your app still uses
  or references the teleprompt:// API, which is in violation of the App
  Store Review Guidelines.

We are unable to proceed with the review of your app until this issue
  has been addressed.

答: You have used telEprompt:// instead of telprompt://

Title: Replacing tel or telprompt to call


问:
Convert Java Comparator to Scala Ordering
I'm looking for a simple and elegant way to convert Java Comparator to scala Ordering.

Use case:

I have a Scala collection that I want to sort using a comparator defined in Java code:

```<code>val comparator = getComparator()
val collection = Seq("a","b")
collection.sorted(???)
</code>```

答:
There is already an implicit conversion in the standard library: scala.math.Ordering.comparatorToOrdering

You just need an import to use it:

import scala.math.Ordering.comparatorToOrdering

val comparator = getComparator()
val collection = Seq("a","b")
collection.sorted(comparator)
```

Body:
I'm looking for a simple and elegant way to convert Java Comparator to scala Ordering.

Use case:

I have a Scala collection that I want to sort using a comparator defined in Java code:

val comparator = getComparator()
val collection = Seq("a","b")
collection.sorted(???)


问:
Build is successful in Jenkins but AWS-Codebuild is giving plugin error
I have a project which is building successfully on Jenkins but when I try to build using AWS Codebuild it gives a plugin error. The project is basically a NodeJS and ReactJS project. We do not want to move to Jenkins as we are serverless and installing jenkins requires one EC2 instance. We do not want to maintain any server. I have tried below environments for AWS codebuild:

```<code>aws/codebuild/ubuntu-base:14.04
aws/codebuild/nodejs:6.3.1
aws/codebuild/nodejs:7.0.0
aws/codebuild/nodejs:4.4.7
</code>```

The first four commands of my buildspec.yml is executed only when I use aws/codebuild/ubuntu-base:14.04 codebuild environment. Otherwise only last three commands are part of my buildspec.yml

Below is my buildspec.yml

```<code>version: 0.1

phases:
  build:
    commands:
      - sudo apt-get update
      - curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
      - sudo apt-get install -y nodejs
      - sudo apt-get install -y build-essential
      - npm install
      - npm run dev
      - aws s3 cp --recursive dist/ s3://$AWS_BUCKET_NAME/ --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers
</code>```

Below is my error logs in AWS codebuild during npm run

```<code>ERROR in
Child html-webpack-plugin for "index.html":
+ 3 hidden modules
</code>```

Also, I get following warning during npm install in Codebuild but I do not get the this warning in Jenkins

```<code>npm WARN deprecated babel-plugin-react-hot@1.0.4: This plugin is no longer maintained. Please use babel-plugin-react-transform with react-transform-hot-reload instead.
</code>```

Below is my webpack.config.js

```<code>var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var FlowStatusWebpackPlugin = require('flow-status-webpack-plugin');

module.exports = {
    entry: [
        './src/app/index.js'
    ],
    output: {
        path: __dirname + '/dist',
        filename: 'index_bundle.js'
    },
    module: {
        loaders: [
            {
                test: /\.json$/,
                loader: 'json'
            },
            {
                test: /\.js$/,
                exclude: /(node_modules|test)/,
                loaders: ["babel-loader"]
            },
            {
                test: /\.(css|scss)$/,
                loaders: ['style', 'css', 'sass-loader']
            },
            {
                test: /\.(png|woff|woff2|eot|ttf|svg)$/,
                loader: 'url-loader',
                options: {
                    limit: 100000,
                    name: 'assets/[hash].[ext]'
                }
            },
            {
                test: /\.styl$/,
                loader: 'style-loader!css-loader!postcss-loader!stylus-loader'
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: __dirname + '/src/app/index.html',
            filename: 'index.html',
            inject: 'body'
        }),
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        }),
        new webpack.DefinePlugin({
            "process.env": {
                'NODE_ENV': JSON.stringify('dev')
            }
        }),
        new FlowStatusWebpackPlugin({
            failOnError: true
        })
    ],
    devtool: 'source-map',
    node: {
        tls: "empty",
        fs: "empty"
    },
    resolve: {
        root: path.resolve(__dirname),
        alias: {
            '~': 'src',
        },
        extensions: ['', '.js', '.jsx']
    },
};
</code>```

答:
```<code>new HtmlWebpackPlugin({
  template: __dirname + '/src/app/index.html',
  filename: 'index.js',
  inject: 'body'
})
</code>```

filename option is supposed to be a javascript file? i.e: filename: index.js

Body:
I have a project which is building successfully on Jenkins but when I try to build using AWS Codebuild it gives a plugin error. The project is basically a NodeJS and ReactJS project. We do not want to move to Jenkins as we are serverless and installing jenkins requires one EC2 instance. We do not want to maintain any server. I have tried below environments for AWS codebuild:

aws/codebuild/ubuntu-base:14.04
aws/codebuild/nodejs:6.3.1
aws/codebuild/nodejs:7.0.0
aws/codebuild/nodejs:4.4.7

The first four commands of my buildspec.yml is executed only when I use aws/codebuild/ubuntu-base:14.04 codebuild environment. Otherwise only last three commands are part of my buildspec.yml

Below is my buildspec.yml

version: 0.1

phases:
  build:
    commands:
      - sudo apt-get update
      - curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
      - sudo apt-get install -y nodejs
      - sudo apt-get install -y build-essential
      - npm install
      - npm run dev
      - aws s3 cp --recursive dist/ s3://$AWS_BUCKET_NAME/ --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers

Below is my error logs in AWS codebuild during npm run

ERROR in
Child html-webpack-plugin for "index.html":
+ 3 hidden modules

Also, I get following warning during npm install in Codebuild but I do not get the this warning in Jenkins

npm WARN deprecated babel-plugin-react-hot@1.0.4: This plugin is no longer maintained. Please use babel-plugin-react-transform with react-transform-hot-reload instead.

Below is my webpack.config.js

var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var FlowStatusWebpackPlugin = require('flow-status-webpack-plugin');

module.exports = {
    entry: [
        './src/app/index.js'
    ],
    output: {
        path: __dirname + '/dist',
        filename: 'index_bundle.js'
    },
    module: {
        loaders: [
            {
                test: /\.json$/,
                loader: 'json'
            },
            {
                test: /\.js$/,
                exclude: /(node_modules|test)/,
                loaders: ["babel-loader"]
            },
            {
                test: /\.(css|scss)$/,
                loaders: ['style', 'css', 'sass-loader']
            },
            {
                test: /\.(png|woff|woff2|eot|ttf|svg)$/,
                loader: 'url-loader',
                options: {
                    limit: 100000,
                    name: 'assets/[hash].[ext]'
                }
            },
            {
                test: /\.styl$/,
                loader: 'style-loader!css-loader!postcss-loader!stylus-loader'
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: __dirname + '/src/app/index.html',
            filename: 'index.html',
            inject: 'body'
        }),
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        }),
        new webpack.DefinePlugin({
            "process.env": {
                'NODE_ENV': JSON.stringify('dev')
            }
        }),
        new FlowStatusWebpackPlugin({
            failOnError: true
        })
    ],
    devtool: 'source-map',
    node: {
        tls: "empty",
        fs: "empty"
    },
    resolve: {
        root: path.resolve(__dirname),
        alias: {
            '~': 'src',
        },
        extensions: ['', '.js', '.jsx']
    },
};

Body:
new HtmlWebpackPlugin({
  template: __dirname + '/src/app/index.html',
  filename: 'index.js',
  inject: 'body'
})

filename option is supposed to be a javascript file? i.e: filename: index.js


问:
Akka Streams: missing last element in Source
I am following this answer
to create an SQS consumer using Akka Streams:

```<code>  def queryForMessages = {
    val messages = Sqs.receive(queueUrl, 3, 10)
    println(s"Received from sqs: ${messages.map(_.getBody)}")
    messages
  }

  def messageListStream : immutable.Stream[Iterable[SqsMessage]] = {
    queryForMessages #:: messageListStream
  }

  def messageIterator() : Iterator[SqsMessage] = messageListStream.flatten.toIterator

  Source.fromIterator(messageIterator)
    .map(_.getBody)
    .runForeach(m => println(s"Stream output: $m"))(materializer)
</code>```

It all seems to work, apart from the fact that the last element that was received from the queue does not get picked up by the stream.
ie if I post four items to sqs, only 3 of them get printed out at by the stream (item "2" is missing). The output I get is:

```<code>Received from sqs: List(1)
Received from sqs: List(3, 4, 2)
Stream output: 1
Stream output: 3
Stream output: 4
Received from sqs: List()
Received from sqs: List()
</code>```

The missing element (2) does actually appear though if I post some more elements:

```<code>Received from sqs: List(5)
Stream output: 2
Received from sqs: List(6)
Stream output: 5
</code>```

Any ideas?

答:
As I wrote in the comments section I believe the source of the problem is the fact that Streams, and therefore lazy tail evaluation, are being used as an intermediary.

The Stream component is unnecessary because an Iterator alone can solve the problem:

```<code>val messageListIterator : () => Iterator[Iterable[SqsMessage]] =
  () => Iterator continually queryForMessages

val messageIterator : () => Iterator[SqsMessage] =
  () => messageListIterator() flatMap identity
</code>```

This can now be used in your akka stream Source:

```<code>Source
  .fromIterator(messageIterator)
  .map(_.getBody)
  .runForeach(m => println(s"Stream output: $m"))(materializer)
</code>```

I have updated the linked question accordingly.

Body:
I am following this answer
to create an SQS consumer using Akka Streams:

  def queryForMessages = {
    val messages = Sqs.receive(queueUrl, 3, 10)
    println(s"Received from sqs: ${messages.map(_.getBody)}")
    messages
  }

  def messageListStream : immutable.Stream[Iterable[SqsMessage]] = {
    queryForMessages #:: messageListStream
  }

  def messageIterator() : Iterator[SqsMessage] = messageListStream.flatten.toIterator

  Source.fromIterator(messageIterator)
    .map(_.getBody)
    .runForeach(m => println(s"Stream output: $m"))(materializer)

It all seems to work, apart from the fact that the last element that was received from the queue does not get picked up by the stream.
ie if I post four items to sqs, only 3 of them get printed out at by the stream (item "2" is missing). The output I get is:

Received from sqs: List(1)
Received from sqs: List(3, 4, 2)
Stream output: 1
Stream output: 3
Stream output: 4
Received from sqs: List()
Received from sqs: List()

The missing element (2) does actually appear though if I post some more elements:

Received from sqs: List(5)
Stream output: 2
Received from sqs: List(6)
Stream output: 5

Any ideas?

Body:
As I wrote in the comments section I believe the source of the problem is the fact that Streams, and therefore lazy tail evaluation, are being used as an intermediary.

The Stream component is unnecessary because an Iterator alone can solve the problem:

val messageListIterator : () => Iterator[Iterable[SqsMessage]] =
  () => Iterator continually queryForMessages

val messageIterator : () => Iterator[SqsMessage] =
  () => messageListIterator() flatMap identity

This can now be used in your akka stream Source:

Source
  .fromIterator(messageIterator)
  .map(_.getBody)
  .runForeach(m => println(s"Stream output: $m"))(materializer)

I have updated the linked question accordingly.


答:
 is a block level element, which takes up 100 % of the available width by default.  is an inline element, which only takes up the minimum amount of width it needs to display its content.

There's a really good article on learnlayout.com that does a great job explaining this.

Happy coding :)

Title: why is there a difference if I add a class to a span tag as opposed to a div tag?

Body:
<div /> is a block level element, which takes up 100 % of the available width by default. <span /> is an inline element, which only takes up the minimum amount of width it needs to display its content.

There's a really good article on learnlayout.com that does a great job explaining this.

Happy coding :)


问:
Deploy custom InfoPath form with SharePoint list in VS2010
when I make a list in SharePoint 2010, I have the option to edit the forms for this list using InfoPath (by enabling a feature on the site collection and one on the site). When I save this form, it is saved as the default edit form for the list.

Now I am deploying my list from Visual Studio, as a WSP file. I would like to supply an InfoPath form with this list so that when the feature is activated, the list is created with the custom form attached. I can't seem to be able to find a way to add an InfoPath form to a list in this way though? I have tried creating a module and adding the form in there, but the only thing I can get it to do is to add the form into the list, not associate it with the list as an edit form.

I've found this blog post, which explains something similar but I'm not sure how it applies to my situation.

Any pointers would be greatly appreciated!

答:
The following tutorial will help you:

http://www.stuartroberts.net/index.php/2010/11/30/deploying-infopath-form-sharepoint/

Important steps along the way:

Deploy as module

Use RegisterForms in the feature manifest

And here is a link on how to attach your template to your list: http://spforsquirrels.blogspot.com/2008/03/assigning-infopath-form-template-to.html

Take note that you cannot have custom Infopath New/Edit forms for the list as described here, you can only create a forms library and attach your custom forms template to that library.


问:
Comparing tables in MySQL and adding a yes/no response
Can someone help me tweak my SQL to get the desired result. I have a table of users, a table of cases, and a relationship table for users attached to cases.

Users Table - users

```<code>+----+-------+--------+
| id | first |  last  |
+----+-------+--------+
|  1 | Joe   | Bloggs |
|  2 | John  | Doe    |
|  3 | Jane  | Doe    |
|  4 | Dave  | Smith  |
+----+-------+--------+
</code>```

Case Table - cases

```<code>+----+--------+------+
| id |  Case  | Code |
+----+--------+------+
|  1 | Case 1 | C1   |
|  2 | Case 2 | C2   |
|  3 | Case 3 | C3   |
+----+--------+------+
</code>```

Case Users Table - case_users

```<code>+----+---------+---------+
| id | case_id | user_id |
+----+---------+---------+
|  1 |       1 |       1 |
|  2 |       1 |       2 |
|  3 |       2 |       4 |
|  4 |       3 |       1 |
|  5 |       1 |       4 |
+----+---------+---------+
</code>```

I want to query the database to return me a full list of users and return a yes or no if they are linked to case 1 and then case 2 case 3 etc.

The SQL I've got so far (selecting for Case ID 1) returns all users but is assigning 'no' to everyone:

```<code>SELECT
    users.first,
    users.last,
    CASE WHEN case_users.case_id IS NULL THEN 'N' ELSE 'Y' END AS 'yes/no'
FROM
    users
        LEFT OUTER JOIN case_users ON case_users.case_id = 1
</code>```

My actual result is:

```<code>+-------+--------+--------+
| First |  Last  | Yes/No |
+-------+--------+--------+
| Joe   | Bloggs | Y      |
| John  | Doe    | Y      |
| Jane  | Doe    | Y      |
| Dave  | Smith  | Y      |
+-------+--------+--------+
</code>```

My desired result should be:

```<code>+-------+--------+--------+
| First |  Last  | Yes/No |
+-------+--------+--------+
| Joe   | Bloggs | Y      |
| John  | Doe    | Y      |
| Jane  | Doe    | N      |
| Dave  | Smith  | Y      |
+-------+--------+--------+
</code>```

Can someone help me as I can't get the desired result?

答:
```<code> SELECT u.*
      , CASE WHEN cu.case_id IS NULL THEN 'N' ELSE 'Y' END linked
   FROM users u
   JOIN cases c
   LEFT
   JOIN case_users cu
     ON cu.user_id = u.id
    AND cu.case_id = c.id
  WHERE c.id = 1;
</code>```

Body:
Can someone help me tweak my SQL to get the desired result. I have a table of users, a table of cases, and a relationship table for users attached to cases.

Users Table - users

+----+-------+--------+
| id | first |  last  |
+----+-------+--------+
|  1 | Joe   | Bloggs |
|  2 | John  | Doe    |
|  3 | Jane  | Doe    |
|  4 | Dave  | Smith  |
+----+-------+--------+

Case Table - cases

+----+--------+------+
| id |  Case  | Code |
+----+--------+------+
|  1 | Case 1 | C1   |
|  2 | Case 2 | C2   |
|  3 | Case 3 | C3   |
+----+--------+------+

Case Users Table - case_users

+----+---------+---------+
| id | case_id | user_id |
+----+---------+---------+
|  1 |       1 |       1 |
|  2 |       1 |       2 |
|  3 |       2 |       4 |
|  4 |       3 |       1 |
|  5 |       1 |       4 |
+----+---------+---------+

I want to query the database to return me a full list of users and return a yes or no if they are linked to case 1 and then case 2 case 3 etc.

The SQL I've got so far (selecting for Case ID 1) returns all users but is assigning 'no' to everyone:

SELECT
    users.first,
    users.last,
    CASE WHEN case_users.case_id IS NULL THEN 'N' ELSE 'Y' END AS 'yes/no'
FROM
    users
        LEFT OUTER JOIN case_users ON case_users.case_id = 1

My actual result is:

+-------+--------+--------+
| First |  Last  | Yes/No |
+-------+--------+--------+
| Joe   | Bloggs | Y      |
| John  | Doe    | Y      |
| Jane  | Doe    | Y      |
| Dave  | Smith  | Y      |
+-------+--------+--------+

My desired result should be:

+-------+--------+--------+
| First |  Last  | Yes/No |
+-------+--------+--------+
| Joe   | Bloggs | Y      |
| John  | Doe    | Y      |
| Jane  | Doe    | N      |
| Dave  | Smith  | Y      |
+-------+--------+--------+

Can someone help me as I can't get the desired result?


问:
Djikstra's Shortest path algorithm
I am learning Djikstra's and i have prepared the code below based on slightly different idea than Djikstra.
Now, In many of the websites, i have seen the use of Extract min and boolean array of visited edges.
I have used none and my answer is also correct. Is there any test case or scenario where my algo won't work.</p>
```<code>    import java.util.*;
    class ShortestPath2 {
        static int Ar[][];
        static int dist[];

        static int nodes;
        public static void djikstra(int source) {
            LinkedList < Integer > list = new LinkedList < Integer > ();
            dist[source] = 0;

            list.add(source);
            while (!list.isEmpty()) {
                source = list.removeFirst();

                for (int i = 0; i < nodes; i++) {
                    if (Ar[source][i] != 0) {

                        if (dist[i] > dist[source] + Ar[source][i]) {
                            dist[i] = Math.min(dist[i], dist[source] + Ar[source][i]);
                            list.add(i);
                        }
                    }
                }

            }
            System.out.println(Arrays.toString(dist));
        }

        public static void main(String[] args) {
            nodes = 9;

            Ar = new int[nodes][nodes];
            dist = new int[nodes];

            Arrays.fill(dist, Integer.MAX_VALUE);

            Ar = new int[][] {
                 {0,  4, 0,  0,  0,  0, 0,  8, 0},
                 {4,  0, 8,  0,  0,  0, 0, 11, 0},
                 {0,  8, 0,  7,  0,  4, 0,  0, 2},
                 {0,  0, 7,  0,  9, 14, 0,  0, 0},
                 {0,  0, 0,  9,  0, 10, 0,  0, 0},
                 {0,  0, 4, 14, 10,  0, 2,  0, 0},
                 {0,  0, 0,  0,  0,  2, 0,  1, 6},
                 {8, 11, 0,  0,  0,  0, 1,  0, 7},
                 {0,  0, 2,  0,  0,  0, 6,  7, 0}
            };

            djikstra(0);
        }
    }

</code>```

答:
Dijkstra's Original Implementation doesn't resolve the negative edge (but can detect it) and negative cycle problem.

To resolve this, we can use the Bellman Ford Algorithm.

It will give the correct shortest path even if there is a negative edge (but no negative cycle)

It can detect whether a negative cycle is there or not (but doesn't give the correct solution if a negative cycle is there, so better we terminate the code)

Title: Djikstra's Shortest path algorithm

Body:
I am learning Djikstra's and i have prepared the code below based on slightly different idea than Djikstra.
Now, In many of the websites, i have seen the use of Extract min and boolean array of visited edges.
I have used none and my answer is also correct. Is there any test case or scenario where my algo won't work.

    import java.util.*;
    class ShortestPath2 {
        static int Ar[][];
        static int dist[];

        static int nodes;
        public static void djikstra(int source) {
            LinkedList < Integer > list = new LinkedList < Integer > ();
            dist[source] = 0;

            list.add(source);
            while (!list.isEmpty()) {
                source = list.removeFirst();

                for (int i = 0; i < nodes; i++) {
                    if (Ar[source][i] != 0) {

                        if (dist[i] > dist[source] + Ar[source][i]) {
                            dist[i] = Math.min(dist[i], dist[source] + Ar[source][i]);
                            list.add(i);
                        }
                    }
                }

            }
            System.out.println(Arrays.toString(dist));
        }

        public static void main(String[] args) {
            nodes = 9;

            Ar = new int[nodes][nodes];
            dist = new int[nodes];

            Arrays.fill(dist, Integer.MAX_VALUE);

            Ar = new int[][] {
                 {0,  4, 0,  0,  0,  0, 0,  8, 0},
                 {4,  0, 8,  0,  0,  0, 0, 11, 0},
                 {0,  8, 0,  7,  0,  4, 0,  0, 2},
                 {0,  0, 7,  0,  9, 14, 0,  0, 0},
                 {0,  0, 0,  9,  0, 10, 0,  0, 0},
                 {0,  0, 4, 14, 10,  0, 2,  0, 0},
                 {0,  0, 0,  0,  0,  2, 0,  1, 6},
                 {8, 11, 0,  0,  0,  0, 1,  0, 7},
                 {0,  0, 2,  0,  0,  0, 6,  7, 0}
            };

            djikstra(0);
        }
    }


问:
Pass a JSON string as a command line argument
I am trying to pass a json string to a C#-Program using Commandline.

The JSON-String looks like this:

```<code>{
    "config": {
        "script": {
            "script_name": "test",
            "dir": "D:\\test",
            "destination": "M:\\neu\\test",
            "params": "/b /s /r:3 /w:5"
        }
    }
}
</code>```

In Commandline it looks like this:

```<code>{"config":{"script":{"script_name":"test","dir":"D:\\test","destination":"M:\\neu\\test","params":"/b /s /r:3 /w:5"}}}
</code>```

But if I just pass the string then it gets chunked into several pieces. But I want my program to see it as just a single string.

Do I have to adapt my JSON-String?

答:
Just send json value to commandline after catch value and replace it. It's work for me.</p>

```<code>args[1].Replace("{","{\"").Replace(":","\":\"").Replace(",","\",\"").Replace("}","\"}");
</code>```

Body:
I am trying to pass a json string to a C#-Program using Commandline.

The JSON-String looks like this:

{
    "config": {
        "script": {
            "script_name": "test",
            "dir": "D:\\test",
            "destination": "M:\\neu\\test",
            "params": "/b /s /r:3 /w:5"
        }
    }
}

In Commandline it looks like this:

{"config":{"script":{"script_name":"test","dir":"D:\\test","destination":"M:\\neu\\test","params":"/b /s /r:3 /w:5"}}}

But if I just pass the string then it gets chunked into several pieces. But I want my program to see it as just a single string.

Do I have to adapt my JSON-String?

Body:
Just send json value to commandline after catch value and replace it. It's work for me.

args[1].Replace("{","{\"").Replace(":","\":\"").Replace(",","\",\"").Replace("}","\"}");


问:
Own Set whih inherited from List<int>
Hi I want create class Set which inherited from List<int>

```<code>class Set : List<int>
{
  public void Add(tmp)
  public void Pop(tmp)
  public print()
}
</code>```

But I have problem how should look consturctor could someone give me example?
I know how should looks methods(I will write them myself).

答:
An alternative possibility is the use of extension methods as it seems to me you are only trying to add functionality to List by way of methods. Here is an example:</p>

```<code>public static class ListExtensions
{
    /// <summary>
    /// Adds an empty Dropdown Option at the start of the list
    /// If the list is null then null will be returned and nothing happens
    /// </summary>
    /// <param name="list">
    /// List of dropdown options
    /// </param>
    /// <returns >The list of dropdown options with the prepended empty option</returns>
    public static IList<SelectListItem> AddEmpty(this IList<SelectListItem> list)
    {
        list?.Insert(0, new SelectListItem {Value = string.Empty, Text = Resources.Labels.ChooseListItem});

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

Title: Own Set whih inherited from List<int>

Body:
Hi I want create class Set which inherited from List<int>

class Set : List<int>
{
  public void Add(tmp)
  public void Pop(tmp)
  public print()
}

But I have problem how should look consturctor could someone give me example?
I know how should looks methods(I will write them myself).

Body:
An alternative possibility is the use of extension methods as it seems to me you are only trying to add functionality to List by way of methods. Here is an example:

public static class ListExtensions
{
    /// <summary>
    /// Adds an empty Dropdown Option at the start of the list
    /// If the list is null then null will be returned and nothing happens
    /// </summary>
    /// <param name="list">
    /// List of dropdown options
    /// </param>
    /// <returns >The list of dropdown options with the prepended empty option</returns>
    public static IList<SelectListItem> AddEmpty(this IList<SelectListItem> list)
    {
        list?.Insert(0, new SelectListItem {Value = string.Empty, Text = Resources.Labels.ChooseListItem});

        return list;
    }
}


问:
Learning COBOL Without Access to Mainframe
I am a graduate student majoring in Computer Science.  My department teaches the majority of its courses using Java (though I did take one course on system architecture that used C to demonstrate processor scheduling, memory management, etc....but I digress).

I want to learn more about COBOL, but I don't have access to a mainframe system.  Can anyone please recommend a free COBOL compiler for Windows that would enable me to get through some basic COBOL tutorials?

Disclaimer:  yes, I've Googled this already, so hoping for some experienced individuals to give some further info.

Thanks!

答:
There used to be a Cobol-to-C compiler and Eclipse IDE from a company called "The Kompany".  The product was called "Kobol".  It would let you write Cobol using an eclipse based environment that would be similar to what you would use for a mainframe (Rational Developer for Z).  They have a free demo version and a cheap student version IIRC.

You will find that Cobol is easy to learn, easy to write and hard to shoot yourself in the foot with.  That is one of the reasons it is so very popular with financial institutions.

I think it is great that you are adding Cobol to your toolbox.


问:
Getting the COM port name for a known Bluetooth device in UWP
I'm using a DeviceWatcher to get the DeviceInformation for a paired Bluetooth device in a UWP app. I set the DeviceWatcher up like this

```<code>var requestedProperties = new string[] { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };
var deviceWatcher = DeviceInformation.CreateWatcher("(System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\")", requestedProperties, DeviceInformationKind.AssociationEndpoint); // ClassGuid = {e0cbf06c-cd8b-4647-bb8a-263b43f0f974} includes all Bluetooth devices
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.Start();
</code>```

When the DeviceWatcher_Added event handler is called I check to see if the device is the one I am interested in by checking its name and that it offers the RfcommServiceId.SerialPort.Uuid service.

Once I have the DeviceInformation for the bluetooth device I am interested in how do I get the COM port for it? I can see it in the Device Manager, where it is listed as "Standard Serial over Bluetooth link (COM8)", but I cannot see how to get that "COM8" in UWP programmatically.

I've tried making the DeviceInformation into a SerialDevice, whereby I could then get SerialDevice.PortName (c.f. this answer) but my call to SerialDevice.FromIdAsync(deviceInfo.Id) fails with a System.Exception: The data is invalid.

(N.B. Some tantalizing answers, like this and this, use the Windows Management Intrumentation WMI functions but these are not available in UWP.)

答:
On another question Rita suggested looking at the Serial UART sample which helped me see a way to do this. I won't mark this as the answer for a while as it seems too indirect to be the canonical way.

Although I have the the DeviceInformation for the paired Bluetooth device in my UWP app I also need the list of SerialDevices so that I can match them up. Here's the resulting code.

```<code>public async Task<string> ComPort(DeviceInformation deviceInfo)
{
    var serialDevices = new Dictionary<string, SerialDevice>();
    var serialSelector = SerialDevice.GetDeviceSelector();
    var serialDeviceInformations = (await DeviceInformation.FindAllAsync(serialSelector)).ToList();
    var hostNames = NetworkInformation.GetHostNames().Select(hostName => hostName.DisplayName.ToUpper()).ToList(); // So we can ignore inbuilt ports
    foreach (var serialDeviceInformation in serialDeviceInformations)
    {
        if (hostNames.FirstOrDefault(hostName => hostName.StartsWith(serialDeviceInformation.Name.ToUpper())) == null)
        {
            try
            {
                var serialDevice = await SerialDevice.FromIdAsync(serialDeviceInformation.Id);
                if (serialDevice != null)
                {
                    serialDevices.Add(deviceInfo.Id, serialDevice);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
        }
    }
    // Example Bluetooth DeviceInfo.Id: "Bluetooth#Bluetooth9c:b6:d0:d6:d7:56-00:07:80:cb:56:6d"
    // from device with Association Endpoint Address: "00:07:80:cb:56:6d"
    var lengthOfTrailingAssociationEndpointAddresss = (2 * 6) + 5;
    var bluetoothDeviceAddress = deviceInfo.Id.Substring(deviceInfo.Id.Length - lengthOfTrailingAssociationEndpointAddresss, lengthOfTrailingAssociationEndpointAddresss).Replace(":", "").ToUpper();
    var matchingKey = serialDevices.Keys.FirstOrDefault(id => id.Contains(bluetoothDeviceAddress));
    if (matchingKey != null)
    {
        return serialDevices[matchingKey].PortName;
    }
    return "";
}
</code>```

Body:
I'm using a DeviceWatcher to get the DeviceInformation for a paired Bluetooth device in a UWP app. I set the DeviceWatcher up like this

var requestedProperties = new string[] { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };
var deviceWatcher = DeviceInformation.CreateWatcher("(System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\")", requestedProperties, DeviceInformationKind.AssociationEndpoint); // ClassGuid = {e0cbf06c-cd8b-4647-bb8a-263b43f0f974} includes all Bluetooth devices
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.Start();

When the DeviceWatcher_Added event handler is called I check to see if the device is the one I am interested in by checking its name and that it offers the RfcommServiceId.SerialPort.Uuid service.

Once I have the DeviceInformation for the bluetooth device I am interested in how do I get the COM port for it? I can see it in the Device Manager, where it is listed as "Standard Serial over Bluetooth link (COM8)", but I cannot see how to get that "COM8" in UWP programmatically.

I've tried making the DeviceInformation into a SerialDevice, whereby I could then get SerialDevice.PortName (c.f. this answer) but my call to SerialDevice.FromIdAsync(deviceInfo.Id) fails with a System.Exception: The data is invalid.

(N.B. Some tantalizing answers, like this and this, use the Windows Management Intrumentation WMI functions but these are not available in UWP.)

Body:
On another question Rita suggested looking at the Serial UART sample which helped me see a way to do this. I won't mark this as the answer for a while as it seems too indirect to be the canonical way.

Although I have the the DeviceInformation for the paired Bluetooth device in my UWP app I also need the list of SerialDevices so that I can match them up. Here's the resulting code.

public async Task<string> ComPort(DeviceInformation deviceInfo)
{
    var serialDevices = new Dictionary<string, SerialDevice>();
    var serialSelector = SerialDevice.GetDeviceSelector();
    var serialDeviceInformations = (await DeviceInformation.FindAllAsync(serialSelector)).ToList();
    var hostNames = NetworkInformation.GetHostNames().Select(hostName => hostName.DisplayName.ToUpper()).ToList(); // So we can ignore inbuilt ports
    foreach (var serialDeviceInformation in serialDeviceInformations)
    {
        if (hostNames.FirstOrDefault(hostName => hostName.StartsWith(serialDeviceInformation.Name.ToUpper())) == null)
        {
            try
            {
                var serialDevice = await SerialDevice.FromIdAsync(serialDeviceInformation.Id);
                if (serialDevice != null)
                {
                    serialDevices.Add(deviceInfo.Id, serialDevice);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
        }
    }
    // Example Bluetooth DeviceInfo.Id: "Bluetooth#Bluetooth9c:b6:d0:d6:d7:56-00:07:80:cb:56:6d"
    // from device with Association Endpoint Address: "00:07:80:cb:56:6d"
    var lengthOfTrailingAssociationEndpointAddresss = (2 * 6) + 5;
    var bluetoothDeviceAddress = deviceInfo.Id.Substring(deviceInfo.Id.Length - lengthOfTrailingAssociationEndpointAddresss, lengthOfTrailingAssociationEndpointAddresss).Replace(":", "").ToUpper();
    var matchingKey = serialDevices.Keys.FirstOrDefault(id => id.Contains(bluetoothDeviceAddress));
    if (matchingKey != null)
    {
        return serialDevices[matchingKey].PortName;
    }
    return "";
}


问:
var j in forloop undefined but i in previous loop defined
I have the following function below that's returning an error

j is not defined

I'm not sure why this is as i in my first for loop is not returning undefined. If I change the second forloop to for(var j =0.... then it works. Anyone care to explain why this is?

```<code>;(function (window, document, undefined) {
  'use strict';
  var DOMState = document.readyState;
if (DOMState === 'interactive' || DOMState === 'complete') {
      setTimeout(init, 250);
    } else if (document.addEventListener) {
      document.addEventListener('DOMContentLoaded', init);
    }
  function init() {
    var links = $('#list_of_recs a');

    for (i=0;i<links.length;i++) {
      var href = links[i].href;
      var campaignCode1 = "?intcam=ON_D_homepage_recently_viewed";
      var newHref = href + campaignCode1;
      links[i].href = newHref;
    }

    var recTotalDevices = $('#list_of_recs .one_image');

    for (j=0;j<recTotalDevices.length;j++) {
      var aLinks = $('#list_of_recs a')[j];
      var link = aLinks.href;
      var newLink = link.replace("upg-","");
      var newLinknew = newLink.replace("additional-line","");
      aLinks.href = newLinknew;
    }

  }
})(window, document);
</code>```

答:
Without the full context of any other scripts that are running on your page it's hard to be certain but likely there is another script on your page which contains an global scope assignment to i=0 as it is a common convention.

I would suggest you place a

```<code>var i=0,j=0;
</code>```

at the start of your function to ensure localised variables are being referenced in your loop. This is better practice than putting the var in the top of the for() loop

Body:
I have the following function below that's returning an error

j is not defined

I'm not sure why this is as i in my first for loop is not returning undefined. If I change the second forloop to for(var j =0.... then it works. Anyone care to explain why this is?

;(function (window, document, undefined) {
  'use strict';
  var DOMState = document.readyState;
if (DOMState === 'interactive' || DOMState === 'complete') {
      setTimeout(init, 250);
    } else if (document.addEventListener) {
      document.addEventListener('DOMContentLoaded', init);
    }
  function init() {
    var links = $('#list_of_recs a');

    for (i=0;i<links.length;i++) {
      var href = links[i].href;
      var campaignCode1 = "?intcam=ON_D_homepage_recently_viewed";
      var newHref = href + campaignCode1;
      links[i].href = newHref;
    }

    var recTotalDevices = $('#list_of_recs .one_image');

    for (j=0;j<recTotalDevices.length;j++) {
      var aLinks = $('#list_of_recs a')[j];
      var link = aLinks.href;
      var newLink = link.replace("upg-","");
      var newLinknew = newLink.replace("additional-line","");
      aLinks.href = newLinknew;
    }

  }
})(window, document);

Body:
Without the full context of any other scripts that are running on your page it's hard to be certain but likely there is another script on your page which contains an global scope assignment to i=0 as it is a common convention.

I would suggest you place a

var i=0,j=0;

at the start of your function to ensure localised variables are being referenced in your loop. This is better practice than putting the var in the top of the for() loop


问:
How to handle query parameters in angular 2
In my routable component I have

```<code>@RouteConfig {
  {path: '/login',   name: 'Login', component: LoginComponent}
}
</code>```

But how do I get the query params if I go to app_url/login?token=1234?

答:
For Angular 4

Url:

```<code>http://example.com/company/100
</code>```

Router Path :

```<code>const routes: Routes = [
  { path: 'company/:companyId', component: CompanyDetailsComponent},

]
</code>```

Component:

```<code>@Component({
  selector: 'company-details',
  templateUrl: './company.details.component.html',
  styleUrls: ['./company.component.css']
})
export class CompanyDetailsComponent{
   companyId: string;

   constructor(private router: Router, private route: ActivatedRoute) {
          this.route.params.subscribe(params => {
          this.companyId = params.companyId;
          console.log('companyId :'+this.companyId);
     });
  }
}
</code>```

Console Output:

companyId : 100

Body:
In my routable component I have

@RouteConfig {
  {path: '/login',   name: 'Login', component: LoginComponent}
}

But how do I get the query params if I go to app_url/login?token=1234?

Body:
For Angular 4

Url:

http://example.com/company/100

Router Path :

const routes: Routes = [
  { path: 'company/:companyId', component: CompanyDetailsComponent},

]

Component:

@Component({
  selector: 'company-details',
  templateUrl: './company.details.component.html',
  styleUrls: ['./company.component.css']
})
export class CompanyDetailsComponent{
   companyId: string;

   constructor(private router: Router, private route: ActivatedRoute) {
          this.route.params.subscribe(params => {
          this.companyId = params.companyId;
          console.log('companyId :'+this.companyId);
     });
  }
}

Console Output:

companyId : 100


问:
How to extract and split a string in multiple parts
I would like to search and split different files in a directory based on some pattern  which may contain different file formats:

```<code>/path/

somefile.txt 2010-01-01
file.txt 2010-01-02
f.txt 2010-01-03
test.txt 2010-01-04
photo.jpg 2010-01-04
script.py  2010-01-05
</code>```

In order to get:

```<code>somefile.txt
file.txt
f.txt
test.txt
</code>```

Here first I would like to catch all files which contains .txt and split them accordingly:

```<code>def catch_txt(path):
    result = [os.path.join(path, f) for f in os.listdir(path) if
re.search(r"\w+\.\w+\txt", f)]
    splitted_result = [files for files in result if
re.split(r"\w+\.\w+\txt", f)]
    # some other stuff
    return splitted_result
</code>```

But only gives a emtpy list.

答:
Here's a solution without using re. Assuming your list of filetypes is short, you can just create a list for each filetype

```<code>import os

files = [f for f in os.listdir('.') if os.path.isfile(f)]
txt_files = [] #create additional lists/loops for each filetype
for file in files:
        if file.endswith('.txt'):
            txt_files.append(file)
print (txt_files)
</code>```

Body:
I would like to search and split different files in a directory based on some pattern  which may contain different file formats:

/path/

somefile.txt 2010-01-01
file.txt 2010-01-02
f.txt 2010-01-03
test.txt 2010-01-04
photo.jpg 2010-01-04
script.py  2010-01-05

In order to get:

somefile.txt
file.txt
f.txt
test.txt

Here first I would like to catch all files which contains .txt and split them accordingly:

def catch_txt(path):
    result = [os.path.join(path, f) for f in os.listdir(path) if
re.search(r"\w+\.\w+\txt", f)]
    splitted_result = [files for files in result if
re.split(r"\w+\.\w+\txt", f)]
    # some other stuff
    return splitted_result

But only gives a emtpy list.

Body:
Here's a solution without using re. Assuming your list of filetypes is short, you can just create a list for each filetype

import os

files = [f for f in os.listdir('.') if os.path.isfile(f)]
txt_files = [] #create additional lists/loops for each filetype
for file in files:
        if file.endswith('.txt'):
            txt_files.append(file)
print (txt_files)


问:
How do I listen to URL changes in Chrome Custom Tabs
Im working on an android app, that requires Chrome Custom Tabs (It uses an API that requires this exact package).

I want to know when ChromeTabs gets redirected to a specific URL, but i haven't found anything useful yet.

Does anyone have experience with this?

Thanks

答:
Instead of using the ChromeTabs callback method to check the URL, i used deeplinking instead.
I visited this method earlier without any luck, and it seems that because i didn't tell the android to autoVerify it didn't list the app as a browser app.

```<code><activity
            android:name=".Activity"
            android:launchMode="singleTask">
            <intent-filter android:autoVerify="true"> <--! to tell android
      that its a browsable app -->
                <data
                    android:host="open"
                    android:scheme="myapp" />

                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
            </intent-filter>
        </activity>
</code>```

Hope it helps

Body:
Instead of using the ChromeTabs callback method to check the URL, i used deeplinking instead.
I visited this method earlier without any luck, and it seems that because i didn't tell the android to autoVerify it didn't list the app as a browser app.

<activity
            android:name=".Activity"
            android:launchMode="singleTask">
            <intent-filter android:autoVerify="true"> <--! to tell android
      that its a browsable app -->
                <data
                    android:host="open"
                    android:scheme="myapp" />

                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
            </intent-filter>
        </activity>

Hope it helps


问:
Debugging SMTP email failures - GSuite
I am working on an eCommerce site that sends a number of emails to the customer when they complete their order using G Suite SMTP relay service. But a large number of these emails are failing. There does not seems to be any pattern to it either - sometimes all emails will send, some times just one or two, and sometimes none.

I am getting the following error: 421, "4.7.0", Try again later, closing connection.

Looking here: https://support.google.com/a/answer/3726730?hl=en doesn't really help me debug this or figure out why some emails fail.

I am using the phpmailer class (https://sourceforge.net/projects/phpmailer/)

The issue seems to occur when the first handshake fails:

```<code>function Hello($host="") {
    $this->error = null; # so no confusion is caused

    if(!$this->connected()) {
      $this->error = array(
            "error" => "Called Hello() without being connected");
      return false;
    }

    # if a hostname for the HELO was not specified determine
    # a suitable one to send
    if(empty($host)) {
      # we need to determine some sort of appopiate default
      # to send to the server
      $host = "localhost";
    }

    // Send extended hello first (RFC 2821)
    //If this fails then the second attempt will always fail
    if(!$this->SendHello("EHLO", $host))
    {
      //when this fails it generates the try again later error
      if(!$this->SendHello("HELO", $host))
          return false;
    }

    return true;
  }
</code>```

So what is the best approach for debugging this?

答: The error message is pretty explicit. You call a 3rd party web service, which returns an error code which says the server you are calling is at capacity, try later. Is this a free service which allows you to upgrade to a paid plan? Usually whee you see his kind of thing.</p>

Title: Debugging SMTP email failures - GSuite

Body:
I am working on an eCommerce site that sends a number of emails to the customer when they complete their order using G Suite SMTP relay service. But a large number of these emails are failing. There does not seems to be any pattern to it either - sometimes all emails will send, some times just one or two, and sometimes none.

I am getting the following error: 421, "4.7.0", Try again later, closing connection.

Looking here: https://support.google.com/a/answer/3726730?hl=en doesn't really help me debug this or figure out why some emails fail.

I am using the phpmailer class (https://sourceforge.net/projects/phpmailer/)

The issue seems to occur when the first handshake fails:

function Hello($host="") {
    $this->error = null; # so no confusion is caused

    if(!$this->connected()) {
      $this->error = array(
            "error" => "Called Hello() without being connected");
      return false;
    }

    # if a hostname for the HELO was not specified determine
    # a suitable one to send
    if(empty($host)) {
      # we need to determine some sort of appopiate default
      # to send to the server
      $host = "localhost";
    }

    // Send extended hello first (RFC 2821)
    //If this fails then the second attempt will always fail
    if(!$this->SendHello("EHLO", $host))
    {
      //when this fails it generates the try again later error
      if(!$this->SendHello("HELO", $host))
          return false;
    }

    return true;
  }

So what is the best approach for debugging this?


问:
Email validation, using if else statements wont allow it to continue checking if there was an error with the first if?
I have:

```<code>if(isset($_POST['submit'])) {
    if (empty($name)) {
        echo'<span class="error">ERROR: Missing Name </span><br/>';
    } else if(empty($phone) || empty($email)) {
        echo'<span class="error">ERROR: You must insert a phone number or email</span><br/>';
    } else if(!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        echo'<span class="error">ERROR: Please Insert a valid Email</span><br/>';
    }  else {
        mail( "anEmail@hotmail.com", "Monthly Specials Email",
            "Name: $name
            Email: $email
            Phone Number: $phone
            Comment: $comment", "From: $email" );
        echo'<span id="valid">Message has been sent</span><br/>';
    }
}
</code>```

How else could I check for all of those issues without using else if?
When I use else if, it checks through the first if statement, if there is an issue with it it will not continue going through the other if statements following that one.

Any ideas? Thank you

答:
```<code>if(isset($_POST['submit'])) {
    $valid = true;
    if (empty($name)) {
        echo'<span class="error">ERROR: Missing Name </span><br/>';
        $valid = false;
    }

    if(empty($phone) || empty($email)) {
        echo'<span class="error">ERROR: You must insert a phone number or email</span><br/>';
        $valid=false;
    }

    if(!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        echo'<span class="error">ERROR: Please Insert a valid Email</span><br/>';
        $valid = FALSE;
    }

    if($valid) {
        mail( "anEmail@hotmail.com", "Monthly Specials Email",
            "Name: $name
            Email: $email
            Phone Number: $phone
            Comment: $comment", "From: $email" );
        echo'<span id="valid">Message has been sent</span><br/>';
    }
}
</code>```

Body:
I have:

if(isset($_POST['submit'])) {
    if (empty($name)) {
        echo'ERROR: Missing Name
';
    } else if(empty($phone) || empty($email)) {
        echo'ERROR: You must insert a phone number or email
';
    } else if(!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        echo'ERROR: Please Insert a valid Email
';
    }  else {
        mail( "anEmail@hotmail.com", "Monthly Specials Email",
            "Name: $name
            Email: $email
            Phone Number: $phone
            Comment: $comment", "From: $email" );
        echo'Message has been sent
';
    }
}

How else could I check for all of those issues without using else if?
When I use else if, it checks through the first if statement, if there is an issue with it it will not continue going through the other if statements following that one.

Any ideas? Thank you


问:
How to authenticate user with just a Google account on Actions on Google?
Currently Google Assitant includes an easy way to request non-identifiable information about the user and a detailed flow to authenticate the user on a third party service through OAuth2. What about if all I need is have the user authenticate on Google itself? I tried filling in the account linking flow using Google OAuth2 information, but that seems not to work. If that last thing is supposed to work fluently than that would be enough of an answer.

Context: Users already authenticate only with Google on a related webpage. All I need is to link this already authenticated account with the less-authenticated account on Google Assistant.

答:
You need to implement the Oauth protocol with whatever Google Assistant app you are developing. Let me be a bit more clear:

The user is on the assistant, you need to link him to any data
you have on your App side

The access to the data you have about
your user is protected by an access token

Google then needs to
ask you for this token to have access to this resource

When
google has the token it can send it to the app so it validates every
requests to get the resource.

This is why you need to implement your own oauth server (Honestly it is just two more endpoints in your application): the identity is checked on google's side, but the link between the user and the resource to access can only be known by you.
The process above is valid, you just need to specify your own token endpoint and your own auth endpoint.
Note that if you only want to check that the user is logged in into google and get his email, you just need to implement the streamlined identity flow that does not require the /auth endpoint (Automatically Sign Up Users with Streamlined Identity Flows)

That beeing said I implemented the flow but get the same error :

expected_inputs[0].possible_intents[0]: Transactions/Identity API must be enabled before using.


问:
How do owl and rdfs property domain range work?
I am trying to understand the semantics of rdfs domain and range.  Because I am from an object oriented background, I am struggling to understand the semantics and how to validate data against the rdfs statements.

Here is a sample file in turtle format:

```<code>PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
prefix tmpl: <http://template.example.com/>
prefix data: <http://data.example.com/>

    tmpl:Thing a owl:Class.
    tmpl:Employment rdfs:subClassOf tmpl:TemporalThing.
    tmpl:Party rdfs:subClassOf tmpl:Thing.
    tmpl:Individual rdfs:subClassOf tmpl:Party.
    tmpl:Organisation rdfs:subClassOf tmpl:Party.
    tmpl:LimitedLiabilityCompany rdfs:subClassOf tmpl:Organisation.
    tmpl:hasCurrentEmployer a owl:ObjectProperty;
        rdfs:domain tmpl:Party;
        rdfs:range tmpl:Party.
    data:Simon a tmpl:Individual;
        skos:prefLabel "Simon S".
    data:PtyLtd a tmpl:LimitedLiabilityCompany.
    data:Simon tmpl:hasCurrentEmployer data:PtyLtd.

    tmpl:Animal a owl:Thing.
    data:Beans a tmpl:Animal.
    data:Simon tmpl:hasCurrentEmployer data:Beans.
</code>```

I am using GRAPHDB as my test environment.  I would expect the last statement to fail with some sort of message because 'Beans' is an 'Animal' which is not a 'Party'.

Yet, GRAPHDB just accepts the statement.

Any ideas?

EDIT

Based on Stanislav's comment below: While An inference engine might not have a problem with this, we can use the domain and range for error checking in an application.

答:
As said in the comments, you misunderstood the semantics of domain and range.

```<code>P rdfs:domain D
P rdfs:range R
</code>```

mean that if a statement s P o holds, then (with a reasoner running), it could be inferred that s rdf:type D and o rdf:type R.

Domain and range are never restrictions on the the property. That has to be clear.

To understand how things work, check for examplem OWL direct semantics for object properties here.

Body:
I am trying to understand the semantics of rdfs domain and range.  Because I am from an object oriented background, I am struggling to understand the semantics and how to validate data against the rdfs statements.

Here is a sample file in turtle format:

PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
prefix tmpl: <http://template.example.com/>
prefix data: <http://data.example.com/>

    tmpl:Thing a owl:Class.
    tmpl:Employment rdfs:subClassOf tmpl:TemporalThing.
    tmpl:Party rdfs:subClassOf tmpl:Thing.
    tmpl:Individual rdfs:subClassOf tmpl:Party.
    tmpl:Organisation rdfs:subClassOf tmpl:Party.
    tmpl:LimitedLiabilityCompany rdfs:subClassOf tmpl:Organisation.
    tmpl:hasCurrentEmployer a owl:ObjectProperty;
        rdfs:domain tmpl:Party;
        rdfs:range tmpl:Party.
    data:Simon a tmpl:Individual;
        skos:prefLabel "Simon S".
    data:PtyLtd a tmpl:LimitedLiabilityCompany.
    data:Simon tmpl:hasCurrentEmployer data:PtyLtd.

    tmpl:Animal a owl:Thing.
    data:Beans a tmpl:Animal.
    data:Simon tmpl:hasCurrentEmployer data:Beans.

I am using GRAPHDB as my test environment.  I would expect the last statement to fail with some sort of message because 'Beans' is an 'Animal' which is not a 'Party'.

Yet, GRAPHDB just accepts the statement.

Any ideas?

EDIT

Based on Stanislav's comment below: While An inference engine might not have a problem with this, we can use the domain and range for error checking in an application.

Body:
As said in the comments, you misunderstood the semantics of domain and range.

P rdfs:domain D
P rdfs:range R

mean that if a statement s P o holds, then (with a reasoner running), it could be inferred that s rdf:type D and o rdf:type R.

Domain and range are never restrictions on the the property. That has to be clear.

To understand how things work, check for examplem OWL direct semantics for object properties here.


问:
setClientIdentifier on oracle Connection from java application
how to set client identifier to oracle connection from java application. My stack is hibernate 4.3.6 and spring 4.1.0. Transaction are managed by spring with annotation @Transactional

My first try does't work

```<code>    @Autowired
private QueryDslUtil queryDslUtil;

@Autowired
private SessionFactory sessionFactory;

@Override
@Transactional(readOnly = true)
public void test(String kod) {

    Session tmpSession = sessionFactory.getCurrentSession();
    tmpSession.doWork(connection -> {
        Properties prop = new Properties();
        prop.put("userId", "mito");
        connection.setClientInfo(prop);
    });

    Objects.requireNonNull(kod);
    QOrganizacia source = QOrganizacia.organizacia;
    queryDslUtil.from(source).where(source.kod.eq(kod)).uniqueResult(source);
}
</code>```

my datasource is provided by weblogic server via jndi register or c3po in dev enviroment and I use oracle driver v 11.2.0.1.0

Thanks for help.

答:
OraclConnection interface has dedicated method to do this.
Some time ago it was setClientIdentifier but it is deprecated. Now it is setEndToEndMetrics. It allows to set up these columns in v$session.
select MODULE, ACTION , CLIENT_IDENTIFIER from v$session;

```<code>      String metric[] = new String[OracleConnection.END_TO_END_STATE_INDEX_MAX];
      metric[OracleConnection.END_TO_END_ACTION_INDEX]   = "I'm ACTION ";
      metric[OracleConnection.END_TO_END_MODULE_INDEX]   = "i'm MODULE";
      metric[OracleConnection.END_TO_END_CLIENTID_INDEX] = "I'm CLIENT_IDENTIFIER";
      ((OracleConnection) connection).setEndToEndMetrics(metric, (short) 0);
</code>```

Body:
how to set client identifier to oracle connection from java application. My stack is hibernate 4.3.6 and spring 4.1.0. Transaction are managed by spring with annotation @Transactional

My first try does't work

    @Autowired
private QueryDslUtil queryDslUtil;

@Autowired
private SessionFactory sessionFactory;

@Override
@Transactional(readOnly = true)
public void test(String kod) {

    Session tmpSession = sessionFactory.getCurrentSession();
    tmpSession.doWork(connection -> {
        Properties prop = new Properties();
        prop.put("userId", "mito");
        connection.setClientInfo(prop);
    });

    Objects.requireNonNull(kod);
    QOrganizacia source = QOrganizacia.organizacia;
    queryDslUtil.from(source).where(source.kod.eq(kod)).uniqueResult(source);
}

my datasource is provided by weblogic server via jndi register or c3po in dev enviroment and I use oracle driver v 11.2.0.1.0

Thanks for help.

Body:
OraclConnection interface has dedicated method to do this.
Some time ago it was setClientIdentifier but it is deprecated. Now it is setEndToEndMetrics. It allows to set up these columns in v$session.
select MODULE, ACTION , CLIENT_IDENTIFIER from v$session;

      String metric[] = new String[OracleConnection.END_TO_END_STATE_INDEX_MAX];
      metric[OracleConnection.END_TO_END_ACTION_INDEX]   = "I'm ACTION ";
      metric[OracleConnection.END_TO_END_MODULE_INDEX]   = "i'm MODULE";
      metric[OracleConnection.END_TO_END_CLIENTID_INDEX] = "I'm CLIENT_IDENTIFIER";
      ((OracleConnection) connection).setEndToEndMetrics(metric, (short) 0);


问:
PHP: Change only a portion of a URL string?
I’m working on a small hoppy project where I want to replace a specific page on a URL. Let me explain:

I’ve got the URL

http://www.example.com/article/paragraph/low/

I want to keep the URL but replace the last segment /low/ with /high/ so the new URL is:

http://www.example.com/article/paragraph/high/

I’ve tried different explode, split and splice but I just can’t seem to wrap my head around it and make it work. I can change the entire URL but not just the last segment and save it in a new variable.

I’m pretty confidence that it is a pretty straight forward case but I’ve never worked that much with arrays / string-manipulation in PHP so I’m pretty lost.

I guess that I have to first split the URL up in segments, using the "\" to separate it (I tried that but have problems by using explode("\", $string)) and then replace the last \low\ with \high\

Hope someone could help or point me in the right direction to what methods to use for doing this.

Sincere

Mestika

答:
how about str_replace?

```<code><?php
$newurl = str_replace('low', 'high', $oldurl);
?>
</code>```

documentation;
http://php.net/manual/en/function.str-replace.php

edit;
Rik is right; if your domain (or any other part of the url for that matter) includes the string "low", this will mess up your link.
So: if your url may contain multiple 'low' 's, you will have to add an extra indicator in the script. An example of that would be including the /'s in your str_replace.

Body:
how about str_replace?

<?php
$newurl = str_replace('low', 'high', $oldurl);
?>

documentation;
http://php.net/manual/en/function.str-replace.php

edit;
Rik is right; if your domain (or any other part of the url for that matter) includes the string "low", this will mess up your link.
So: if your url may contain multiple 'low' 's, you will have to add an extra indicator in the script. An example of that would be including the /'s in your str_replace.


问:
Over current context presentation with gestures
I am trying to implement the functionality of Youtube's video player. ATM I have a FloatingViewController (the video player) which gets presented modally (overCurrentContext) on a MainViewController which has it's definesPresentationContext set to true.

Everything works fine except the touch recognition (no scrolling) on the MainViewController when I pull down the player into minimized mode. I am pretty sure that this is happening because the FloatingViewController's view (with a clear background) is over every view in the MainVC as it got presented over it.

Mostly looking for any solutions or workarounds...

Yellow thingy is the FloatingVC. The rest is MainVC...

答: Try to check overlapping one view by the other one using debug view hierarchy in xcode.


问:
iterating over sorted treemap: java.util.ConcurrentModificationException
I have basic knowledge in Java and working currently on a Java based code.

EDIT: I didn't write the code

I am iterating over a sorted treemap of Event Objects and getting this exception when I am trying to get the next element:

java.util.ConcurrentModificationException
    at java.util.TreeMap$PrivateEntryIterator.nextEntry(Unknown Source)
    at java.util.TreeMap$KeyIterator.next(Unknown Source)

I think this should be due to the existence of mutiple entries with same value that are merged by the iterator comparator (be refering to this question, but I don't know how to find the keys used in the comparator. The object Event has many parameters (like id, time, etc)but not sure which one is used for the iterator.

Here is the related code portion (exception in the second SimEvent first = fit.next();):

    if (future.size() > 0) {
        List<SimEvent> toRemove = new ArrayList<SimEvent>();
        Iterator<SimEvent> fit = future.iterator();
        queue_empty = false;
        SimEvent first = fit.next();
        processEvent(first);
        future.remove(first);

        fit = future.iterator();

        // Check if next events are at same time...
        boolean trymore = fit.hasNext();
        while (trymore) {
            SimEvent next = fit.next();
            if (next.eventTime() == first.eventTime()) {
                processEvent(next);
                toRemove.add(next);
                trymore = fit.hasNext();
            } else {
                trymore = false;
            }
        }

        future.removeAll(toRemove);

    } else {...}
```

<p>EDIT: The hall code of <code>future</code> class:</p>

<pre class="lang-java prettyprint-override"><code>public class FutureQueue {

    /** The sorted set. */
    private final SortedSet<SimEvent> sortedSet = new TreeSet<SimEvent>();

    /** The serial. */
    private long serial = 0;

    /**
     * Add a new event to the queue. Adding a new event to the queue preserves the temporal order of
     * the events in the queue.
         *
     * @param newEvent The event to be put in the queue.
     */
    public void addEvent(SimEvent newEvent) {
        newEvent.setSerial(serial++);
        sortedSet.add(newEvent);
    }

    /**
    * Add a new event to the head of the queue.
    *
    * @param newEvent The event to be put in the queue.
    */
    public void addEventFirst(SimEvent newEvent) {
        newEvent.setSerial(0);
        sortedSet.add(newEvent);
    }

    /**
     * Returns an iterator to the queue.
     *
     * @return the iterator
     */
     public Iterator<SimEvent> iterator() {
        return sortedSet.iterator();
     }

    /**
     * Returns the size of this event queue.
     *
     * @return the size
     */
    public int size() {
        return sortedSet.size();
    }

    /**
     * Removes the event from the queue.
     *
     * @param event the event
     * @return true, if successful
     */
    public boolean remove(SimEvent event) {
        return sortedSet.remove(event);
    }

    /**
     * Removes all the events from the queue.
     *
     * @param events the events
     * @return true, if successful
     */
    public boolean removeAll(Collection<SimEvent> events) {
        return sortedSet.removeAll(events);
    }

    public void clear() {
        sortedSet.clear();
    }
}
</code>```

Any suggestion on how to proceed to debug this problem?

答:
EDITED: This is a common mistake. You cannot modify a collection directly (add or remove elements) when iterating through the collection using an Iterator. Removal, for example, must be done via the Iterator itself.

The correct way to do it is as follows (not a complete example, just to illustrate the point):

```<code>Iterator<SimEvent> fit = future.iterator();
while (fit.hasNext()) {
    SimEvent event = fit.next();
    processEvent(event);
    fit.remove();
}
</code>```

Watch for other threads that might add to or remove from the collection while you are iterating through it.

Body:
I have basic knowledge in Java and working currently on a Java based code.

EDIT: I didn't write the code

I am iterating over a sorted treemap of Event Objects and getting this exception when I am trying to get the next element:

java.util.ConcurrentModificationException
    at java.util.TreeMap$PrivateEntryIterator.nextEntry(Unknown Source)
    at java.util.TreeMap$KeyIterator.next(Unknown Source)

I think this should be due to the existence of mutiple entries with same value that are merged by the iterator comparator (be refering to this question, but I don't know how to find the keys used in the comparator. The object Event has many parameters (like id, time, etc)but not sure which one is used for the iterator.

Here is the related code portion (exception in the second SimEvent first = fit.next();):

    if (future.size() > 0) {
        List<SimEvent> toRemove = new ArrayList<SimEvent>();
        Iterator<SimEvent> fit = future.iterator();
        queue_empty = false;
        SimEvent first = fit.next();
        processEvent(first);
        future.remove(first);

        fit = future.iterator();

        // Check if next events are at same time...
        boolean trymore = fit.hasNext();
        while (trymore) {
            SimEvent next = fit.next();
            if (next.eventTime() == first.eventTime()) {
                processEvent(next);
                toRemove.add(next);
                trymore = fit.hasNext();
            } else {
                trymore = false;
            }
        }

        future.removeAll(toRemove);

    } else {...}

EDIT: The hall code of future class:

public class FutureQueue {

    /** The sorted set. */
    private final SortedSet<SimEvent> sortedSet = new TreeSet<SimEvent>();

    /** The serial. */
    private long serial = 0;

    /**
     * Add a new event to the queue. Adding a new event to the queue preserves the temporal order of
     * the events in the queue.
         *
     * @param newEvent The event to be put in the queue.
     */
    public void addEvent(SimEvent newEvent) {
        newEvent.setSerial(serial++);
        sortedSet.add(newEvent);
    }

    /**
    * Add a new event to the head of the queue.
    *
    * @param newEvent The event to be put in the queue.
    */
    public void addEventFirst(SimEvent newEvent) {
        newEvent.setSerial(0);
        sortedSet.add(newEvent);
    }

    /**
     * Returns an iterator to the queue.
     *
     * @return the iterator
     */
     public Iterator<SimEvent> iterator() {
        return sortedSet.iterator();
     }

    /**
     * Returns the size of this event queue.
     *
     * @return the size
     */
    public int size() {
        return sortedSet.size();
    }

    /**
     * Removes the event from the queue.
     *
     * @param event the event
     * @return true, if successful
     */
    public boolean remove(SimEvent event) {
        return sortedSet.remove(event);
    }

    /**
     * Removes all the events from the queue.
     *
     * @param events the events
     * @return true, if successful
     */
    public boolean removeAll(Collection<SimEvent> events) {
        return sortedSet.removeAll(events);
    }

    public void clear() {
        sortedSet.clear();
    }
}

Any suggestion on how to proceed to debug this problem?

Body:
EDITED: This is a common mistake. You cannot modify a collection directly (add or remove elements) when iterating through the collection using an Iterator. Removal, for example, must be done via the Iterator itself.

The correct way to do it is as follows (not a complete example, just to illustrate the point):

Iterator<SimEvent> fit = future.iterator();
while (fit.hasNext()) {
    SimEvent event = fit.next();
    processEvent(event);
    fit.remove();
}

Watch for other threads that might add to or remove from the collection while you are iterating through it.


问:
Angular ngRepeat - How to have multiple objects containing radio buttons
I am doing some updates to a clients Ionic app but stuck on some binding.

There is a form with some fields including a couple of radio buttons.

E.g.

```<code><div class="fields">
    <input ng-model="student.name" type="text" name="student_name" id="name" />

    <input ng-model="student.has_booked" type="radio" checked="checked" name="made_booking" id="made_booking_yes" value="1" />
</div>
</code>```

The request for the update is to have a button that duplicates the details in this first form and add its to an array where the details can be used for another student as they are normally similar.

To do this I have a button that calls this method:

```<code>$scope.additionalStudents = []; // <-- for context of question

$scope.duplicateStudentDetails = function() {
    var firstStudent = angular.copy($scope.student);
    $scope.additionalStudents.push(firstStudent);
}
</code>```

Then in my view:

```<code><div class="fields" ng-repeat="(key, student) in additionalStudents track by $index">
    <input ng-model="student.name" type="text" name="student_name" id="name" />

    <input ng-model="student.has_booked" type="radio" checked="checked" name="made_booking" id="made_booking_yes" value="1" />
</div>
</code>```

The issue I am having is that the name came be changed independently, but the checkbox always affects the original student. Im guessing this is because of the name attribute...

How do I go around this?

答:
There might be two solutions to your problem.

If your case is just to show the status and not to change the booking status

Then, remove name attribute

If you want change the booking status in future

Better to have input of type checkbox with different names

Body:
I am doing some updates to a clients Ionic app but stuck on some binding.

There is a form with some fields including a couple of radio buttons.

E.g.

    <input ng-model="student.name" type="text" name="student_name" id="name" />

    <input ng-model="student.has_booked" type="radio" checked="checked" name="made_booking" id="made_booking_yes" value="1" />

The request for the update is to have a button that duplicates the details in this first form and add its to an array where the details can be used for another student as they are normally similar.

To do this I have a button that calls this method:

$scope.additionalStudents = []; // <-- for context of question

$scope.duplicateStudentDetails = function() {
    var firstStudent = angular.copy($scope.student);
    $scope.additionalStudents.push(firstStudent);
}

Then in my view:

    <input ng-model="student.name" type="text" name="student_name" id="name" />

    <input ng-model="student.has_booked" type="radio" checked="checked" name="made_booking" id="made_booking_yes" value="1" />

The issue I am having is that the name came be changed independently, but the checkbox always affects the original student. Im guessing this is because of the name attribute...

How do I go around this?