问:
Transfer MSSQL table to In-Memory OLTP technique without timestamp column
As MS SQL Server Express 2016 offers the new In-Memory OLTP for free, I want to transfer my tables to the new technique. Doing this, I have a problem, because I'm using timestamp-columns to find out the newest data set of a person - e.g. the newest email address.

To demonstrate the problem, you'll neet to generate 3 tables. The first one for persons:

```<code>CREATE TABLE [dbo].[persons](
[Pers_ID] [int] IDENTITY(1,1) NOT NULL,
[Pers_surname] [nvarchar](100) NULL,
[Pers_forename] [nvarchar](100) NULL,
[Pers_birthdate] [datetime] NULL,
[Pers_last_change] [datetime] NULL,
[Pers_changed_by] [nvarchar](100) NULL,
[Pers_Timestamp] [timestamp] NULL,
CONSTRAINT [PK_persons] PRIMARY KEY CLUSTERED
([Pers_ID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON,
FILLFACTOR = 90) ON [PRIMARY]) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
</code>```

The second one for email addresses:

```<code>CREATE TABLE [dbo].[emailadress](
[Email_ID] [int] IDENTITY(1,1) NOT NULL,
[Email_adress] [nvarchar](255) NULL,
[Email_up_to_date] [bit] NOT NULL,
[Email_last_change] [datetime] NULL,
[Email_changed_by] [nvarchar](100) NULL,
[Email_Timestamp] [timestamp] NULL,
CONSTRAINT [PK_emailadress] PRIMARY KEY CLUSTERED
([Email_ID] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON,
FILLFACTOR = 90) ON [PRIMARY]) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

ALTER TABLE [dbo].[emailadress] ADD  CONSTRAINT
[DF_emailadress_up_to_date]  DEFAULT ((1)) FOR [Email_up_to_date]
GO
</code>```

The last one for the link between the two first tables:

```<code>CREATE TABLE [dbo].[PersEmail](
[PersEmail_ID] [int] IDENTITY(1,1) NOT NULL,
[Pers_ID] [int] NULL,
[Email_ID] [int] NULL,
[PersEmail_out_of_date] [bit] NOT NULL,
[PersEmail_last_change] [datetime] NULL,
[PersEmail_changed_by] [nvarchar](255) NULL,
[PersEmail_Timestamp] [timestamp] NULL,
CONSTRAINT [PK_PersEmail] PRIMARY KEY CLUSTERED
([PersEmail_ID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON,
FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO
</code>```

Every person could have several email adresses and one email adress could be linked to several persons. There is an trigger which set the connection out of date if the email address is out of date.

For a lot of reports I just need one email adress of the persons. This should be the newest email adress. To find out, which is the newest, I use the timestamp column:

```<code>SELECT P.Pers_ID, Pers_surname, Pers_forename, Pers_birthdate,
PersEmail_ID, Email_adress

FROM persons P

LEFT OUTER JOIN
(SELECT * FROM dbo.PersEmail WHERE PersEmail_out_of_date = 0) AS PE
ON PE.Pers_ID = P.Pers_ID

LEFT OUTER JOIN
(SELECT * FROM dbo.emailadress WHERE Email_up_to_date = 1) AS email
ON email.Email_ID = PE.Email_ID

WHERE P.Pers_ID = @intID AND

((PE.PersEmail_Timestamp IS NULL) OR
(PE.PersEmail_Timestamp = ( SELECT MAX(PersEmail_Timestamp) AS Expr1
FROM (SELECT * FROM dbo.PersEmail WHERE PersEmail_out_of_date = 0) AS
persemail2
WHERE       Pers_ID = P.Pers_ID)))

RETURN
</code>```

I tried to use an datetime2(7) column instead of the timestamp column. But it is possible that the person has two email addresses changed with an "Update" statement at once. The datetime2 column now will contain two identical datetimes. Then my query will show two lines instead of one. In comparison the timestamp column delivers two different contents and my query delivers just one line as wished.

Does anyone know how to replace the timestamp columns for the descriped goal?

If there is independently of the In-Memory-Question an suggestion to improve the query to find out the newest email address, please let me know also.

Note: I hope the above quoted code is correct. I translated the column names from german and tried to use english versions instead. The original code will work fine... just let me know if I overlooked a fault.

At last this Code seems to work for me, but I'm not sure, wheter it is the best:

```<code>SELECT      P.Pers_ID, Pers_surname, Pers_forename, Pers_birthdate,
PE.PersEmail_ID, Email_adress

FROM        persons P

LEFT OUTER JOIN
(SELECT * FROM PersEmail WHERE PersEmail_out_of_date = 0) AS PE
ON  PE.Pers_ID = P.Pers_ID

LEFT OUTER JOIN
(SELECT * FROM emailadress WHERE Email_up_to_date = 1) AS email ON
email.Email_ID = PE.Email_ID

WHERE       P.Pers_ID = @intID AND

((PE.PersEmail_TS IS NULL) OR
(PE.PersEmail_ID =  (   SELECT TOP 1    PersEmail_ID
FROM        (SELECT * FROM dbo.PersEmail WHERE PersEmail_out_of_date = 0)
AS persemail3
WHERE       Pers_ID = @intID

AND PersEmail_TS = (    SELECT      MAX(PersEmail_TS) AS Expr1
FROM        (SELECT * FROM dbo.PersEmail WHERE PersEmail_out_of_date = 0)
AS persemail2
WHERE       Pers_ID = @intID))))
</code>```

答:
If you update two email addresses for the same person in one UPDATE statement, then there is no guarantee which one of these email addresses will receive the highest timestamp. @Jeroen Mostert also mentioned this in a comment.

When you are moving to In-Memory OLTP (where the timestamp data type is not supported) it should be fine to use a datetime2(7) column. You would have to make a minor change to your query to ensure that you do not receive multiple rows.

One suggestion of a query rewrite would be this:

```<code>SELECT TOP 1
    P.Pers_ID, Pers_surname, Pers_forename, Pers_birthdate, PersEmail_ID, Email_adress
FROM persons P
    LEFT OUTER JOIN dbo.PersEmail PE
        ON PE.Pers_ID = P.Pers_ID
        AND PE.PersEmail_inaktuell = 0
    LEFT OUTER JOIN dbo.emailadress email
        ON email.Email_ID = PE.Email_ID
        AND email.Email_up_to_date = 1
WHERE P.Pers_ID = @intID
ORDER BY PE.PersEmail_Timestamp DESC, PE.Email_ID DESC
</code>```

This query still ensures that you only receive 1 record, and that the received record is one of the latest updated records. I.e. if two or more records in your PersEmail table were updated in the same UPDATE statement, then you will receive the one with the highest Email_ID.

Body:
As MS SQL Server Express 2016 offers the new In-Memory OLTP for free, I want to transfer my tables to the new technique. Doing this, I have a problem, because I'm using timestamp-columns to find out the newest data set of a person - e.g. the newest email address.

To demonstrate the problem, you'll neet to generate 3 tables. The first one for persons:

CREATE TABLE [dbo].[persons](
[Pers_ID] [int] IDENTITY(1,1) NOT NULL,
[Pers_surname] [nvarchar](100) NULL,
[Pers_forename] [nvarchar](100) NULL,
[Pers_birthdate] [datetime] NULL,
[Pers_last_change] [datetime] NULL,
[Pers_changed_by] [nvarchar](100) NULL,
[Pers_Timestamp] [timestamp] NULL,
CONSTRAINT [PK_persons] PRIMARY KEY CLUSTERED
([Pers_ID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON,
FILLFACTOR = 90) ON [PRIMARY]) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

The second one for email addresses:

CREATE TABLE [dbo].[emailadress](
[Email_ID] [int] IDENTITY(1,1) NOT NULL,
[Email_adress] [nvarchar](255) NULL,
[Email_up_to_date] [bit] NOT NULL,
[Email_last_change] [datetime] NULL,
[Email_changed_by] [nvarchar](100) NULL,
[Email_Timestamp] [timestamp] NULL,
CONSTRAINT [PK_emailadress] PRIMARY KEY CLUSTERED
([Email_ID] ASC) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON,
FILLFACTOR = 90) ON [PRIMARY]) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

ALTER TABLE [dbo].[emailadress] ADD  CONSTRAINT
[DF_emailadress_up_to_date]  DEFAULT ((1)) FOR [Email_up_to_date]
GO

The last one for the link between the two first tables:

