问:
Possible to add Index to a javascript Object
Is it possible for me to create an Index into an Object? Here is my object:

```<code>var objName = {};
var array1 = ['apple','sugar'];
var array2 = ['spoon','fork'];
var array3 = ['spoon2','fork2'];
var array4 = ['spoon3','fork3'];

objName['main'] = array1;
objName['submain'] = array2;
objName['main'] = array3;
objName['submain'] = array4;

console.log(objName);
</code>```

question is, I want to add another value to the object without my previous object being erased. Assuming that the objName is a global object variable and I'm going to use it again and again and pushing different values into it. I am expecting an output where in I can see also my previous records.

JSFiddle

答:
Same key in single object is not working.so create the array and pass with objects same key name also

var objName = [];
var array1 = ['apple', 'sugar'];

var array2 = ['spoon', 'fork'];

var array3 = ['spoon2', 'fork2'];

var array4 = ['spoon3', 'fork3'];

objName.push({
  main: array1
});
objName.push({
  submain: array2
});
objName.push({
  main: array3
});
objName.push({
  main: array4
});
console.log(objName);```

Body:
Is it possible for me to create an Index into an Object? Here is my object:

var objName = {};
var array1 = ['apple','sugar'];
var array2 = ['spoon','fork'];
var array3 = ['spoon2','fork2'];
var array4 = ['spoon3','fork3'];

objName['main'] = array1;
objName['submain'] = array2;
objName['main'] = array3;
objName['submain'] = array4;

console.log(objName);

question is, I want to add another value to the object without my previous object being erased. Assuming that the objName is a global object variable and I'm going to use it again and again and pushing different values into it. I am expecting an output where in I can see also my previous records.

JSFiddle


来源: stackexchange

答:
I am assuming you wish to keep all the values you added already, so I added getter and setter for main``andsubmain` variables.

This will return the last entry when a new entry was added, and you would have some kind of history afterwards by the _main and _submain properties.

var objName = {
  get main() {
    if (this._main === undefined) {
      return undefined;
    }
    return this._main[this._main.length-1];
  },
  set main(value) {
    if (this._main === undefined) {
      this._main = [];
    }
    this._main.push( value );
  },
  get submain() {
    if (this._submain === undefined) {
      return undefined;
    }
    return this._submain[this._submain.length-1];
  },
  set submain(value) {
    if (this._submain === undefined) {
      this._submain = [];
    }
    this._submain.push( value );
  },
};
var array1 = ['apple','sugar'];
var array2 = ['spoon','fork'];
var array3 = ['spoon2','fork2'];
var array4 = ['spoon3','fork3'];

objName['main'] = array1;
objName['submain'] = array2;
objName['main'] = array3;
objName['submain'] = array4;

console.log(objName);```

ContentLicense: CC BY-SA 3.0

Title: Possible to add Index to a javascript Object


问:
How to overload << for a vector of structures
I'm having trouble with the syntax for a homework program. The prompt is to overload an inserter in such a way that it can properly execute the program fragment:

for (int i = 0; i < v.size(); ++i)
     cout << v[i] << endl;
cout << endl;

So, this is what I have so far, but I still get an error at the cout << v[i] statement (Invalid operands to binary expression):

```<code>    unsigned int seed;
    struct node
    {
         int integer;
         double value;
    };

    double random(unsigned int &seed);
    void initialize_vector(vector<node> &v);
    template<typename T>
    void print_vector(const vector<T> &v);
    template<typename T>
    ostream &operator <<(ostream &out, const vector<T> &v);
    template<typename T>
    void output(ostream &out, const vector<T> &v);

    int main()
    {
        vector<node> v(10);

        initialize_vector(v);
        print_vector(v);

        return 0;
    }

    double random(unsigned int &seed)
    {
        const int MODULUS = 15749;
        const int MULTIPLIER = 69069;
        const int INCREMENT = 1;

        seed = ((MULTIPLIER * seed) + INCREMENT) % MODULUS;

        return double(seed) / double(MODULUS);
    }

    void initialize_vector(vector<node> &v)
    {
        for (int i = 0; i < v.size(); ++i)
        {
            v[i].integer = int (11 * random(seed));
            v[i].value = double (11 * random(seed));
        }
    }

    template<typename T>
    void print_vector(const vector<T> &v)
    {
        for (int i = 0; i < v.size(); ++i)
            cout << v[i] << endl;
        cout << endl;
    }

    template<typename T>
    ostream &operator <<(ostream &out, const vector<T> &v)
    {
        output(out, v);
        return (out);
    }

    template<typename T>
    void output(ostream &out, const vector<T> &v)
    {
        cout << v.integer;
        cout << setprecision(2) << fixed << setw(6) << v.value;
    }
</code>```

I've tried passing node instead of T, along with passing with and without const references for the last 3 functions, so again I assume my syntax in the void output function is wrong somehow. Any help or points in the right direction would be greatly appreciated.

*Note: I can't change the ostream &operator function.

答:
```<code>  cout << v[i] << endl;
</code>```

If v is a vector of node, then you need one more function to overload operator << for a node

```<code>ostream &operator <<(ostream &out, const node &n)
{
    out << n.interger << " " << n.value;
    return out;
}
</code>```

Body:
I'm having trouble with the syntax for a homework program. The prompt is to overload an inserter in such a way that it can properly execute the program fragment:

for (int i = 0; i < v.size(); ++i)
     cout << v[i] << endl;
cout << endl;

So, this is what I have so far, but I still get an error at the cout << v[i] statement (Invalid operands to binary expression):

    unsigned int seed;
    struct node
    {
         int integer;
         double value;
    };

    double random(unsigned int &seed);
    void initialize_vector(vector<node> &v);
    template<typename T>
    void print_vector(const vector<T> &v);
    template<typename T>
    ostream &operator <<(ostream &out, const vector<T> &v);
    template<typename T>
    void output(ostream &out, const vector<T> &v);

    int main()
    {
        vector<node> v(10);

        initialize_vector(v);
        print_vector(v);

        return 0;
    }

    double random(unsigned int &seed)
    {
        const int MODULUS = 15749;
        const int MULTIPLIER = 69069;
        const int INCREMENT = 1;

        seed = ((MULTIPLIER * seed) + INCREMENT) % MODULUS;

        return double(seed) / double(MODULUS);
    }

    void initialize_vector(vector<node> &v)
    {
        for (int i = 0; i < v.size(); ++i)
        {
            v[i].integer = int (11 * random(seed));
            v[i].value = double (11 * random(seed));
        }
    }

    template<typename T>
    void print_vector(const vector<T> &v)
    {
        for (int i = 0; i < v.size(); ++i)
            cout << v[i] << endl;
        cout << endl;
    }

    template<typename T>
    ostream &operator <<(ostream &out, const vector<T> &v)
    {
        output(out, v);
        return (out);
    }

    template<typename T>
    void output(ostream &out, const vector<T> &v)
    {
        cout << v.integer;
        cout << setprecision(2) << fixed << setw(6) << v.value;
    }

I've tried passing node instead of T, along with passing with and without const references for the last 3 functions, so again I assume my syntax in the void output function is wrong somehow. Any help or points in the right direction would be greatly appreciated.

*Note: I can't change the ostream &operator function.

Body:
  cout << v[i] << endl;

If v is a vector of node, then you need one more function to overload operator << for a node

ostream &operator <<(ostream &out, const node &n)
{
    out << n.interger << " " << n.value;
    return out;
}


问:
Optimize a function call with array index
I have a function with the following prototype:

```<code>def fun(signal,const):
    n = len(signal);
    index = np.arange(n);
    F = np.sum(signal*np.exp((-2*np.pi*np.complex(1j)*const*index)/n));
    return F;
</code>```

The end result I would like to have is the output of:

```<code>for i in np.arange(4):
    out[i] = fun(inp,i)
</code>```

How could I get this result without the loop and without vectorize fo a lambda function since my understanding is that vectorize uses also a loop. I am looking for a function from the numpy family to achieve this.

I tried the following without luck:

```<code>b= np.array([0,1,2,3]);
print(fun(inp,b));
</code>```

The problem with the above is it passes the entire array where what I need is passing just the current index.

答:
With one little change fun can work with a array const; add axis parameter to the sum:

```<code>def fun(signal,const):
    n = len(signal);
    index = np.arange(n);
    F = np.sum(signal*np.exp((-2*np.pi*np.complex(1j)*const*index)/n),axis=-1);
    return F;

In [126]: signal = np.arange(10)*.1
In [139]: for i in range(4):
     ...:     print(fun(signal,i))
(4.5+0j)
(-0.5+1.53884176859j)
(-0.5+0.688190960236j)
(-0.5+0.363271264003j)
</code>```

I generate the same numbers by providing a column vector:

```<code>In [142]: fun(signal, np.arange(4)[:,None])
Out[142]:
array([ 4.5+0.j        , -0.5+1.53884177j, -0.5+0.68819096j,
       -0.5+0.36327126j])
</code>```

This const multiplies with index to produce a (4,n) array:

```<code>In [143]: np.arange(4)[:,None]*np.arange(10)
Out[143]:
array([[ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18],
       [ 0,  3,  6,  9, 12, 15, 18, 21, 24, 27]])
