问:
r - Binding sparse matrices of different sizes on rows
I am attempting to use the Matrix package to bind two sparse matrices of different size together. The binding is on rows, using the column names for matching.

Table A:

```<code>ID     | AAAA   | BBBB   |
------ | ------ | ------ |
XXXX   | 1      | 2      |
</code>```

Table B:

```<code>ID     | BBBB   | CCCC   |
------ | ------ | ------ |
YYYY   | 3      | 4      |
</code>```

Binding table A and B:

```<code>ID     | AAAA   | BBBB   | CCCC   |
------ | ------ | ------ | ------ |
XXXX   | 1      | 2      |        |
YYYY   |        | 3      | 4      |
</code>```

The intention is to insert a large number of small matrices into a single large matrix, to enable continuous querying and update/inserts.

I find that neither the Matrix or slam packages have functionality to handle this.

Similar questions have been asked in the past, but it seems no solution has been found:

Post 1: in-r-when-using-named-rows-can-a-sparse-matrix-column-be-added-concatenated

Post 2: bind-together-sparse-model-matrices-by-row-names

Ideas on how to solve it will be highly appreciated.

Best regards,

Frederik

答:
We can create an empty sparse Matrix that has all the rows and columns, then insert the values into it using subset assignment:

```<code>my.bind = function(A, B){
  C = Matrix(0, nrow = NROW(A) + NROW(B), ncol = length(union(colnames(A), colnames(B))),
             dimnames = list(c(rownames(A), rownames(B)), union(colnames(A), colnames(B))))
  C[rownames(A), colnames(A)] = A
  C[rownames(B), colnames(B)] = B
  return(C)
}

my.bind(A,B)
# 2 x 3 sparse Matrix of class "dgCMatrix"
#      AAAA BBBB CCCC
# XXXX    1    2    .
# YYYY    .    3    4
</code>```

Note that the above assumes that the A and B do not share row names.  If there are shared row names, then you should use row numbers instead of names for the assignment.

The data:

```<code>library(Matrix)
A = Matrix(c(1,2), 1, dimnames = list('XXXX', c('AAAA','BBBB')))
B = Matrix(c(3,4), 1, dimnames = list('YYYY', c('BBBB','CCCC')))
</code>```

Body:
I am attempting to use the Matrix package to bind two sparse matrices of different size together. The binding is on rows, using the column names for matching.

Table A:

ID     | AAAA   | BBBB   |
------ | ------ | ------ |
XXXX   | 1      | 2      |

Table B:

ID     | BBBB   | CCCC   |
------ | ------ | ------ |
YYYY   | 3      | 4      |

Binding table A and B:

ID     | AAAA   | BBBB   | CCCC   |
------ | ------ | ------ | ------ |
XXXX   | 1      | 2      |        |
YYYY   |        | 3      | 4      |

The intention is to insert a large number of small matrices into a single large matrix, to enable continuous querying and update/inserts.

I find that neither the Matrix or slam packages have functionality to handle this.

Similar questions have been asked in the past, but it seems no solution has been found:

Post 1: in-r-when-using-named-rows-can-a-sparse-matrix-column-be-added-concatenated

Post 2: bind-together-sparse-model-matrices-by-row-names

Ideas on how to solve it will be highly appreciated.

Best regards,

Frederik

Body:
We can create an empty sparse Matrix that has all the rows and columns, then insert the values into it using subset assignment:

my.bind = function(A, B){
  C = Matrix(0, nrow = NROW(A) + NROW(B), ncol = length(union(colnames(A), colnames(B))),
             dimnames = list(c(rownames(A), rownames(B)), union(colnames(A), colnames(B))))
  C[rownames(A), colnames(A)] = A
  C[rownames(B), colnames(B)] = B
  return(C)
}

my.bind(A,B)
# 2 x 3 sparse Matrix of class "dgCMatrix"
#      AAAA BBBB CCCC
# XXXX    1    2    .
# YYYY    .    3    4

Note that the above assumes that the A and B do not share row names.  If there are shared row names, then you should use row numbers instead of names for the assignment.

The data:

library(Matrix)
A = Matrix(c(1,2), 1, dimnames = list('XXXX', c('AAAA','BBBB')))
B = Matrix(c(3,4), 1, dimnames = list('YYYY', c('BBBB','CCCC')))


来源: stackexchange

问:
Need suggestions in generating sql query
We have below type of records in a table:

table_example:

```<code>id|desc|is_parent_record|parent_id
1|parent record|yes|
2|child record|no|1
3|standalone record|no
</code>```

we want to retrieve all records in below format

```<code>id|parent id|desc
1| |parent record
2|1|child record
3| |no parent, standalone record
</code>```

Any suggestions and help for generating sql query ?

Thanks,
Rajesh

答:
Use simply hierarchical query with case when and connect_by_isleaf:

```<code>select id, parent_id,
       case when level = 1 and connect_by_isleaf = 1
            then 'no parent, '||descr
            else descr
       end descr
  from t
  connect by prior id = parent_id
  start with parent_id is null
</code>```

demo

```<code>    ID  PARENT_ID DESCR
------ ---------- ----------------------------
     1            parent record
     2          1 child record
     3            no parent, standalone record
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We have below type of records in a table:

table_example:

id|desc|is_parent_record|parent_id
1|parent record|yes|
2|child record|no|1
3|standalone record|no

we want to retrieve all records in below format

id|parent id|desc
1| |parent record
2|1|child record
3| |no parent, standalone record

Any suggestions and help for generating sql query ?

Thanks,
Rajesh

Body:
Use simply hierarchical query with case when and connect_by_isleaf:

select id, parent_id,
       case when level = 1 and connect_by_isleaf = 1
            then 'no parent, '||descr
            else descr
       end descr
  from t
  connect by prior id = parent_id
  start with parent_id is null

demo

    ID  PARENT_ID DESCR
------ ---------- ----------------------------
     1            parent record
     2          1 child record
     3            no parent, standalone record


问:
How to make InnerHTML of 2 elements switch every time the program is run
My task is to make this so that when i press run, the 2 pieces of text switch, so "headline" text appears in the "news", and vice versa.

```<code>var headline = document.getElementById("headline");
var headline2 = "Student Wins Lottery";
headline.innerHTML = headline2;

var news = document.getElementById("news");
var news2 = "A student has won a million pounds";
news.innerHTML = news2;
</code>```

I'm just stack at how you make them switch around, any help and explanations would be great, cheers.

答:
Possible approach:

var headline = document.getElementById("headline"),
    headline2 = document.getElementById("news"),
    str1 = "Student Wins Lottery",
    str2 = "A student has won a million pounds",
    bool = true;

function change() {
  if (!bool) {
    headline.innerHTML = str1;
    news.innerHTML = str2;
    bool = true;
  } else {
    headline.innerHTML = str2;
    news.innerHTML = str1;
    bool = false;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 id="headline">Student Wins Lottery</h1>
<div id="news">A student has won a million pounds</div>
<button onclick="change()">change heading</button></code>```

Body:
My task is to make this so that when i press run, the 2 pieces of text switch, so "headline" text appears in the "news", and vice versa.

var headline = document.getElementById("headline");
var headline2 = "Student Wins Lottery";
headline.innerHTML = headline2;

var news = document.getElementById("news");
var news2 = "A student has won a million pounds";
news.innerHTML = news2;

I'm just stack at how you make them switch around, any help and explanations would be great, cheers.

Body:
Possible approach:

var headline = document.getElementById("headline"),
    headline2 = document.getElementById("news"),
    str1 = "Student Wins Lottery",
    str2 = "A student has won a million pounds",
    bool = true;

function change() {
  if (!bool) {
    headline.innerHTML = str1;
    news.innerHTML = str2;
    bool = true;
  } else {
    headline.innerHTML = str2;
    news.innerHTML = str1;
    bool = false;
  }
}

<h1 id="headline">Student Wins Lottery</h1>
<div id="news">A student has won a million pounds</div>
<button onclick="change()">change heading</button>


问:
Pass text of Listview.ItemTemplate to antoher frame uwp
I have to pass the Text={Binding Id}of textBlock idName from a frame to another frame. the text is an Id from an SQLite database. I have an Listview.ItemTemplate that define the item

```<code><ListView.ItemTemplate>
                    <DataTemplate>
                        <Grid Height="Auto" Margin="0,5">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>

                            <StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="12,0,0,0">

                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="Auto"/>
                                        <ColumnDefinition Width="*"/>
                                    </Grid.ColumnDefinitions>
                                    <TextBlock x:Name="idName" Text="{Binding Id}" FontSize="12" VerticalAlignment="Center" Grid.Column="0" Margin="5,0,12,0"/>
                                    <RelativePanel Grid.Column="1">
                                        <TextBlock x:Name="titleBlock" Text="{Binding Title}" FontSize="25" HorizontalAlignment="Left" VerticalAlignment="Top"/>
                                        <TextBlock x:Name="directorLabel" Text="REGISTA:" FontSize="20" RelativePanel.Below="titleBlock" FontWeight="Light"/>
                                        <TextBlock x:Name="directorBlock" Text="{Binding Director}"  FontSize="20" RelativePanel.Below="titleBlock" RelativePanel.RightOf="directorLabel"/>
                                        <TextBlock x:Name="yearLabel" Text="ANNO:" FontSize="20" FontWeight="Light" RelativePanel.RightOf="directorBlock" Margin="12,0,0,0" RelativePanel.Below="titleBlock"/>
                                        <TextBlock x:Name="yearBlock" Text="{Binding Year}" FontSize="20" RelativePanel.Below="titleBlock" RelativePanel.RightOf="yearLabel"/>
                                    </RelativePanel>
                                </Grid>
                            </StackPanel>
                        </Grid>
                    </DataTemplate>
                </ListView.ItemTemplate>
</code>```

I use in the Code Behind this:

```<code>this.Frame.Navigate(typeof(FilmInfo), idName.Text);
</code>```

but idName.Text is an ItemTemplate.

How can I do that?

答:
I'm assuming the item must somehow be selected in the ListView in order to take action on it... if so, you can use the item directly.

```<code>YourClassName selectedFilm = YourListView.SelectedItem as YourClassName;
If(selectedFilm != null)
{
    this.Frame.Navigate(typeof(FilmInfo), selectedFilm.Id);
}
</code>```

UPDATE after comment

OK... if you're using the item click event, you can do the same thing...

```<code>private void ItemClickEvent(object sender, ItemClickEventArgs e)
{
    YourClassName selectedFilm = e.ClickedItem as YourClassName;
    if(selectedFilm != null)
    {
        this.Frame.Navigate(typeof(FilmInfo), selectedFilm.Id);
    }
}
</code>```

Body:
I have to pass the Text={Binding Id}of textBlock idName from a frame to another frame. the text is an Id from an SQLite database. I have an Listview.ItemTemplate that define the item