CREATE TABLE [dbo].[PersEmail](
[PersEmail_ID] [int] IDENTITY(1,1) NOT NULL,
[Pers_ID] [int] NULL,
[Email_ID] [int] NULL,
[PersEmail_out_of_date] [bit] NOT NULL,
[PersEmail_last_change] [datetime] NULL,
[PersEmail_changed_by] [nvarchar](255) NULL,
[PersEmail_Timestamp] [timestamp] NULL,
CONSTRAINT [PK_PersEmail] PRIMARY KEY CLUSTERED
([PersEmail_ID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON,
FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]
GO

Every person could have several email adresses and one email adress could be linked to several persons. There is an trigger which set the connection out of date if the email address is out of date.

For a lot of reports I just need one email adress of the persons. This should be the newest email adress. To find out, which is the newest, I use the timestamp column:

SELECT P.Pers_ID, Pers_surname, Pers_forename, Pers_birthdate,
PersEmail_ID, Email_adress

FROM persons P

LEFT OUTER JOIN
(SELECT * FROM dbo.PersEmail WHERE PersEmail_out_of_date = 0) AS PE
ON PE.Pers_ID = P.Pers_ID

LEFT OUTER JOIN
(SELECT * FROM dbo.emailadress WHERE Email_up_to_date = 1) AS email
ON email.Email_ID = PE.Email_ID

WHERE P.Pers_ID = @intID AND

((PE.PersEmail_Timestamp IS NULL) OR
(PE.PersEmail_Timestamp = ( SELECT MAX(PersEmail_Timestamp) AS Expr1
FROM (SELECT * FROM dbo.PersEmail WHERE PersEmail_out_of_date = 0) AS
persemail2
WHERE       Pers_ID = P.Pers_ID)))

RETURN

I tried to use an datetime2(7) column instead of the timestamp column. But it is possible that the person has two email addresses changed with an "Update" statement at once. The datetime2 column now will contain two identical datetimes. Then my query will show two lines instead of one. In comparison the timestamp column delivers two different contents and my query delivers just one line as wished.

Does anyone know how to replace the timestamp columns for the descriped goal?

If there is independently of the In-Memory-Question an suggestion to improve the query to find out the newest email address, please let me know also.

Note: I hope the above quoted code is correct. I translated the column names from german and tried to use english versions instead. The original code will work fine... just let me know if I overlooked a fault.

At last this Code seems to work for me, but I'm not sure, wheter it is the best:

SELECT      P.Pers_ID, Pers_surname, Pers_forename, Pers_birthdate,
PE.PersEmail_ID, Email_adress

FROM        persons P

LEFT OUTER JOIN
(SELECT * FROM PersEmail WHERE PersEmail_out_of_date = 0) AS PE
ON  PE.Pers_ID = P.Pers_ID

LEFT OUTER JOIN
(SELECT * FROM emailadress WHERE Email_up_to_date = 1) AS email ON
email.Email_ID = PE.Email_ID

WHERE       P.Pers_ID = @intID AND

((PE.PersEmail_TS IS NULL) OR
(PE.PersEmail_ID =  (   SELECT TOP 1    PersEmail_ID
FROM        (SELECT * FROM dbo.PersEmail WHERE PersEmail_out_of_date = 0)
AS persemail3
WHERE       Pers_ID = @intID

AND PersEmail_TS = (    SELECT      MAX(PersEmail_TS) AS Expr1
FROM        (SELECT * FROM dbo.PersEmail WHERE PersEmail_out_of_date = 0)
AS persemail2
WHERE       Pers_ID = @intID))))

Body:
If you update two email addresses for the same person in one UPDATE statement, then there is no guarantee which one of these email addresses will receive the highest timestamp. @Jeroen Mostert also mentioned this in a comment.

When you are moving to In-Memory OLTP (where the timestamp data type is not supported) it should be fine to use a datetime2(7) column. You would have to make a minor change to your query to ensure that you do not receive multiple rows.

One suggestion of a query rewrite would be this:

SELECT TOP 1
    P.Pers_ID, Pers_surname, Pers_forename, Pers_birthdate, PersEmail_ID, Email_adress
FROM persons P
    LEFT OUTER JOIN dbo.PersEmail PE
        ON PE.Pers_ID = P.Pers_ID
        AND PE.PersEmail_inaktuell = 0
    LEFT OUTER JOIN dbo.emailadress email
        ON email.Email_ID = PE.Email_ID
        AND email.Email_up_to_date = 1
WHERE P.Pers_ID = @intID
ORDER BY PE.PersEmail_Timestamp DESC, PE.Email_ID DESC

This query still ensures that you only receive 1 record, and that the received record is one of the latest updated records. I.e. if two or more records in your PersEmail table were updated in the same UPDATE statement, then you will receive the one with the highest Email_ID.


来源: stackexchange

问:
Django uploaded files not displaying in template page
I am trying to display the top 5 recently posted files but doesnt seem to show up.
When i get all the objects by using Model.objects.all(), it gives me all the objects from Db but when i am trying to get the top 5, it does not display.
Kindly help and suggest me. Thanks

my views.py is

```<code>def about_experiment(request, ex_link_name):
  researcher = None
  study = None
  posts = None
  exp = get_object_or_404(Experiment,link_name = ex_link_name)
  high_scores = ScoreItem.objects.filter(experiment=exp,active=True)
  context = {
    'request': request,
    'exp':exp,
    'high_scores': high_scores,
    'awards':AwardItem.objects.filter(experiment=exp,visible=True),
    'posts':Help.objects.filter().order_by('-date')[0],
    'documents':Help.objects.filter().order_by('-document')[:5]
  }

  if exp.about_file:
    context['about_file'] = settings.EXPERIMENT_DIRS+exp.about_file.get_include_path()

  if request.method == 'POST':
        form = AboutHelp(request.POST, request.FILES)
        if form.is_valid():
            obj = form.save(commit = False)
            obj.save()
            return HttpResponseRedirect('/about/%s/' %ex_link_name)
            #return redirect(reverse('lazer.views.about_experiment', kwargs={ 'ex_link_name':obj.link_name }))

  else:
      form = AboutHelp()

  return render(request, 'about_experiment.html', context)
</code>```

destination template page

```<code>  <div class="tab-pane" id="irb">
          <h4> List of file(s) uploaded:</h4>
        <!--File upload-->
            {% if documents %}
                <ul>
                    <li><a href="#"> {{ documents.document }} </a></li>
                </ul>
            {% else %}
                <p>No such documents available.</p>
            {% endif %}
       <!--File upload ends-->
</code>```

答:
documents is a queryset and you are picking top 5. You need to do this like this.

```<code>  <div class="tab-pane" id="irb">
      <h4> List of file(s) uploaded:</h4>
    <!--File upload-->
            {% for doc in documents %}
            <ul>
                <li><a href="#"> {{ doc.document }} </a></li>
            </ul>
            {% empty %}
            <p>No such documents available.</p>
            {% endfor %}
   <!--File upload ends-->
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to display the top 5 recently posted files but doesnt seem to show up.
When i get all the objects by using Model.objects.all(), it gives me all the objects from Db but when i am trying to get the top 5, it does not display.
Kindly help and suggest me. Thanks

my views.py is

def about_experiment(request, ex_link_name):
  researcher = None
  study = None
  posts = None
  exp = get_object_or_404(Experiment,link_name = ex_link_name)
  high_scores = ScoreItem.objects.filter(experiment=exp,active=True)
  context = {
    'request': request,
    'exp':exp,
    'high_scores': high_scores,
    'awards':AwardItem.objects.filter(experiment=exp,visible=True),
    'posts':Help.objects.filter().order_by('-date')[0],
    'documents':Help.objects.filter().order_by('-document')[:5]
  }

  if exp.about_file:
    context['about_file'] = settings.EXPERIMENT_DIRS+exp.about_file.get_include_path()

  if request.method == 'POST':
        form = AboutHelp(request.POST, request.FILES)
        if form.is_valid():
            obj = form.save(commit = False)
            obj.save()
            return HttpResponseRedirect('/about/%s/' %ex_link_name)
            #return redirect(reverse('lazer.views.about_experiment', kwargs={ 'ex_link_name':obj.link_name }))

  else:
      form = AboutHelp()

  return render(request, 'about_experiment.html', context)

destination template page

 List of file(s) uploaded:

            {% if documents %}

 {{ documents.document }}

            {% else %}

No such documents available.

            {% endif %}

Body:
documents is a queryset and you are picking top 5. You need to do this like this.

  <div class="tab-pane" id="irb">
      <h4> List of file(s) uploaded:</h4>
    <!--File upload-->
            {% for doc in documents %}
            <ul>
                <li><a href="#"> {{ doc.document }} </a></li>
            </ul>
            {% empty %}
            <p>No such documents available.</p>
            {% endfor %}
   <!--File upload ends-->


问:
Annoying IE8 dropdown issue in XP but not windows 7
I have an annoying issue with a select html element that cuts off the text in the dropdown when it is longer then the set width of the select html element.

The select elements need to be a set width to stop the page misalinging, Every browser seems to work except for IE8 running on XP. why? so random and bad compatibility.

please let me know if you need more infomation.

Thanks!

答:
It's a how IE interprets it should render the drop downs ... Unfortunately,there's no easy fix, what you can do is create a replacement for drop downs that handles this in a different way, that can work consistently across browsers ...

Here's a solution I came up with

http://weblogs.asp.net/jaimedelpalacio/archive/2008/11/22/custom-html-dropdown-control-part-1.aspx

ContentLicense: CC BY-SA 2.5


问:
Unable to execute statement in php only when user selects yes in dialog box
Hi am trying to insert data into mysql only when user enters yes in confirm dialog but the data always inserted into mysql even if the user enters no.Here is my code..</p>

```<code><?php if (mysqli_num_rows($data_query) >= 1) { ?>
    <script>
        var txt;
        var r = confirm('Duplicate Data! Click OK to Add & Cancel to Cancel it')
        if (r == true) {
            <?php
                $query="INSERT INTO video_data(date) " ;
                $query .= "VALUES('{$date}')";
                $create_video_query=mysqli_query($connection,$query);

                if (!$create_video_query) {
                    die("failed".mysqli_error());
                } else {
                    $success = "Video added succesfully";
                }
            ?>
        }
    </script>
<?php } ?>
</code>```

答:
Test your code without the php.

you are missing a semicolon after "Click OK to Add & Cancel to Cancel it')"

Make sure you really have "if(r==true)" and not "if(r=true)"

I tested the following code (php is removed) and it works:

```<code>     <html>
     <body>
     <script>
        var txt;
        var r = confirm('Duplicate Data! Click OK to Add & Cancel to Cancel it');
        if(r==true){
            alert('Clicked OK: Run insert sql');
        } else {
            alert('Clicked Cancel: Do nothing');
        }
     </script>
     </body>
     </html>
</code>```

Body:
Hi am trying to insert data into mysql only when user enters yes in confirm dialog but the data always inserted into mysql even if the user enters no.Here is my code..

<?php if (mysqli_num_rows($data_query) >= 1) { ?>

<?php } ?>

Body:
Test your code without the php.

you are missing a semicolon after "Click OK to Add & Cancel to Cancel it')"

Make sure you really have "if(r==true)" and not "if(r=true)"

I tested the following code (php is removed) and it works:

     <html>
     <body>
     <script>
        var txt;
        var r = confirm('Duplicate Data! Click OK to Add & Cancel to Cancel it');
        if(r==true){
            alert('Clicked OK: Run insert sql');
        } else {
            alert('Clicked Cancel: Do nothing');
        }
     </script>
     </body>
     </html>


问:
Change all elements in Numpy array that end up as individual arrays to floats Python
I have an array in which all of the elements in the array are also arrays:

```<code>a = [[array([ 4.15167139]) array([ 2.80260218]) array([ 3.34189103])
  array([ 3.73434426]) array([ 3.76504973]) array([ 3.91946708])
  array([ 2.850741]) array([ 1.9985034]) array([ 4.05191836])
  array([ 3.46145848]) array([ 2.99489689]) array([ 2.60462582])
  array([ 1.91031189]) array([ 2.90006744]) array([ 3.69799451])
  array([ 3.83314665]) array([ 4.42917628]) array([ 5.17647658])
  array([ 4.63462677]) array([ 4.69085313]) array([ 4.84746095])
  array([ 5.04396694]) array([ 5.10152712]) array([ 3.33442499])
  array([ 4.87380637]) ...]]
</code>```

I want this to be the same shape array that it is now (20,96) but instead of all of the elements within this array being arrays I would just like them to be floats:

```<code> a = [[ 4.15167139  2.80260218  3.34189103...4.87380637 ...]]
</code>```

What is the best way to iterate over this array and change all of the elements from individual arrays to floats?

Body:
I have an array in which all of the elements in the array are also arrays:

a = [[array([ 4.15167139]) array([ 2.80260218]) array([ 3.34189103])
  array([ 3.73434426]) array([ 3.76504973]) array([ 3.91946708])
  array([ 2.850741]) array([ 1.9985034]) array([ 4.05191836])
  array([ 3.46145848]) array([ 2.99489689]) array([ 2.60462582])
  array([ 1.91031189]) array([ 2.90006744]) array([ 3.69799451])
  array([ 3.83314665]) array([ 4.42917628]) array([ 5.17647658])
  array([ 4.63462677]) array([ 4.69085313]) array([ 4.84746095])
  array([ 5.04396694]) array([ 5.10152712]) array([ 3.33442499])
  array([ 4.87380637]) ...]]

I want this to be the same shape array that it is now (20,96) but instead of all of the elements within this array being arrays I would just like them to be floats:

 a = [[ 4.15167139  2.80260218  3.34189103...4.87380637 ...]]

What is the best way to iterate over this array and change all of the elements from individual arrays to floats?

Body:
Use indexing to remove a top layer of []

In [159]: array=np.array
In [161]: a = [[array([ 4.15167139]), array([ 2.80260218]), array([ 3.34189103]),
     ...:   array([ 3.73434426]), array([ 3.76504973]), array([ 3.91946708])]]
In [162]: len(a)
Out[162]: 1
In [163]: len(a[0])
Out[163]: 6

Use concatenate or stack to join a list of arrays.

In [164]: np.stack(a[0])
Out[164]:
array([[ 4.15167139],
       [ 2.80260218],
       [ 3.34189103],
       [ 3.73434426],
       [ 3.76504973],
       [ 3.91946708]])
In [165]: np.concatenate(a[0])
Out[165]:
array([ 4.15167139,  2.80260218,  3.34189103,  3.73434426,  3.76504973,
        3.91946708])

Reshape as needed.

In this case np.array also works, but I found that the concatenate approach is more reliable.  Sometimes np.array just produces an object array.

In [166]: np.array(a[0])
Out[166]:
array([[ 4.15167139],
       [ 2.80260218],
       [ 3.34189103],
       [ 3.73434426],
       [ 3.76504973],
       [ 3.91946708]])


问:
How does (?=[A-Z]) regex work with split() function?
I tried

```<code>var str = "thisIsATest";

var newStr = str.split(/(?=[A-Z])/);

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

The result came out as I wanted:

```<code>['this', 'Is', 'A', 'Test']
</code>```

but the function of

```<code>?= is

x(?=y)
</code>```

Matches x only if x is followed by y.

So shouldn't split happen at the last letter of each word.

```<code>['thi', 'I', '', 'Test']
</code>```

something like this... or not .

since if i do split(' '); it will split at every "space"

答:
When you try to split, don't imagine that it looks at each character. Instead, try to imagine that it works kind of a like a cursor, going from:

```<code>|thisIsATest
</code>```

to:

```<code>thisIsATest|
</code>```

The reason why it works like a cursor is because you are telling it to match every empty string "", so obviously, you only need to consider the stuff "between" the characters.

Each time it moves, ?= tells it to look at the characters ahead, without moving ahead. If the characters ahead matches [A-Z]. If it matches, split the string!

Here:

```<code>this|IsATest
</code>```

the character after the cursor is I, so it matches and it splits.

It also splits at the following positions:

```<code>thisIs|ATest
thisIsA|Test
</code>```

Body:
I tried

var str = "thisIsATest";

var newStr = str.split(/(?=[A-Z])/);

console.log(newStr);

The result came out as I wanted:

['this', 'Is', 'A', 'Test']

but the function of

?= is

x(?=y)

Matches x only if x is followed by y.

So shouldn't split happen at the last letter of each word.

['thi', 'I', '', 'Test']

something like this... or not .

since if i do split(' '); it will split at every "space"

Body:
When you try to split, don't imagine that it looks at each character. Instead, try to imagine that it works kind of a like a cursor, going from:

|thisIsATest

to:

thisIsATest|

The reason why it works like a cursor is because you are telling it to match every empty string "", so obviously, you only need to consider the stuff "between" the characters.

Each time it moves, ?= tells it to look at the characters ahead, without moving ahead. If the characters ahead matches [A-Z]. If it matches, split the string!

Here:

this|IsATest

the character after the cursor is I, so it matches and it splits.

It also splits at the following positions:

thisIs|ATest
thisIsA|Test


问:
Firebase HTTPS Cloud Function Triggered Twice
I've read through the Firebase Cloud Functions reference, guides and sample code to try and determine why my function is triggered twice, but am yet to find a successful resolution. I've also trialed Firebase-Queue as a work-around, however its latest update suggests Cloud Functions is the way to go.

In short, I'm retrieving notices from an external API using request-promise, checking those notices against ones I already have in my database, and when a new notice is identified, posting it to said database. The corresponding venue is then updated with a reference to the new notice. Code is as follows:

```<code>'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const request = require('request');
const rp = require('request-promise');

admin.initializeApp(functions.config().firebase);

const db = admin.database();
const venues = db.ref("/venues/");

exports.getNotices = functions.https.onRequest((req, res) => {
    var options = {
        uri: 'https://xxxxx.xxxxx',
        qs: {
            format: 'json',
            type: 'venue',
            ...
        },
        json: true
    };
    rp(options).then(data => {
            processNotices(data);
            console.log(`venues received: ${data.length}`);
            res.status(200).send('OK');
        })
        .catch(error => {
            console.log(`Caught Error: ${error}`);
            res.status(`${error.statusCode}`).send(`Error: ${error.statusCode}`);
    });
});

function processNotices(data) {
    venues.once("value").then(snapshot => {
        snapshot.forEach(childSnapshot => {
            var existingKey = childSnapshot.val().key;
            for (var i = 0; i < data.length; i++) {
                var notice = data[i];
                var noticeKey = notice.key;
                if (noticeKey !== existingKey) {
                    console.log(`New notice identified: ${noticeKey}`)
                    postNotice(notice);
                }
            }
            return true;
        });
    });
}

function postNotice(notice) {
    var ref = venues.push();
    var key = ref.key;
    var loc = notice.location;
    return ref.set(notice).then(() => {
        console.log('notice posted...');
        updateVenue(key, loc);
    });
}

function updateVenue(key, location) {
    var updates = {};
    updates[key] = "true";
    var venueNoticesRef = db.ref("/venues/" + location + "/notices/");
    return venueNoticesRef.update(updates).then(() => {
        console.log(`${location} successfully updated with ${key}`);
    });
}
</code>```

Any suggestions as to how to rectify the double-triggering would be greatly appreciated. Thanks in advance!

答: Problem solved - some misinformation from the Firebase Console Logs (repeating entries), coupled with nested for loops in the wrong order were responsible for the apparent double triggering.

Body:
I've read through the Firebase Cloud Functions reference, guides and sample code to try and determine why my function is triggered twice, but am yet to find a successful resolution. I've also trialed Firebase-Queue as a work-around, however its latest update suggests Cloud Functions is the way to go.

In short, I'm retrieving notices from an external API using request-promise, checking those notices against ones I already have in my database, and when a new notice is identified, posting it to said database. The corresponding venue is then updated with a reference to the new notice. Code is as follows:

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const request = require('request');
const rp = require('request-promise');

admin.initializeApp(functions.config().firebase);

const db = admin.database();
const venues = db.ref("/venues/");

exports.getNotices = functions.https.onRequest((req, res) => {
    var options = {
        uri: 'https://xxxxx.xxxxx',
        qs: {
            format: 'json',
            type: 'venue',
            ...
        },
        json: true
    };
    rp(options).then(data => {
            processNotices(data);
            console.log(`venues received: ${data.length}`);
            res.status(200).send('OK');
        })
        .catch(error => {
            console.log(`Caught Error: ${error}`);
            res.status(`${error.statusCode}`).send(`Error: ${error.statusCode}`);
    });
});

function processNotices(data) {
    venues.once("value").then(snapshot => {
        snapshot.forEach(childSnapshot => {
            var existingKey = childSnapshot.val().key;
            for (var i = 0; i < data.length; i++) {
                var notice = data[i];
                var noticeKey = notice.key;
                if (noticeKey !== existingKey) {
                    console.log(`New notice identified: ${noticeKey}`)
                    postNotice(notice);
                }
            }
            return true;
        });
    });
}

function postNotice(notice) {
    var ref = venues.push();
    var key = ref.key;
    var loc = notice.location;
    return ref.set(notice).then(() => {
        console.log('notice posted...');
        updateVenue(key, loc);
    });
}

function updateVenue(key, location) {
    var updates = {};
    updates[key] = "true";
    var venueNoticesRef = db.ref("/venues/" + location + "/notices/");
    return venueNoticesRef.update(updates).then(() => {
        console.log(`${location} successfully updated with ${key}`);
    });
}

Any suggestions as to how to rectify the double-triggering would be greatly appreciated. Thanks in advance!


问:
PGP: Not enough random bytes available. Please do some other work to give the OS a chance to collect more entropy
Setup : Ubuntu Server on Virtual Machine with 6 cores and 3GB of RAM.

when I am trying to generate a asymmetric key pair via GPG like this gpg --gen-key . I get the following error :

```<code>Not enough random bytes available.  Please do some other work to give
the OS a chance to collect more entropy!
</code>```

I tried to google a little bit. This is what I realise ,
I need to fire up another terminal and type in cat /udev/random --> It randomly generates a series of randomly generated values to increase the entropy.

I dont see any change in here watch cat /proc/sys/kernel/random/entropy_avail

and it still persists to give me the same error

答:
You can install daemons to gather entropy.
This command would install two such daemons:

```<code>sudo apt-get install haveged rng-tools
</code>```

I would personally perfer haveged (because of the people who have created it) over rng-tools.
But, I prefer to install both since they quite different.

ContentLicense: CC BY-SA 4.0

Body:
Setup : Ubuntu Server on Virtual Machine with 6 cores and 3GB of RAM.

when I am trying to generate a asymmetric key pair via GPG like this gpg --gen-key . I get the following error :

Not enough random bytes available.  Please do some other work to give
the OS a chance to collect more entropy!

I tried to google a little bit. This is what I realise ,
I need to fire up another terminal and type in cat /udev/random --> It randomly generates a series of randomly generated values to increase the entropy.

I dont see any change in here watch cat /proc/sys/kernel/random/entropy_avail

and it still persists to give me the same error

Body:
You can install daemons to gather entropy.
This command would install two such daemons:

sudo apt-get install haveged rng-tools

I would personally perfer haveged (because of the people who have created it) over rng-tools.
But, I prefer to install both since they quite different.


问:
Swift - Create Custom Capture Session Preset
I want to create a custom camera that records square videos. However, all of the capture session presets are not in square format

For example:

1920x1080

1280x720

640x480

Is there anyway i can create a custom preset. I still want to have high quality videos but in square format. The closest thing to square format is 640x480, but i still want HD Quality.

Is this possible, if so how? Thank you

答:
import necessary frameworks:

```<code>import UIKit
import AVFoundation
import Photos
</code>```

Than define your class with needed delegates

```<code>class CameraViewController: UIViewController,
    AVCaptureAudioDataOutputSampleBufferDelegate,
    AVCaptureVideoDataOutputSampleBufferDelegate { }
</code>```

You will need next properties for capture and save audio and video streams

```<code>private var session: AVCaptureSession = AVCaptureSession()
private var deviceInput: AVCaptureDeviceInput?
private var previewLayer: AVCaptureVideoPreviewLayer?
private var videoOutput: AVCaptureVideoDataOutput = AVCaptureVideoDataOutput()
private var audioOutput: AVCaptureAudioDataOutput = AVCaptureAudioDataOutput()

private var videoDevice: AVCaptureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
private var audioConnection: AVCaptureConnection?
private var videoConnection: AVCaptureConnection?

private var assetWriter: AVAssetWriter?
private var audioInput: AVAssetWriterInput?
private var videoInput: AVAssetWriterInput?

private var fileManager: FileManager = FileManager()
private var recordingURL: URL?

private var isCameraRecording: Bool = false
private var isRecordingSessionStarted: Bool = false

private var recordingQueue = DispatchQueue(label: "recording.queue")
</code>```

Now you can start from configuration of your AVCaptureSession and AVAssetWriter

```<code>self.session.sessionPreset = AVCaptureSessionPresetHigh
self.recordingURL = URL(fileURLWithPath: "\(NSTemporaryDirectory() as String)/file.mov")
if self.fileManager.isDeletableFile(atPath: self.recordingURL!.path) {
    _ = try? self.fileManager.removeItem(atPath: self.recordingURL!.path)
}
self.assetWriter = try? AVAssetWriter(outputURL: self.recordingURL!,
    fileType: AVFileTypeQuickTimeMovie)
</code>```

Descrive audio and video settings. For example we will make square in full screen width

```<code>let audioSettings = [
    AVFormatIDKey : kAudioFormatAppleIMA4,
    AVNumberOfChannelsKey : 1,
    AVSampleRateKey : 16000.0
] as [String : Any]

let videoSettings = [
    AVVideoCodecKey : AVVideoCodecH264,
    AVVideoWidthKey : UIScreen.main.bounds.width,
    AVVideoHeightKey : UIScreen.main.bounds.width
] as [String : Any]
</code>```

Add this settings to AVAssetWriterInput

```<code>self.videoInput = AVAssetWriterInput(mediaType: AVMediaTypeVideo,
     outputSettings: videoSettings)
self.audioInput = AVAssetWriterInput(mediaType: AVMediaTypeAudio,
     outputSettings: audioSettings)

self.videoInput?.expectsMediaDataInRealTime = true
self.audioInput?.expectsMediaDataInRealTime = true

if self.assetWriter!.canAdd(self.videoInput!) {
    self.assetWriter?.add(self.videoInput!)
}

if self.assetWriter!.canAdd(self.audioInput!) {
    self.assetWriter?.add(self.audioInput!)
}
</code>```

Add AVCaptureDeviceInput to your session

```<code>self.deviceInput = try? AVCaptureDeviceInput(device: self.videoDevice)
if self.session.canAddInput(self.deviceInput) {
    self.session.addInput(self.deviceInput)
}
</code>```

Now you can configure AVCaptureVideoPreviewLayer to be a square

```<code>self.previewLayer = AVCaptureVideoPreviewLayer(session: self.session)

//importent line of code what will did a trick
self.previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill

let rootLayer = self.view.layer
rootLayer.masksToBounds = true
self.previewLayer?.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width)

rootLayer.insertSublayer(self.previewLayer!, at: 0)
        otLayer.insertSublayer(self.previewLayer!, at: 0)
</code>```

Start session

```<code>self.session.startRunning()
</code>```

Add video and audio outputs to session

```<code>DispatchQueue.main.async {
    self.session.beginConfiguration()

    if self.session.canAddOutput(self.videoOutput) {
        self.session.addOutput(self.videoOutput)
    }

    self.videoConnection = self.videoOutput.connection(withMediaType: AVMediaTypeVideo)
    if self.videoConnection?.isVideoStabilizationSupported == true {
        self.videoConnection?.preferredVideoStabilizationMode = .auto
    }
    self.session.commitConfiguration()

    let audioDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio)
    let audioIn = try? AVCaptureDeviceInput(device: audioDevice)

    if self.session.canAddInput(audioIn) {
        self.session.addInput(audioIn)
    }

    if self.session.canAddOutput(self.audioOutput) {
        self.session.addOutput(self.audioOutput)
    }

    self.audioConnection = self.audioOutput.connection(withMediaType: AVMediaTypeAudio)
}
</code>```

}

From this point your Camera is properly configured. Your need to implement next method what will record video and audio samples

```<code>class CameraViewController: UIViewController,
    AVCaptureAudioDataOutputSampleBufferDelegate,
    AVCaptureVideoDataOutputSampleBufferDelegate { }
</code>```0

}