</code>```

That multplies the other scalars and the (n,) signal, staying (4,n).  Sum on the last dimension, and the result is a (4,) array.

I explained this way of thinking recently in:

How do I shift my thinking to 'vectorize my computation' more than using 'for-loops'?

Body:
I have a function with the following prototype:

def fun(signal,const):
    n = len(signal);
    index = np.arange(n);
    F = np.sum(signal*np.exp((-2*np.pi*np.complex(1j)*const*index)/n));
    return F;

The end result I would like to have is the output of:

for i in np.arange(4):
    out[i] = fun(inp,i)

How could I get this result without the loop and without vectorize fo a lambda function since my understanding is that vectorize uses also a loop. I am looking for a function from the numpy family to achieve this.

I tried the following without luck:

b= np.array([0,1,2,3]);
print(fun(inp,b));

The problem with the above is it passes the entire array where what I need is passing just the current index.

Body:
With one little change fun can work with a array const; add axis parameter to the sum:

def fun(signal,const):
    n = len(signal);
    index = np.arange(n);
    F = np.sum(signal*np.exp((-2*np.pi*np.complex(1j)*const*index)/n),axis=-1);
    return F;

In [126]: signal = np.arange(10)*.1
In [139]: for i in range(4):
     ...:     print(fun(signal,i))
(4.5+0j)
(-0.5+1.53884176859j)
(-0.5+0.688190960236j)
(-0.5+0.363271264003j)

I generate the same numbers by providing a column vector:

In [142]: fun(signal, np.arange(4)[:,None])
Out[142]:
array([ 4.5+0.j        , -0.5+1.53884177j, -0.5+0.68819096j,
       -0.5+0.36327126j])

This const multiplies with index to produce a (4,n) array:

In [143]: np.arange(4)[:,None]*np.arange(10)
Out[143]:
array([[ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18],
       [ 0,  3,  6,  9, 12, 15, 18, 21, 24, 27]])

That multplies the other scalars and the (n,) signal, staying (4,n).  Sum on the last dimension, and the result is a (4,) array.

I explained this way of thinking recently in:

How do I shift my thinking to 'vectorize my computation' more than using 'for-loops'?


问:
PHP Automated Deployment and Testing
I asked a question here on automated deployment of automatically deploying java code.

Our back-end Java API is accessed by a PHP web app. It would be nice to be able to automatically deploy this web app (along with static files like CSS, JS and images) to our web server while performing automatic testing on PHP code. Is there something similar to this for PHP?

I also wonder if as part of this automated testing you can check that each actual page loads without a fatal error. I am sure I read about a google project which allows you to write page tests e.g. click on link a, go to page b etc etc.

Thanks

答:
Since you're working with Java, you might consider using Hudson (also mentioned in your other question), which has the ability to execute build tasks consisting of several 'steps' One step step could be unit testing your Java App, another unit testing a PHP app, yet another deployinhg Java app, and another deploying a PHP app (and you could add some more ;P )

It has a Maven plugin, so you could actually use your existing Maven scripts.

ContentLicense: CC BY-SA 2.5

Title: PHP Automated Deployment and Testing


问:
Deploy Angular 4 App on Apache Webserver
I want to deploy my Angular Application on my Apache Webserver. I already added a .htaccess file to my /var/www/html folder, I tried several base-hrefs. But like many people I have problems with routing. I can only see my Startpage, but when I want to get to a other URL it fails. What else can I try or have I missed something?

答:
You have to enable/install the Apache mod_rewrite module, and then put this in either your .htaccess or your apache configuration for your site:

```<code><IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>
</code>```

Body:
You have to enable/install the Apache mod_rewrite module, and then put this in either your .htaccess or your apache configuration for your site:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>


问:
return self.user as foreignkey
I have a model with foreignkeys. For this model I want to set the 'def str' as the user.

I have done this

```<code>from django.contrib.auth import get_user_model

User = get_user_model()

class Rosters(models.Model):
        place = models.ForeignKey('Places')
        position = models.ForeignKey('Positions', blank=True, null=True)
        user = models.ForeignKey(User, related_name='roster')
        validfrom = models.DateTimeField(blank=True, null=True)
        validto = models.DateTimeField(blank=True, null=True)

        def __str__(self):
            return self.user
</code>```

This will fetch username and show in admin pages. But when I try to create a new Roster. I get a TypeError __str__ returned non-string (type User)

I can remove the 'def str...' and create a Roster with no problem. But each Roster shows as Object in admin pages. So I can add back the 'def str..' to see the usernames of each roster.

I want them to always display as usernames. And I can't figure out why it's not working when I'm adding rosters.

答:
You need to show the attribute of the user that you wish to display

```<code>def __str__(self):
   return self.user
</code>```

should return any of the following (or similar)

```<code>return str(self.user)
return self.user.get_username()
return self.user.get_full_name()
</code>```

Title: return self.user as foreignkey

Body:
I have a model with foreignkeys. For this model I want to set the 'def str' as the user.

I have done this

from django.contrib.auth import get_user_model

User = get_user_model()

class Rosters(models.Model):
        place = models.ForeignKey('Places')
        position = models.ForeignKey('Positions', blank=True, null=True)
        user = models.ForeignKey(User, related_name='roster')
        validfrom = models.DateTimeField(blank=True, null=True)
        validto = models.DateTimeField(blank=True, null=True)

        def __str__(self):
            return self.user

This will fetch username and show in admin pages. But when I try to create a new Roster. I get a TypeError __str__ returned non-string (type User)

I can remove the 'def str...' and create a Roster with no problem. But each Roster shows as Object in admin pages. So I can add back the 'def str..' to see the usernames of each roster.

I want them to always display as usernames. And I can't figure out why it's not working when I'm adding rosters.

Body:
You need to show the attribute of the user that you wish to display

def __str__(self):
   return self.user

should return any of the following (or similar)

return str(self.user)
return self.user.get_username()
return self.user.get_full_name()


问:
SQL Query to find out specific column from all database
I wanted to find out the columns which contains the word "VAP" or cancellation. but the problem is we have several number of databases in our server. I wanted to know in which database/table contains the columns name which consist these words. Can anyone let us know if there is any query which can be used to search column name from all databases? I have tried below query but it will only help to find from a single database.</p>

```<code>select distinct
    t.name as TableName,
    SCHEMA_NAME(t.schema_id)   as TableSchema,
    c.name as ColumnName,
    ct.name as ColumnDataType,
    c.is_nullable as IsNullable
from
    sys.tables t with(nolock)
inner join
    sys.columns c with(nolock) on t.object_id = c.object_id
inner join
    sys.types ct with(nolock) on ct.system_type_id = c.system_type_id
where
    c.name like '%VAP%'
order by
    t.name
</code>```

答:
Use sp_MSForeachdb for getting details. Try below query.</p>

```<code>-------------------------

create table #temp
(dbname varchar(100),
tablename varchar(100)
)

EXECUTE master..sp_MSForeachdb '
USE [?]
IF ''?'' <> ''master'' AND ''?'' <> ''model'' AND ''?'' <> ''msdb'' AND ''?'' <> ''tempdb''
BEGIN

IF (EXISTS (SELECT *
                 FROM INFORMATION_SCHEMA.columns where COLUMN_NAME = ''VAP''))
BEGIN
insert into #temp
select ''?'',table_name FROM INFORMATION_SCHEMA.columns where COLUMN_NAME = ''VAP''

end

END
'

select * from #temp
</code>```

Body:
I wanted to find out the columns which contains the word "VAP" or cancellation. but the problem is we have several number of databases in our server. I wanted to know in which database/table contains the columns name which consist these words. Can anyone let us know if there is any query which can be used to search column name from all databases? I have tried below query but it will only help to find from a single database.

select distinct
    t.name as TableName,
    SCHEMA_NAME(t.schema_id)   as TableSchema,
    c.name as ColumnName,
    ct.name as ColumnDataType,
    c.is_nullable as IsNullable
from
    sys.tables t with(nolock)
inner join
    sys.columns c with(nolock) on t.object_id = c.object_id
inner join
    sys.types ct with(nolock) on ct.system_type_id = c.system_type_id
where
    c.name like '%VAP%'
order by
    t.name

Body:
Use sp_MSForeachdb for getting details. Try below query.

-------------------------

create table #temp
(dbname varchar(100),
tablename varchar(100)
)

EXECUTE master..sp_MSForeachdb '
USE [?]
IF ''?'' <> ''master'' AND ''?'' <> ''model'' AND ''?'' <> ''msdb'' AND ''?'' <> ''tempdb''
BEGIN

IF (EXISTS (SELECT *
                 FROM INFORMATION_SCHEMA.columns where COLUMN_NAME = ''VAP''))
BEGIN
insert into #temp
select ''?'',table_name FROM INFORMATION_SCHEMA.columns where COLUMN_NAME = ''VAP''

end

END
'

select * from #temp

ContentLicense: CC BY-SA 4.0


答:
You can check if your object contains a given key, then you can array#concat your array, otherwise simply assign array to that key.

obj[name] = obj[name] ? obj[name].concat(array) : array;
where obj is your object, name is the name of your key and array is the new array you want to add.

var objName = {};
var array1 = ['apple','sugar'];
var array2 = ['spoon','fork'];
var array3 = ['spoon2','fork2'];
var array4 = ['spoon3','fork3'];

var addInObject = function(obj, name, array){
  obj[name] = obj[name] ? obj[name].concat(array) : array;
}

addInObject(objName, 'main', array1);
addInObject(objName, 'submain', array2);
addInObject(objName, 'main', array3);
addInObject(objName, 'submain', array4);

console.log(objName);```


问:
Tagret parent of parent on click Javascript
I have the following html:

```<code><div class="parent-portlet
     ng-mouseenter="hoverIn($event)" ng-mouseleave="hoverOut($event)">
    <div class="portlet-titlebar" ng-click="toggleCollapsed($event)">
        <span class="remove" ng-click="removePortlet()">
               Remove
        </span>
        <span class="add-back" ng-click="addPortlet()">
               Add Back
        </span>
    </div>
</div>
</code>```

I want to somehow catch the "parent-portlet" element when either of the spans are clicked. That is the parent of their parent. Is there a way similar to:

angular.element(event.currentTarget).parentElement();

to do that, but for the parent of the parent?

Thanks in advance.

答:
Here you go with a solution using jQuery