<ListView.ItemTemplate>
                    <DataTemplate>
                        <Grid Height="Auto" Margin="0,5">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>

                            <StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="12,0,0,0">

                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="Auto"/>
                                        <ColumnDefinition Width="*"/>
                                    </Grid.ColumnDefinitions>
                                    <TextBlock x:Name="idName" Text="{Binding Id}" FontSize="12" VerticalAlignment="Center" Grid.Column="0" Margin="5,0,12,0"/>
                                    <RelativePanel Grid.Column="1">
                                        <TextBlock x:Name="titleBlock" Text="{Binding Title}" FontSize="25" HorizontalAlignment="Left" VerticalAlignment="Top"/>
                                        <TextBlock x:Name="directorLabel" Text="REGISTA:" FontSize="20" RelativePanel.Below="titleBlock" FontWeight="Light"/>
                                        <TextBlock x:Name="directorBlock" Text="{Binding Director}"  FontSize="20" RelativePanel.Below="titleBlock" RelativePanel.RightOf="directorLabel"/>
                                        <TextBlock x:Name="yearLabel" Text="ANNO:" FontSize="20" FontWeight="Light" RelativePanel.RightOf="directorBlock" Margin="12,0,0,0" RelativePanel.Below="titleBlock"/>
                                        <TextBlock x:Name="yearBlock" Text="{Binding Year}" FontSize="20" RelativePanel.Below="titleBlock" RelativePanel.RightOf="yearLabel"/>
                                    </RelativePanel>
                                </Grid>
                            </StackPanel>
                        </Grid>
                    </DataTemplate>
                </ListView.ItemTemplate>

I use in the Code Behind this:

this.Frame.Navigate(typeof(FilmInfo), idName.Text);

but idName.Text is an ItemTemplate.

How can I do that?

Body:
I'm assuming the item must somehow be selected in the ListView in order to take action on it... if so, you can use the item directly.

YourClassName selectedFilm = YourListView.SelectedItem as YourClassName;
If(selectedFilm != null)
{
    this.Frame.Navigate(typeof(FilmInfo), selectedFilm.Id);
}

UPDATE after comment

OK... if you're using the item click event, you can do the same thing...

private void ItemClickEvent(object sender, ItemClickEventArgs e)
{
    YourClassName selectedFilm = e.ClickedItem as YourClassName;
    if(selectedFilm != null)
    {
        this.Frame.Navigate(typeof(FilmInfo), selectedFilm.Id);
    }
}


问:
Postgres: upsert a row and update a primary key column
Suppose I have two tables in my Postgres database:

```<code>create table transactions
(
    id bigint primary key,
    doc_id bigint not null,
    -- lots of other columns...
    amount numeric not null
);

-- same columns
create temporary table updated_transactions
(
    id bigint primary key,
    doc_id bigint not null,
    -- lots of other columns...
    amount numeric not null
);
</code>```

Both tables have just a primary key, and no unique indexes.

I need to upsert rows from updated_transactions into transactions using the following rules:

id column values in transactions and updated_transactions don't match

other columns like doc_id, etc (except of the amount) should match

when a matching row is found, update both amount and id columns

when a matching row is not found, insert it

id values in updated_transactions are taken from a sequence.
A business object just populates updated_transactions and then merges the
new or updated rows from it into transactions using an upsert query.
So my old unchanged transactions keep their ids intact, and the updated ones
are assigned new ids.

In MSSQL and Oracle, it would be a merge statement similar to this:

```<code>merge into transactions t
using updated_transactions ut on t.doc_id = ut.doc_id, ...
when matched then
    update set t.id = ut.id, t.amount = ut.amount
when not matched then
    insert (t.id, t.doc_id, ..., t.amount)
    values (ut.id, ut.doc_id, ..., ut.amount);
</code>```

In PostgreSQL, I suppose it should be something like this:

```<code>insert into transactions(id, doc_id, ..., amount)
select coalesce(t.id, ut.id), ut.doc_id, ... ut.amount
from updated_transactions ut
left join transactions t on t.doc_id = ut.doc_id, ....
    on conflict
    on constraint transactions_pkey
    do update
    set amount = excluded.amount, id = excluded.id
</code>```

The problem is with the do update clause: excluded.id is an old value
from transactions table, while I need a new value from updated_transactions.

ut.id value is inaccessible for the do update clause, and the only thing I can
use is the excluded row. But the excluded row has only coalesce(t.id, ut.id)
expression which returns old id values for the existing rows.

Is it possible to update both id and amount columns using the upsert query?

答:
Looks like the task can be accomplished using writable CTEs instead of the plain upsert.

First, I'll post the easier version of the query that answers the original question as it was asked. This solution assumes that doc_id, unit_id columns address a candidate key, but doesn't require a unique index on these columns.

Test data:

```<code>create temp table transactions
(
    id bigint primary key,
    doc_id bigint,
    unit_id bigint,
    amount numeric
);

create temp table updated_transactions
(
    id bigint primary key,
    doc_id bigint,
    unit_id bigint,
    amount numeric
);

insert into transactions(id, doc_id, unit_id, amount)
values (1, 1, 1, 10), (2, 1, 2, 15), (3, 1, 3, 10);

insert into updated_transactions(id, doc_id, unit_id, amount)
values (6, 1, 1, 11), (7, 1, 2, 15), (8, 1, 4, 20);
</code>```

The query to merge updated_transactions into transactions:

```<code>with new_values as
(
    select ut.id new_id, t.id old_id, ut.doc_id, ut.unit_id, ut.amount
    from updated_transactions ut
    left join transactions t
        on t.doc_id = ut.doc_id and t.unit_id = ut.unit_id
),
updated as
(
    update transactions tr
    set id = nv.new_id, amount = nv.amount
    from new_values nv
    where id = nv.old_id
    returning tr.*
)
insert into transactions(id, doc_id, unit_id, amount)
select ut.new_id, ut.doc_id, ut.unit_id, ut.amount
from new_values ut
where ut.new_id not in (select id from updated);
</code>```

The results:

```<code>select * from transactions

-- id | doc_id | unit_id | amount
------+--------+---------+-------
--  3 |   1    |    3    |  10    -- not changed
--  6 |   1    |    1    |  11    -- updated
--  7 |   1    |    2    |  15    -- updated
--  8 |   1    |    4    |  20    -- inserted
</code>```

In my real application doc_id, unit_id aren't always unique, so they don't represent a candidate key. To match the rows I take into account the row number, calculated for the rows sorted by their ids. So here's my second solution.

Test data:

```<code>-- the tables are the same as above
insert into transactions(id, doc_id, unit_id, amount)
values (1, 1, 1, 10), (2, 1, 1, 15), (3, 1, 3, 10);

insert into updated_transactions(id, doc_id, unit_id, amount)
values (6, 1, 1, 11), (7, 1, 1, 15), (8, 1, 4, 20);
</code>```

The merge query:

```<code>with trans as
(
    select id, doc_id, unit_id, amount,
        row_number() over(partition by doc_id, unit_id order by id) row_num
    from transactions
),
updated_trans as
(
    select id, doc_id, unit_id, amount,
        row_number() over(partition by doc_id, unit_id order by id) row_num
    from updated_transactions
),
new_values as
(
    select ut.id new_id, t.id old_id, ut.doc_id, ut.unit_id, ut.amount
    from updated_trans ut
    left join trans t
        on t.doc_id = ut.doc_id and t.unit_id = ut.unit_id and t.row_num = ut.row_num
),
updated as
(
    update transactions tr
    set id = nv.new_id, amount = nv.amount
    from new_values nv
    where id = nv.old_id
    returning tr.*
)
insert into transactions(id, doc_id, unit_id, amount)
select ut.new_id, ut.doc_id, ut.unit_id, ut.amount
from new_values ut
where ut.new_id not in (select id from updated);
</code>```

The results:

```<code>select * from transactions;

-- id | doc_id | unit_id | amount
------+--------+---------+-------
--  3 |   1    |    3    | 10     -- not changed
--  6 |   1    |    1    | 11     -- updated
--  7 |   1    |    1    | 15     -- updated
--  8 |   1    |    4    | 20     -- inserted
</code>```

References:

Insert on duplicate update in PostgreSQL

Upserting via Writeable CTE

Waiting for 9.1 — Writable CTE

Why is UPSERT so complicated?

Body:
Suppose I have two tables in my Postgres database:

create table transactions
(
    id bigint primary key,
    doc_id bigint not null,
    -- lots of other columns...
    amount numeric not null
);

-- same columns
create temporary table updated_transactions
(
    id bigint primary key,
    doc_id bigint not null,
    -- lots of other columns...
    amount numeric not null
);

Both tables have just a primary key, and no unique indexes.

I need to upsert rows from updated_transactions into transactions using the following rules:

id column values in transactions and updated_transactions don't match

other columns like doc_id, etc (except of the amount) should match

when a matching row is found, update both amount and id columns

when a matching row is not found, insert it

id values in updated_transactions are taken from a sequence.
A business object just populates updated_transactions and then merges the
new or updated rows from it into transactions using an upsert query.
So my old unchanged transactions keep their ids intact, and the updated ones
are assigned new ids.

In MSSQL and Oracle, it would be a merge statement similar to this:

merge into transactions t
using updated_transactions ut on t.doc_id = ut.doc_id, ...
when matched then
    update set t.id = ut.id, t.amount = ut.amount
when not matched then
    insert (t.id, t.doc_id, ..., t.amount)
    values (ut.id, ut.doc_id, ..., ut.amount);

In PostgreSQL, I suppose it should be something like this:

insert into transactions(id, doc_id, ..., amount)
select coalesce(t.id, ut.id), ut.doc_id, ... ut.amount
from updated_transactions ut
left join transactions t on t.doc_id = ut.doc_id, ....
    on conflict
    on constraint transactions_pkey
    do update
    set amount = excluded.amount, id = excluded.id

The problem is with the do update clause: excluded.id is an old value
from transactions table, while I need a new value from updated_transactions.

ut.id value is inaccessible for the do update clause, and the only thing I can
use is the excluded row. But the excluded row has only coalesce(t.id, ut.id)
expression which returns old id values for the existing rows.

Is it possible to update both id and amount columns using the upsert query?

Body:
Looks like the task can be accomplished using writable CTEs instead of the plain upsert.

First, I'll post the easier version of the query that answers the original question as it was asked. This solution assumes that doc_id, unit_id columns address a candidate key, but doesn't require a unique index on these columns.

Test data:

create temp table transactions
(
    id bigint primary key,
    doc_id bigint,
    unit_id bigint,
    amount numeric
);

create temp table updated_transactions
(
    id bigint primary key,
    doc_id bigint,
    unit_id bigint,
    amount numeric
);

insert into transactions(id, doc_id, unit_id, amount)
values (1, 1, 1, 10), (2, 1, 2, 15), (3, 1, 3, 10);

insert into updated_transactions(id, doc_id, unit_id, amount)
values (6, 1, 1, 11), (7, 1, 2, 15), (8, 1, 4, 20);

The query to merge updated_transactions into transactions:

with new_values as
(
    select ut.id new_id, t.id old_id, ut.doc_id, ut.unit_id, ut.amount
    from updated_transactions ut
    left join transactions t
        on t.doc_id = ut.doc_id and t.unit_id = ut.unit_id
),
updated as
(
    update transactions tr
    set id = nv.new_id, amount = nv.amount
    from new_values nv
    where id = nv.old_id
    returning tr.*
)
insert into transactions(id, doc_id, unit_id, amount)
select ut.new_id, ut.doc_id, ut.unit_id, ut.amount
from new_values ut
where ut.new_id not in (select id from updated);