Add add method what will start/stop recording

```<code>class CameraViewController: UIViewController,
    AVCaptureAudioDataOutputSampleBufferDelegate,
    AVCaptureVideoDataOutputSampleBufferDelegate { }
</code>```1

And now you can start/stop camera recording from IBActionfunction

```<code>class CameraViewController: UIViewController,
    AVCaptureAudioDataOutputSampleBufferDelegate,
    AVCaptureVideoDataOutputSampleBufferDelegate { }
</code>```2

Here is GitHub example: https://github.com/ChernyshenkoTaras/CustomCamera

Body:
import necessary frameworks:

import UIKit
import AVFoundation
import Photos

Than define your class with needed delegates

class CameraViewController: UIViewController,
    AVCaptureAudioDataOutputSampleBufferDelegate,
    AVCaptureVideoDataOutputSampleBufferDelegate { }

You will need next properties for capture and save audio and video streams

private var session: AVCaptureSession = AVCaptureSession()
private var deviceInput: AVCaptureDeviceInput?
private var previewLayer: AVCaptureVideoPreviewLayer?
private var videoOutput: AVCaptureVideoDataOutput = AVCaptureVideoDataOutput()
private var audioOutput: AVCaptureAudioDataOutput = AVCaptureAudioDataOutput()

private var videoDevice: AVCaptureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
private var audioConnection: AVCaptureConnection?
private var videoConnection: AVCaptureConnection?