$('span').click(function(){
  console.log($(this).closest('div.parent-portlet').attr('class'));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent-portlet
     ng-mouseenter="hoverIn($event)" ng-mouseleave="hoverOut($event)">
    <div class="portlet-titlebar" ng-click="toggleCollapsed($event)">
        <span class="remove">
               Remove
        </span>
        <span class="add-back">
               Add Back
        </span>
    </div>
</div></code>```

Hope this will help you.

Body:
I have the following html:

               Remove

               Add Back

I want to somehow catch the "parent-portlet" element when either of the spans are clicked. That is the parent of their parent. Is there a way similar to:

angular.element(event.currentTarget).parentElement();

to do that, but for the parent of the parent?

Thanks in advance.

Body:
Here you go with a solution using jQuery

$('span').click(function(){
  console.log($(this).closest('div.parent-portlet').attr('class'));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent-portlet
     ng-mouseenter="hoverIn($event)" ng-mouseleave="hoverOut($event)">
    <div class="portlet-titlebar" ng-click="toggleCollapsed($event)">
        <span class="remove">
               Remove
        </span>
        <span class="add-back">
               Add Back
        </span>
    </div>
</div>

Hope this will help you.


问:
How to include single row multiple column subquery (PIPELINED function) results in the result set
I am using Oracle 11g.

So, lets say that I have a test data table like this one

```<code>with test_data as (
    select 1 as id, 'John' as name from dual
        union all
    select 2 as id, 'Jack' as name from dual
        union all
    select 3 as id, 'Peter' as name from dual
)
</code>```

Also I have a piplined function that returns one row per call, with multiple columns like the following:

```<code>CREATE OR REPLACE PACKAGE MY_PACK AS
  TYPE result_record is RECORD(
   surname           varchar2(27),
   telephone          varchar2(50),
   place_of_birth     varchar2(50)
       );

  TYPE result_table IS TABLE OF result_record;
  function runPipe(id number) RETURN result_table PIPELINED;
END ERC_PACK;
/

CREATE OR REPLACE PACKAGE BODY MY_PACK AS
    function runPipe(id number) RETURN result_table PIPELINED IS
    rec           result_record:=null;
    begin
       if  (id=1) then
         select 'Smih','139289289','Paris' into rec from dual;
       end if;
       if  (id=2) then
         select 'Lock','1888888888','London' into rec from dual;
       end if;
       if  (id=3) then
         select 'May','99999999999','Berlin' into rec from dual;
       end if;
       pipe row (rec);
       return;
  end;
END ERC_PACK;
/
</code>```

And of course the

```<code>select * from table(MY_PACK.runPipe(1))
</code>```

returns

```<code>Smih    139289289   Paris
</code>```

Now I would like a select statement that will return all the rows of the test_data  along with the corresponding values from pipeline function

e.g. something like

```<code>select test_data.*, (select * from table(MY_PACK.runPipe(id))) from test_data
</code>```

which of course doses not work
but the expected results would be something like:

```<code>1 John  Smih    139289289   Paris
2 Jack  Lock    1888888888  London
3 Peter May     99999999999 Berlin
</code>```

So how to achieve the above expected result, given the test_data table and the pipelined function?

答:
You could use OUTER APPLY:

```<code>select td.*, s.*
from test_data td
outer apply (select * from table(MY_PACK.runPipe(td.id))) s
</code>```

Body:
I am using Oracle 11g.

So, lets say that I have a test data table like this one

with test_data as (
    select 1 as id, 'John' as name from dual
        union all
    select 2 as id, 'Jack' as name from dual
        union all
    select 3 as id, 'Peter' as name from dual
)

Also I have a piplined function that returns one row per call, with multiple columns like the following:

CREATE OR REPLACE PACKAGE MY_PACK AS
  TYPE result_record is RECORD(
   surname           varchar2(27),
   telephone          varchar2(50),
   place_of_birth     varchar2(50)
       );

  TYPE result_table IS TABLE OF result_record;
  function runPipe(id number) RETURN result_table PIPELINED;
END ERC_PACK;
/

CREATE OR REPLACE PACKAGE BODY MY_PACK AS
    function runPipe(id number) RETURN result_table PIPELINED IS
    rec           result_record:=null;
    begin
       if  (id=1) then
         select 'Smih','139289289','Paris' into rec from dual;
       end if;
       if  (id=2) then
         select 'Lock','1888888888','London' into rec from dual;
       end if;
       if  (id=3) then
         select 'May','99999999999','Berlin' into rec from dual;
       end if;
       pipe row (rec);
       return;
  end;
END ERC_PACK;
/

And of course the

select * from table(MY_PACK.runPipe(1))

returns

Smih    139289289   Paris

Now I would like a select statement that will return all the rows of the test_data  along with the corresponding values from pipeline function

e.g. something like

select test_data.*, (select * from table(MY_PACK.runPipe(id))) from test_data

which of course doses not work
but the expected results would be something like:

1 John  Smih    139289289   Paris
2 Jack  Lock    1888888888  London
3 Peter May     99999999999 Berlin

So how to achieve the above expected result, given the test_data table and the pipelined function?

Body:
You could use OUTER APPLY:

select td.*, s.*
from test_data td
outer apply (select * from table(MY_PACK.runPipe(td.id))) s


问:
HTML5 application manifest not clearing cache on manifest change
I have a rails app that I'm trying to get using HTML5 application caching using Rack::Offline. The application.manifest file is set up and is being downloaded and checked by my HTML page.
The manifest looks as follows:

```<code>CACHE MANIFEST
# 2d9bf2b03a07dc960fd8fe69659ceeffd4d28ccf8619669a506c3682bf223878
404.html
422.html
500.html
login.html
stylesheets/scaffold.css
javascripts/jquery.min.js
javascripts/jquery.js
javascripts/application.js
javascripts/rmbz.js
javascripts/rails.js
images/rails.png

NETWORK:
/
</code>```

The page I'm accessing is localhost:3000/mobile, and it has cached wonderfully (viewable when I take down the rails server).  However, the application.manifest file that it references has changed (in fact it changes with each request by manipulating the commented hexadecimal id), but Chrome is not updating the page.  The console log in Chrome gives the following:

```<code>Document was loaded from Application Cache with manifest http://localhost:3000/application.manifest
Application Cache Checking event
Application Cache Downloading event
Application Cache Progress event (0 of 12) http://localhost:3000/login.html
Application Cache Progress event (1 of 12) http://localhost:3000/404.html
Application Cache Progress event (2 of 12) http://localhost:3000/422.html
Application Cache Progress event (3 of 12) http://localhost:3000/javascripts/rails.js
Application Cache Progress event (4 of 12) http://localhost:3000/javascripts/rmbz.js
Application Cache Progress event (5 of 12) http://localhost:3000/images/rails.png
Application Cache Progress event (6 of 12) http://localhost:3000/500.html
Application Cache Progress event (7 of 12) http://localhost:3000/javascripts/jquery.js
Application Cache Progress event (8 of 12) http://localhost:3000/stylesheets/scaffold.css
Application Cache Progress event (9 of 12) http://localhost:3000/javascripts/jquery.min.js
Application Cache Progress event (10 of 12) http://localhost:3000/mobile
Application Cache Progress event (11 of 12) http://localhost:3000/javascripts/application.js
Application Cache Error event: Manifest changed during update, scheduling retry
</code>```

I don't quite understand why it's failing. It seems to be doing everything it should until the last line! I get a similar log if I navigate in my browser to localhost:3000/application.manifest - it seems that the manifest is cached itself, so could that be why it complains that the manifest has changed?  Any ideas?

Thanks!

答: The last file requested by Chrome is application.manifest, if this has changed since the original request (as you say it has) then that invalidates the cache.  You need to keep the manifest unchanged until one of the files listed in the manifest has changed.

Body:
I have a rails app that I'm trying to get using HTML5 application caching using Rack::Offline. The application.manifest file is set up and is being downloaded and checked by my HTML page.
The manifest looks as follows:

CACHE MANIFEST
# 2d9bf2b03a07dc960fd8fe69659ceeffd4d28ccf8619669a506c3682bf223878
404.html
422.html
500.html
login.html
stylesheets/scaffold.css
javascripts/jquery.min.js
javascripts/jquery.js
javascripts/application.js
javascripts/rmbz.js
javascripts/rails.js
images/rails.png

NETWORK:
/

The page I'm accessing is localhost:3000/mobile, and it has cached wonderfully (viewable when I take down the rails server).  However, the application.manifest file that it references has changed (in fact it changes with each request by manipulating the commented hexadecimal id), but Chrome is not updating the page.  The console log in Chrome gives the following:

Document was loaded from Application Cache with manifest http://localhost:3000/application.manifest
Application Cache Checking event
Application Cache Downloading event
Application Cache Progress event (0 of 12) http://localhost:3000/login.html
Application Cache Progress event (1 of 12) http://localhost:3000/404.html
Application Cache Progress event (2 of 12) http://localhost:3000/422.html
Application Cache Progress event (3 of 12) http://localhost:3000/javascripts/rails.js
Application Cache Progress event (4 of 12) http://localhost:3000/javascripts/rmbz.js
Application Cache Progress event (5 of 12) http://localhost:3000/images/rails.png
Application Cache Progress event (6 of 12) http://localhost:3000/500.html
Application Cache Progress event (7 of 12) http://localhost:3000/javascripts/jquery.js
Application Cache Progress event (8 of 12) http://localhost:3000/stylesheets/scaffold.css
Application Cache Progress event (9 of 12) http://localhost:3000/javascripts/jquery.min.js
Application Cache Progress event (10 of 12) http://localhost:3000/mobile
Application Cache Progress event (11 of 12) http://localhost:3000/javascripts/application.js
Application Cache Error event: Manifest changed during update, scheduling retry

I don't quite understand why it's failing. It seems to be doing everything it should until the last line! I get a similar log if I navigate in my browser to localhost:3000/application.manifest - it seems that the manifest is cached itself, so could that be why it complains that the manifest has changed?  Any ideas?

Thanks!


问:
How to make changes in script files like widget.js , store,js and make them reflecting in the store of Aurora JQuery Store?
I am using Aurora JQuery Store (WCS 8), I want to make changes in the java script files (widget.js, store.js , vendor.js) but when i make make changes directly in those files its not getting reflected. Please explain the flow of making changes in the script files of WCS 8 - Aurora JQuery Store.</p>

答:
Have a look at the overall picture here: jQuery Aurora starter store

There is a build/re-build stage involved to combine, minify, etc. JS & CSS (step 3).


问:
Why am i getting this error in logcat (Android)?

FATAL EXCEPTION: main
                                                                         Process: org.example.easyparking, PID: 6371
                                                                         java.lang.RuntimeException: Unable to start activity
  ComponentInfo{org.example.easyparking/org.example.easyparking.MapActivity}:
  android.view.InflateException: Binary XML file line #0: Binary XML
  file line #0: Error inflating class fragment

This is my mapactivity

```<code>    package org.example.easyparking;
    import android.app.Dialog;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.Toast;

    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.GoogleApiAvailability;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.MapFragment;
    import com.google.android.gms.maps.OnMapReadyCallback;

    public class MapActivity extends AppCompatActivity implements
    OnMapReadyCallback {

    GoogleMap mGoogleMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    if(googleServicesAvailable()){

        setContentView(R.layout.activity_map);
        initMap();
    }else{
        //No Google Map Layout
    }
}

private void initMap() {
    MapFragment mapFragment = (MapFragment) getFragmentManager().
            findFragmentById(R.id.mapFragment);
    mapFragment.getMapAsync(this);
}

public boolean googleServicesAvailable(){
    GoogleApiAvailability api = GoogleApiAvailability.getInstance();
    int isAvailable = api.isGooglePlayServicesAvailable(this);
    if(isAvailable == ConnectionResult.SUCCESS){
        return true;
    }else if (api.isUserResolvableError(isAvailable)){
        Dialog dialog = api.getErrorDialog(this, isAvailable, 0);
        dialog.show();
    }else{
        Toast.makeText(this, "Can't connect", Toast.LENGTH_LONG)
                .show();
    }
    return false;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;
}
}
</code>```

This is menifest

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.example.easyparking">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<permission android:name="org.example.easyparking.permission.MAP_RECEIVE"
    android:protectionLevel="signature"/>

<uses-permission android:name="org.example.easyparking.permission.MAP_RECEIVE"/>
<uses-permission android:name="com.google.android.providers.gsf.permissions.READ_GSERVICES"/>

<uses-feature android:glEsVersion="0x00020000"
    android:required="true"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".FirstActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".MapActivity" />

    <activity
        android:name=".SecondActivity">

    </activity>

    <meta-data android:name="com.google.android.maps.v2.API_KEY"
        android:value="AIzaSyDGpV3ndPQ1Z4zf1nXi5AW1c7jGPL1La7Q"/>

    <meta-data android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version"/>

</application>
</manifest>
</code>```

This is the first activity

```<code>    package org.example.easyparking;
    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;

public class FirstActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_first);
    Button button = (Button) this.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Toast.makeText(getApplicationContext(),
                    "Make sure that your location is turned on",
                    Toast.LENGTH_LONG).show();

            Intent newacti = new Intent(FirstActivity.this, MapActivity.class);
            startActivity(newacti);
        }
    });

    Button button_parking_owner = (Button) this.findViewById(R.id.button2);
    button_parking_owner.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent newacti = new Intent(FirstActivity.this, SecondActivity.class);
            startActivity(newacti);
        }
    });
}
}
</code>```

答:
In your MapActivity you are checking if googleServicesAvailable() is available and if not you are not providing a default content to render

```<code>if(googleServicesAvailable()){

        setContentView(R.layout.activity_map);
        initMap();
    }else{
        //No Google Map Layout
    }
</code>```

try creating a basic layout to render that says something like No Google Map
i.e you should have something like

```<code>if(googleServicesAvailable()){

        setContentView(R.layout.activity_map);
        initMap();
    }else{
        //No Google Map Layout
        setContentView(R.layout.no_activity_map);
    }
</code>```

then create a no_activity_map layout

Body:
FATAL EXCEPTION: main
                                                                         Process: org.example.easyparking, PID: 6371
                                                                         java.lang.RuntimeException: Unable to start activity
  ComponentInfo{org.example.easyparking/org.example.easyparking.MapActivity}:
  android.view.InflateException: Binary XML file line #0: Binary XML
  file line #0: Error inflating class fragment

This is my mapactivity

    package org.example.easyparking;
    import android.app.Dialog;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.Toast;

    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.GoogleApiAvailability;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.MapFragment;
    import com.google.android.gms.maps.OnMapReadyCallback;

    public class MapActivity extends AppCompatActivity implements
    OnMapReadyCallback {

    GoogleMap mGoogleMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    if(googleServicesAvailable()){

        setContentView(R.layout.activity_map);
        initMap();
    }else{
        //No Google Map Layout
    }
}

private void initMap() {
    MapFragment mapFragment = (MapFragment) getFragmentManager().
            findFragmentById(R.id.mapFragment);
    mapFragment.getMapAsync(this);
}

public boolean googleServicesAvailable(){
    GoogleApiAvailability api = GoogleApiAvailability.getInstance();
    int isAvailable = api.isGooglePlayServicesAvailable(this);
    if(isAvailable == ConnectionResult.SUCCESS){
        return true;
    }else if (api.isUserResolvableError(isAvailable)){
        Dialog dialog = api.getErrorDialog(this, isAvailable, 0);
        dialog.show();
    }else{
        Toast.makeText(this, "Can't connect", Toast.LENGTH_LONG)
                .show();
    }
    return false;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;
}
}