The results:

select * from transactions

-- id | doc_id | unit_id | amount
------+--------+---------+-------
--  3 |   1    |    3    |  10    -- not changed
--  6 |   1    |    1    |  11    -- updated
--  7 |   1    |    2    |  15    -- updated
--  8 |   1    |    4    |  20    -- inserted

In my real application doc_id, unit_id aren't always unique, so they don't represent a candidate key. To match the rows I take into account the row number, calculated for the rows sorted by their ids. So here's my second solution.

Test data:

-- the tables are the same as above
insert into transactions(id, doc_id, unit_id, amount)
values (1, 1, 1, 10), (2, 1, 1, 15), (3, 1, 3, 10);

insert into updated_transactions(id, doc_id, unit_id, amount)
values (6, 1, 1, 11), (7, 1, 1, 15), (8, 1, 4, 20);

The merge query:

with trans as
(
    select id, doc_id, unit_id, amount,
        row_number() over(partition by doc_id, unit_id order by id) row_num
    from transactions
),
updated_trans as
(
    select id, doc_id, unit_id, amount,
        row_number() over(partition by doc_id, unit_id order by id) row_num
    from updated_transactions
),
new_values as
(
    select ut.id new_id, t.id old_id, ut.doc_id, ut.unit_id, ut.amount
    from updated_trans ut
    left join trans t
        on t.doc_id = ut.doc_id and t.unit_id = ut.unit_id and t.row_num = ut.row_num
),
updated as
(
    update transactions tr
    set id = nv.new_id, amount = nv.amount
    from new_values nv
    where id = nv.old_id
    returning tr.*
)
insert into transactions(id, doc_id, unit_id, amount)
select ut.new_id, ut.doc_id, ut.unit_id, ut.amount
from new_values ut
where ut.new_id not in (select id from updated);

The results:

select * from transactions;

-- id | doc_id | unit_id | amount
------+--------+---------+-------
--  3 |   1    |    3    | 10     -- not changed
--  6 |   1    |    1    | 11     -- updated
--  7 |   1    |    1    | 15     -- updated
--  8 |   1    |    4    | 20     -- inserted

References:

Insert on duplicate update in PostgreSQL

Upserting via Writeable CTE

Waiting for 9.1 — Writable CTE

Why is UPSERT so complicated?


问:
Microsoft Access - Combo Box - cannot add record, join key of table is not in recordset
No matter how many tutorial, guides, or example I try to learn from; I can't seem to figure out how to make mine work. Its almost like a hit and miss when it comes to it. I got it working on some forms but I can't seem to get it working on others. Is there a trick to getting a combo box working; That I am missing?!

for example in my vendor form.

frm_vendor

```<code>   tbl_vendor  ->      tbl_address    ->     tbl_addressType
PK vendorID         PK addressID          PK addressTypeID
FK addressID        FK addressTypeID
</code>```

I am able to create a combo box which allows you to select the addressTypeID <- no problem

control source = addressTypeID

row source =SELECT [tbl_addressType].[addressTypeID], [tbl_addressType].[addressType] FROM tbl_addressType;

row source type = Query/Table

bound to column = 1

limit to list = 1

not editable

But on this new form, I can't see to get it working.

control source = addressTypeID seems to be invalid and gives me a warning.

When you create a form base off a query. Should I be including every PK / FK in this query even thought I wont be displaying it, so the form can understand the links?

答:
I agree with @Rikalous

you need to make sure the query you have based the form on has got a field called addressTypeID

Hope this link can help:
Microsoft Access cannot add records join key of table not in recordset

Body:
No matter how many tutorial, guides, or example I try to learn from; I can't seem to figure out how to make mine work. Its almost like a hit and miss when it comes to it. I got it working on some forms but I can't seem to get it working on others. Is there a trick to getting a combo box working; That I am missing?!

for example in my vendor form.

frm_vendor

   tbl_vendor  ->      tbl_address    ->     tbl_addressType
PK vendorID         PK addressID          PK addressTypeID
FK addressID        FK addressTypeID

I am able to create a combo box which allows you to select the addressTypeID <- no problem

control source = addressTypeID

row source =SELECT [tbl_addressType].[addressTypeID], [tbl_addressType].[addressType] FROM tbl_addressType;

row source type = Query/Table

bound to column = 1

limit to list = 1

not editable

But on this new form, I can't see to get it working.

control source = addressTypeID seems to be invalid and gives me a warning.

When you create a form base off a query. Should I be including every PK / FK in this query even thought I wont be displaying it, so the form can understand the links?


问:
Android ListView Scrollbar
I created a list view.I need to increase the width of the vertical scrollbar. I changed android:scrollbarSize. But it is not working .Also want to decrease length of scrollbar thumb.Is it posiible. Please help me. </p>

```<code><LinearLayout android:id="@+id/LinearLayout01"
 android:layout_width="fill_parent" android:layout_height="fill_parent"
 xmlns:android="http://schemas.android.com/apk/res/android">

<ListView
 android:id="@+id/list_view"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:scrollbars="vertical"
 android:scrollbarAlwaysDrawVerticalTrack="true"
 android:scrollX="0px"
 android:scrollY="0px"
 android:background="#515151"
 android:layout_weight="1"
 android:scrollbarStyle="outsideOverlay"
 android:divider="#FFF"
 android:fadeScrollbars="false"
 android:scrollbarSize="20dip"/>

 </LinearLayout>
</code>```

答:
I asked this same question and didn't receive any answer: android ignores scrollbarsize

Then, there was an issue opened but the closed it stating "working as intended":
http://code.google.com/p/android/issues/detail?id=7711&can=1&q=scrollbar%20width&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars

So far, I haven't seen a solution, tho I haven't researched that much. If you find any solution, please update this question.

ContentLicense: CC BY-SA 2.5

Title: Android ListView Scrollbar

Body:
I created a list view.I need to increase the width of the vertical scrollbar. I changed android:scrollbarSize. But it is not working .Also want to decrease length of scrollbar thumb.Is it posiible. Please help me.

<LinearLayout android:id="@+id/LinearLayout01"
 android:layout_width="fill_parent" android:layout_height="fill_parent"
 xmlns:android="http://schemas.android.com/apk/res/android">

<ListView
 android:id="@+id/list_view"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:scrollbars="vertical"
 android:scrollbarAlwaysDrawVerticalTrack="true"
 android:scrollX="0px"
 android:scrollY="0px"
 android:background="#515151"
 android:layout_weight="1"
 android:scrollbarStyle="outsideOverlay"
 android:divider="#FFF"
 android:fadeScrollbars="false"
 android:scrollbarSize="20dip"/>

 </LinearLayout>


问:
Ul tag. How to identify the begin and end of a list with Regex
I have a lot of different blog posts in a database. They are in markdown. I want to convert them to html. I have problems with the ul tag.

For instance in a simplified way I have that:

```<code>Something
- First
- Second
Something else

Second ul
- First
- Second
Some final text
</code>```

I could put the li tags:

```<code>$text = preg_replace("/^- (.*)/m", "<li>$1</li>", $text);
</code>```

But how can I identify the beginning or end of the list to put the ul tag?

I want this result:

```<code>Something
<ul>
<li>- First</li>
<li>- Second</li>
</ul>
Something else

Second ul
<ul>
<li>- First</li>
<li>- Second</li>
</ul>
Some final text
</code>```

答:
You need to do this in two passes, so with two preg_replace calls:

```<code>$text = preg_replace("/^- (.*)/m", "<li>$1</li>",
            preg_replace("/^- .*(\R- .*)*/m", "<ul>\n$0\n</ul>", $text)
        );
</code>```

The inner one executes first, and finds lines that starts with - and captures all the following lines that also start with - until the line that follows does not start -.

.* matches anything up to the end of the current line. The new line character is not matched by .. So the next \R is used for matching anything considered a linebreak sequence. And then again the hyphen check is done and the remainder of the line is captured. This can repeat (( ... )*) as many times as possible.

That matched block is then wrapped in an ul tag. The hyphens are not removed at this stage.

The outer one will wrap lines that start with - in li tags, taking out the -.

Body:
I have a lot of different blog posts in a database. They are in markdown. I want to convert them to html. I have problems with the ul tag.

For instance in a simplified way I have that:

Something
- First
- Second
Something else

Second ul
- First
- Second
Some final text

I could put the li tags:

$text = preg_replace("/^- (.*)/m", "
$1
", $text);

But how can I identify the beginning or end of the list to put the ul tag?

I want this result:

Something

- First

- Second

Something else

Second ul

- First

- Second

Some final text

Body:
You need to do this in two passes, so with two preg_replace calls:

$text = preg_replace("/^- (.*)/m", "<li>$1</li>",
            preg_replace("/^- .*(\R- .*)*/m", "<ul>\n$0\n</ul>", $text)
        );

The inner one executes first, and finds lines that starts with - and captures all the following lines that also start with - until the line that follows does not start -.

.* matches anything up to the end of the current line. The new line character is not matched by .. So the next \R is used for matching anything considered a linebreak sequence. And then again the hyphen check is done and the remainder of the line is captured. This can repeat (( ... )*) as many times as possible.

That matched block is then wrapped in an ul tag. The hyphens are not removed at this stage.

The outer one will wrap lines that start with - in li tags, taking out the -.


问:
Snackbar action text color not changing
I want to change the action text color for my snackbar, but it is not working for some reason.

I use the following code to display a snackbar:

```<code>Snackbar.make(findViewById(R.id.root), "text", Snackbar.LENGTH_LONG).setActionTextColor(R.color.yellow).setAction("OK", new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    }
}).show();
</code>```

答:
None of above answers helped me.
I found this solution, and it works by changing manually the TextView's text color</p>

```<code>Snackbar snack = Snackbar.make(v, "Snackbar message", Snackbar.LENGTH_LONG);
View view = snack.getView();
TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
tv.setTextColor(Color.WHITE);
snack.show();
</code>```

Title: Snackbar action text color not changing

Body:
I want to change the action text color for my snackbar, but it is not working for some reason.

I use the following code to display a snackbar:

Snackbar.make(findViewById(R.id.root), "text", Snackbar.LENGTH_LONG).setActionTextColor(R.color.yellow).setAction("OK", new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    }
}).show();

Body:
None of above answers helped me.
I found this solution, and it works by changing manually the TextView's text color

Snackbar snack = Snackbar.make(v, "Snackbar message", Snackbar.LENGTH_LONG);
View view = snack.getView();
TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
tv.setTextColor(Color.WHITE);
snack.show();


问:
Using Actors to exploit cores
I'm new to Scala in general and Actors in particular and my problem is so basic, the online resources I have found don't cover it.