private var assetWriter: AVAssetWriter?
private var audioInput: AVAssetWriterInput?
private var videoInput: AVAssetWriterInput?

private var fileManager: FileManager = FileManager()
private var recordingURL: URL?

private var isCameraRecording: Bool = false
private var isRecordingSessionStarted: Bool = false

private var recordingQueue = DispatchQueue(label: "recording.queue")

Now you can start from configuration of your AVCaptureSession and AVAssetWriter

self.session.sessionPreset = AVCaptureSessionPresetHigh
self.recordingURL = URL(fileURLWithPath: "\(NSTemporaryDirectory() as String)/file.mov")
if self.fileManager.isDeletableFile(atPath: self.recordingURL!.path) {
    _ = try? self.fileManager.removeItem(atPath: self.recordingURL!.path)
}
self.assetWriter = try? AVAssetWriter(outputURL: self.recordingURL!,
    fileType: AVFileTypeQuickTimeMovie)

Descrive audio and video settings. For example we will make square in full screen width

let audioSettings = [
    AVFormatIDKey : kAudioFormatAppleIMA4,
    AVNumberOfChannelsKey : 1,
    AVSampleRateKey : 16000.0
] as [String : Any]

let videoSettings = [
    AVVideoCodecKey : AVVideoCodecH264,
    AVVideoWidthKey : UIScreen.main.bounds.width,
    AVVideoHeightKey : UIScreen.main.bounds.width
] as [String : Any]

Add this settings to AVAssetWriterInput

self.videoInput = AVAssetWriterInput(mediaType: AVMediaTypeVideo,
     outputSettings: videoSettings)
self.audioInput = AVAssetWriterInput(mediaType: AVMediaTypeAudio,
     outputSettings: audioSettings)

self.videoInput?.expectsMediaDataInRealTime = true
self.audioInput?.expectsMediaDataInRealTime = true

if self.assetWriter!.canAdd(self.videoInput!) {
    self.assetWriter?.add(self.videoInput!)
}

if self.assetWriter!.canAdd(self.audioInput!) {
    self.assetWriter?.add(self.audioInput!)
}

Add AVCaptureDeviceInput to your session

self.deviceInput = try? AVCaptureDeviceInput(device: self.videoDevice)
if self.session.canAddInput(self.deviceInput) {
    self.session.addInput(self.deviceInput)
}

Now you can configure AVCaptureVideoPreviewLayer to be a square

self.previewLayer = AVCaptureVideoPreviewLayer(session: self.session)

//importent line of code what will did a trick
self.previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill

let rootLayer = self.view.layer
rootLayer.masksToBounds = true
self.previewLayer?.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width)

rootLayer.insertSublayer(self.previewLayer!, at: 0)
        otLayer.insertSublayer(self.previewLayer!, at: 0)

Start session

self.session.startRunning()

Add video and audio outputs to session

DispatchQueue.main.async {
    self.session.beginConfiguration()

    if self.session.canAddOutput(self.videoOutput) {
        self.session.addOutput(self.videoOutput)
    }

    self.videoConnection = self.videoOutput.connection(withMediaType: AVMediaTypeVideo)
    if self.videoConnection?.isVideoStabilizationSupported == true {
        self.videoConnection?.preferredVideoStabilizationMode = .auto
    }
    self.session.commitConfiguration()

    let audioDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio)
    let audioIn = try? AVCaptureDeviceInput(device: audioDevice)

    if self.session.canAddInput(audioIn) {
        self.session.addInput(audioIn)
    }

    if self.session.canAddOutput(self.audioOutput) {
        self.session.addOutput(self.audioOutput)
    }

    self.audioConnection = self.audioOutput.connection(withMediaType: AVMediaTypeAudio)
}

}