This is menifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.example.easyparking">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<permission android:name="org.example.easyparking.permission.MAP_RECEIVE"
    android:protectionLevel="signature"/>

<uses-permission android:name="org.example.easyparking.permission.MAP_RECEIVE"/>
<uses-permission android:name="com.google.android.providers.gsf.permissions.READ_GSERVICES"/>

<uses-feature android:glEsVersion="0x00020000"
    android:required="true"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".FirstActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".MapActivity" />

    <activity
        android:name=".SecondActivity">

    </activity>

    <meta-data android:name="com.google.android.maps.v2.API_KEY"
        android:value="AIzaSyDGpV3ndPQ1Z4zf1nXi5AW1c7jGPL1La7Q"/>

    <meta-data android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version"/>

</application>
</manifest>

This is the first activity

    package org.example.easyparking;
    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;

public class FirstActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_first);
    Button button = (Button) this.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Toast.makeText(getApplicationContext(),
                    "Make sure that your location is turned on",
                    Toast.LENGTH_LONG).show();

            Intent newacti = new Intent(FirstActivity.this, MapActivity.class);
            startActivity(newacti);
        }
    });

    Button button_parking_owner = (Button) this.findViewById(R.id.button2);
    button_parking_owner.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent newacti = new Intent(FirstActivity.this, SecondActivity.class);
            startActivity(newacti);
        }
    });
}
}

Body:
In your MapActivity you are checking if googleServicesAvailable() is available and if not you are not providing a default content to render

if(googleServicesAvailable()){

        setContentView(R.layout.activity_map);
        initMap();
    }else{
        //No Google Map Layout
    }

try creating a basic layout to render that says something like No Google Map
i.e you should have something like

if(googleServicesAvailable()){

        setContentView(R.layout.activity_map);
        initMap();
    }else{
        //No Google Map Layout
        setContentView(R.layout.no_activity_map);
    }

then create a no_activity_map layout


问:
read .txt file content into php multi dimensional array
I have a .txt file with content like this

Abuja, the Federal Capital Territory has -- -- -- -- -- area Council

A. 4

B. 6

C. 7

D. 2

ANSWER: B

The Federal Capital Territory is associated with-- -- -- -- -- -- -- vegetation belt

A. Sahel savanna

B. Rainforest

C. Guinea savanna

D. Sudan savanna

ANSWER: C

The most significant factor responsible for the ever increasing population of FCT is

A. High birth rate

B. Immigration

C. Death rate

D. CENSUS

ANSWER: B

i would love to read the file content into a multi dimensional array so i can get each questions, its answers and the correct answer for each of the questions.

i have tried this:-

```<code>$array=explode("\n", file_get_contents('file.txt'));
print_r($array);
</code>```

but it doesn't give me what i want..

答:
Alives answer gives a result that you probably can work with, but I think associative array is probably the way to go.

I look at each line to see if it has a question number => add new item in array with question number and question text.

If first char is letter and second is a dot, it's an answer => add answer letter as key and text as value.

If it's none of above it's the answer text => add key with ANSWER and value as the correct answer.

I use explode to split the lines. The third argument tells how many parts to split the string in.

With "2" it splits at first space meaning I have the question# as item 1 and question text as item 2 in the array.

https://3v4l.org/ZqppN

```<code>// $str = file_get_contents("text.txt");
$str = "1. Abuja, the Federal Capital Territory has -- -- -- -- -- area Council
A. 4
B. 6
C. 7
D. 2
ANSWER: B

2. The Federal Capital Territory is associated with-- -- -- -- -- -- -- vegetation belt
A. Sahel savanna
B. Rainforest
C. Guinea savanna
D. Sudan savanna
ANSWER: C

3. The most significant factor responsible for the ever increasing population of FCT is
A. High birth rate
B. Immigration
C. Death rate
D. CENSUS
ANSWER: B";

$arr = explode("\n", $str);

$res=[];

Foreach($arr as $line){
    If($line != ""){
        If(is_numeric($line[0])){
            Preg_match("/^\d+/", $line, $num);
            $res[$num[0]] =["QUESTION" =>explode(" ", $line,2)[1]];
            $q = $num[0];
        }Else if(ctype_alpha($line[0]) && $line[1] == "."){
            $res[$q][$line[0]] = explode(" ", $line, 2)[1];
        }Else{
            $res[$q]["ANSWER"] = trim(explode(":", $line, 2)[1]);
        }
    }
}

Var_dump($res);
</code>```

Body:
I have a .txt file with content like this

Abuja, the Federal Capital Territory has -- -- -- -- -- area Council

A. 4

B. 6

C. 7

D. 2

ANSWER: B

The Federal Capital Territory is associated with-- -- -- -- -- -- -- vegetation belt

A. Sahel savanna

B. Rainforest

C. Guinea savanna

D. Sudan savanna

ANSWER: C

The most significant factor responsible for the ever increasing population of FCT is

A. High birth rate

B. Immigration

C. Death rate

D. CENSUS

ANSWER: B

i would love to read the file content into a multi dimensional array so i can get each questions, its answers and the correct answer for each of the questions.

i have tried this:-

$array=explode("\n", file_get_contents('file.txt'));
print_r($array);

but it doesn't give me what i want..

Body:
Alives answer gives a result that you probably can work with, but I think associative array is probably the way to go.

I look at each line to see if it has a question number => add new item in array with question number and question text.

If first char is letter and second is a dot, it's an answer => add answer letter as key and text as value.

If it's none of above it's the answer text => add key with ANSWER and value as the correct answer.

I use explode to split the lines. The third argument tells how many parts to split the string in.

With "2" it splits at first space meaning I have the question# as item 1 and question text as item 2 in the array.

https://3v4l.org/ZqppN

// $str = file_get_contents("text.txt");
$str = "1. Abuja, the Federal Capital Territory has -- -- -- -- -- area Council
A. 4
B. 6
C. 7
D. 2
ANSWER: B