I have a CPU-intensive, easily parallelized algorithm that will be run on an n-core machine (I don't know n).  How do I implement this in Actors so that all available cores address the problem?

The first way I thought of was to simple break the problem into m pieces (where m is some medium number like 10,000) and create m Actors, one for each piece, give each Actor its little piece and let 'em go.

Somehow, this struck me as inefficient.  Zillions of Actors just hanging around, waiting for some CPU love, pointlessly switching contexts...

Then I thought, make some smaller number of Actors, and feed each one several pieces.  The problem was, there's no reason to expect the pieces are the same size, so one core might get bogged down, with many of its tasks still queued, while other cores are idle.

I noodled around with a Supervisor that knew which Actors were busy, and eventually realized that this has to be a solved problem.  There must be a standard pattern (maybe even a standard library) for dealing with this very generic issue.  Any suggestions?

答:
Generally, there're 2 kinds of actors: those that are tied to threads (one thread per actor), and those that share 1+ thread, working behind a scheduler/dispatcher that allocates resources (= possibility to execute a task/handle incoming message against controlled thread-pool or a single thread).

I assume, you use second type of actors - event-driven actors, because you mention that you run 10k of them. No matter how many event-driven actors you have (thousands or millions), all of them will be fighting for the small thread pool to handle the message. Therefore, you will even have a worse performance dividing your task queue into that huge number of portions - scheduler will either try to handle messages sent to 10k actors against a fixed thread pool (which is slow), or will allocate new threads in the pool (if the pool is not bounded), which is dangerous (in the worst case, there will be started 10k threads to handle messages).

Event-driven actors are good for short-time (ideally, non-blocking) tasks. If you're dealing with CPU-intensive tasks I'd limit number of threads in the scheduler/dispatcher pool (when you use event-driven actors) or actors themselves (when you use thread-based actors) to the number of cores to achieve the best performance.

If you want this to be done automatically (adjust number of threads in dispatcher pool to the number of cores), you should use HawtDisaptch (or it's Akka implementation), as it was proposed earlier:

The 'HawtDispatcher' uses the
  HawtDispatch threading library which
  is a Java clone of libdispatch. All
  actors with this type of dispatcher
  are executed on a single system wide
  fixed sized thread pool. The number of
  of threads will match the number of
  cores available on your system. The
  dispatcher delivers messages to the
  actors in the order that they were
  producer at the sender.

Title: Using Actors to exploit cores


问:
:after content displaying over original element
The .back-btn servers as a background image of an arrow. I am wanting the :after content to display under the image. I am unsure what I am doing wrong. I have tried adding margin-top and position:relative to the :after element, but nothing seems to work. Does anyone see what I am doing wrong?

.back-btn {
    position: fixed;
    left: 2%;
    display: block;
    cursor: pointer;
    background-image: url("https://d30y9cdsu7xlg0.cloudfront.net/png/41-200.png");
    background-repeat: no-repeat;
    background-size: 35px 35px;
    height: 35px;
    width: 35px;
}
.back-btn:after {
    content: "Back";
    color: #303030;
    font-size: .8em;
    display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="back-btn"></div></code>```

答:
Try this

```<code>.back-btn:after {
    content: "Back";
    color: #303030;
    font-size: .8em;
    display: block;
    margin-top:35px;
}
</code>```

update link of your code

Body:
Try this

.back-btn:after {
    content: "Back";
    color: #303030;
    font-size: .8em;
    display: block;
    margin-top:35px;
}

update link of your code


问:
Mongodb aggregation for date comparison
I have a collection that contains documents in the following format.

```<code>{
    "_id" : ObjectId("58d9fa5cb35630097b96acab"),
    "invoice_id" : ObjectId("58d9fa5cb35630097b96acaa"),
    "amount" : 717.6,
    "date" : "2017-03-28",
    "by_id" : ObjectId("58d9d6a0b35630097b96a729")

},
{
    "_id" : ObjectId("58d9ff77b35630097b96acb8"),
    "invoice_id" : ObjectId("58d9ff77b35630097b96acb7"),
    "amount" : 717.6,
    "date" : "2017-03-28",
    "by_id" : ObjectId("58d9d6a0b35630097b96a729")
}
</code>```

I need to make a date comparison using aggregation, but dates in the documents are not in the correct format. So I'm trying to add a new field called c_date with correctly formatted date value, using $addFields function for each document.

```<code>db.table.aggregate([
{ $addFields: { c_date : new ISODate('2017-03-29')} }
])
</code>```

The above query results

```<code>{
    "_id" : ObjectId("58d9fa5cb35630097b96acab"),
    "invoice_id" : ObjectId("58d9fa5cb35630097b96acaa"),
    "amount" : 717.6,
    "date" : "2017-03-28",
    "by_id" : ObjectId("58d9d6a0b35630097b96a729"),
    "c_date": 2017-03-29 00:00:00.000Z
},
{
    "_id" : ObjectId("58d9ff77b35630097b96acb8"),
    "invoice_id" : ObjectId("58d9ff77b35630097b96acb7"),
    "amount" : 717.6,
    "date" : "2017-03-28",
    "by_id" : ObjectId("58d9d6a0b35630097b96a729")
    "c_date": 2017-03-29 00:00:00.000Z
}
</code>```

I want to add the formatted value of date field to the c_date field in the each document. How to achieve it?

答:
My approach to update the c_date with formatted date field from the same document is as shown below

```<code>db.table.find().forEach(function(element){
 element.c_date = new Date(element.date);
 db.table.save(element);
});
</code>```

Initial records

```<code>{
        "_id" : ObjectId("58d9fa5cb35630097b96acab"),
        "invoice_id" : ObjectId("58d9fa5cb35630097b96acaa"),
        "amount" : 717.6,
        "date" : "2017-03-28",
        "by_id" : ObjectId("58d9d6a0b35630097b96a729"),
        "c_date" : ISODate("2017-03-29T00:00:00Z")
}
{
        "_id" : ObjectId("58d9ff77b35630097b96acb8"),
        "invoice_id" : ObjectId("58d9ff77b35630097b96acb7"),
        "amount" : 717.6,
        "date" : "2017-03-28",
        "by_id" : ObjectId("58d9d6a0b35630097b96a729"),
        "c_date" : ISODate("2017-03-29T00:00:00Z")
}
</code>```

After execution of the function

```<code>{
        "_id" : ObjectId("58d9fa5cb35630097b96acab"),
        "invoice_id" : ObjectId("58d9fa5cb35630097b96acaa"),
        "amount" : 717.6,
        "date" : "2017-03-28",
        "by_id" : ObjectId("58d9d6a0b35630097b96a729"),
        "c_date" : ISODate("2017-03-28T00:00:00Z")
}
{
        "_id" : ObjectId("58d9ff77b35630097b96acb8"),
        "invoice_id" : ObjectId("58d9ff77b35630097b96acb7"),
        "amount" : 717.6,
        "date" : "2017-03-28",
        "by_id" : ObjectId("58d9d6a0b35630097b96a729"),
        "c_date" : ISODate("2017-03-28T00:00:00Z")
}
</code>```

Using $project you can add new fields or project the existing fields in the documents to next stage of pipeline, but modify/update a field is on same document is not possible.

Whereas we have a workaround and $out, which will takes the documents returned by the aggregation pipeline and writes them to a specified collection.

Hope it Helps!

Title: Mongodb aggregation for date comparison

Body:
I have a collection that contains documents in the following format.

{
    "_id" : ObjectId("58d9fa5cb35630097b96acab"),
    "invoice_id" : ObjectId("58d9fa5cb35630097b96acaa"),
    "amount" : 717.6,
    "date" : "2017-03-28",
    "by_id" : ObjectId("58d9d6a0b35630097b96a729")

},
{
    "_id" : ObjectId("58d9ff77b35630097b96acb8"),
    "invoice_id" : ObjectId("58d9ff77b35630097b96acb7"),
    "amount" : 717.6,
    "date" : "2017-03-28",
    "by_id" : ObjectId("58d9d6a0b35630097b96a729")
}

I need to make a date comparison using aggregation, but dates in the documents are not in the correct format. So I'm trying to add a new field called c_date with correctly formatted date value, using $addFields function for each document.

db.table.aggregate([
{ $addFields: { c_date : new ISODate('2017-03-29')} }
])

The above query results

{
    "_id" : ObjectId("58d9fa5cb35630097b96acab"),
    "invoice_id" : ObjectId("58d9fa5cb35630097b96acaa"),
    "amount" : 717.6,
    "date" : "2017-03-28",
    "by_id" : ObjectId("58d9d6a0b35630097b96a729"),
    "c_date": 2017-03-29 00:00:00.000Z
},
{
    "_id" : ObjectId("58d9ff77b35630097b96acb8"),
    "invoice_id" : ObjectId("58d9ff77b35630097b96acb7"),
    "amount" : 717.6,
    "date" : "2017-03-28",
    "by_id" : ObjectId("58d9d6a0b35630097b96a729")
    "c_date": 2017-03-29 00:00:00.000Z
}

I want to add the formatted value of date field to the c_date field in the each document. How to achieve it?

Body:
My approach to update the c_date with formatted date field from the same document is as shown below

db.table.find().forEach(function(element){
 element.c_date = new Date(element.date);
 db.table.save(element);
});

Initial records

{
        "_id" : ObjectId("58d9fa5cb35630097b96acab"),
        "invoice_id" : ObjectId("58d9fa5cb35630097b96acaa"),
        "amount" : 717.6,
        "date" : "2017-03-28",
        "by_id" : ObjectId("58d9d6a0b35630097b96a729"),
        "c_date" : ISODate("2017-03-29T00:00:00Z")
}
{
        "_id" : ObjectId("58d9ff77b35630097b96acb8"),
        "invoice_id" : ObjectId("58d9ff77b35630097b96acb7"),
        "amount" : 717.6,
        "date" : "2017-03-28",
        "by_id" : ObjectId("58d9d6a0b35630097b96a729"),
        "c_date" : ISODate("2017-03-29T00:00:00Z")
}

After execution of the function

{
        "_id" : ObjectId("58d9fa5cb35630097b96acab"),
        "invoice_id" : ObjectId("58d9fa5cb35630097b96acaa"),
        "amount" : 717.6,
        "date" : "2017-03-28",
        "by_id" : ObjectId("58d9d6a0b35630097b96a729"),
        "c_date" : ISODate("2017-03-28T00:00:00Z")
}
{
        "_id" : ObjectId("58d9ff77b35630097b96acb8"),
        "invoice_id" : ObjectId("58d9ff77b35630097b96acb7"),
        "amount" : 717.6,
        "date" : "2017-03-28",
        "by_id" : ObjectId("58d9d6a0b35630097b96a729"),
        "c_date" : ISODate("2017-03-28T00:00:00Z")
}

Using $project you can add new fields or project the existing fields in the documents to next stage of pipeline, but modify/update a field is on same document is not possible.

Whereas we have a workaround and $out, which will takes the documents returned by the aggregation pipeline and writes them to a specified collection.

Hope it Helps!


问:
Nginx config SSL Error
nginx won't start.
I'm using the turnkeylinux NGINX image for VMware and installed the NGINX module for the included webmin. this is the printout when I try to start NGINX via ssh:</p>

```<code>root@nginx-php-fastcgi ~# nginx
nginx: [emerg] BIO_new_file("/etc/ssl/nginx/server.crt") failed (SSL: error:02001002:system library:fopen:No such file or dire
ctory:fopen('/etc/ssl/nginx/server.crt','r') error:2006D080:BIO routines:BIO_new_file:no such file)
root@nginx-php-fastcgi ~# nginx -s reload
nginx: [emerg] BIO_new_file("/etc/ssl/nginx/server.crt") failed (SSL: error:02001002:system library:fopen:No such file or dire
ctory:fopen('/etc/ssl/nginx/server.crt','r') error:2006D080:BIO routines:BIO_new_file:no such file)
root@nginx-php-fastcgi ~#
</code>```

答: Most likely you have to either switch SSL off for your website in /etc/nginx/nginx.conf or make sure the SSL-certificate file exists in the /etc/ssl/nginx/server.crt path and is valid.

Title: Nginx config SSL Error

Body:
nginx won't start.
I'm using the turnkeylinux NGINX image for VMware and installed the NGINX module for the included webmin. this is the printout when I try to start NGINX via ssh:

root@nginx-php-fastcgi ~# nginx
nginx: [emerg] BIO_new_file("/etc/ssl/nginx/server.crt") failed (SSL: error:02001002:system library:fopen:No such file or dire
ctory:fopen('/etc/ssl/nginx/server.crt','r') error:2006D080:BIO routines:BIO_new_file:no such file)
root@nginx-php-fastcgi ~# nginx -s reload
nginx: [emerg] BIO_new_file("/etc/ssl/nginx/server.crt") failed (SSL: error:02001002:system library:fopen:No such file or dire
ctory:fopen('/etc/ssl/nginx/server.crt','r') error:2006D080:BIO routines:BIO_new_file:no such file)
root@nginx-php-fastcgi ~#


问:
shell script command error
I try executing the CPU monitoring script below, and the script throws an error.  But direct execution of top -bn1 | grep "Cpu(s)" | awk '{print$2}' | sed -e 's/%us,//g' does not throw an error.  Can someone help here??

```<code> if (top -bn1 | grep "Cpu(s)" | awk '{print$2}' | sed -e 's/%us,//g') -gt 1 ; then
     echo ('CPU percentage is $CPU_PER, which is higher than 50%. Kindly login to server and validate the process.')
 else
     echo  ('Executing Else statement.')
 fi
</code>```

答:
With less fuss, awk can do the parsing, the decimal comparison, and then output an exit status.  Any code with a true/false exit status  can be used after an if or before a &&:

```<code>top -bn1 | awk 'NR == 3 { f=($2 > 1) } END{exit !f}'  && echo "yadda yadda"
</code>```

The awk code checks only the 3rd line: NR == 3; then compares the second item to 1: ($2 > 1); and stores that true/false value in f, and outputs the logical NOT of that, exit !f, so the unix shell understands.

Output:

```<code>yadda yadda
</code>```

Adding a print to the awk code allows storing the value to a shell variable $n at the same time:

```<code>if n=$(top -bn1 | \
       awk 'NR == 3 { print $2 ; f=($2 > 1) } END{exit !f}') ; \
then echo "$n > 1" ; else echo "$n <= 1" ; fi
</code>```

Output (on my system):

```<code>18.6 > 1
</code>```

Title: shell script command error

Body:
I try executing the CPU monitoring script below, and the script throws an error.  But direct execution of top -bn1 | grep "Cpu(s)" | awk '{print$2}' | sed -e 's/%us,//g' does not throw an error.  Can someone help here??

 if (top -bn1 | grep "Cpu(s)" | awk '{print$2}' | sed -e 's/%us,//g') -gt 1 ; then
     echo ('CPU percentage is $CPU_PER, which is higher than 50%. Kindly login to server and validate the process.')
 else
     echo  ('Executing Else statement.')
 fi

Body:
With less fuss, awk can do the parsing, the decimal comparison, and then output an exit status.  Any code with a true/false exit status  can be used after an if or before a &&:

top -bn1 | awk 'NR == 3 { f=($2 > 1) } END{exit !f}'  && echo "yadda yadda"

The awk code checks only the 3rd line: NR == 3; then compares the second item to 1: ($2 > 1); and stores that true/false value in f, and outputs the logical NOT of that, exit !f, so the unix shell understands.

Output:

yadda yadda

Adding a print to the awk code allows storing the value to a shell variable $n at the same time:

if n=$(top -bn1 | \
       awk 'NR == 3 { print $2 ; f=($2 > 1) } END{exit !f}') ; \
then echo "$n > 1" ; else echo "$n <= 1" ; fi

Output (on my system):

18.6 > 1


问:
How to find a particular table cell in Watir
Using Watir to regression test some changes: I want to 'click' a row in a typical old style web page menu, where the menu is a table of tables.  In this particular example, the table cell contains the menu item, and the row, which only consists of the one cell, has an onclick handler.  I thought I could

```<code>cell = browser.element_by_xpath("//div[@id='Menu']/descendant::td[text()='New!'")
</code>```

and use the cell to get the parent row, but I get the message

c:/ruby/lib/ruby/1.8/rexml/parsers/xpathparser.rb:330:in 'Predicate': undefined
  method `[]' for nil:NilClass (NoMethodError)

which makes no sense to me.

答:
try this

```<code>cell = browser.div(:id,'Menu').cell(:text,'New!')
cell.click
</code>```

and, maybe you lost closing ']' ?

```<code>cell = browser.element_by_xpath("//div[@id='Menu']/descendant::td[text()='New!']")
</code>```

Body:
Using Watir to regression test some changes: I want to 'click' a row in a typical old style web page menu, where the menu is a table of tables.  In this particular example, the table cell contains the menu item, and the row, which only consists of the one cell, has an onclick handler.  I thought I could

cell = browser.element_by_xpath("//div[@id='Menu']/descendant::td[text()='New!'")

and use the cell to get the parent row, but I get the message

c:/ruby/lib/ruby/1.8/rexml/parsers/xpathparser.rb:330:in 'Predicate': undefined
  method `[]' for nil:NilClass (NoMethodError)

which makes no sense to me.

Body:
try this

cell = browser.div(:id,'Menu').cell(:text,'New!')
cell.click

and, maybe you lost closing ']' ?

cell = browser.element_by_xpath("//div[@id='Menu']/descendant::td[text()='New!']")


问:
Using Variable in Filter
I'm trying to query AD for a list of users from their Surname, which are help in a list.

I've tried most of the afternoon, but I just get a blank Excel sheet.

Also I want to know if there is more than one person with that username in AD, no idea how to even start with that one.

What I have so far:

```<code>Import-module ActiveDirectory
$names = get-content c:\tempfiles\Final.txt
$names | ForEach-Object {
$ADUserParams=@{
'Searchbase' = 'OU=Administrators,OU=Locations,DC=The,DC=group,DC=com'
'Searchscope'= 'Subtree'
}
get-aduser @ADUserParams  -filter 'surname -like "$Names*"' | Select-Object Samaccountname, UserPrincipalName | export-csv C:\TempFiles\Usernames.csv
}
</code>```

Do I even need a filter if it's a foreach-object? And is there a way to then check AD within that OU if there are more than one surname that are the same, and how would I count them? I can pull out a list of users surnames and then run the following, but it's then a manual task to locate the missing names. (If that makes sense)

What I have for that so far is:

```<code>get-content C:\TempFiles\Users.txt | sort -u > C:\TempFiles\users_cleaned.txt
</code>```

答:
This should do it (however is untested as I don't have access to an AD right now):

```<code>Import-module ActiveDirectory
$names = get-content c:\tempfiles\Final.txt

$ADUserParams=@{
    'Searchbase' = 'OU=Administrators,OU=Locations,DC=The,DC=group,DC=com'
    'Searchscope'= 'Subtree'
}

$names | ForEach-Object {
    $CurrentUser = get-aduser @ADUserParams -filter "surname -like '$_*'" | Select-Object Samaccountname, UserPrincipalName

    If ($CurrentUser) {

        If ($CurrentUser.Count -gt 1){ $DuplicateSurname = $true }Else{ $DuplicateSurname=$false }

        $CurrentUser | ForEach-Object {
            $_ | Add-Member -MemberType NoteProperty -Name DuplicateSurname -Value $DuplicateSurname
            Write-Output $_
        }
    } Else {
        Write-Warning "$_* did not matched any users."
    }

} | export-csv C:\TempFiles\Usernames.csv
</code>```

Explanation:

Within a ForEach-Object loop the current item in the pipeline is represented by $_. You also need to use double quotes for the filter string, as variables (like $_) are expanded in double quoted strings, not single quoted strings.

You don't need to declare your $ADUserParams hashtable within the loop (that's wasteful) so I moved it outside.

The result of Get-ADUser will be returned to the pipeline, so finally I moved the | export-csv outside of the ForEach-Object so that the result of the processing is piped in to it. I think without this you'd only get the final result.

"Also I want to know if there is more than one person with that username in AD"

To handle this I have put a second ForEach-Object that loops through every user returned in to $CurrentUser and adds a "DuplicateSurname" property to the object (which should then be an additional column in your CSV) based on whether the count of $CurrentUser is more than 1 or not.

Finally we have to make sure that the contents of $_ are put back in to the pipeline which we do with Write-Object $_.

Title: Using Variable in Filter

Body:
I'm trying to query AD for a list of users from their Surname, which are help in a list.

I've tried most of the afternoon, but I just get a blank Excel sheet.

Also I want to know if there is more than one person with that username in AD, no idea how to even start with that one.

What I have so far:

Import-module ActiveDirectory
$names = get-content c:\tempfiles\Final.txt
$names | ForEach-Object {
$ADUserParams=@{
'Searchbase' = 'OU=Administrators,OU=Locations,DC=The,DC=group,DC=com'
'Searchscope'= 'Subtree'
}
get-aduser @ADUserParams  -filter 'surname -like "$Names*"' | Select-Object Samaccountname, UserPrincipalName | export-csv C:\TempFiles\Usernames.csv
}

Do I even need a filter if it's a foreach-object? And is there a way to then check AD within that OU if there are more than one surname that are the same, and how would I count them? I can pull out a list of users surnames and then run the following, but it's then a manual task to locate the missing names. (If that makes sense)

What I have for that so far is:

get-content C:\TempFiles\Users.txt | sort -u > C:\TempFiles\users_cleaned.txt

Body:
This should do it (however is untested as I don't have access to an AD right now):

Import-module ActiveDirectory
$names = get-content c:\tempfiles\Final.txt

$ADUserParams=@{
    'Searchbase' = 'OU=Administrators,OU=Locations,DC=The,DC=group,DC=com'
    'Searchscope'= 'Subtree'
}

$names | ForEach-Object {
    $CurrentUser = get-aduser @ADUserParams -filter "surname -like '$_*'" | Select-Object Samaccountname, UserPrincipalName

    If ($CurrentUser) {

        If ($CurrentUser.Count -gt 1){ $DuplicateSurname = $true }Else{ $DuplicateSurname=$false }

        $CurrentUser | ForEach-Object {
            $_ | Add-Member -MemberType NoteProperty -Name DuplicateSurname -Value $DuplicateSurname
            Write-Output $_
        }
    } Else {
        Write-Warning "$_* did not matched any users."
    }

} | export-csv C:\TempFiles\Usernames.csv

Explanation:

Within a ForEach-Object loop the current item in the pipeline is represented by $_. You also need to use double quotes for the filter string, as variables (like $_) are expanded in double quoted strings, not single quoted strings.

You don't need to declare your $ADUserParams hashtable within the loop (that's wasteful) so I moved it outside.

The result of Get-ADUser will be returned to the pipeline, so finally I moved the | export-csv outside of the ForEach-Object so that the result of the processing is piped in to it. I think without this you'd only get the final result.

"Also I want to know if there is more than one person with that username in AD"

To handle this I have put a second ForEach-Object that loops through every user returned in to $CurrentUser and adds a "DuplicateSurname" property to the object (which should then be an additional column in your CSV) based on whether the count of $CurrentUser is more than 1 or not.

Finally we have to make sure that the contents of $_ are put back in to the pipeline which we do with Write-Object $_.

ContentLicense: CC BY-SA 4.0


问:
Visual studio loadtest run from VNext
I have a visual studio loadTest project and LoadTest2010 result database, when I run the test from visual studio then test work fine and test data save in the LoadTest2010 DB but when run the test from VNext then test run fine (did all the configurations) but data does not save in the DB LoadTest2010.
In VNext VsoAgent agent is running the test.
Did any one face this issue?</p>

答: this is the only one option right now in the VNext to run the loadtest and data will save to the loadtest database. Below is the snapshot from VNext

Title: Visual studio loadtest run from VNext


问:
How to sleep a thread and then break its sleep at any random moment in Android
Developing a realtime application where I have to make the thread go to  sleep as soon as I emit a message through SocketIo to the server and wait until response come from the server through SocketIo and then break the sleep of the thread.

```<code> for (TruckEnquiry value : list.values()) {

                String json = "any random string";
                SocketIO.mSocket.emit("server", json);
                try {
                    sleep(5000);  // Need to break this sleep from the UI thread of Android.
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

 }
</code>```

// Here we get the message from the server and at this point I would like to reume the thread
    private Emitter.Listener onNewMessage = new Emitter.Listener() {

```<code>    @Override
    public void call(final Object... args) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                JSONObject data = (JSONObject) args[0];
                // threadArray.get(perticular_thread).resume();  // Want to implement this.
            }
        });
    }
};
</code>```

I have more then one thread in this file and threadArray will contain all of them.

Thank You in advance.

答:
You can't put a single Thread to sleep because Thread.sleep(int) is a static method which "puts to sleep" all Threads in the application's thread pool.

You could:

1) Get the server response in the same connection you sent the JSON data.

2) Listen for a server eventual response by setting up a TCP (or UDP) listener in your app. Then the server would make a connection to your app with the URL "device_ip:listening_port", and the app would retrieve the response.

Body:
Developing a realtime application where I have to make the thread go to  sleep as soon as I emit a message through SocketIo to the server and wait until response come from the server through SocketIo and then break the sleep of the thread.

 for (TruckEnquiry value : list.values()) {

                String json = "any random string";
                SocketIO.mSocket.emit("server", json);
                try {
                    sleep(5000);  // Need to break this sleep from the UI thread of Android.
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

 }

// Here we get the message from the server and at this point I would like to reume the thread
    private Emitter.Listener onNewMessage = new Emitter.Listener() {

    @Override
    public void call(final Object... args) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                JSONObject data = (JSONObject) args[0];
                // threadArray.get(perticular_thread).resume();  // Want to implement this.
            }
        });
    }
};

I have more then one thread in this file and threadArray will contain all of them.

Thank You in advance.


问:
How to make a shared library reload itself under Linux
I'm developing a shared library in C++ under Linux.

Is there a way from the shared library code to reload itself when a new build is available for example?

I was thinking of using dlclose and dlopen to reload but the former needs a handle which is accessible to the running process only.

Any idea how to retrieve that handle from the shared library code? Any better solution to the whole idea?

I understand hot swapping is dangerous but this will make development and testing much more easier.

答:
When you rebuild a shared library its exported symbol addresses may change.

Hence, when reloading a shared library, all symbols its users import must be re-resolved.

Objects with virtual tables residing the shared library must be destroyed before unloading the shared library1.

If the library was loaded automatically by ld.so you cannot reload it.

If the application loaded the shared library using dlopen, the same code must be run again to re-load the library and re-resolve the symbols.

There is also thread-local storage that may complicate things.

In other words, it is too complicated to make re-loading a shared library work without the application being aware of it.

1I once debugged an intersting bug in the past. There was a shared library which was loaded at run-time using dlopen and unloaded after use. The application would later crash in std::cout destructor during termination. Turned out that the shared library was outputting Boost.Date_Time objects into std::cout. When doing so, the library would std::cout.imbue a new locale with a custom facet object from Boost.Date_Time (facets have virtual functions). When the library got unloaded, the facet object was still there owned by that locale, but its vtable pointer was referring the virtual table in the unloaded shared library, which would cause the crash when destroying the facet.


问:
For through html elements and appending only appends to last element
I have a text input and on focusout, I have couple of select elements which I want to fill with the text field's value.

And I have bunch of select tags with 'NameSelect' class

```<code>$('.textField').focusout(function() {
   var name = $(this).val();

   var NameOption = $('<option>', { value: name, text: name, attrid: '1'});

   var selects = $('#mainForm').find('.NameSelect');

   $(selects).each(function(i, obj) {
       console.log($(obj));  // it seems to get the right select
       $(obj).append(NameOption);
   })
}
</code>```

However, when I do that, even though the selects get all the right elements and for loop for the right count, it only appends the option input to the latest object, not all of them.

What am I missing here?

答:
The issue is because NameOption holds a reference to the option, hence if you append() it multiple times it will move between each parent element.

To fix this you can either clone() the element when you append it:

```<code>selects.append(NameOption.clone());
</code>```

Or you could just provide append() with a string to create a new element each time it's called:

```<code>$('.textField').focusout(function() {
   var name = $(this).val();
   $('#mainForm').find('.NameSelect').append('<option value="' + name + '" attrid="1">' + name + '</option>');
   })
});
</code>```

Note that in both cases the each() is not required.

Body:
I have a text input and on focusout, I have couple of select elements which I want to fill with the text field's value.

And I have bunch of select tags with 'NameSelect' class

$('.textField').focusout(function() {
   var name = $(this).val();

   var NameOption = $('<option>', { value: name, text: name, attrid: '1'});

   var selects = $('#mainForm').find('.NameSelect');

   $(selects).each(function(i, obj) {
       console.log($(obj));  // it seems to get the right select
       $(obj).append(NameOption);
   })
}

However, when I do that, even though the selects get all the right elements and for loop for the right count, it only appends the option input to the latest object, not all of them.

What am I missing here?

Body:
The issue is because NameOption holds a reference to the option, hence if you append() it multiple times it will move between each parent element.

To fix this you can either clone() the element when you append it:

selects.append(NameOption.clone());

Or you could just provide append() with a string to create a new element each time it's called:

$('.textField').focusout(function() {
   var name = $(this).val();
   $('#mainForm').find('.NameSelect').append('<option value="' + name + '" attrid="1">' + name + '</option>');
   })
});

Note that in both cases the each() is not required.


问:
YAML scalar with double %
I am trying to connect to a database with symfony3 but the problem is when I put the password in parameters.yml, I get this error:

database_password: xx%xxxxx%x

You have requested a non-existent parameter "xxxxx".

I tried with

database_password: "xx%xxxxx%x"

database_password: 'xx%xxxxx%x'

database_password: "xx\%xxxxx\%x"

I always have the same problem

答:
You need to escape percentage signs by putting two:

```<code>database_password: 'xx%%xxxxx%%x'
</code>```

See http://symfony.com/doc/current/service_container/parameters.html#parameters-in-configuration-files for more info.

Note: technically the quotes are unnecessary in this example, but if a %-sign appears at the start of the scalar, the scalar must be quoted.

Title: YAML scalar with double %

Body:
You need to escape percentage signs by putting two:

database_password: 'xx%%xxxxx%%x'

See http://symfony.com/doc/current/service_container/parameters.html#parameters-in-configuration-files for more info.

Note: technically the quotes are unnecessary in this example, but if a %-sign appears at the start of the scalar, the scalar must be quoted.


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答: ? "HELLO WORLD"</p>

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych

Body: ? "HELLO WORLD"

OwnerDisplayName: Leon


问:
"Assertion Failed: undefined must be a subclass or an instance of Ember.View, not " with no useful info
I started getting this error, but all attempts to debug the reason failed.

The whole info is like this:

```<code>Ember.assert    @   ember-1.10.0.debug.js:3940
readViewFactory @   ember-1.10.0.debug.js:39239
viewHelper  @   ember-1.10.0.debug.js:7521
inline  @   ember-1.10.0.debug.js:7948
render  @   VM4480:884
render  @   ember-1.10.0.debug.js:44625
EmberRenderer_createElement @   ember-1.10.0.debug.js:40279
Renderer_renderTree @   ember-1.10.0.debug.js:8768
ensureChildrenAreInDOM  @   ember-1.10.0.debug.js:41922
_ensureChildrenAreInDOM @   ember-1.10.0.debug.js:41885
invoke  @   ember-1.10.0.debug.js:854
flush   @   ember-1.10.0.debug.js:919
flush   @   ember-1.10.0.debug.js:724
end @   ember-1.10.0.debug.js:149
(anonymous) @   ember-1.10.0.debug.js:552
</code>```

which doesn't help me at all. Nothing is pointing me to the element that is failing, and at the same time a lot of ember elements fail to render.

Any ideas what I'm doing wrong? Or how to find the exact problematic problem?

(Installed Ember inspector which also doesn't help me at all.)

答:
After a lot of dumping stuff I figured out that I have elements ({{view ...}}) which behavior is not described in the JS file for that page. So I changed them to some custom {{#view ...}} ... {{/view}} elements with identical functionality, but the code about them is described in the JS files on the page.

That was the reason, and it's pretty sad Ember doesn't show such stuff in a better way.

Body:
I started getting this error, but all attempts to debug the reason failed.

The whole info is like this:

Ember.assert    @   ember-1.10.0.debug.js:3940
readViewFactory @   ember-1.10.0.debug.js:39239
viewHelper  @   ember-1.10.0.debug.js:7521
inline  @   ember-1.10.0.debug.js:7948
render  @   VM4480:884
render  @   ember-1.10.0.debug.js:44625
EmberRenderer_createElement @   ember-1.10.0.debug.js:40279
Renderer_renderTree @   ember-1.10.0.debug.js:8768
ensureChildrenAreInDOM  @   ember-1.10.0.debug.js:41922
_ensureChildrenAreInDOM @   ember-1.10.0.debug.js:41885
invoke  @   ember-1.10.0.debug.js:854
flush   @   ember-1.10.0.debug.js:919
flush   @   ember-1.10.0.debug.js:724
end @   ember-1.10.0.debug.js:149
(anonymous) @   ember-1.10.0.debug.js:552

which doesn't help me at all. Nothing is pointing me to the element that is failing, and at the same time a lot of ember elements fail to render.

Any ideas what I'm doing wrong? Or how to find the exact problematic problem?

(Installed Ember inspector which also doesn't help me at all.)


问:
Get input value with javascript
Hi I'm a newbie and new on javascript.
I was following some suggestion to get value from an input.
What I need is a value from that input when I pressed enter to put in a query.

I have an input

```<code><input id="search" type="text" placeholder="Search here" onkeyup="getval(this)"></input>
</code>```

and this is my script on my php page

```<code>function getval(e) {
    if(e.which == 13) {
        alert(e.value);
    }
}
</code>```

But that doesn't work. No alert appear.

答:
can you use jquery on your page?

if so...

$("#search").keyup(function(){
  alert($(this).val());
});

Title: Get input value with javascript

Body:
Hi I'm a newbie and new on javascript.
I was following some suggestion to get value from an input.
What I need is a value from that input when I pressed enter to put in a query.

I have an input

<input id="search" type="text" placeholder="Search here" onkeyup="getval(this)"></input>

and this is my script on my php page

function getval(e) {
    if(e.which == 13) {
        alert(e.value);
    }
}

But that doesn't work. No alert appear.


问:
"Unable to open registry key <name> for reading" [Windows 10 Education]
I started getting this error a while ago at every startup. After searching on Microsoft's website, I now know what the error is, but I don't know where it is. Does anyone know where to find the respective source code file so I can try to correct this (or any other way to correct it, for that matter)?

Thanks!

答:
Don't click the message away, run ProcessExplorer, use the cross hair from toolbar

and move it to the Error message. This will highlight the program which causes the error message. Process Explorer whill tell you the command line, so you see where the script is located and in the properties of the script process you can see the parent process which started the script.

Now uninstall the program that causes this message.


问:
Gui and binary files
I'm currently working on a project for a class I have, where we have to create a GUI that asks for a number, then read a binary files of 10,000 customers and return the other information on the one with the customer number entered. We also have to have an error that pops up as a JOptionPane when a number outside of 1-10,000 is entered. I'm having some problems with the error message, and my professor also said we need to have a method with this signature:

```<code>      private Customer getCustomer(long custNumber) throws IOException
</code>```

that searches the file and returns a customer object. I'm also not sure where exactly to do that. So I started with what I already know, and here's what I have:

```<code>import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class CustomerLocator extends JFrame
{
private JPanel panel;
private JLabel custNumLabel;
private JLabel custNameLabel;
private JLabel custDisLabel;
private JLabel custBalLabel;
private JLabel custPrefLabel;
private JTextField custNumField;
private JTextField custNameField;
private JTextField custDisField;
private JTextField custBalField;
  private JTextField custPrefField;
  private JButton findCustBut;
  private final int WINDOW_WIDTH = 300;
  private final int WINDOW_HEIGHT = 500;

 public CustomerLocator()
  {
    setTitle("Customer Locator");

    setSize(WINDOW_WIDTH, WINDOW_HEIGHT);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    buildPanel();

    add(panel);

    setVisible(true);
   }

  private void buildPanel()
   {
    custNumLabel = new JLabel("Enter a valid Customer Number: ");

    custNumField = new JTextField(10);

    custNameLabel = new JLabel("Customer Name: ");

    custNameField = new JTextField(10);
    custNameField.setEditable(false);

    custDisLabel = new JLabel("Customer Discount: ");

    custDisField = new JTextField(10);
    custDisField.setEditable(false);

    custBalLabel = new JLabel("Customer Balance: ");

    custBalField = new JTextField(10);
    custBalField.setEditable(false);

    custPrefLabel = new JLabel("Preferred? ");

    custPrefField = new JTextField(10);
    custPrefField.setEditable(false);

    findCustBut = new JButton("Find this Customer!");

    panel = new JPanel();

   findCustBut.addActionListener(new ListenerToFindCustomer());

    panel.add(custNumLabel);
    panel.add(custNumField);
    panel.add(findCustBut);
    panel.add(custNameLabel);
    panel.add(custNameField);
    panel.add(custDisLabel);
    panel.add(custDisField);
    panel.add(custBalLabel);
    panel.add(custBalField);
    panel.add(custPrefLabel);
    panel.add(custPrefField);

}
private class ListenerToFindCustomer implements ActionListener
  {
  public void actionPerformed(ActionEvent e)
  {
        String numEnteredStr;
        long custNumEntered;
        String custName;
        boolean preferred;
        String preferredDisplay;
        double acctBal;
        String acctBalDisplay;
        double discount;
        String discountDisplay;
        numEnteredStr = custNumField.getText();
        custNumEntered = Long.parseLong(numEnteredStr);
        int ct=0;
    try
    {

        FileInputStream inStream =
        new FileInputStream("c:\\cps\\CustomerObjects.dat");
//          DataInputStream inputFile = new DataInputStream(inStream);
        ObjectInputStream objectInputFile =
        new ObjectInputStream(inStream);

        while(true)
            {
                ct++;
                Customer obj = (Customer)objectInputFile.readObject();
                //System.out.println(obj.getCustName());
                if (custNumEntered == obj.getCustNum())
                {
                    custName = obj.getCustName();
                    acctBal = obj.getBalance();
                    acctBalDisplay = Double.toString(acctBal);
                    discount = obj.getDiscount();
                    discountDisplay = Double.toString(discount);
                    preferred = obj.getPreferred();
                    preferredDisplay = Boolean.toString(preferred);

                    custNameField.setText(custName);
                    custBalField.setText(acctBalDisplay);
                    custPrefField.setText(preferredDisplay);
                    custDisField.setText(discountDisplay);

                    if (custNameField == null)
                    {
                        JOptionPane.showMessageDialog(null, "Error");
                    }
                }

            }
    }
    catch (Exception ex)
    {
        System.out.println(ex.toString());

    }
}
}
public static void main(String[] args)
{
new CustomerLocator();
}
}
</code>```

So, with this, the JOptionPane doesn't show up, so my questions are
1. How do I get the error message to pop up?
2. How do I incorporate the method my professor requested?

答:
Your code

```<code>                if (custNameField == null)
                {
                    JOptionPane.showMessageDialog(null, "Error");
                }