From this point your Camera is properly configured. Your need to implement next method what will record video and audio samples

func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer
    sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {

if !self.isRecordingSessionStarted {
    let presentationTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
    self.assetWriter?.startSession(atSourceTime: presentationTime)
    self.isRecordingSessionStarted = true
}

let description = CMSampleBufferGetFormatDescription(sampleBuffer)!

if CMFormatDescriptionGetMediaType(description) == kCMMediaType_Audio {
    if self.audioInput!.isReadyForMoreMediaData {
        print("appendSampleBuffer audio");
        self.audioInput?.append(sampleBuffer)
    }
} else {
    if self.videoInput!.isReadyForMoreMediaData {
        print("appendSampleBuffer video");
        if !self.videoInput!.append(sampleBuffer) {
            print("Error writing video buffer");
        }
    }
}

}

Add add method what will start/stop recording

private func startRecording() {
    if self.assetWriter?.startWriting() != true {
        print("error: \(self.assetWriter?.error.debugDescription ?? "")")
    }

    self.videoOutput.setSampleBufferDelegate(self, queue: self.recordingQueue)
    self.audioOutput.setSampleBufferDelegate(self, queue: self.recordingQueue)
}

private func stopRecording() {
    self.videoOutput.setSampleBufferDelegate(nil, queue: nil)
    self.audioOutput.setSampleBufferDelegate(nil, queue: nil)

    self.assetWriter?.finishWriting {
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: self.recordingURL!)
        }) { saved, error in
            if saved {
                let alertController = UIAlertController(title: "Your video was successfully saved", message: nil, preferredStyle: .alert)
                let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                alertController.addAction(defaultAction)
                self.present(alertController, animated: true, completion: nil)
            } else {
                print(error.debugDescription)
            }
        }
        print("saved")
    }
}

And now you can start/stop camera recording from IBActionfunction

@IBAction func recordingButton(_ sender: Any) {
    if self.isCameraRecording {
        self.stopRecording()
    } else {
        self.startRecording()
    }
    self.isCameraRecording = !self.isCameraRecording
}

Here is GitHub example: https://github.com/ChernyshenkoTaras/CustomCamera


问:
how to select id from one table and insert into other table
```<code> $select = "SELECT MAX(order_id) FROM `order`";
       mysql_query($select);

   foreach ($_COOKIE['item'] as $key12 => $value) {
        $value22 = explode("__", $value);

        $query1 = "INSERT INTO `cart`(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`) VALUES ('',$value22[5],'$select','$value22[3]','$value22[4]')";
        $result2 = mysql_query($query1);
</code>```

The output of this is SELECT MAX(order_id) FROM order, so what is the solution of this selection and insertion of the id

答:
```<code>$select="SELECT MAX(order_id) FROM `order`";
$row = mysqli_query($con,$select);
if(mysqli_num_rows($row)>0)
{
    while($data = mysqli_fetch_assoc($row))
    {
       $order_id = $data['order_id'];
    }
}

  //This way you can fetch data
</code>```

Then use this while inserting value for order_id in your query as in

```<code>$query1="INSERT INTO `cart`(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`) VALUES ('',$value22[5],'$select','$order_id','$value22[4]')";
</code>```

Body:
 $select = "SELECT MAX(order_id) FROM `order`";
       mysql_query($select);

   foreach ($_COOKIE['item'] as $key12 => $value) {
        $value22 = explode("__", $value);

        $query1 = "INSERT INTO `cart`(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`) VALUES ('',$value22[5],'$select','$value22[3]','$value22[4]')";
        $result2 = mysql_query($query1);

The output of this is SELECT MAX(order_id) FROM order, so what is the solution of this selection and insertion of the id

Body:
$select="SELECT MAX(order_id) FROM `order`";
$row = mysqli_query($con,$select);
if(mysqli_num_rows($row)>0)
{
    while($data = mysqli_fetch_assoc($row))
    {
       $order_id = $data['order_id'];
    }
}

  //This way you can fetch data

Then use this while inserting value for order_id in your query as in

$query1="INSERT INTO `cart`(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`) VALUES ('',$value22[5],'$select','$order_id','$value22[4]')";


问:
Yii2 Search filter dropdown with different models
I just used Yii2 for my app. I'm want to create search filter form in index view with attribute from different model for filter active and not active.

I've two tables "Employee" and "Contract"..

tbl_employee

id_employee

name

dob

address

etc.

tbl_contract

id

date

status

in index I used this code

```<code><?php echo $this->render('_search', ['model' => $searchModel]); ?>
</code>```

I want to filter employee in index view who has an active contract an who's not

This _search.php

```<code><?php $form = ActiveForm::begin([
    'action' => ['index'],
    'method' => 'get',
]); ?>

<?= $form->field($model, 'id_number')->textInput(['maxlength'=>6,'style'=>'width:225px']) ?>

<?= $form->field($model, 'name') ->textInput(['maxlength'=>30,'style'=>'width:225px']) ?>

<?php $data = ['Active'=> 'Active', 'Inactive'=>'Inactive'];

echo '<label class="control-label">Status</label>';
echo Select2::widget([
'name' => 'Status_Contract',
'data' => $data,
'options' => [
    'placeholder' => 'Select Status Contract ...',
    ],
]);
?>

<div class="form-group">
    <?= Html::submitButton(Yii::t('app', 'Search'), ['class' => 'btn btn-success']) ?>
    <?= Html::a('Reset', ['/employee/index'], ['class'=>'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</code>```

Models\employee EmpSearch.php

```<code>$query = Employee::find()->joinWith('p_contract');

$dataProvider = new ActiveDataProvider([
        'query' => $query,

if (!($this->load($params) && $this->validate())) {
        return $dataProvider;
    }
    ]);
$query->andFilterWhere([
'id' => $this->id,
]);

$query->andFilterWhere(['like', 'name', $this->name]);
</code>```

This search form in my web

Attribute "status" located in Contract Models. the relation like this.

```<code>public function getP_contract()
{
    return $this->hasOne(Contract::className(), ['id_emp' => 'id_employee', 'id' => 'id_contract']);
}
</code>```

So, How can I create search form based on contract "active" or "Inactive"..
Please help me solve this problem.

答:
seems You have already a proper relation in model for get status so you should add  an attribute for your new field search status

```<code>/* your related attribute */
public $status;
</code>```

and you have alredy a joinwith for p_contract so you should add  the filter where for status

```<code> // filter by status
   $query->joinWith(['p_contract' => function ($q) {
       $q->where('contratct_table_name.status LIKE "%' . $this->status. '%"');
}]);
</code>```

you can take a look at this tutorial for more info  http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/  (see scenario 2)

Body:
I just used Yii2 for my app. I'm want to create search filter form in index view with attribute from different model for filter active and not active.

I've two tables "Employee" and "Contract"..

tbl_employee

id_employee

name

dob

address

etc.

tbl_contract

id

date

status

in index I used this code

<?php echo $this->render('_search', ['model' => $searchModel]); ?>

I want to filter employee in index view who has an active contract an who's not

This _search.php

<?php $form = ActiveForm::begin([
    'action' => ['index'],
    'method' => 'get',
]); ?>

<?= $form->field($model, 'id_number')->textInput(['maxlength'=>6,'style'=>'width:225px']) ?>

<?= $form->field($model, 'name') ->textInput(['maxlength'=>30,'style'=>'width:225px']) ?>

<?php $data = ['Active'=> 'Active', 'Inactive'=>'Inactive'];

echo 'Status';
echo Select2::widget([
'name' => 'Status_Contract',
'data' => $data,
'options' => [
    'placeholder' => 'Select Status Contract ...',
    ],
]);
?>

    <?= Html::submitButton(Yii::t('app', 'Search'), ['class' => 'btn btn-success']) ?>
    <?= Html::a('Reset', ['/employee/index'], ['class'=>'btn btn-default']) ?>

<?php ActiveForm::end(); ?>

Models\employee EmpSearch.php

$query = Employee::find()->joinWith('p_contract');

$dataProvider = new ActiveDataProvider([
        'query' => $query,

if (!($this->load($params) && $this->validate())) {
        return $dataProvider;
    }
    ]);
$query->andFilterWhere([
'id' => $this->id,
]);

$query->andFilterWhere(['like', 'name', $this->name]);

This search form in my web

Attribute "status" located in Contract Models. the relation like this.

public function getP_contract()
{
    return $this->hasOne(Contract::className(), ['id_emp' => 'id_employee', 'id' => 'id_contract']);
}

So, How can I create search form based on contract "active" or "Inactive"..
Please help me solve this problem.

Body:
seems You have already a proper relation in model for get status so you should add  an attribute for your new field search status

/* your related attribute */
public $status;

and you have alredy a joinwith for p_contract so you should add  the filter where for status

 // filter by status
   $query->joinWith(['p_contract' => function ($q) {
       $q->where('contratct_table_name.status LIKE "%' . $this->status. '%"');
}]);

you can take a look at this tutorial for more info  http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/  (see scenario 2)


问:
How to change variable from within qmake replace function
I am trying to create a custom qmake "replace function" that basically appends some stuff to the INCLUDEPATH variables like so:

```<code>defineReplace(myFunc) {
    lo=$$lower($$1)
    INCLUDEPATH += /someDir/libs/lib$${lo}
    message("| INCLUDEPATH A: " $${INCLUDEPATH})
    return (true)
}
</code>```

However when I run this function with a parameter and then print out INCLUDEPATH variables like this:

```<code>$$myFunc(whatever)
message("| INCLUDEPATH B: " $${INCLUDEPATH})
</code>```

I get the following in the log:

```<code>Project MESSAGE: | INCLUDEPATH A: /someDir/libs/libwhatever
Project MESSAGE: | INCLUDEPATH B:
</code>```

This indicates that the function works, but somehow the changes made to the INCLUDEPATH variable are not preserved.

I want to know how I can get the behavior I expected (INCLUDEPATH maintains the changes made to it after I run my function). How can I do that?

答:
You need to add a call to export. From the qmake manual:

export(variablename)

Exports the current value of variablename from the local context of a function > to the global context

So your code should be