2. The Federal Capital Territory is associated with-- -- -- -- -- -- -- vegetation belt
A. Sahel savanna
B. Rainforest
C. Guinea savanna
D. Sudan savanna
ANSWER: C

3. The most significant factor responsible for the ever increasing population of FCT is
A. High birth rate
B. Immigration
C. Death rate
D. CENSUS
ANSWER: B";

$arr = explode("\n", $str);

$res=[];

Foreach($arr as $line){
    If($line != ""){
        If(is_numeric($line[0])){
            Preg_match("/^\d+/", $line, $num);
            $res[$num[0]] =["QUESTION" =>explode(" ", $line,2)[1]];
            $q = $num[0];
        }Else if(ctype_alpha($line[0]) && $line[1] == "."){
            $res[$q][$line[0]] = explode(" ", $line, 2)[1];
        }Else{
            $res[$q]["ANSWER"] = trim(explode(":", $line, 2)[1]);
        }
    }
}

Var_dump($res);


问:
XUnit Assert.IsType() with multiple expected types
I need to check one from three possible types of exceptions. If one of these exceptions thrown, the test considered passed. I'm using [Theory] and [MemberData] for several scenarios.

```<code>[Theory]
[MemberData(nameof(GetInvalidMimeMessages))]
public async Task ProcessAsync_TestFail(MimeMessage message)
{
    var stub = Mock.Of<IOptions<ScrapyardFilesOptions>>(s => s.Value.ConnectionString == "UseDevelopmentStorage=true" && s.Value.Container == "exchange");
    var loggerMock = new Mock<ILogger<ScrapyardFilesHandler>>(MockBehavior.Loose);
    var scrapyard = new ScrapyardFilesHandler(loggerMock.Object, stub);
    var ex = await Assert.ThrowsAnyAsync<Exception>(() => scrapyard.ProcessAsync(message));

    // imagine solution somehow like that
    Assert.IsType(
                    {
                      typeof(NullReferenceException)    ||
                      typeof(KeyNotFoundException)      ||
                      typeof(InvalidOperationException) ||
                    },
                    ex);
}

private static IEnumerable<object[]> GetInvalidMimeMessages()
{
    yield return new object[] { null };
    yield return new object[] { new MimeMessage() };
    yield return new object[]
    {
        new MimeMessage(
            new List<InternetAddress>(),
            new InternetAddressList() { new MailboxAddress("ExchangeScrapyard@ol.su"), new MailboxAddress("exchange+scrapyard@Olex.su"), },
            string.Empty,
            MimeEntity.Load(ParserOptions.Default, Stream.Null))
    };
    yield return new object[]
    {
        new MimeMessage(
            new List<InternetAddress>(),
            new InternetAddressList() { new MailboxAddress("ExchangeOLC449@ol.su"), new MailboxAddress("exchange+olc@Ol.su"), },
            string.Empty,
            MimeEntity.Load(ParserOptions.Default, Stream.Null))
    };
}
</code>```

How can I get such assert?

答:
```<code>var exceptions = new List<Type>()
            {
                typeof(NullReferenceException),
                typeof(KeyNotFoundException),
                typeof(InvalidOperationException),
            };

var ex = await Assert.ThrowsAnyAsync<Exception>(() => foo.Bar());
Assert.Contains(ex.GetType(), exceptions);
</code>```

Body:
I need to check one from three possible types of exceptions. If one of these exceptions thrown, the test considered passed. I'm using [Theory] and [MemberData] for several scenarios.

[Theory]
[MemberData(nameof(GetInvalidMimeMessages))]
public async Task ProcessAsync_TestFail(MimeMessage message)
{
    var stub = Mock.Of<IOptions<ScrapyardFilesOptions>>(s => s.Value.ConnectionString == "UseDevelopmentStorage=true" && s.Value.Container == "exchange");
    var loggerMock = new Mock<ILogger<ScrapyardFilesHandler>>(MockBehavior.Loose);
    var scrapyard = new ScrapyardFilesHandler(loggerMock.Object, stub);
    var ex = await Assert.ThrowsAnyAsync<Exception>(() => scrapyard.ProcessAsync(message));

    // imagine solution somehow like that
    Assert.IsType(
                    {
                      typeof(NullReferenceException)    ||
                      typeof(KeyNotFoundException)      ||
                      typeof(InvalidOperationException) ||
                    },
                    ex);
}

private static IEnumerable<object[]> GetInvalidMimeMessages()
{
    yield return new object[] { null };
    yield return new object[] { new MimeMessage() };
    yield return new object[]
    {
        new MimeMessage(
            new List<InternetAddress>(),
            new InternetAddressList() { new MailboxAddress("ExchangeScrapyard@ol.su"), new MailboxAddress("exchange+scrapyard@Olex.su"), },
            string.Empty,
            MimeEntity.Load(ParserOptions.Default, Stream.Null))
    };
    yield return new object[]
    {
        new MimeMessage(
            new List<InternetAddress>(),
            new InternetAddressList() { new MailboxAddress("ExchangeOLC449@ol.su"), new MailboxAddress("exchange+olc@Ol.su"), },
            string.Empty,
            MimeEntity.Load(ParserOptions.Default, Stream.Null))
    };
}

How can I get such assert?


问:
Button enableWhen TableView selectedItem is not empty
TableView selectedItem is bind to ViewModel and i want to button be disabled when selectedItem is null and enabled otherwise.

```<code>class MainView: View("TheSubberKt") {
  override val root = Form()
  val model = MainViewModel()

  init {
    with(root) {
      fieldset {
        field("Media:") {
          textfield(model.mediaPath)
          button("...")
        }
      }
      tableview(subs) {
        // ...
        bindSelected(model.selectedSubtitle)
      }
      hbox {
        button("Hash Search")
        button("Download Selected") {
          // what to do here?
        }
      }
    }
  }
}
</code>```

I imagine that i have to create a OvservableValue<Boolean> and then pass to enableWhen but, how to do that?

Is it possible to map a property onChange to a custom observable? (just another idea)

答:
Observable values have a function that will return an BooleanBinding when they don't contain a value, and since you've already bound the selected item to model.selectedSubtitle, you can simply add the following expression inside of the button builder:

enableWhen(model.selectedSubtitle.isNotNull)

If you didn't bind the selected item of the TableView to a property accessible in the view, you could store a reference to the table directly and bind to state in the table's selection model:

enableWhen(table.selectionModel.selectedItemProperty().isNotNull)

On another note, you can clean up your syntax by getting rid of the init block and declare the root node directly with a builder:

```<code>override val root = tableview(subs) {
   ...
}
</code>```

Hope this helps :)

Body:
TableView selectedItem is bind to ViewModel and i want to button be disabled when selectedItem is null and enabled otherwise.

class MainView: View("TheSubberKt") {
  override val root = Form()
  val model = MainViewModel()

  init {
    with(root) {
      fieldset {
        field("Media:") {
          textfield(model.mediaPath)
          button("...")
        }
      }
      tableview(subs) {
        // ...
        bindSelected(model.selectedSubtitle)
      }
      hbox {
        button("Hash Search")
        button("Download Selected") {
          // what to do here?
        }
      }
    }
  }
}

I imagine that i have to create a OvservableValue<Boolean> and then pass to enableWhen but, how to do that?

Is it possible to map a property onChange to a custom observable? (just another idea)

Body:
Observable values have a function that will return an BooleanBinding when they don't contain a value, and since you've already bound the selected item to model.selectedSubtitle, you can simply add the following expression inside of the button builder:

enableWhen(model.selectedSubtitle.isNotNull)

If you didn't bind the selected item of the TableView to a property accessible in the view, you could store a reference to the table directly and bind to state in the table's selection model:

enableWhen(table.selectionModel.selectedItemProperty().isNotNull)

On another note, you can clean up your syntax by getting rid of the init block and declare the root node directly with a builder:

override val root = tableview(subs) {
   ...
}

Hope this helps :)


问:
Is there a macro or similar workaround to include the source folder (src) path at compile time?
Is there a Rust macro or a similar workaround to include the path of the 'src' folder created via cargo new in my source file as a string literal at compile time or specifically when doing cargo build?

I have successfully done something similar where I use include_str! to include file content but I need to know if it is possible to directly include the src path in the code.

答:
No, but you can get close using file!:

```<code>const FILE: &'static str = concat!(env!("CARGO_MANIFEST_DIR"), "/", file!());

fn main() {
    use std::path::Path;

    println!("FILE: {:?}", FILE);
    println!("src path: {:?}", Path::new(FILE).parent());
}
</code>```

Outputs, on the playground:

FILE: "/playground/src/main.rs"
src path: Some("/playground/src")
```

Body:
No, but you can get close using file!:

const FILE: &'static str = concat!(env!("CARGO_MANIFEST_DIR"), "/", file!());

fn main() {
    use std::path::Path;

    println!("FILE: {:?}", FILE);
    println!("src path: {:?}", Path::new(FILE).parent());
}

Outputs, on the playground:

FILE: "/playground/src/main.rs"
src path: Some("/playground/src")


问:
Centering the navbar links
I have tried most of the approach, but I'm unable to center align the links in my navbar.

.navbar-nav {
  margin: 30px 20px !important;
}

a {
  /* color: #fff !important;*/
  font-family: 'Caesar Dressing';
  font-size: 18px;
  padding: 10px 30px !important;
}

a:hover {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}

.active {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<body>
  <div class="container-fluid bg">
    <nav class="navbar">
      <div class="container-fluid">
        <ul class="nav navbar-nav">
          <li class="active">Home</li>
          <li>About</li>
          <li>Education</li>
          <li>Contact</li>
        </ul>
      </div>
    </nav>
  </div>
</body></code>```

this is what I'm getting

But I want all the 4 links to be vertically centered on the screen

答:
You can do it by using text-align property on li of navbar like this

```<code>.navbar-nav > li
{
text-align :center;
}
</code>```

.navbar-nav {
  margin: 30px 20px !important;
}

a {
  /* color: #fff !important;*/
  font-family: 'Caesar Dressing';
  font-size: 18px;
  padding: 10px 30px !important;
}

a:hover {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}