</code>```

should read

```<code>                if (custName == null)
                {
                    JOptionPane.showMessageDialog(null, "Error");
                }
</code>```

It should also be moved outside of the while loop.
You also need a way to break the loop once you reach the end of the file.
Everything inside and including your try { ... } catch (Exception ex) { ... } can be moved to the method that your instructor suggests.
You should also change the try-catch to have another catch (IOException ioEx) { throw ioEx; }

Title: Gui and binary files

Body:
I'm currently working on a project for a class I have, where we have to create a GUI that asks for a number, then read a binary files of 10,000 customers and return the other information on the one with the customer number entered. We also have to have an error that pops up as a JOptionPane when a number outside of 1-10,000 is entered. I'm having some problems with the error message, and my professor also said we need to have a method with this signature:

      private Customer getCustomer(long custNumber) throws IOException

that searches the file and returns a customer object. I'm also not sure where exactly to do that. So I started with what I already know, and here's what I have:

import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class CustomerLocator extends JFrame
{
private JPanel panel;
private JLabel custNumLabel;
private JLabel custNameLabel;
private JLabel custDisLabel;
private JLabel custBalLabel;
private JLabel custPrefLabel;
private JTextField custNumField;
private JTextField custNameField;
private JTextField custDisField;
private JTextField custBalField;
  private JTextField custPrefField;
  private JButton findCustBut;
  private final int WINDOW_WIDTH = 300;
  private final int WINDOW_HEIGHT = 500;

 public CustomerLocator()
  {
    setTitle("Customer Locator");

    setSize(WINDOW_WIDTH, WINDOW_HEIGHT);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    buildPanel();

    add(panel);

    setVisible(true);
   }

  private void buildPanel()
   {
    custNumLabel = new JLabel("Enter a valid Customer Number: ");

    custNumField = new JTextField(10);

    custNameLabel = new JLabel("Customer Name: ");

    custNameField = new JTextField(10);
    custNameField.setEditable(false);

    custDisLabel = new JLabel("Customer Discount: ");

    custDisField = new JTextField(10);
    custDisField.setEditable(false);

    custBalLabel = new JLabel("Customer Balance: ");

    custBalField = new JTextField(10);
    custBalField.setEditable(false);

    custPrefLabel = new JLabel("Preferred? ");

    custPrefField = new JTextField(10);
    custPrefField.setEditable(false);

    findCustBut = new JButton("Find this Customer!");

    panel = new JPanel();

   findCustBut.addActionListener(new ListenerToFindCustomer());

    panel.add(custNumLabel);
    panel.add(custNumField);
    panel.add(findCustBut);
    panel.add(custNameLabel);
    panel.add(custNameField);
    panel.add(custDisLabel);
    panel.add(custDisField);
    panel.add(custBalLabel);
    panel.add(custBalField);
    panel.add(custPrefLabel);
    panel.add(custPrefField);

}
private class ListenerToFindCustomer implements ActionListener
  {
  public void actionPerformed(ActionEvent e)
  {
        String numEnteredStr;
        long custNumEntered;
        String custName;
        boolean preferred;
        String preferredDisplay;
        double acctBal;
        String acctBalDisplay;
        double discount;
        String discountDisplay;
        numEnteredStr = custNumField.getText();
        custNumEntered = Long.parseLong(numEnteredStr);
        int ct=0;
    try
    {

        FileInputStream inStream =
        new FileInputStream("c:\\cps\\CustomerObjects.dat");
//          DataInputStream inputFile = new DataInputStream(inStream);
        ObjectInputStream objectInputFile =
        new ObjectInputStream(inStream);

        while(true)
            {
                ct++;
                Customer obj = (Customer)objectInputFile.readObject();
                //System.out.println(obj.getCustName());
                if (custNumEntered == obj.getCustNum())
                {
                    custName = obj.getCustName();
                    acctBal = obj.getBalance();
                    acctBalDisplay = Double.toString(acctBal);
                    discount = obj.getDiscount();
                    discountDisplay = Double.toString(discount);
                    preferred = obj.getPreferred();
                    preferredDisplay = Boolean.toString(preferred);

                    custNameField.setText(custName);
                    custBalField.setText(acctBalDisplay);
                    custPrefField.setText(preferredDisplay);
                    custDisField.setText(discountDisplay);

                    if (custNameField == null)
                    {
                        JOptionPane.showMessageDialog(null, "Error");
                    }
                }

            }
    }
    catch (Exception ex)
    {
        System.out.println(ex.toString());

    }
}
}
public static void main(String[] args)
{
new CustomerLocator();
}
}

So, with this, the JOptionPane doesn't show up, so my questions are
1. How do I get the error message to pop up?
2. How do I incorporate the method my professor requested?

Body:
Your code

                if (custNameField == null)
                {
                    JOptionPane.showMessageDialog(null, "Error");
                }

should read

                if (custName == null)
                {
                    JOptionPane.showMessageDialog(null, "Error");
                }

It should also be moved outside of the while loop.
You also need a way to break the loop once you reach the end of the file.
Everything inside and including your try { ... } catch (Exception ex) { ... } can be moved to the method that your instructor suggests.
You should also change the try-catch to have another catch (IOException ioEx) { throw ioEx; }


问:
osticket email validation when a user opens a new ticket

in osticket version 1.10, i wish to apply a validation rule on email input field so that users with email id only from specific domain can open new ticket or apply for registration i.e. email address always should look like id@specificdomain.com . however i tried to edit the is_email() function in includes/class.validator.php as bellow

```<code>static function is_email($email, $list=false, $verify=false){
        $domains = array('specificdomain.com');
        $pattern = "/^[a-z0-9._%+-]+@([a-z0-9.-]+.)*(" . implode('|', $domains) . ")$/i";
        if (!preg_match($pattern, $email)) {
            return false;
        }

    }