```<code>defineReplace(myFunc) {
    lo=$$lower($$1)
    INCLUDEPATH += /someDir/libs/lib$${lo}
    message("| INCLUDEPATH A: " $${INCLUDEPATH})

    export(INCLUDEPATH)                            # <-- This is new

    return (true)
}
</code>```

Body:
I am trying to create a custom qmake "replace function" that basically appends some stuff to the INCLUDEPATH variables like so:

defineReplace(myFunc) {
    lo=$$lower($$1)
    INCLUDEPATH += /someDir/libs/lib$${lo}
    message("| INCLUDEPATH A: " $${INCLUDEPATH})
    return (true)
}

However when I run this function with a parameter and then print out INCLUDEPATH variables like this:

$$myFunc(whatever)
message("| INCLUDEPATH B: " $${INCLUDEPATH})

I get the following in the log:

Project MESSAGE: | INCLUDEPATH A: /someDir/libs/libwhatever
Project MESSAGE: | INCLUDEPATH B:

This indicates that the function works, but somehow the changes made to the INCLUDEPATH variable are not preserved.

I want to know how I can get the behavior I expected (INCLUDEPATH maintains the changes made to it after I run my function). How can I do that?

Body:
You need to add a call to export. From the qmake manual:

export(variablename)

Exports the current value of variablename from the local context of a function > to the global context

So your code should be

defineReplace(myFunc) {
    lo=$$lower($$1)
    INCLUDEPATH += /someDir/libs/lib$${lo}
    message("| INCLUDEPATH A: " $${INCLUDEPATH})

    export(INCLUDEPATH)                            # <-- This is new

    return (true)
}


问:
Eclipse Open Type Pick Absolute Match First
I have two classes, UserServiceDBImpl and UsergroupServiceDBImpl.  When I use the "Open Type" dialog and type in 'UserServiceDBImpl' it often puts UsergroupServiceDBImpl first even though the other class is an exact match.

Is there any way to convince Eclipse to put the absolute match ahead of whatever it decides is the "best" solution according to its internal rules?

答:
There has been a bug report open for this since 2005:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=109670

If you include the package when typing the classname into the dialog eg: "*.user.UserServiceDBImpl" it will help narrow it down, at least if the wrong options are in different packages anyway. Tedious though.


问:
ng-repeat add and remove styling from div
I have an issue with ng-repeat and ng-class I have predefined data that i get from server where i run it trough ng-repeat and print them in div where I have a another div styled as button I would like to be able to set initial div say it nth:child(3) a specific styling that will highlight it from the rest but still be able to if button from other div is pressed to transfer that highlight to it. In short take the style from the highlighted div and transfer it to clicked.

I have managed to do this so far.

For sake of simplicity I will trim the code to bare necessities.

view.html

//Omited code

Select

```

<blockquote>
  <p>ViewCtrl.js</p>
</blockquote>

<pre class="lang-js prettyprint-override"><code>//Omitted code

$scope.select = function(price) {
    price.selected = !price.selected;
}
</code>```

stlye.css

//Omitted

.selected {
    background-color: red;
    font-size: 3em;
}
```

At the current state div styled as button when clicked applies the change to parent div and on subsequent click it does take the style off. I now just need the way to make it unique so if say it first div is clicked it will have style but if 4th is clicked it should take off the style from first and apply it to 4th and so on...

答:
```<code><div ng-repeat = "price in settingsPrices">

<div ng-class="$index == seletedDiv ?'selected':''" ngclick="select($index)">select {{price}}</div>

</div>

$scope.seletedDiv = 0;
$scope.select = function(index) {
  $scope.seletedDiv = index;
}

 Hope this works for u.
</code>```

Body:
I have an issue with ng-repeat and ng-class I have predefined data that i get from server where i run it trough ng-repeat and print them in div where I have a another div styled as button I would like to be able to set initial div say it nth:child(3) a specific styling that will highlight it from the rest but still be able to if button from other div is pressed to transfer that highlight to it. In short take the style from the highlighted div and transfer it to clicked.

I have managed to do this so far.

For sake of simplicity I will trim the code to bare necessities.

view.html

//Omited code

Select

ViewCtrl.js

//Omitted code

$scope.select = function(price) {
    price.selected = !price.selected;
}

stlye.css

//Omitted

.selected {
    background-color: red;
    font-size: 3em;
}

At the current state div styled as button when clicked applies the change to parent div and on subsequent click it does take the style off. I now just need the way to make it unique so if say it first div is clicked it will have style but if 4th is clicked it should take off the style from first and apply it to 4th and so on...


问:
View doesn't go under status bar and status bar is black
I'm hiding the Navigation Bar on one of the screens, and if is set:

```<code>navigationController?.navigationBarHidden = true
</code>```

The status bar becomes black. Also, the image doesn't fit all the screen (see the screenshot).
If I comment this line, Navigation bar stays on screen, and the status bar is white.

Full code:

```<code>override func viewWillAppear(animated: Bool) {
        navigationController?.navigationBarHidden = true
        navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
        navigationController?.navigationBar.translucent = true
        navigationController?.navigationBar.backgroundColor = UIColor.clearColor()
        navigationController?.view.backgroundColor = UIColor.clearColor()
</code>```

All constraints of ImageView are set to 0 and it's set to fill the screen:

So, I want to put ImageView under the status bar and make the status bar icons/text white. What I'm doing wrong?

答:
To place the image view under the status bar, and have the image view fill the UIViewControllers view:

Clear all constraints for the image view

Add a constraint to set the image view to have the same width as the parent view

Add a constraint to set the image view to have the same height as the parent view

Pin the image view to the nearest neighbor as shown below. Add the constraints

The final constraints will look like the following:

Body:
I'm hiding the Navigation Bar on one of the screens, and if is set:

navigationController?.navigationBarHidden = true

The status bar becomes black. Also, the image doesn't fit all the screen (see the screenshot).
If I comment this line, Navigation bar stays on screen, and the status bar is white.

Full code:

override func viewWillAppear(animated: Bool) {
        navigationController?.navigationBarHidden = true
        navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
        navigationController?.navigationBar.translucent = true
        navigationController?.navigationBar.backgroundColor = UIColor.clearColor()
        navigationController?.view.backgroundColor = UIColor.clearColor()

All constraints of ImageView are set to 0 and it's set to fill the screen:

So, I want to put ImageView under the status bar and make the status bar icons/text white. What I'm doing wrong?


问:
Json data bind div in angularjs
Please help. I am new at angularjs, I want to bind json data into div as list using angularjs

Sample Data

```<code>"[{"T_FORM_CODE":"T12040"},{"T_FORM_CODE":"T18025"},{"T_FORM_CODE":"Q12014"},{"T_FORM_CODE":"R12039"}]"
</code>```

答:
do like this:</p>

```<code><div ng-app="myApp" ng-controller="myCtrl">
        <table>
             <tr ng-repeat="x in array">
                 <td>{{x.T_FORM_CODE}}</td>
             </tr>
        </table>
    </div>

    <script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
        $scope.array = [{"T_FORM_CODE":"T12040"},{"T_FORM_CODE":"T18025"},{"T_FORM_CODE":"Q12014"},{"T_FORM_CODE":"R12039"}];
    });
    </script>
</code>```

Title: Json data bind div in angularjs

Body:
Please help. I am new at angularjs, I want to bind json data into div as list using angularjs

Sample Data

"[{"T_FORM_CODE":"T12040"},{"T_FORM_CODE":"T18025"},{"T_FORM_CODE":"Q12014"},{"T_FORM_CODE":"R12039"}]"

Body:
do like this:

<div ng-app="myApp" ng-controller="myCtrl">
        <table>
             <tr ng-repeat="x in array">
                 <td>{{x.T_FORM_CODE}}</td>
             </tr>
        </table>
    </div>

    <script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
        $scope.array = [{"T_FORM_CODE":"T12040"},{"T_FORM_CODE":"T18025"},{"T_FORM_CODE":"Q12014"},{"T_FORM_CODE":"R12039"}];
    });
    </script>


问:
How to check if the button is clickable using selenium webdriver
I am trying to find if the button element is clickable which I am not able to validate successfully using selenium webdriver.

Here is my code to validate if the element is clickable

```<code>    boolean installAFile;

    String classValues = driver.findElement(by.XPATH("//button[contains(., 'Install a new file')]")).getAttribute("class");
    installAFIle = classValues.contains("iconbutton-button--clickable");

    return installAFIle;
</code>```

Here is the HTML

```<code><div>
<!-- react-text: 406 -->
test message 1
<!-- /react-text -->
<div class="iconbutton">
<button class="iconbutton-button iconbutton-button--clickable" type="button"
tabindex="0">
<div class="iconbutton-button-label">Install a new file</div>
</button>
</div>
<!-- react-text: 410 -->
under File > Install.
<!-- /react-text -->
</div>
</code>```

I keep on getting following validation message:
no such element: Unable to locate element: {"method":"xpath","selector":"//button[contains(., 'Install a new file')]"}

答:
Element xpath will be;

```<code>/html/body/div/div/button/div
</code>```

Or

```<code>//button/div
</code>```

Or

```<code>//div[contains(@class,'iconbutton-button-label')]
</code>```

Or

```<code>//*[contains(text(), 'Install a new file')]
</code>```

Body:
I am trying to find if the button element is clickable which I am not able to validate successfully using selenium webdriver.

Here is my code to validate if the element is clickable

    boolean installAFile;

    String classValues = driver.findElement(by.XPATH("//button[contains(., 'Install a new file')]")).getAttribute("class");
    installAFIle = classValues.contains("iconbutton-button--clickable");

    return installAFIle;

Here is the HTML

test message 1

<button class="iconbutton-button iconbutton-button--clickable" type="button"
tabindex="0">

Install a new file

</button>

under File > Install.

I keep on getting following validation message:
no such element: Unable to locate element: {"method":"xpath","selector":"//button[contains(., 'Install a new file')]"}

Body:
Element xpath will be;

/html/body/div/div/button/div

Or

//button/div

Or

//div[contains(@class,'iconbutton-button-label')]

Or

//*[contains(text(), 'Install a new file')]


问:
Trying not to overwrite a file in C?
Hi I'm trying not to overwrite a file in C using fopen(file, "w");

My question is the file already exists as a 10 MB file but when I used the fopen the file ends up becoming 1KB. I want to write something to the file but I want it to stay the same size as well. How would I accomplish this? I saw that the "a+" appends things to the end of the file but what if I want to write something to the beginning of the file without expanding the size? It's just an empty file

Alternatively, is there a way to create a file in C with a certain size (such as 10MB)?

答:
Hye! I worked on a project for adding text or 'blog' post on my web page and I found a pretty cool way to do it.
For this, I'll use a HTML file and my program.
HTML FILE:

 Hey this is the asssdsadasdsadas paragraph

 Hey this is the asssdsadasdsadas paragraph

```
</div>
</div>
</p>