.active {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}
.navbar-nav > li
{
  text-align :center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<body>
  <div class="container-fluid bg">
    <nav class="navbar">
      <div class="container-fluid">
        <ul class="nav navbar-nav">
          <li class="active">Home</li>
          <li>About</li>
          <li>Education</li>
          <li>Contact</li>
        </ul>
      </div>
    </nav>
  </div>
</body></code>```

Title: Centering the navbar links

Body:
I have tried most of the approach, but I'm unable to center align the links in my navbar.

.navbar-nav {
  margin: 30px 20px !important;
}

a {
  /* color: #fff !important;*/
  font-family: 'Caesar Dressing';
  font-size: 18px;
  padding: 10px 30px !important;
}

a:hover {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}

.active {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

Home

About

Education

Contact

this is what I'm getting

But I want all the 4 links to be vertically centered on the screen

Body:
You can do it by using text-align property on li of navbar like this

.navbar-nav > li
{
text-align :center;
}

.navbar-nav {
  margin: 30px 20px !important;
}

a {
  /* color: #fff !important;*/
  font-family: 'Caesar Dressing';
  font-size: 18px;
  padding: 10px 30px !important;
}

a:hover {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}

.active {
  border: 2px solid #fff !important;
  background-color: transparent !important;
}
.navbar-nav > li
{
  text-align :center;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<body>
  <div class="container-fluid bg">
    <nav class="navbar">
      <div class="container-fluid">
        <ul class="nav navbar-nav">
          <li class="active"><a href="#">Home</a></li>
          <li><a href="#">About</a></li>
          <li><a href="#">Education</a></li>
          <li><a href="#">Contact</a></li>
        </ul>
      </div>
    </nav>
  </div>
</body>


问:
variable in ionic 3 when making http request
I am a newbie. So I don't understand how variables run in ionic 3. I can't read the value of variables in constructor function when I make a HTTP request. Can anyone help me? thank you, pro.</p>

```<code>constructor(private fire: AngularFireAuth, public navCtrl: NavController, public navParams: NavParams, public http: Http) {

    this.email = fire.auth.currentUser.email;
    this.films = this.http.get('https://api.thingspeak.com/channels/329601/feeds.json?results=10');
    this.films
        .map(res => res.json())
        .subscribe(data => {
            console.log(data);
            this.dulieu = data.feeds;
            console.log("Du lieu", this.dulieu[2].field2);
        })
}

ionViewDidLoad() {
    console.log('ionViewDidLoad LoggedinPage');
}
</code>```

答: This is not a problem with Ionic3. You should first learn angular4. Go through this Tutorial and you'll know everything you need to know. </p>

Body:
I am a newbie. So I don't understand how variables run in ionic 3. I can't read the value of variables in constructor function when I make a HTTP request. Can anyone help me? thank you, pro.

constructor(private fire: AngularFireAuth, public navCtrl: NavController, public navParams: NavParams, public http: Http) {

    this.email = fire.auth.currentUser.email;
    this.films = this.http.get('https://api.thingspeak.com/channels/329601/feeds.json?results=10');
    this.films
        .map(res => res.json())
        .subscribe(data => {
            console.log(data);
            this.dulieu = data.feeds;
            console.log("Du lieu", this.dulieu[2].field2);
        })
}

ionViewDidLoad() {
    console.log('ionViewDidLoad LoggedinPage');
}


问:
Confusing documentation of flock(2)

If a process uses open(2) (or similar) to obtain more than one
  descriptor for the same file, these descriptors are treated
  independently by flock(). An attempt to lock the file using one of
  these file descriptors may be denied by a lock that the calling
  process has already placed via another descriptor.

If flock() treats the descriptors independently, why locking the file using one of the file descriptors would be denied by a lock placed via another descriptor? What does independent here mean?

Also if I unlock one of the descriptor, would other descriptors unlock as well?

答:
Suppose your process has two file descriptors, fd1 and fd2, that operate on the same file.  If you lock a segment of the file on fd1, and then lock another overlapping segment also on fd1, the two locks won't interfere with each other because they're on the same file descriptor.

However, if the second lock was applied on fd2 instead of fd1, then the locks would be overlapping and the second lock would be deemed to interfere with first and would fail, despite the fact that it is the same process doing the locking.

This is the sense in which the locks on the file descriptors are independent of each other — the locking system doesn't check which process owns the interfering locks on a different file descriptor; it is sufficient that it is not the current file descriptor.

When you unlock one descriptor, you don't change the locks on any other file descriptor.

Title: Confusing documentation of flock(2)


问:
Possible to add Index to a javascript Object
Is it possible for me to create an Index into an Object? Here is my object:

```<code>var objName = {};
var array1 = ['apple','sugar'];
var array2 = ['spoon','fork'];
var array3 = ['spoon2','fork2'];
var array4 = ['spoon3','fork3'];

objName['main'] = array1;
objName['submain'] = array2;
objName['main'] = array3;
objName['submain'] = array4;

console.log(objName);
</code>```

question is, I want to add another value to the object without my previous object being erased. Assuming that the objName is a global object variable and I'm going to use it again and again and pushing different values into it. I am expecting an output where in I can see also my previous records.

JSFiddle

答:
Imagine you have 4 children and you named them 2x John and 2x Kate. Now, you gave something to one of John's and now you want it back. So you are calling "Jooooohn! Come here for a sec!". Which John should come? The first one or the second one? Even more, which one is the first one?

Do you see now, what you did wrong? You cannot assign two identical keys to the Javascript object because none would know which property you want to access at the time. That's why keys have to be unique.

If you want to have also previous records in your object, then use an array, as other guys suggested.

Body:
Is it possible for me to create an Index into an Object? Here is my object:

var objName = {};
var array1 = ['apple','sugar'];
var array2 = ['spoon','fork'];
var array3 = ['spoon2','fork2'];
var array4 = ['spoon3','fork3'];

objName['main'] = array1;
objName['submain'] = array2;
objName['main'] = array3;
objName['submain'] = array4;

console.log(objName);

question is, I want to add another value to the object without my previous object being erased. Assuming that the objName is a global object variable and I'm going to use it again and again and pushing different values into it. I am expecting an output where in I can see also my previous records.

JSFiddle


问:
Repeating a value when a previous variable value has occured
I have a data set with the following variables:
1. Group
2. Status (Takes on variables 1-7)

I need to create a flag where the following conditions are met:
-Flag 1=0 when Status <6, else Flag 1= 1 when Status >=6
-Within each group: If Status has reached 6 or higher and goes back down to below 6, the flag 1 must remain as 1.

The desired table would look as follows:

答:
df$flag <- ifelse(df$status >6,0,1)

df$status <- ifelse(df$status =>6,5,df$status)


问:
Chipmunk shapes not colliding
I am able to create spaces, bodies, and shapes, put them together, and draw them on screen... yet somehow none of my shapes are interacting with each other or colliding. My collision callback isn't getting called either. What could be causing this?

I create a space:

```<code>cpSpace *space = cpSpaceNew();
cpSpaceSetDefaultCollisionHandler(space,handleCollision,NULL,NULL, NULL,self);
</code>```

I create bodies:

```<code>body = cpBodyNew(mass, moment);
</code>```

I create shapes for the bodies:

```<code>cpCircleShapeNew(body, radius, offset);
</code>```

I add the body to the space:

```<code>cpSpaceAddShape(space, shape);
</code>```

I step through time, (and draw, obviously):

```<code>cpSpaceStep(space, dt);
</code>```

And yet my shapes and bodies refuse to interact with eachother.

答: lol! forgot to call cpInitChipmunk()

Title: Chipmunk shapes not colliding

Body:
I am able to create spaces, bodies, and shapes, put them together, and draw them on screen... yet somehow none of my shapes are interacting with each other or colliding. My collision callback isn't getting called either. What could be causing this?

I create a space:

cpSpace *space = cpSpaceNew();
cpSpaceSetDefaultCollisionHandler(space,handleCollision,NULL,NULL, NULL,self);

I create bodies:

body = cpBodyNew(mass, moment);

I create shapes for the bodies:

cpCircleShapeNew(body, radius, offset);

I add the body to the space:

cpSpaceAddShape(space, shape);

I step through time, (and draw, obviously):

cpSpaceStep(space, dt);

And yet my shapes and bodies refuse to interact with eachother.

Body: lol! forgot to call cpInitChipmunk()


问:
error while upgrading to angular5
I am trying to upgrade my angular4 app to angular 5 by using npm-check-updates.
I ran below three commands:

```<code>npm install -g npm-check-updates
ncu -u
npm update
</code>```

After that i tried to run up the app using my command:
   npm run serve

My package.json looks like this:

```<code>"scripts": {
"ng": "ng",
"start-ng": "ng serve",
"start": "node src/server/index.js",
"build": "ng build",
"build-dev": "ng build -dev",
"build-local": "ng build -dev -e local",
"build-test": "ng build -prod -e test",
"build-prod": "ng build -prod -e prod",
"serve": "ng serve -dev -e local -o",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"sme": "./node_modules/.bin/source-map-explorer"
</code>```

},

I am unable to run up the app as i am getting below mentioned error:

```<code>An asset cannot be written to a location outside of the output path.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! my-client-app@0.0.0 serve: `ng serve -dev -e local -o`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the my-client-app@0.0.0 serve script.
npm ERR! This is probably not a problem with npm. There is likely additional
 logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\mack\AppData\Roaming\npm-cache\_logs\2017-11-
03T12_15_23_604Z-debug.log
</code>```

答:
Possible duplicate of : Update to Angular 5

As Now, angular 5 has been released officially on 1st Novemebr 2017,
So for those who want to update your old angular applications to angular 5:

1) The Angular team has also put a handy tool to make upgrading from any version to angular 5, as simple as possible.

2) You will have to upgrade all of your angular packages to version 5.0, run the following command:

```<code>$ npm install @angular/{animations,common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router}@5.0.0
---for those who are using yarn.
$ yarn add @angular/{animations,common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router}@5.0.0
</code>```

3) Angular 5 now also depends on TypeScript 2.4.2 and RxJS 5.5.2, so you’ll have to upgrade those package as well.

```<code>npm install typescript@2.4.2 --save-exact
</code>```

4) If you rely on the date, currency, decimal, or percent pipes, in 5 you will see minor changes to the format. For applications using locales other than en-us you will need to import it and optionally locale_extended_fr from @angular/common/i18n_data/locale_fr and registerLocaleData(local).
For more information on pipes breaking changes:
https://stackoverflow.com/a/47263949/2810015

5) Use of implements instead of extends withany lifecycle events : Ensure you don't use extends OnInit, or use extends with any lifecycle event. Instead use implements .

6) Switch from HttpModule and the Http service to HttpClientModule and the HttpClient service. HttpClient simplifies the default ergonomics (You don't need to map to json anymore) and now supports typed return values and interceptors.

I have tried to explain more here.
https://onlyforcoder.blogspot.in/2017/11/angular-5-upgrade-your-project-To-Angular5.html

Title: error while upgrading to angular5

Body:
I am trying to upgrade my angular4 app to angular 5 by using npm-check-updates.
I ran below three commands:

npm install -g npm-check-updates
ncu -u
npm update

After that i tried to run up the app using my command:
   npm run serve

My package.json looks like this:

"scripts": {
"ng": "ng",
"start-ng": "ng serve",
"start": "node src/server/index.js",
"build": "ng build",
"build-dev": "ng build -dev",
"build-local": "ng build -dev -e local",
"build-test": "ng build -prod -e test",
"build-prod": "ng build -prod -e prod",
"serve": "ng serve -dev -e local -o",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"sme": "./node_modules/.bin/source-map-explorer"

},

I am unable to run up the app as i am getting below mentioned error:

An asset cannot be written to a location outside of the output path.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! my-client-app@0.0.0 serve: `ng serve -dev -e local -o`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the my-client-app@0.0.0 serve script.
npm ERR! This is probably not a problem with npm. There is likely additional
 logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\mack\AppData\Roaming\npm-cache\_logs\2017-11-
03T12_15_23_604Z-debug.log

Body:
Possible duplicate of : Update to Angular 5

As Now, angular 5 has been released officially on 1st Novemebr 2017,
So for those who want to update your old angular applications to angular 5:

1) The Angular team has also put a handy tool to make upgrading from any version to angular 5, as simple as possible.

2) You will have to upgrade all of your angular packages to version 5.0, run the following command:

$ npm install @angular/{animations,common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router}@5.0.0
---for those who are using yarn.
$ yarn add @angular/{animations,common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router}@5.0.0

3) Angular 5 now also depends on TypeScript 2.4.2 and RxJS 5.5.2, so you’ll have to upgrade those package as well.

npm install typescript@2.4.2 --save-exact

4) If you rely on the date, currency, decimal, or percent pipes, in 5 you will see minor changes to the format. For applications using locales other than en-us you will need to import it and optionally locale_extended_fr from @angular/common/i18n_data/locale_fr and registerLocaleData(local).
For more information on pipes breaking changes:
https://stackoverflow.com/a/47263949/2810015

5) Use of implements instead of extends withany lifecycle events : Ensure you don't use extends OnInit, or use extends with any lifecycle event. Instead use implements .

6) Switch from HttpModule and the Http service to HttpClientModule and the HttpClient service. HttpClient simplifies the default ergonomics (You don't need to map to json anymore) and now supports typed return values and interceptors.

I have tried to explain more here.
https://onlyforcoder.blogspot.in/2017/11/angular-5-upgrade-your-project-To-Angular5.html


问:
Dismiss keyboard in iOS
I looked at and tried multiple solutions for Swift 3, Xcode 8 but couldn't get any to work. I've tried:

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}
</code>```

and also setting a text field input as first responder:

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    pressureInput.resignFirstResponder()
}
</code>```

I don't know if something from Xcode 8 to Xcode 9 that cause these methods to not work, or if I messed elsewhere. I have 9 text fields and they've all set delegate to self. Their tags are incremented to move on to the next text field on pressing return. Don't think that would affect it. Sorry, new at this! The code runs fine with either of those attempted functions, but they keyboard stays. I would just like to dismiss keyboard when touched outside of any text field.

答:
first of all write this extension in any swift file

```<code>extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        view.addGestureRecognizer(tap)

    }

    func dismissKeyboard() {
        view.endEditing(true)
    }
}
</code>```

Than in viewDidLoad of that View only call in any view controller there are textFields.

```<code>self.hideKeyboardWhenTappedAround()
</code>```

Title: Dismiss keyboard in iOS

Body:
I looked at and tried multiple solutions for Swift 3, Xcode 8 but couldn't get any to work. I've tried:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

and also setting a text field input as first responder:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    pressureInput.resignFirstResponder()
}

I don't know if something from Xcode 8 to Xcode 9 that cause these methods to not work, or if I messed elsewhere. I have 9 text fields and they've all set delegate to self. Their tags are incremented to move on to the next text field on pressing return. Don't think that would affect it. Sorry, new at this! The code runs fine with either of those attempted functions, but they keyboard stays. I would just like to dismiss keyboard when touched outside of any text field.

Body:
first of all write this extension in any swift file

extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        view.addGestureRecognizer(tap)

    }

    func dismissKeyboard() {
        view.endEditing(true)
    }
}

Than in viewDidLoad of that View only call in any view controller there are textFields.

self.hideKeyboardWhenTappedAround()


问:
Constructing a std::string_view from a braced std::string, clang and gcc disagree with -Wconversion
GCC 7.2 and clang 5.0 seem to disagree about the following code when compiled with -std=c++17 -Werror -Wconversion:

```<code>#include <iostream>
#include <string>
#include <string_view>