</code>```

But no use. can any body help me in this regard.

答:
You can create an organization for each domain. Go on Users->Organizations-> define one, then click on its name-> Settings tab-> define the domain

This will allow all the users from that domain to open calls. They will also be added as users underneath the organization page.

If you want to block other domains, you have to go to the admin panel, then settings->users->tick registration required, and select in registration method "only agents can register user". Despite what it seems, if a user is part of the domain he will be able to open a call even if he has not been registered yet.

A bit late, but I hope it will help you.

Body:
in osticket version 1.10, i wish to apply a validation rule on email input field so that users with email id only from specific domain can open new ticket or apply for registration i.e. email address always should look like id@specificdomain.com . however i tried to edit the is_email() function in includes/class.validator.php as bellow

static function is_email($email, $list=false, $verify=false){
        $domains = array('specificdomain.com');
        $pattern = "/^[a-z0-9._%+-]+@([a-z0-9.-]+.)*(" . implode('|', $domains) . ")$/i";
        if (!preg_match($pattern, $email)) {
            return false;
        }

    }

But no use. can any body help me in this regard.


问:
bootstrap 4 new line space in grid
I am using bootstrap 4 grid.

my grid has 3 columns and each column has key value. It's a nested grid.

when key or value has more words then it comes to new line, my issue is how I can decrease space between those lines.

I would like to have no space or less space where I have shown the red lines

```<code><!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-4">
                <div class="row">
                    <div class="col-6 "><strong>Customer Name</strong></div>
                    <div class="col-6 ">smith</div>
                </div>
                <div class="row">
                    <div class="col-6 "><strong>Company</strong></div>
                    <div class="col-6 ">facebook</div>
                </div>
                <div class="row">
                    <div class="col-6 "><strong>header</strong></div>
                    <div class="col-6 ">value</div>
                </div>
            </div>
            <div class="col-4">
                <div class="row">
                    <div class="col-6 "><strong>Customer Name</strong></div>
                    <div class="col-6 ">smith abcdefg xyz</div>
                </div>
                <div class="row">
                    <div class="col-6 "><strong>Company</strong></div>
                    <div class="col-6 ">This can be very long company
                                                            name</div>
                </div>
                <div class="row">
                    <div class="col-6 "><strong>header</strong></div>
                    <div class="col-6 ">value 11111</div>
                </div>
            </div>
            <div class="col-4">
                <div class="row">
                    <div class="col-6 "><strong>Customer Name</strong></div>
                    <div class="col-6 ">dave</div>
                </div>
                <div class="row">
                    <div class="col-6 "><strong>Company</strong></div>
                    <div class="col-6 ">Google</div>
                </div>
                <div class="row">
                    <div class="col-6 "><strong>header</strong></div>
                    <div class="col-6 ">value 11111</div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