<p>C FILE:</p>

```printf("Please enter the number of bytes to write from in %s .\n", argv[0]);
    int offset;
    scanf("%d", &offset);
    fseek(fp, -offset, SEEK_END);
    strcat(argv[1], "
\n\n");
    fprintf(fp, "%s", argv[1]);
    fprintf(fp, "\n\n");
```

HTML explanation:

I start with one line defined

I put a blank line which I am going to write there.

Then I got all my ending tags.

C explanation:

I ask how many bytes I want to seek from the ending of the file wich is 17 in this case(to write to the blank line).

I get the number with scanf()

Then I seek in the file at minus x bytes because normally it's going to add bytes and we specify the whence.

Then for the purpose, here I add a break tag and also 2 newline to continue the cycle.

Then I write my wanted text.

Last, I add my 2 last tags, because when I write my text, it overwrites all after it. So after, the cursor is positioned after the last newline and I can write the ending tags.

So... This is how you can do it.

Title: Trying not to overwrite a file in C?

Body:
Hye! I worked on a project for adding text or 'blog' post on my web page and I found a pretty cool way to do it.
For this, I'll use a HTML file and my program.
HTML FILE:

<html>
<body>
<p> Hey this is the asssdsadasdsadas paragraph</p><br>
<p> Hey this is the asssdsadasdsadas paragraph</p><br>

</body>
</html>

C FILE:

printf("Please enter the number of bytes to write from in %s .\n", argv[0]);
    int offset;
    scanf("%d", &offset);
    fseek(fp, -offset, SEEK_END);
    strcat(argv[1], "<br>\n\n");
    fprintf(fp, "%s", argv[1]);
    fprintf(fp, "</body>\n</html>\n");

HTML explanation:

I start with one line defined

I put a blank line which I am going to write there.

Then I got all my ending tags.

C explanation:

I ask how many bytes I want to seek from the ending of the file wich is 17 in this case(to write to the blank line).

I get the number with scanf()

Then I seek in the file at minus x bytes because normally it's going to add bytes and we specify the whence.

Then for the purpose, here I add a break tag and also 2 newline to continue the cycle.

Then I write my wanted text.

Last, I add my 2 last tags, because when I write my text, it overwrites all after it. So after, the cursor is positioned after the last newline and I can write the ending tags.

So... This is how you can do it.


问:
The Instrument removeTransformer does not work when in different thread
I am trying to learn the Instrument to addTransformer, removeTransformer and reTransformer.

I tried to add transformer, it works well.

when I remove transformer after added transformer as following, it also works well.

```<code> public static void premain(String agentArgs, Instrumentation instrumentation) {
    ClassFileTransformer transformer = new ClassFileTransformer() {
        public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
            if (!className.contains("Test")) {
                return classfileBuffer;
            }
            ClassReader cr = new ClassReader(classfileBuffer);

            ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
            cr.accept(new FieldAdapter(cw, new FieldNode(ASM5, Opcodes.ACC_PRIVATE, "hello", Type.getDescriptor(String.class), "test", "first")), 0);
            return cw.toByteArray();
        }
    };

    instrumentation.addTransformer(transformer, true);
    instrumentation.removeTransformer(transformer);
  }
</code>```

But it does not work when I tried to remove the transformer in different thread.

```<code>public static void premain(String agentArgs, Instrumentation instrumentation) {
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    ClassFileTransformer transformer = new ClassFileTransformer() {
        public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
            if (!className.contains("Test")) {
                return classfileBuffer;
            }
            ClassReader cr = new ClassReader(classfileBuffer);

            ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
            cr.accept(new FieldAdapter(cw, new FieldNode(ASM5, Opcodes.ACC_PRIVATE, "hello", Type.getDescriptor(String.class), "test", "first")), 0);
            return cw.toByteArray();
        }
    };
    instrumentation.addTransformer(transformer, true);

    executor.scheduleAtFixedRate(new RemoveTransform(instrumentation, transformer), 3, 10, TimeUnit.SECONDS);
}
static class RemoveTransform implements Runnable {
    private Instrumentation instrumentation;
    private ClassFileTransformer classFileTransformer;
    public RemoveTransform(Instrumentation instrumentation, ClassFileTransformer classFileTransformer) {
        this.instrumentation = instrumentation;
        this.classFileTransformer = classFileTransformer;
    }

    public void run() {
        System.out.println("removed transform.....");
        instrumentation.removeTransformer(classFileTransformer);
    }
}
</code>```

I checked by the output, I am sure the thread for removing transformer executed.

答:
When you remove a transformer, this does not mean that classes that already were transformed at reset to their old state. For this to happen, you have to explicitly retransform already loaded classes. I assume that in your first example, the class in question is loaded after the transformer is removed while this is no longer true in the second example.

Class file transformers can be removed from any thread.

Body:
I am trying to learn the Instrument to addTransformer, removeTransformer and reTransformer.

I tried to add transformer, it works well.

when I remove transformer after added transformer as following, it also works well.

 public static void premain(String agentArgs, Instrumentation instrumentation) {
    ClassFileTransformer transformer = new ClassFileTransformer() {
        public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
            if (!className.contains("Test")) {
                return classfileBuffer;
            }
            ClassReader cr = new ClassReader(classfileBuffer);

            ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
            cr.accept(new FieldAdapter(cw, new FieldNode(ASM5, Opcodes.ACC_PRIVATE, "hello", Type.getDescriptor(String.class), "test", "first")), 0);
            return cw.toByteArray();
        }
    };

    instrumentation.addTransformer(transformer, true);
    instrumentation.removeTransformer(transformer);
  }

But it does not work when I tried to remove the transformer in different thread.

public static void premain(String agentArgs, Instrumentation instrumentation) {
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    ClassFileTransformer transformer = new ClassFileTransformer() {
        public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
            if (!className.contains("Test")) {
                return classfileBuffer;
            }
            ClassReader cr = new ClassReader(classfileBuffer);

            ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
            cr.accept(new FieldAdapter(cw, new FieldNode(ASM5, Opcodes.ACC_PRIVATE, "hello", Type.getDescriptor(String.class), "test", "first")), 0);
            return cw.toByteArray();
        }
    };
    instrumentation.addTransformer(transformer, true);

    executor.scheduleAtFixedRate(new RemoveTransform(instrumentation, transformer), 3, 10, TimeUnit.SECONDS);
}
static class RemoveTransform implements Runnable {
    private Instrumentation instrumentation;
    private ClassFileTransformer classFileTransformer;
    public RemoveTransform(Instrumentation instrumentation, ClassFileTransformer classFileTransformer) {
        this.instrumentation = instrumentation;
        this.classFileTransformer = classFileTransformer;
    }

    public void run() {
        System.out.println("removed transform.....");
        instrumentation.removeTransformer(classFileTransformer);
    }
}

I checked by the output, I am sure the thread for removing transformer executed.


问:
Why getting Double.isNan() value as False in below scenario?
Can anyone explain why the flag value is returning False?   </p>

```<code>double a = 1.0;
double b = 0.0;
double c = a / b;
boolean flag = Double.isNaN(c);
System.out.println(flag); // False?
System.out.println(c); // Infinity
</code>```

答:
This is due to the definition of floating-point representation in the IEEE 754 standard.  The standard has representations for both "infinity" and "NaN".  "Infinity" is for operations that either produce an infinite result (such as 1/0 or tan(pi/2) [*]) or produce a result whose absolute value is larger than the largest possible number the format can represent.  More precisely, in math, there really isn't such a thing as an infinite result; rather, it's defined in terms of limits.  Thus, 1/0 doesn't exist, but the limit of 1/x as x approaches 0 is infinite.

NaN is returned for "indeterminate forms".  In math, these are cases such as 0/0 when the limit can't be determined just by looking at the numerator and denominator.  (If you have two functions f(x) and g(x) where the values are both 0 at some point f(a)=g(a)=0, then you can't determine the limit of f(x)/g(x) as x approaches a, without extra work such as L'Hopital's rule.)  NaN is also returned for things like taking the square root of a negative number.

In Java, isNan returns true only for actual NaN's, not for infinities.  Even though infinity really is "not a number", it doesn't meet the definition of a NaN according to the IEEE standard.

See here for a definition of which operations generate NaN.

[*] Note that "pi" can't be represented exactly in a floating-point number, so this really isn't an operation that could produce an "infinite result" on a computer.

Body:
Can anyone explain why the flag value is returning False?

double a = 1.0;
double b = 0.0;
double c = a / b;
boolean flag = Double.isNaN(c);
System.out.println(flag); // False?
System.out.println(c); // Infinity


问:
Pause an android application until input is provided
I have made an application where in the starting we ask for username and security password and then let the user use the application.

Currently, my application asks for username and security question one after the other in a pop out box but in the background the application also runs.

The application is waiting for the user to enter the username and security question answer because of which post url request fails to get a request because by that time "ans1[0]" variable is not set.

```<code>public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    securityquestion(); // **This part calls the pop up dialog boxes**
    statusTxtView = (TextView) findViewById(R.id.status_text);
    //Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    intentFilter
            .addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    intentFilter
            .addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

    manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
    channel = manager.initialize(this, getMainLooper(), null);
   // super.onPause();
    startRegistrationAndDiscovery();
    //super.onResume();
    servicesList = new WiFiDirectServicesList();
    getFragmentManager().beginTransaction()
            .add(R.id.container_root, servicesList, "services").commit();

}

    public void securityquestion(){
        final EditText txtUrl = new EditText(this);
        final EditText txtUrl2 = new EditText(this);
        final String[] ans1 = {""};
        final String[] ans2 = {""};
// Set the default text to a link of the Queen
        int num = getradomquestionumber();
        String messge = "";
        if(num==1)
        {
            txtUrl.setHint("First Pet name");
            messge = "What is your first pet name?";
        }else{
            txtUrl.setHint("Mother's maiden name");
            messge = "What is your mother's maiden name?";
        }
        txtUrl2.setHint("User Name");

        new AlertDialog.Builder(this)
                .setTitle("Security Question")
                .setMessage(messge)
                .setView(txtUrl)
                .setPositiveButton("Enter", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String url = txtUrl.getText().toString();
                        ans2[0] = url;
                        // moustachify(null, url);
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                })
                .show();

        new AlertDialog.Builder(this)
                .setTitle("User Name")
                .setMessage("Enter UserName")
                .setView(txtUrl2)
                .setPositiveButton("Enter", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String url = txtUrl.getText().toString();
                        ans1[0] = url;
                        // moustachify(null, url);
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                })
                .show();

        HashMap<String , String> postDataParams = new HashMap<String, String>();
        postDataParams.put("key", String.valueOf(num));
        postDataParams.put("key2", ans1[0]);
        response = performPostCall("http://10.19.23.2/NEWS/SecurityQuestion.php", postDataParams);
        System.out.println("response -------------- "+response);
        if(response == ans2[0]){

        }else{
            System.exit(0);
        }
    }
</code>```