int main(int argc, char* argv[]) {
    std::string s = "Hello, World";
    std::string_view vs{s};
    std::cout << std::string{vs} << '\n';
    return EXIT_SUCCESS;
}
</code>```

Compiled with clang++ -std=c++17 -Wall -Werror -Wconversion, it compiles correctly (see https://godbolt.org/g/JZn8cL)

However, GCC 7.2 issues a somewhat perplexing diagnostic (see https://godbolt.org/g/kmYbJ3):

```<code><source>: In function 'int main(int, char**)':
7 : <source>:7:26: error: choosing 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::__sv_type() const [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::__sv_type = std::basic_string_view<char>]' over 'constexpr std::basic_string_view<_CharT, _Traits>::basic_string_view(const std::basic_string_view<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits<char>]' [-Werror=conversion]
     std::string_view vs{s};
                          ^
7 : <source>:7:26: error:   for conversion from 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'std::basic_string_view<char>' [-Werror=conversion]
7 : <source>:7:26: note:   because conversion sequence for the argument is better
cc1plus: all warnings being treated as errors
Compiler exited with result code 1
</code>```

Both compilers compile the code fine after changing vs{s} to vs(s).

Which compiler is right here? Is brace initialization of a std::string_view from a std::string running afoul of conversion rules somehow, and clang is failing to issue a diagnostic when it could/should? Or is GCC in the wrong and the diagnostic is erroneous?

答:
Your original question ("is this invalid C++?") has now been answered ("no."), but it's clear from the comments you're now interested in why gcc warns about this valid code. That is a more interesting question.

Removing the template arguments, the warning reduces to this:

```<code>warning: choosing 'std::string::operator std::string_view()' over 'constexpr std::string_view(const std::string_view&) ' [-Wconversion]
</code>```

So it's warning about a user-defined conversion operator being chosen over a constructor... but that constructor couldn't actually be used for conversion. Here is another example that warns for the same reason:

```<code>class A {  // Like string_view
public:
    A() {}
};
class B {  // Like string
public:
    operator A() {return A();}
};

int main() {
    B b;
    A a{b};
}
</code>```

This gives:

```<code><source>: In function 'int main()':
12 : <source>:12:10: warning: choosing 'B::operator A()' over 'constexpr A::A(A&&)' [-Wconversion]
     A a{b};
          ^