</code>```

plunker for this issue

https://plnkr.co/edit/TecPEUgj7YsgnrGVZytO?p=preview

答:
The default Bootstrap 4 line-height is 1.5. Add some CSS to override it. For example, this would override it everywhere..

```<code>body {
    line-height: 1;
}
</code>```

Title: bootstrap 4 new line space in grid

Body:
I am using bootstrap 4 grid.

my grid has 3 columns and each column has key value. It's a nested grid.

when key or value has more words then it comes to new line, my issue is how I can decrease space between those lines.

I would like to have no space or less space where I have shown the red lines

<!DOCTYPE html>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

Customer Name

smith

Company

facebook

header

value

Customer Name

smith abcdefg xyz

Company

This can be very long company
                                                            name

header

value 11111

Customer Name

dave

Company

Google

header

value 11111

plunker for this issue

https://plnkr.co/edit/TecPEUgj7YsgnrGVZytO?p=preview

Body:
The default Bootstrap 4 line-height is 1.5. Add some CSS to override it. For example, this would override it everywhere..

body {
    line-height: 1;
}


问:
angularjs1 collapse same pannel with different content
hey guys I'm trying to create a collapsible panel: so should have panel header and panel body to show the content. The behavior on click is when a button is pressed the content will collapse down and if you click the same button the content will close up. If you click the second button will collapse the content for the second button and the first button collapse is closed. Basically should work like a collapsible panel (bootstrap) but developed only with angular. I had done this so far but I'm beginner with angular so if you can help me ...

fiddle:

```<code><body ng-app="app">
  <div ng-controller="Test" class="container">
  <div class="custom">
    <button ng-click="show = 1" class="btn">collapse 1</button>
    <button ng-click="show = 2" class="btn">Collapse 2</button>
      <div class="form-group" ng-show="show==1">
      <div class="sec">show 1</div>
    </div>
    <div class="form-group" ng-show="show==2">
      <div class="sec">show 2</div>
    </div>
    <div class="form-group" ng-show="show==3">
    </div>
  </div>
  </div>