Currently I am unable to get a response from the server because the application doesn't wait for the response from the user. How do I pause the application so that fir the dialog box appears first, takes users input and then further after authentication, only continue the application.

Requesting you to please help me with your suggestions.

答:
Try this by change method securityquestion() like below:

```<code>public void securityquestion(){
    final EditText txtUrl = new EditText(this);
    final EditText txtUrl2 = new EditText(this);
    final String[] ans1 = {""};
    final String[] ans2 = {""};
// Set the default text to a link of the Queen
        final int num = getradomquestionumber();
        String messge = "";
        if(num==1)
        {
            txtUrl.setHint("First Pet name");
            messge = "What is your first pet name?";
        }else{
            txtUrl.setHint("Mother's maiden name");
            messge = "What is your mother's maiden name?";
        }
        txtUrl2.setHint("User Name");
    new AlertDialog.Builder(LoginActivity.this)
            .setTitle("User Name")
            .setMessage("Enter UserName")
            .setView(txtUrl2)
            .setPositiveButton("Enter", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    String url = txtUrl2.getText().toString();
                    ans1[0] = url;
                    // moustachify(null, url);

                    //ask question and get result
                    new AlertDialog.Builder(LoginActivity.this)
                            .setTitle("Security Question")
                            .setMessage(messge)
                            .setView(txtUrl)
                            .setPositiveButton("Enter", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int whichButton) {
                                    String url = txtUrl.getText().toString();
                                    ans2[0] = url;
                                    // moustachify(null, url);

                                    //Now call or make server request
                                    HashMap<String , String> postDataParams = new HashMap<String, String>();
                                    postDataParams.put("key", String.valueOf(num));
                                    postDataParams.put("key2", ans1[0]);
                                    response = performPostCall("http://10.19.23.2/NEWS/SecurityQuestion.php", postDataParams);
                                    System.out.println("response -------------- "+response);
                                    if(response == ans2[0]){

                                    }else{
                                        System.exit(0);
                                    }
                                }
                            })
                            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int whichButton) {
                                }
                            })
                            .show();
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                }
            })
            .show();
}
</code>```

Body:
I have made an application where in the starting we ask for username and security password and then let the user use the application.

Currently, my application asks for username and security question one after the other in a pop out box but in the background the application also runs.

The application is waiting for the user to enter the username and security question answer because of which post url request fails to get a request because by that time "ans1[0]" variable is not set.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    securityquestion(); // **This part calls the pop up dialog boxes**
    statusTxtView = (TextView) findViewById(R.id.status_text);
    //Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    intentFilter
            .addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    intentFilter
            .addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

    manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
    channel = manager.initialize(this, getMainLooper(), null);
   // super.onPause();
    startRegistrationAndDiscovery();
    //super.onResume();
    servicesList = new WiFiDirectServicesList();
    getFragmentManager().beginTransaction()
            .add(R.id.container_root, servicesList, "services").commit();

}

    public void securityquestion(){
        final EditText txtUrl = new EditText(this);
        final EditText txtUrl2 = new EditText(this);
        final String[] ans1 = {""};
        final String[] ans2 = {""};
// Set the default text to a link of the Queen
        int num = getradomquestionumber();
        String messge = "";
        if(num==1)
        {
            txtUrl.setHint("First Pet name");
            messge = "What is your first pet name?";
        }else{
            txtUrl.setHint("Mother's maiden name");
            messge = "What is your mother's maiden name?";
        }
        txtUrl2.setHint("User Name");

        new AlertDialog.Builder(this)
                .setTitle("Security Question")
                .setMessage(messge)
                .setView(txtUrl)
                .setPositiveButton("Enter", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String url = txtUrl.getText().toString();
                        ans2[0] = url;
                        // moustachify(null, url);
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                })
                .show();

        new AlertDialog.Builder(this)
                .setTitle("User Name")
                .setMessage("Enter UserName")
                .setView(txtUrl2)
                .setPositiveButton("Enter", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String url = txtUrl.getText().toString();
                        ans1[0] = url;
                        // moustachify(null, url);
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                })
                .show();

        HashMap<String , String> postDataParams = new HashMap<String, String>();
        postDataParams.put("key", String.valueOf(num));
        postDataParams.put("key2", ans1[0]);
        response = performPostCall("http://10.19.23.2/NEWS/SecurityQuestion.php", postDataParams);
        System.out.println("response -------------- "+response);
        if(response == ans2[0]){

        }else{
            System.exit(0);
        }
    }

Currently I am unable to get a response from the server because the application doesn't wait for the response from the user. How do I pause the application so that fir the dialog box appears first, takes users input and then further after authentication, only continue the application.

Requesting you to please help me with your suggestions.

Body:
Try this by change method securityquestion() like below:

public void securityquestion(){
    final EditText txtUrl = new EditText(this);
    final EditText txtUrl2 = new EditText(this);
    final String[] ans1 = {""};
    final String[] ans2 = {""};
// Set the default text to a link of the Queen
        final int num = getradomquestionumber();
        String messge = "";
        if(num==1)
        {
            txtUrl.setHint("First Pet name");
            messge = "What is your first pet name?";
        }else{
            txtUrl.setHint("Mother's maiden name");
            messge = "What is your mother's maiden name?";
        }
        txtUrl2.setHint("User Name");
    new AlertDialog.Builder(LoginActivity.this)
            .setTitle("User Name")
            .setMessage("Enter UserName")
            .setView(txtUrl2)
            .setPositiveButton("Enter", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    String url = txtUrl2.getText().toString();
                    ans1[0] = url;
                    // moustachify(null, url);

                    //ask question and get result
                    new AlertDialog.Builder(LoginActivity.this)
                            .setTitle("Security Question")
                            .setMessage(messge)
                            .setView(txtUrl)
                            .setPositiveButton("Enter", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int whichButton) {
                                    String url = txtUrl.getText().toString();
                                    ans2[0] = url;
                                    // moustachify(null, url);

                                    //Now call or make server request
                                    HashMap<String , String> postDataParams = new HashMap<String, String>();
                                    postDataParams.put("key", String.valueOf(num));
                                    postDataParams.put("key2", ans1[0]);
                                    response = performPostCall("http://10.19.23.2/NEWS/SecurityQuestion.php", postDataParams);
                                    System.out.println("response -------------- "+response);
                                    if(response == ans2[0]){

                                    }else{
                                        System.exit(0);
                                    }
                                }
                            })
                            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int whichButton) {
                                }
                            })
                            .show();
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                }
            })
            .show();
}


问:
Calling Fragment method from Parent Activity
I want to invoke a (tabbed)fragment method to bring the data to activity.

I read this

But I get null object reference

I tried this

But my activity is already implementing the fragment class so it's not a legal expression

So when the tab is changed I want the form of the first tab to send to details to Activity by getDetails() method

```<code>        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            if (tab.getText().equals("Owner")) {
                //invoking method here
                Log.i(TAG, tab.getText().toString() + " unselected");
            }
</code>```

I tried with FragmentManager but no luck, Please help!

EDIT- This is the method I want to invoke

```<code>public Bundle getData() {
    Bundle bundle = new Bundle();
    bundle.putString("area", area);
    bundle.putString("villageTown", villageTown.getSelectedItem().toString());
    bundle.putString("ownerName", ownerName);
    bundle.putString("fatherHusbandName", fatherHusbandName);
    bundle.putString("category", category.getSelectedItem().toString());
    bundle.putString("address", address);
    bundle.putString("mobileNumber", mobileNumber);
    bundle.putString("telephoneNumber", telephoneNumber);

    return bundle;
}
</code>```

答:
```<code>@Override
public void onTabUnselected(TabLayout.Tab tab) {
    if (tab.getText().toString().equalsIgnoreCase("owner")) {
        OwnerForm frag = (OwnerForm) getSupportFragmentManager()
            .getFragments()
            .get(0);
        bundle = frag.getData();
    }

    Log.i(TAG, tab.getText().toString() + " says hi"); //test statement
}
</code>```

Using getFragments().get() did the trick for me, I didn't know FragmentManager keeps a list of all the active Fragments so you don't have to use getFragmentById() which causes the null object error.

Body:
I want to invoke a (tabbed)fragment method to bring the data to activity.

I read this

But I get null object reference

I tried this

But my activity is already implementing the fragment class so it's not a legal expression

So when the tab is changed I want the form of the first tab to send to details to Activity by getDetails() method

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            if (tab.getText().equals("Owner")) {
                //invoking method here
                Log.i(TAG, tab.getText().toString() + " unselected");
            }

I tried with FragmentManager but no luck, Please help!

EDIT- This is the method I want to invoke

public Bundle getData() {
    Bundle bundle = new Bundle();
    bundle.putString("area", area);
    bundle.putString("villageTown", villageTown.getSelectedItem().toString());
    bundle.putString("ownerName", ownerName);
    bundle.putString("fatherHusbandName", fatherHusbandName);
    bundle.putString("category", category.getSelectedItem().toString());
    bundle.putString("address", address);
    bundle.putString("mobileNumber", mobileNumber);
    bundle.putString("telephoneNumber", telephoneNumber);

    return bundle;
}

Body:
@Override
public void onTabUnselected(TabLayout.Tab tab) {
    if (tab.getText().toString().equalsIgnoreCase("owner")) {
        OwnerForm frag = (OwnerForm) getSupportFragmentManager()
            .getFragments()
            .get(0);
        bundle = frag.getData();
    }

    Log.i(TAG, tab.getText().toString() + " says hi"); //test statement
}

Using getFragments().get() did the trick for me, I didn't know FragmentManager keeps a list of all the active Fragments so you don't have to use getFragmentById() which causes the null object error.