12 : <source>:12:10: warning:   for conversion from 'B' to 'A' [-Wconversion]
12 : <source>:12:10: note:   because conversion sequence for the argument is better
12 : <source>:12:10: warning: choosing 'B::operator A()' over 'constexpr A::A(const A&)' [-Wconversion]
12 : <source>:12:10: warning:   for conversion from 'B' to 'A' [-Wconversion]
12 : <source>:12:10: note:   because conversion sequence for the argument is better
</code>```

By the way, adding e.g. A(int) constructor does not add anything to the warning, so it is focused on the move constructor and copy constructor of A. Deleting the copy and move constructors with =delete does not change the warning either.

This clarifies what is causing the warning, but not why it warns. The gcc documentation for -Wconversion says:

Warn for implicit conversions that may alter a value. This includes conversions between real and integer, like abs (x) when x is double; conversions between signed and unsigned, like unsigned ui = -1; and conversions to smaller types, like sqrtf (M_PI). Do not warn for explicit casts like abs ((int) x) and ui = (unsigned) -1, or if the value is not changed by the conversion like in abs (2.0). Warnings about conversions between signed and unsigned integers can be disabled by using -Wno-sign-conversion.

For C++, also warn for confusing overload resolution for user-defined conversions; and conversions that never use a type conversion operator: conversions to void, the same type, a base class or a reference to them. Warnings about conversions between signed and unsigned integers are disabled by default in C++ unless -Wsign-conversion is explicitly enabled.

So it depends on what you consider to be "confusing overload resolution for user-defined conversions". Perhaps the gcc devs consider A a{b} to look like a call to a constructor of A, and so they consider it calling B::operator A() to be "confusing".

Or perhaps it is indeed a bug... Given that this seems to be a rarely-used warning flag (it's not even in -Wall), and given how strange the "choosing x over y" messages are, that is quite possible.

Body:
GCC 7.2 and clang 5.0 seem to disagree about the following code when compiled with -std=c++17 -Werror -Wconversion:

#include <iostream>
#include <string>
#include <string_view>

int main(int argc, char* argv[]) {
    std::string s = "Hello, World";
    std::string_view vs{s};
    std::cout << std::string{vs} << '\n';
    return EXIT_SUCCESS;
}

Compiled with clang++ -std=c++17 -Wall -Werror -Wconversion, it compiles correctly (see https://godbolt.org/g/JZn8cL)

However, GCC 7.2 issues a somewhat perplexing diagnostic (see https://godbolt.org/g/kmYbJ3):

<source>: In function 'int main(int, char**)':
7 : <source>:7:26: error: choosing 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::__sv_type() const [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::__sv_type = std::basic_string_view<char>]' over 'constexpr std::basic_string_view<_CharT, _Traits>::basic_string_view(const std::basic_string_view<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits<char>]' [-Werror=conversion]
     std::string_view vs{s};
                          ^
7 : <source>:7:26: error:   for conversion from 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'std::basic_string_view<char>' [-Werror=conversion]
7 : <source>:7:26: note:   because conversion sequence for the argument is better
cc1plus: all warnings being treated as errors
Compiler exited with result code 1

Both compilers compile the code fine after changing vs{s} to vs(s).

Which compiler is right here? Is brace initialization of a std::string_view from a std::string running afoul of conversion rules somehow, and clang is failing to issue a diagnostic when it could/should? Or is GCC in the wrong and the diagnostic is erroneous?

Body:
Your original question ("is this invalid C++?") has now been answered ("no."), but it's clear from the comments you're now interested in why gcc warns about this valid code. That is a more interesting question.

Removing the template arguments, the warning reduces to this:

warning: choosing 'std::string::operator std::string_view()' over 'constexpr std::string_view(const std::string_view&) ' [-Wconversion]

So it's warning about a user-defined conversion operator being chosen over a constructor... but that constructor couldn't actually be used for conversion. Here is another example that warns for the same reason:

class A {  // Like string_view
public:
    A() {}
};
class B {  // Like string
public:
    operator A() {return A();}
};

int main() {
    B b;
    A a{b};
}

This gives:

<source>: In function 'int main()':
12 : <source>:12:10: warning: choosing 'B::operator A()' over 'constexpr A::A(A&&)' [-Wconversion]
     A a{b};
          ^
12 : <source>:12:10: warning:   for conversion from 'B' to 'A' [-Wconversion]
12 : <source>:12:10: note:   because conversion sequence for the argument is better
12 : <source>:12:10: warning: choosing 'B::operator A()' over 'constexpr A::A(const A&)' [-Wconversion]
12 : <source>:12:10: warning:   for conversion from 'B' to 'A' [-Wconversion]
12 : <source>:12:10: note:   because conversion sequence for the argument is better

By the way, adding e.g. A(int) constructor does not add anything to the warning, so it is focused on the move constructor and copy constructor of A. Deleting the copy and move constructors with =delete does not change the warning either.

This clarifies what is causing the warning, but not why it warns. The gcc documentation for -Wconversion says:

Warn for implicit conversions that may alter a value. This includes conversions between real and integer, like abs (x) when x is double; conversions between signed and unsigned, like unsigned ui = -1; and conversions to smaller types, like sqrtf (M_PI). Do not warn for explicit casts like abs ((int) x) and ui = (unsigned) -1, or if the value is not changed by the conversion like in abs (2.0). Warnings about conversions between signed and unsigned integers can be disabled by using -Wno-sign-conversion.

For C++, also warn for confusing overload resolution for user-defined conversions; and conversions that never use a type conversion operator: conversions to void, the same type, a base class or a reference to them. Warnings about conversions between signed and unsigned integers are disabled by default in C++ unless -Wsign-conversion is explicitly enabled.

So it depends on what you consider to be "confusing overload resolution for user-defined conversions". Perhaps the gcc devs consider A a{b} to look like a call to a constructor of A, and so they consider it calling B::operator A() to be "confusing".

Or perhaps it is indeed a bug... Given that this seems to be a rarely-used warning flag (it's not even in -Wall), and given how strange the "choosing x over y" messages are, that is quite possible.


问:
Difference between x.toString() and x+""
Back in college one of my profs. taught us to just do x + "" as a quick conversion from basic types to strings.

I don't remember which class it was in I had him for some Java and C++ courses(I haven't used either for some time now), but I use it in C#/.Net now which is what I'm primarily developing in lately.

Is there an advantage to using .toString() over +"" for basic types such at int, decimal, float...?
What cases would .toString() be better?

Note:I was shown .toString() as well, that prof just recommended +"" because it was shorter and I have just done that since then without questioning it.

答:
It doesn't matter, really. It is very very unlikely this will cause any performance problems whatsoever. So it remains a matter of personal style.
Use whatever you or your team is comfortable with.</p>


问:
return self.user as foreignkey
I have a model with foreignkeys. For this model I want to set the 'def str' as the user.

I have done this

```<code>from django.contrib.auth import get_user_model

User = get_user_model()

class Rosters(models.Model):
        place = models.ForeignKey('Places')
        position = models.ForeignKey('Positions', blank=True, null=True)
        user = models.ForeignKey(User, related_name='roster')
        validfrom = models.DateTimeField(blank=True, null=True)
        validto = models.DateTimeField(blank=True, null=True)

        def __str__(self):
            return self.user
</code>```

This will fetch username and show in admin pages. But when I try to create a new Roster. I get a TypeError __str__ returned non-string (type User)

I can remove the 'def str...' and create a Roster with no problem. But each Roster shows as Object in admin pages. So I can add back the 'def str..' to see the usernames of each roster.

I want them to always display as usernames. And I can't figure out why it's not working when I'm adding rosters.

答:
You need to refer to the specific field within 'User' you want to display.
Try:</p>

```<code>def __str__(self):
    return self.user.username
</code>```

Title: return self.user as foreignkey

Body:
I have a model with foreignkeys. For this model I want to set the 'def str' as the user.

I have done this

from django.contrib.auth import get_user_model

User = get_user_model()

class Rosters(models.Model):
        place = models.ForeignKey('Places')
        position = models.ForeignKey('Positions', blank=True, null=True)
        user = models.ForeignKey(User, related_name='roster')
        validfrom = models.DateTimeField(blank=True, null=True)
        validto = models.DateTimeField(blank=True, null=True)

        def __str__(self):
            return self.user

This will fetch username and show in admin pages. But when I try to create a new Roster. I get a TypeError __str__ returned non-string (type User)

I can remove the 'def str...' and create a Roster with no problem. But each Roster shows as Object in admin pages. So I can add back the 'def str..' to see the usernames of each roster.

I want them to always display as usernames. And I can't figure out why it's not working when I'm adding rosters.

Body:
You need to refer to the specific field within 'User' you want to display.
Try:

def __str__(self):
    return self.user.username


问:
How do I bind combobox IsChecked to 4 buttons from the same group?
I want the combo box to be enable when pressing one of the radio buttons.

<RadioButton x:Name="A" GroupName="rButton" Content="A" Grid.Column="4"/>
<RadioButton x:Name="B" GroupName="rButton" Content="B" Grid.Column="4"/>
<RadioButton x:Name="C" GroupName="rButton" Content="C" Grid.Column="4"/>
<RadioButton x:Name="D" GroupName="rButton" Content="D" Grid.Column="4"/>

<ComboBox IsEnabled="{Binding IsChecked,?? }" Grid.Column="5" Width="120" Height="30"/>
```

答:
If you want to solve this via Bindings (and you should), you need a MultiBindingConverter that returns true as long as one of the values is true (boolean OR):

public class BooleanOrConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        foreach (object value in values)
        {
            if (value is bool && (bool) value)
                return true;
        }
        return false;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        return Enumerable.Repeat(DependencyProperty.UnsetValue, targetTypes.Length).ToArray();
    }
}
```

<p>Definition:</p>

<pre class="lang-xaml prettyprint-override"><code><Window.Resources>
    <local:BooleanOrConverter x:Key="OrConverter"/>
</Window.Resources>
</code>```

Usage:

<RadioButton x:Name="RadioButtonSource" GroupName="rButton" Content="A" Grid.Column="4"/>
<RadioButton x:Name="RadioButtonToken" GroupName="rButton" Content="B" Grid.Column="4"/>
<RadioButton x:Name="RadioButtonII" GroupName="rButton" Content="C" Grid.Column="4"/>
<RadioButton x:Name="RadioButtonUkey" GroupName="rButton" Content="D" Grid.Column="4"/>

<ComboBox Grid.Column="5" Width="120" Height="30">
    <ComboBox.IsEnabled>
        <MultiBinding Converter="{StaticResource OrConverter}">
            <Binding ElementName="RadioButtonSource" Path="IsChecked"/>
            <Binding ElementName="RadioButtonToken" Path="IsChecked"/>
            <Binding ElementName="RadioButtonII" Path="IsChecked"/>
            <Binding ElementName="RadioButtonUkey" Path="IsChecked"/>
        </MultiBinding>
    </ComboBox.IsEnabled>
</ComboBox>
```

This way, as soon as any of the RadioButtons's IsChecked properties becomes true, the ComboBox is enabled. If you reset the RadioButtons, it get's disabled again.

Body:
If you want to solve this via Bindings (and you should), you need a MultiBindingConverter that returns true as long as one of the values is true (boolean OR):

public class BooleanOrConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        foreach (object value in values)
        {
            if (value is bool && (bool) value)
                return true;
        }
        return false;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        return Enumerable.Repeat(DependencyProperty.UnsetValue, targetTypes.Length).ToArray();
    }
}

Definition:

<Window.Resources>
    <local:BooleanOrConverter x:Key="OrConverter"/>
</Window.Resources>

Usage:

<RadioButton x:Name="RadioButtonSource" GroupName="rButton" Content="A" Grid.Column="4"/>
<RadioButton x:Name="RadioButtonToken" GroupName="rButton" Content="B" Grid.Column="4"/>
<RadioButton x:Name="RadioButtonII" GroupName="rButton" Content="C" Grid.Column="4"/>
<RadioButton x:Name="RadioButtonUkey" GroupName="rButton" Content="D" Grid.Column="4"/>

<ComboBox Grid.Column="5" Width="120" Height="30">
    <ComboBox.IsEnabled>
        <MultiBinding Converter="{StaticResource OrConverter}">
            <Binding ElementName="RadioButtonSource" Path="IsChecked"/>
            <Binding ElementName="RadioButtonToken" Path="IsChecked"/>
            <Binding ElementName="RadioButtonII" Path="IsChecked"/>
            <Binding ElementName="RadioButtonUkey" Path="IsChecked"/>
        </MultiBinding>
    </ComboBox.IsEnabled>
</ComboBox>

This way, as soon as any of the RadioButtons's IsChecked properties becomes true, the ComboBox is enabled. If you reset the RadioButtons, it get's disabled again.