</body>
</code>```

答:
So here's an updated fiddle that should meet the requirement you're looking for. There are a few changes, but it seems to be working.  It doesn't use bootstrap, but you need ng-animate for your animations.

I've put a wrapper around your form-group elements, and I've changed the ng-show to ng-if.

```<code>//html
<button ng-click="showDiv(1)" class="btn">collapse 1</button>
<button ng-click="showDiv(2)" class="btn">Collapse 2</button>

<div class="sec-wrp" ng-if="show === 1">
    <div class="form-group" >
      <div class="sec">show 1</div>
    </div>
</div>

 <div class="sec-wrp" ng-if="show === 2">
    <div class="form-group" >
      <div class="sec">show 2</div>
    </div>
</div>

<div class="form-group" ng-if="show==3" >
</div>
</code>```

The click event now calls a function in your controller with the value of the div you want to show. The controller responds by setting the $scope.show value to 0. If the currentShow value is zero (as it is intialized), it sets the $scope.show value to the value passed and resets the currentShow variable to the new value with no timeout.  If the value passed equals the currentShow value, it treats it as a toggle by not resetting $scope.show and resetting currentShow to zero, closing the div. If the int passed does not equal currentShow, it sets currentShow and $scope.show to the new value.

```<code>//controller
var app = angular.module('app', ['ngAnimate']);
app.controller('Test', ['$timeout','$scope', function($timeout, $scope) {
    $scope.show = 0;
    var currentShow = 0;

    $scope.showDiv = function(int){
        $scope.show = 0;

        if(currentShow === 0){
           currentShow = int;
           $scope.show = int;
           return false;
        }

        if(currentShow === int){
           $timeout(function(){
               currentShow = 0;
               return false;
           }, 1000)
        }else{
           $timeout(function(){
               currentShow = int;
               $scope.show = int;
           }, 1000)
        }
    }

}]);
</code>```

The $timeout value of one second corresponds to the transition times of the animations, i.e., the allows a one second waiting time for the 1 second animation to complete in your css, which uses ng-enter, ng-leave instead of keyframes.  If you want to adjust the transition times here, just make sure you also adjust the $timeouts.

```<code>//css
.custom{position: relative; z-index: 2; border: 1px solid #ccc;}
.sec{
  padding: 20px;
  border: 1px solid orangered;
  background: orange;
  height: 100px;
  z-index: 1;
}

.sec-wrp{
  overflow: hidden;
  transition: all ease 1s;
}

.sec-wrp.ng-enter{
  opacity: 0;
  height: 0;
}

.sec-wrp.ng-enter.ng-enter-active{
  opacity: 1;
  height: 100px;
}

.sec-wrp.ng-leave{
  opacity: 1;
  height: 100px;
}

.sec-wrp.ng-leave.ng-leave-active{
  opacity: 0;
  height: 0;
}
</code>```

Hope this helps.

Body:
hey guys I'm trying to create a collapsible panel: so should have panel header and panel body to show the content. The behavior on click is when a button is pressed the content will collapse down and if you click the same button the content will close up. If you click the second button will collapse the content for the second button and the first button collapse is closed. Basically should work like a collapsible panel (bootstrap) but developed only with angular. I had done this so far but I'm beginner with angular so if you can help me ...

fiddle:

    <button ng-click="show = 1" class="btn">collapse 1</button>
    <button ng-click="show = 2" class="btn">Collapse 2</button>

show 1

show 2

Body:
So here's an updated fiddle that should meet the requirement you're looking for. There are a few changes, but it seems to be working.  It doesn't use bootstrap, but you need ng-animate for your animations.

I've put a wrapper around your form-group elements, and I've changed the ng-show to ng-if.

//html
<button ng-click="showDiv(1)" class="btn">collapse 1</button>
<button ng-click="showDiv(2)" class="btn">Collapse 2</button>

<div class="sec-wrp" ng-if="show === 1">
    <div class="form-group" >
      <div class="sec">show 1</div>
    </div>
</div>

 <div class="sec-wrp" ng-if="show === 2">
    <div class="form-group" >
      <div class="sec">show 2</div>
    </div>
</div>

<div class="form-group" ng-if="show==3" >
</div>

The click event now calls a function in your controller with the value of the div you want to show. The controller responds by setting the $scope.show value to 0. If the currentShow value is zero (as it is intialized), it sets the $scope.show value to the value passed and resets the currentShow variable to the new value with no timeout.  If the value passed equals the currentShow value, it treats it as a toggle by not resetting $scope.show and resetting currentShow to zero, closing the div. If the int passed does not equal currentShow, it sets currentShow and $scope.show to the new value.

//controller
var app = angular.module('app', ['ngAnimate']);
app.controller('Test', ['$timeout','$scope', function($timeout, $scope) {
    $scope.show = 0;
    var currentShow = 0;

    $scope.showDiv = function(int){
        $scope.show = 0;

        if(currentShow === 0){
           currentShow = int;
           $scope.show = int;
           return false;
        }

        if(currentShow === int){
           $timeout(function(){
               currentShow = 0;
               return false;
           }, 1000)
        }else{
           $timeout(function(){
               currentShow = int;
               $scope.show = int;
           }, 1000)
        }
    }

}]);

The $timeout value of one second corresponds to the transition times of the animations, i.e., the allows a one second waiting time for the 1 second animation to complete in your css, which uses ng-enter, ng-leave instead of keyframes.  If you want to adjust the transition times here, just make sure you also adjust the $timeouts.

//css
.custom{position: relative; z-index: 2; border: 1px solid #ccc;}
.sec{
  padding: 20px;
  border: 1px solid orangered;
  background: orange;
  height: 100px;
  z-index: 1;
}

.sec-wrp{
  overflow: hidden;
  transition: all ease 1s;
}

.sec-wrp.ng-enter{
  opacity: 0;
  height: 0;
}

.sec-wrp.ng-enter.ng-enter-active{
  opacity: 1;
  height: 100px;
}

.sec-wrp.ng-leave{
  opacity: 1;
  height: 100px;
}

.sec-wrp.ng-leave.ng-leave-active{
  opacity: 0;
  height: 0;
}

Hope this helps.