问:
System.nanotime return wildly different times
So i'm trying to implement a sort of day-night cycle in my game, and I'm using System.nanotime() to get the approximate time passed between frames, the problem is that it sometimes jumps huge amounts of time

Using lwjgl, and calling Timer.update() before swapBuffers with vsync enabled should be around 16.6ms increase to the current time each loop shouldnt it? Yet it can be much much higher than that with no actual slowdown for rendering

Here's the code : Time class

```<code>public class Time
{
    public static final long SECOND = 1000000000L;

    private static long lastTime;

    public static long getTime()
    {
        return System.nanoTime();
    }

    public static double getDelta()
    {
        return (double)(getTime() - lastTime) / SECOND;
    }

    public static void update()
    {
        Time.lastTime = Time.getTime();
    }
}
</code>```

Update method

```<code>    while ( !glfwWindowShouldClose(window) )
    {
        input();
        update();
        render();
    }

public void update()
{
    //System.out.println("Time since last update " + Time.getDelta());
    Time.update();
}
</code>```

And where i'm using the delta time :

```<code>    if ((timeOfDay + Time.getDelta()) < timeDayTotal)
        timeOfDay += Time.getDelta();
    else
        timeOfDay += Time.getDelta() - timeDayTotal;
    System.out.println("Time of day " + timeOfDay);
</code>```

Ignoring the fact that the precision seems to be waaaay off for now, here's some sample output

```<code>Time of day 0.0077873133
Time of day 0.0077988105
Time of day 0.0078120963
Time of day 0.007860638
Time of day 0.015185255
Time of day 0.01879608
Time of day 0.01880809
Time of day 0.018820863
Time of day 0.018835938
Time of day 0.018851267
</code>```

It seems to mostly increment the correct amount (by a factor of 10^-4, but close enough, thats not the problem), but then it has these massive jumps up that I can't explain

So finally, a) whats the problem with system.nanoTime and b) is there a fix or viable replacement?

Edit : Switched to currentTimeMillis(), the precision is gone which is no big deal, but the jumps are still there

```<code>Time of day 0.03
Time of day 0.03
Time of day 0.03
Time of day 0.03
Time of day 0.06
Time of day 0.06
Time of day 0.06
Time of day 0.06
</code>```

答:
In general, do not use System.nanoTime() in any program which you don’t plan to strongly control how it is run, and the environment it is run in.
  ..

The problem lies in the RDTSC instruction which retrieves the number of CPU ticks since the CPU started. On multi-core systems, each core will have its own tick count, and they will not match, so every time your process switches CPUs, you get a different measurement. The issue is compounded by the fact that some power management systems actually alter the CPU’s frequency to save power, which breaks the functionality even on single core, single CPU systems.

From here

Body:
So i'm trying to implement a sort of day-night cycle in my game, and I'm using System.nanotime() to get the approximate time passed between frames, the problem is that it sometimes jumps huge amounts of time

Using lwjgl, and calling Timer.update() before swapBuffers with vsync enabled should be around 16.6ms increase to the current time each loop shouldnt it? Yet it can be much much higher than that with no actual slowdown for rendering

Here's the code : Time class

public class Time
{
    public static final long SECOND = 1000000000L;

    private static long lastTime;

    public static long getTime()
    {
        return System.nanoTime();
    }

    public static double getDelta()
    {
        return (double)(getTime() - lastTime) / SECOND;
    }

    public static void update()
    {
        Time.lastTime = Time.getTime();
    }
}

Update method

    while ( !glfwWindowShouldClose(window) )
    {
        input();
        update();
        render();
    }

public void update()
{
    //System.out.println("Time since last update " + Time.getDelta());
    Time.update();
}

And where i'm using the delta time :

    if ((timeOfDay + Time.getDelta()) < timeDayTotal)
        timeOfDay += Time.getDelta();
    else
        timeOfDay += Time.getDelta() - timeDayTotal;
    System.out.println("Time of day " + timeOfDay);

Ignoring the fact that the precision seems to be waaaay off for now, here's some sample output

Time of day 0.0077873133
Time of day 0.0077988105
Time of day 0.0078120963
Time of day 0.007860638
Time of day 0.015185255
Time of day 0.01879608
Time of day 0.01880809
Time of day 0.018820863
Time of day 0.018835938
Time of day 0.018851267

It seems to mostly increment the correct amount (by a factor of 10^-4, but close enough, thats not the problem), but then it has these massive jumps up that I can't explain

So finally, a) whats the problem with system.nanoTime and b) is there a fix or viable replacement?

Edit : Switched to currentTimeMillis(), the precision is gone which is no big deal, but the jumps are still there

Time of day 0.03
Time of day 0.03
Time of day 0.03
Time of day 0.03
Time of day 0.06
Time of day 0.06
Time of day 0.06
Time of day 0.06


来源: stackexchange

问:
Learners in CNTK C# API
I am using C# CNTK 2.2.0 API for training.
I have installed Nuget package CNTK.CPUOnly and CNTK.GPU.

I am looking for following learners in C#.
1. AdaDelta
2. Adam
3. AdaGrad
4. Neterov

Looks like Python supports these learners but C#
package is not showing them.

I can see only SGD and SGDMomentun learners in C# there.

Any thoughts, how to get and set other learners in C#.
Do I need to install any additional package to get these learners?

Appreciate your help.

答: Download the NCCL 2 app to configure in c# www.nvidia. com or google NCCL download </p>

ContentLicense: CC BY-SA 3.0

Title: Learners in CNTK C# API


问:
Stored Procedure Efficiency - Null Input Parameters and Where clauses
I like to minimize the number of stored procedures I have by having a bunch of input parameters all defaulting to NULL and then those same parameters included in the WHERE with a test for Equality or NULL.

How inefficient is this in relation to query performance - verses writing stored procedure for 1 specific tasks? e.g. Select by UserId only, select by Username/Password, select by FirstName/LastName...

Example:

```<code>CREATE PROC dbo.up_Select_User

  @UserId int = NULL
, @Username varchar(255) = NULL
, @Password varchar(255) = NULL
, @FirstName varchar(50) = NULL
, @LastName varchar(50) = NULL
, @IsActive bit = NULL

SELECT UserId, Username, FirstName, LastName, EmailAddress
FROM dbo.[User]
WHERE (UserId = @UserId OR @UserId IS NULL)
AND (Username = @Username OR @Username IS NULL)
AND (Password = @Password OR @Password IS NULL)
AND (FirstName = @FirstName OR @FirstName IS NULL)
AND (LastName = @LastName OR @LastName IS NULL)
AND (IsActive = @IsActive OR @IsActive IS NULL)
</code>```

Some additional info - may not be relevant... I am using entity framework 4 to map to stored procedures using a mix of normal entities and complex types depending on the query results.

答:
This is inefficient because it uses OR and the optimiser will default to a scan .

If you have a few 1000 rows, it'll be OK though.

Sometimes, this pattern works better because the ISNULL can become trivial

```<code>SELECT UserId, Username, FirstName, LastName, EmailAddress
FROM dbo.[User]
WHERE
    UserId = ISNULL(@UserId, UserId) AND
    Username = ISNULL(@Username , Username) AND
    Password = ISNULL(@Password , Password ) ...
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I like to minimize the number of stored procedures I have by having a bunch of input parameters all defaulting to NULL and then those same parameters included in the WHERE with a test for Equality or NULL.

How inefficient is this in relation to query performance - verses writing stored procedure for 1 specific tasks? e.g. Select by UserId only, select by Username/Password, select by FirstName/LastName...

Example:

CREATE PROC dbo.up_Select_User

  @UserId int = NULL
, @Username varchar(255) = NULL
, @Password varchar(255) = NULL
, @FirstName varchar(50) = NULL
, @LastName varchar(50) = NULL
, @IsActive bit = NULL

SELECT UserId, Username, FirstName, LastName, EmailAddress
FROM dbo.[User]
WHERE (UserId = @UserId OR @UserId IS NULL)
AND (Username = @Username OR @Username IS NULL)
AND (Password = @Password OR @Password IS NULL)
AND (FirstName = @FirstName OR @FirstName IS NULL)
AND (LastName = @LastName OR @LastName IS NULL)
AND (IsActive = @IsActive OR @IsActive IS NULL)

Some additional info - may not be relevant... I am using entity framework 4 to map to stored procedures using a mix of normal entities and complex types depending on the query results.

Body:
This is inefficient because it uses OR and the optimiser will default to a scan .

If you have a few 1000 rows, it'll be OK though.

Sometimes, this pattern works better because the ISNULL can become trivial

SELECT UserId, Username, FirstName, LastName, EmailAddress
FROM dbo.[User]
WHERE
    UserId = ISNULL(@UserId, UserId) AND
    Username = ISNULL(@Username , Username) AND
    Password = ISNULL(@Password , Password ) ...


问:
How do I merge two lists into a single list?
I have

```<code>a = [1, 2]
b = ['a', 'b']
</code>```

I want

```<code>c = [1, 'a', 2, 'b']
</code>```

答:
Here is a standard / self-explaining solution, i hope someone will find it useful:

```<code>a = ['a', 'b', 'c']
b = ['1', '2', '3']

c = []
for x, y in zip(a, b):
    c.append(x)
    c.append(y)

print (c)
</code>```

output:

```<code>['a', '1', 'b', '2', 'c', '3']
</code>```

Of course, you can change it and do manipulations on the values if needed

Body:
I have

a = [1, 2]
b = ['a', 'b']

I want

c = [1, 'a', 2, 'b']

Body:
Here is a standard / self-explaining solution, i hope someone will find it useful:

a = ['a', 'b', 'c']
b = ['1', '2', '3']

c = []
for x, y in zip(a, b):
    c.append(x)
    c.append(y)

print (c)

output:

['a', '1', 'b', '2', 'c', '3']

Of course, you can change it and do manipulations on the values if needed


问:
Is it possible to write the name of a testng test from a called method?
I'm running Selenium tests using Java (TestNG and IntelliJ) and am currently working on my reporting framework.
My test setup looks something like this:

```<code>@Test
public void testLogin(){
  myKeyword.login();
}
</code>```

myKeyword is a class of keywords that I have created, with a method called login. The login keyword will look like:

```<code>public void login(){
  myPage.typeInTextBox("Username");
  myPage.typeInTextBox("Password");
  myPage.buttonClick("Login");
}
</code>```

My validation is built into the methods "buttonClick" and "typeInTextBox". They will look something like:

```<code>try{
  driver.findelement(By.id("myButton")).click();
}
catch (Exception e){
  Assert.fail("Could not click on the button.");
}
</code>```

What I want to know is, is it possible for the "buttonClick" method to know the name of the test that's calling it?

I want to replace the "Assert.fail..." with my own function that will create a text file that I will use to log the information I want, which will need to include the name of the test that failed (in this case "testLogin).

答:
One option would be to set the name of the current test somewhere, possibly to a static variable. How to do that for TestNG was described here.</p>

```<code>public class Test {
    @BeforeMethod
    public void handleTestMethodName(java.lang.reflect.Method method) {
        GlobalVariables.currentTestName = method.getName();
    }
...
}
</code>```

Body:
I'm running Selenium tests using Java (TestNG and IntelliJ) and am currently working on my reporting framework.
My test setup looks something like this:

@Test
public void testLogin(){
  myKeyword.login();
}

myKeyword is a class of keywords that I have created, with a method called login. The login keyword will look like:

public void login(){
  myPage.typeInTextBox("Username");
  myPage.typeInTextBox("Password");
  myPage.buttonClick("Login");
}

My validation is built into the methods "buttonClick" and "typeInTextBox". They will look something like:

try{
  driver.findelement(By.id("myButton")).click();
}
catch (Exception e){
  Assert.fail("Could not click on the button.");
}

What I want to know is, is it possible for the "buttonClick" method to know the name of the test that's calling it?

I want to replace the "Assert.fail..." with my own function that will create a text file that I will use to log the information I want, which will need to include the name of the test that failed (in this case "testLogin).

Body:
One option would be to set the name of the current test somewhere, possibly to a static variable. How to do that for TestNG was described here.

public class Test {
    @BeforeMethod
    public void handleTestMethodName(java.lang.reflect.Method method) {
        GlobalVariables.currentTestName = method.getName();
    }
...
}


问:
Unable to merge 2 JSON results and get response from a PHP script
I am trying to fetch a result from my select statement, I am using 2 statements and want a JDON response of the 2 outputs. That's all.

Problem: I am testing from Chrome Postman, it is showing result

```<code>[
null,
null
]
</code>```

Below is my php code; where am I going wrong?

```<code><?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type,x-prototype-version,x-requested-with');
    header('Cache-Control: max-age=900');
    header("Content-Type: application/json"); // tell client that we are sending json data

    define("DB_USR","erSKJV");
    define("DB_PsAS","T");
    define("DB","ipaddress/orcl.profits");
    $conn = oci_connect(DB_USR,DB_PAS,DB);

    if (!$conn)
    {
        $e = oci_error();
        $result["message"] = $e['message'];
        echo json_encode($result);
        exit(1);
    }

        $loggedinuser = $_POST['loggedinuser'];

        $stmt = "select count(*) as taskgiven from admtask where CLOSE_DT is null and primary='".$loggedinuser."' ";

        $stmt1 = "select count(*) as mytask from admtask where CLOSE_DT is null and entusr='".$loggedinuser."' ";

        $result=oci_parse($conn,$stmt);
        $ex2=oci_execute($result);

        while ($row=oci_fetch_assoc($result))
        {
          $stmta[] = $row;
        }
         json_encode($stmta);

        $result1=oci_parse($conn,$stmt1);
        $ex2=oci_execute($result1);

        while ($row1=oci_fetch_assoc($result1))
        {
          $stmtb[] = $row1;
        }
         json_encode($stmtb);

        $final[] = json_decode($stmta,true);
        $final[] = json_decode($stmtb,true);
        $json_merge = json_encode($final);

        echo json_encode($json_merge);

?>
</code>```

You need to concentrate on stmta , stmtb and finally json_merge

答:
You shouldn't call json_encode() on an array that contains JSON. Put the original arrays in the container array, and then call json_encode() on the entire thing.

```<code>$final = array($stmta, $stmtb);
echo json_encode($final);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to fetch a result from my select statement, I am using 2 statements and want a JDON response of the 2 outputs. That's all.

Problem: I am testing from Chrome Postman, it is showing result

[
null,
null
]

Below is my php code; where am I going wrong?

<?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type,x-prototype-version,x-requested-with');
    header('Cache-Control: max-age=900');
    header("Content-Type: application/json"); // tell client that we are sending json data

    define("DB_USR","erSKJV");
    define("DB_PsAS","T");
    define("DB","ipaddress/orcl.profits");
    $conn = oci_connect(DB_USR,DB_PAS,DB);

    if (!$conn)
    {
        $e = oci_error();
        $result["message"] = $e['message'];
        echo json_encode($result);
        exit(1);
    }

        $loggedinuser = $_POST['loggedinuser'];

        $stmt = "select count(*) as taskgiven from admtask where CLOSE_DT is null and primary='".$loggedinuser."' ";

        $stmt1 = "select count(*) as mytask from admtask where CLOSE_DT is null and entusr='".$loggedinuser."' ";

        $result=oci_parse($conn,$stmt);
        $ex2=oci_execute($result);

        while ($row=oci_fetch_assoc($result))
        {
          $stmta[] = $row;
        }
         json_encode($stmta);

        $result1=oci_parse($conn,$stmt1);
        $ex2=oci_execute($result1);

        while ($row1=oci_fetch_assoc($result1))
        {
          $stmtb[] = $row1;
        }
         json_encode($stmtb);

        $final[] = json_decode($stmta,true);
        $final[] = json_decode($stmtb,true);
        $json_merge = json_encode($final);

        echo json_encode($json_merge);

?>

You need to concentrate on stmta , stmtb and finally json_merge

Body:
You shouldn't call json_encode() on an array that contains JSON. Put the original arrays in the container array, and then call json_encode() on the entire thing.

$final = array($stmta, $stmtb);
echo json_encode($final);


问:
How to force VoiceOver to not read the "heading" word for view controller title
Is There any way to force VoiceOver to not read view controller title "heading" word after reading title/accessibilityLabel?

Currently the behaviour is default. If I set title to "My Panel" voice over will read something like this:

"My Panel"...."Heading"

I believe this is the result of accessibility trait UIAccessibilityTraitHeader set on some of the UI element but I don't know exacly which element has this trait. My view controller in nested inside navigation controller. Please don't ask why I need to remove this one speaking word. That is the requirement and I need to get rid of it.

答:
You can customise this headerview, and implement the accessibilityElementDidBecomeFocused method in your custom view, when this view did become focused and post UIAccessibilityLayoutChangedNotification to VoiceOver and focus to itself, and then return the traits UIAccessibilityTraitNone

```<code>- (void)accessibilityElementDidBecomeFocused {
       UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification,   self);
}

- (UIAccessibilityTraits)accessibilityTraits {
    return UIAccessibilityTraitNone;
}
</code>```

Body:
You can customise this headerview, and implement the accessibilityElementDidBecomeFocused method in your custom view, when this view did become focused and post UIAccessibilityLayoutChangedNotification to VoiceOver and focus to itself, and then return the traits UIAccessibilityTraitNone

- (void)accessibilityElementDidBecomeFocused {
       UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification,   self);
}

- (UIAccessibilityTraits)accessibilityTraits {
    return UIAccessibilityTraitNone;
}


问:
Set the tab item text as bold in WPF tab control
When I set my tab item font weight to bold, all the controls within that tab become bold. How do I set just the text header of the tab item without affecting the controls?</p>

答:
This is what I did to get it to work. Thanks, SeeSharp, for the hint.</p>

```<code>            <TabControl.Resources>
            <Style TargetType="{x:Type TabItem}">
                <Setter Property="HeaderTemplate">
                    <Setter.Value>
                            <DataTemplate>
                                <TextBlock FontWeight="Bold" Text="{Binding}"/>
                            </DataTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
            </TabControl.Resources>
</code>```

Body:
This is what I did to get it to work. Thanks, SeeSharp, for the hint.

            <TabControl.Resources>
            <Style TargetType="{x:Type TabItem}">
                <Setter Property="HeaderTemplate">
                    <Setter.Value>
                            <DataTemplate>
                                <TextBlock FontWeight="Bold" Text="{Binding}"/>
                            </DataTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
            </TabControl.Resources>


问:
Access variables inside constructor outside of it in Ionic Local Notifications
```<code>export class HomePage
{

 constructor(public navCtrl: NavController, public alertCtrl: AlertController, private plt: Platform, public localNotifications: LocalNotifications,) {
     this.plt.ready().then((rdy) => {

       let date = new Date();
       let before_work_notification_time = new Date(date.setHours(7,0,0) )

       this.localNotifications.schedule({
         id:1,
         title: 'Good morning',
         text: 'My morning notification' + before_work_notification_time.getHours(),
         at: before_work_notification_time,
         every: 'day',
         data: { mydata: 'My daily before work notification'}
       });
}
}
</code>```

I would like access the value of "work_start_notification_time" outside of constructor in "ionViewDidLoad()". Is it possible to do? i am trying to come up with a graph of all notification times I have created. Or, is it possible to access the localnotification I created using it's "id"?

Thanks in advance,
skr

答:
```<code>export class HomePage
{

//outside scope variables
public work_start_notification_time:any ;

 constructor() {
    //assign a value
this.work_start_notification_time = "somevalue";

}

someMethod()
{
  //access from outside constructor

console.log(this.work_start_notification_time);
}
}
</code>```

Body:
export class HomePage
{

 constructor(public navCtrl: NavController, public alertCtrl: AlertController, private plt: Platform, public localNotifications: LocalNotifications,) {
     this.plt.ready().then((rdy) => {

       let date = new Date();
       let before_work_notification_time = new Date(date.setHours(7,0,0) )

       this.localNotifications.schedule({
         id:1,
         title: 'Good morning',
         text: 'My morning notification' + before_work_notification_time.getHours(),
         at: before_work_notification_time,
         every: 'day',
         data: { mydata: 'My daily before work notification'}
       });
}
}

I would like access the value of "work_start_notification_time" outside of constructor in "ionViewDidLoad()". Is it possible to do? i am trying to come up with a graph of all notification times I have created. Or, is it possible to access the localnotification I created using it's "id"?

Thanks in advance,
skr


问:
need help to update record of database in WordPress plugin
I am developing a plugin now i want to update my table record.... I'm using this code to fetch data from database

```<code>  <?php
    $id = $_GET\['id'\];
    $dirname = dirname(__FILE__);
    $root = false !== mb_strpos( $dirname, 'wp-content' ) ? mb_substr( $dirname, 0, mb_strpos( $dirname, 'wp-content' ) ) : $dirname;
    require_once( $root . "wp-load.php" );

        global $wpdb;
         $post_name_table = $wpdb->prefix . "tropix_dmin";
         $query = "
            SELECT post_name1, id
            FROM $post_name_table
            WHERE id= $id";
        $post_name1_results = $wpdb->get_results($query);
    ?>
      <table class="widefat" style="border-radius:4px;">
      <tr>
        <th class="manage-column" scope="col" style="font-weight:bold; font-size:20px;">Field</th>
        <th class="manage-column" scope="col" style="font-weight:bold; font-size:20px;">Value</th>
      </tr>
      <?php foreach ( $post_name1_results as $post_names ) {
        $this_data = unserialize($post_names->post_name1);
        //echo "```";
        //print_r($this_data);
        if($this_data != ""){
       ?>

        Street Address
        <input type="text" value="<?php echo $this_data\['$Street_Address'\]; ?>"  />

 <?php }
  } ?>

```

<p>But i need to update data... also i am sending the screenshot of the database.... please help me</p>

```  [1]: https://i.stack.imgur.com/4kset.jpg
```

答:
if you want to update a column your query should be:

```<code>   $query = "UPDATE (*table*) SET (*column to update*) = '*value*' WHERE id= $id";
</code>```

to echo an existing column, use:

```<code>$this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$query = mysqli_query($this->db_connection,"SELECT *column* FROM *table* WHERE id='*your id*'");
$value = mysqli_fetch_all($query,MYSQLI_ASSOC);
echo $value[0]['column name'];
</code>```

Care with SQL Injection though.

Body:
I am developing a plugin now i want to update my table record.... I'm using this code to fetch data from database

  <?php
    $id = $_GET\['id'\];
    $dirname = dirname(__FILE__);
    $root = false !== mb_strpos( $dirname, 'wp-content' ) ? mb_substr( $dirname, 0, mb_strpos( $dirname, 'wp-content' ) ) : $dirname;
    require_once( $root . "wp-load.php" );

        global $wpdb;
         $post_name_table = $wpdb->prefix . "tropix_dmin";
         $query = "
            SELECT post_name1, id
            FROM $post_name_table
            WHERE id= $id";
        $post_name1_results = $wpdb->get_results($query);
    ?>

        Field
        Value

      <?php foreach ( $post_name1_results as $post_names ) {
        $this_data = unserialize($post_names->post_name1);
        //echo "
";
        //print_r($this_data);
        if($this_data != ""){
       ?>

        Street Address
        <input type="text" value="<?php echo $this_data\['$Street_Address'\]; ?>"  />

 <?php }
  } ?>

But i need to update data... also i am sending the screenshot of the database.... please help me

  [1]: https://i.stack.imgur.com/4kset.jpg

Body:
if you want to update a column your query should be:

   $query = "UPDATE (*table*) SET (*column to update*) = '*value*' WHERE id= $id";

to echo an existing column, use:

$this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$query = mysqli_query($this->db_connection,"SELECT *column* FROM *table* WHERE id='*your id*'");
$value = mysqli_fetch_all($query,MYSQLI_ASSOC);
echo $value[0]['column name'];

Care with SQL Injection though.


问:
How to export data from textedit to excel file using python 3
Today I have a new problem so I hope that everybody can help me. My problem is export data from textedit to excel file using python 3. I had found many documents but all of them can not help me. Please give me some helps :)</p>

答:
If your data is regular, then the problem will be simple.

For example:
If every line has":",you can catch it with regular expressions":".
Then, Insert the character before and after the colon into a dictionary.

something like:
{date:2017-11-16, time:17:09, ......}

finally， use xlrd and xlwt.

you can easily export data from python dictionary to excel using xlrd and xlwt.

But, if your data is random.
It's too difficult, and I don't have a good way,either.


问:
Javascript Comparing String Not Working
I need to do comparing string because I need to have calculation. The string from select option in HTML and another will be the variable string.

This is my HTML Code:

```<code> <label>Freight Cost Mode</label>
 <select class="form-control" id="freightcostmode_insert" name="freightCostMode_insert" onchange="val()">
 <option>Percentage</option>
 <option>Monetary</option>
 </select>
 <input class="form-control" id="freightcost_insert" type="text" placeholder="Freight Cost Mode" name="freightCost_insert" onkeyup="val()">
 <input type="text" class="form-control" id="freight">
</code>```

This is my javascript code:

```<code>        <script>
        function val() {
        var input = document.getElementById("freightcostmode_insert").value;
        var calculation = document.getElementById("freightCost_insert").value;
        if(inputing == "Percentage"){
            document.getElementById('freight').value = calculation*1.5;
        }if else(inputing == 'Monetary'){

        }

        }
        </script>
</code>```

答:
For first your inputing variable does not exist - maybe input.

For second parse the calculation value into a number.

Also you have some syntax errors in your code.

function val() {
  var input =  document.getElementById("freightcostmode_insert").value;
  var calculation = document.getElementById("freightcost_insert").value;

  if(input == "Percentage"){
     document.getElementById('freight').value = parseInt(calculation) * 1.5;
  } else if(input == 'Monetary'){

  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>Freight Cost Mode</label>
 <select class="form-control" id="freightcostmode_insert" name="freightCostMode_insert" onchange="val()">
 <option>Percentage</option>
 <option>Monetary</option>
 </select>
 <input class="form-control" id="freightcost_insert" type="text" placeholder="Freight Cost Mode" name="freightCost_insert" onkeyup="val()">
 <input type="text" class="form-control" id="freight"></code>```

Title: Javascript Comparing String Not Working

Body:
I need to do comparing string because I need to have calculation. The string from select option in HTML and another will be the variable string.

This is my HTML Code:

 Freight Cost Mode
 <select class="form-control" id="freightcostmode_insert" name="freightCostMode_insert" onchange="val()">
 <option>Percentage</option>
 <option>Monetary</option>
 </select>
 <input class="form-control" id="freightcost_insert" type="text" placeholder="Freight Cost Mode" name="freightCost_insert" onkeyup="val()">
 <input type="text" class="form-control" id="freight">

This is my javascript code:

Body:
For first your inputing variable does not exist - maybe input.

For second parse the calculation value into a number.

Also you have some syntax errors in your code.

function val() {
  var input =  document.getElementById("freightcostmode_insert").value;
  var calculation = document.getElementById("freightcost_insert").value;

  if(input == "Percentage"){
     document.getElementById('freight').value = parseInt(calculation) * 1.5;
  } else if(input == 'Monetary'){

  }
}

<label>Freight Cost Mode</label>
 <select class="form-control" id="freightcostmode_insert" name="freightCostMode_insert" onchange="val()">
 <option>Percentage</option>
 <option>Monetary</option>
 </select>
 <input class="form-control" id="freightcost_insert" type="text" placeholder="Freight Cost Mode" name="freightCost_insert" onkeyup="val()">
 <input type="text" class="form-control" id="freight">


问:
using multiple curly braces in React
I am trying to call the loadData function which is working in the component call. The information also renders correctly on screen. But when I add {this.loadData()} inside the render() it will not work.</p>

```<code>I get Syntax error: C:/Users/jokar38/workspace/react/moviedb/src/App.jsx: Unexpected token, expected , (40:8)

componentDidMount() {
      console.log('GrandChild did mount.');

      this.loadData()
    }
render() {
      const { data } = this.state;
      return (
        <ul>
          // if data not loaded null will render nothing
          // if data is not null, we iterate data.results with map
          { data && data.results.map(function (film, index) {
            // film is an object, just one or more properties to render
            return <li key={ index }>{ film.display_title }</li>;
          }) };
        </ul>
        {this.loadData()} <---------- This won't work
      );
    }
</code>```

答:
The problem is render method can only return a single root node. So what you can do is to wrap your elements inside another
 as such:

```<code>componentDidMount() {
   console.log('GrandChild did mount.');
   this.loadData()
}

render() {
   const { data } = this.state;
   return (
     <div>
        <ul>
           { data && data.results.map(function (film, index) {
               return <li key={ index }>{ film.display_title }</li>;
           }) };
        </ul>
        {this.loadData()}
     </div>
   );
}
</code>```

Alternatively if you use React 16 you could return an array from render method. On a side note, if loadData() does not return any components, I suggest you put it somewhere else like componentDidMount.

Title: using multiple curly braces in React

Body:
I am trying to call the loadData function which is working in the component call. The information also renders correctly on screen. But when I add {this.loadData()} inside the render() it will not work.

I get Syntax error: C:/Users/jokar38/workspace/react/moviedb/src/App.jsx: Unexpected token, expected , (40:8)

componentDidMount() {
      console.log('GrandChild did mount.');

      this.loadData()
    }
render() {
      const { data } = this.state;
      return (

          // if data not loaded null will render nothing
          // if data is not null, we iterate data.results with map
          { data && data.results.map(function (film, index) {
            // film is an object, just one or more properties to render
            return
{ film.display_title }
;
          }) };

        {this.loadData()} <---------- This won't work
      );
    }

Body:
The problem is render method can only return a single root node. So what you can do is to wrap your elements inside another <div> as such:

componentDidMount() {
   console.log('GrandChild did mount.');
   this.loadData()
}

render() {
   const { data } = this.state;
   return (
     <div>
        <ul>
           { data && data.results.map(function (film, index) {
               return <li key={ index }>{ film.display_title }</li>;
           }) };
        </ul>
        {this.loadData()}
     </div>
   );
}

Alternatively if you use React 16 you could return an array from render method. On a side note, if loadData() does not return any components, I suggest you put it somewhere else like componentDidMount.


问:
Adding items to array with while loops
I'm trying to push 1 -> 10 into my "array1"  though I'm sure that it's not working.

array1 = ["123", "abc", "string", "text", "test", "ok"]
                 while (i <= 10){
                    array1.push(i)
                    i++
                 }
    document.getElementById("p0").innerHTML = document.getElementById("p0").innerHTML + " | " + array[Math.floor((Math.random() * array.length))]```

p0's innerhtml stays as "Random Array Item:" and does not change, though when I remove the while loop it seems to work fine, example output, "Random Array Item: | test | text | abc | abc | text | abc"

答:
Follow some adjustments:

```<code>var i = 0;
array1 = ["123", "abc", "string", "text", "test", "ok"]
             while (i <= 10){
                array1.push(i)
                i++
             }
document.getElementById("p0").innerHTML = document.getElementById("p0").innerHTML + " | " + array1[Math.floor((Math.random() * array1.length))]
</code>```

basically, you just need to change the last variable from array to array1.

Title: Adding items to array with while loops

Body:
I'm trying to push 1 -> 10 into my "array1"  though I'm sure that it's not working.

array1 = ["123", "abc", "string", "text", "test", "ok"]
                 while (i <= 10){
                    array1.push(i)
                    i++
                 }
    document.getElementById("p0").innerHTML = document.getElementById("p0").innerHTML + " | " + array[Math.floor((Math.random() * array.length))]

p0's innerhtml stays as "Random Array Item:" and does not change, though when I remove the while loop it seems to work fine, example output, "Random Array Item: | test | text | abc | abc | text | abc"

Body:
Follow some adjustments:

var i = 0;
array1 = ["123", "abc", "string", "text", "test", "ok"]
             while (i <= 10){
                array1.push(i)
                i++
             }
document.getElementById("p0").innerHTML = document.getElementById("p0").innerHTML + " | " + array1[Math.floor((Math.random() * array1.length))]

basically, you just need to change the last variable from array to array1.


问:
ffmpeg Get time of frames from trimmed video
I am using FFmpeg in my application to extract frames from a video, the frames will be added to a trim video view where you get an illustration as to what is happening in the video at a specific time within the video. So each frame needs to represent some time within the video.

I dont quite understand how FFmpeg is producing the frames. Here is my code:

```<code>"-i",
videoCroppedFile.getAbsolutePath(),
"-vf",
"fps=1/" + frameSeperation,
mediaStorageDir.getAbsolutePath() +
"/%d.jpg"
</code>```

My app allows you to record a video at a max length of 20s. The number of frames extracted from the video depnds on how long the captured video is. frameSeperation is calculated doing the below code.

```<code>String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
    long videoLength = Long.parseLong(time) / 1000;
    double frameSeperationDouble = (double) videoLength;
    // Divide by 11 because there is a maximum of 11 frames on trim video view
    frameSeperationDouble /= 11;
    frameSeperationDouble = Math.ceil(frameSeperationDouble);
    int frameSeperation = (int) frameSeperationDouble;
</code>```

Maybe the above logic is very bad, if there is a better way please can somebody tell me.

Anyway I run the code and below are a few test cases:

A video captured with a length of 6 seconds has 7 frames.

A video captured with a length of 2 seconds has 3 frames.

A video captured with a length of 10 seconds has 12 frames.

A video captured with a length of 15 seconds has 9 frames.

A video captured with a length of 20 seconds has 11 frames.

There is no consistency, and I find it hard to put timestamps against each frame because of this. I feel like my logic is wrong or im not understanding. Any help is much appreciated

Update 1

So I did what you said in comments:

```<code> final FFmpeg ffmpeg = FFmpeg.getInstance(mContext);
        final File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
                + "/Android/data/"
                + mContext.getPackageName()
                + "/vFrames");

    if (!mediaStorageDir.exists()){
        mediaStorageDir.mkdirs();
    }

    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    retriever.setDataSource(mContext, Uri.fromFile(videoCroppedFile));
    String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
    long videoLength = Long.parseLong(time) / 1000;
    double frameSeperationDouble = (double) videoLength / 8;

    retriever.release();

    final String cmd[] = {

            "-i",
            videoCroppedFile.getAbsolutePath(),
            "-vf",
            "fps=1/" + frameSeperationDouble,
            "-vframes," + 8,
            mediaStorageDir.getAbsolutePath() +
            "/%d.jpg"
    };
</code>```

I also tried "-vframes=" + 8 at the same point where I put vFrames in cmd. It doesnt seem to work at all now no frames are being extracted from the video

答:
This is the effective flow for fps=x, with the default rounding method near,

Generate intervals of 1/x seconds, e,g. for x=1/3, intervals are 0-3s, 3-6s, 6-9s... Within each interval, pick an earlier frame whose timestamp is nearest to the midpoint of that interval. This may lead to duplicate frames, when that nearest frame belongs to an earlier interval, and was already picked for that interval. Likely to happen if source is variable frame-rate.

In your case, I would suggest to avoid rounding or stripping fractional values, if possible. Or do it at the end.

Body:
I am using FFmpeg in my application to extract frames from a video, the frames will be added to a trim video view where you get an illustration as to what is happening in the video at a specific time within the video. So each frame needs to represent some time within the video.

I dont quite understand how FFmpeg is producing the frames. Here is my code:

"-i",
videoCroppedFile.getAbsolutePath(),
"-vf",
"fps=1/" + frameSeperation,
mediaStorageDir.getAbsolutePath() +
"/%d.jpg"

My app allows you to record a video at a max length of 20s. The number of frames extracted from the video depnds on how long the captured video is. frameSeperation is calculated doing the below code.

String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
    long videoLength = Long.parseLong(time) / 1000;
    double frameSeperationDouble = (double) videoLength;
    // Divide by 11 because there is a maximum of 11 frames on trim video view
    frameSeperationDouble /= 11;
    frameSeperationDouble = Math.ceil(frameSeperationDouble);
    int frameSeperation = (int) frameSeperationDouble;

Maybe the above logic is very bad, if there is a better way please can somebody tell me.

Anyway I run the code and below are a few test cases:

A video captured with a length of 6 seconds has 7 frames.

A video captured with a length of 2 seconds has 3 frames.

A video captured with a length of 10 seconds has 12 frames.

A video captured with a length of 15 seconds has 9 frames.

A video captured with a length of 20 seconds has 11 frames.

There is no consistency, and I find it hard to put timestamps against each frame because of this. I feel like my logic is wrong or im not understanding. Any help is much appreciated

Update 1

So I did what you said in comments:

 final FFmpeg ffmpeg = FFmpeg.getInstance(mContext);
        final File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
                + "/Android/data/"
                + mContext.getPackageName()
                + "/vFrames");

    if (!mediaStorageDir.exists()){
        mediaStorageDir.mkdirs();
    }

    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    retriever.setDataSource(mContext, Uri.fromFile(videoCroppedFile));
    String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
    long videoLength = Long.parseLong(time) / 1000;
    double frameSeperationDouble = (double) videoLength / 8;

    retriever.release();

    final String cmd[] = {

            "-i",
            videoCroppedFile.getAbsolutePath(),
            "-vf",
            "fps=1/" + frameSeperationDouble,
            "-vframes," + 8,
            mediaStorageDir.getAbsolutePath() +
            "/%d.jpg"
    };

I also tried "-vframes=" + 8 at the same point where I put vFrames in cmd. It doesnt seem to work at all now no frames are being extracted from the video


问:
Moving from one activity to another - android
I have the following screen setup in android. A button on screen1 on clicking which you are taken to screen2. Screen2 has 2 buttons at the bottom of the screen. One button that displays a searchable listView and the other that takes you back to screen1. The code for screen1:

```<code>screen1.java

package com.example.screenchange;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class ScreenChange extends Activity {
    /** Called when the activity is first created. */

    private Button button01;

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

        button01 = (Button)findViewById(R.id.button01);
        button01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Log.v(this.toString(), "Inside on click listener for screen 2.");
                Intent intent = new Intent(v.getContext(), screen2.class);
                Log.v(this.toString(), "Intent created. Moving to start activity.");
                startActivity(intent);
            }
        });
    }
}
</code>```

screen1.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <Button
        android:id="@+id/button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Move to screen 2"
        />

</LinearLayout>
</code>```

Screen2.java:

```<code>package com.example.screenchange;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;

public class screen2 extends ListActivity {

    private Button button02;
    private Button button03;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen2);

        button02 = (Button)findViewById(R.id.button02);
        button02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Log.v(this.toString(), "Button02 clicked.");
                Intent intent = new Intent();   //takes control back to screen1.
                finish();
            }
        });

        button03 = (Button)findViewById(R.id.button03);
        button03.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Log.v(this.toString(), "Button03 clicked.");

                ArrayAdapter<String> listView = new ArrayAdapter<String>(v.getContext(), R.layout.listview, COUNTRIES);
                setListAdapter(listView);
                getListView().setTextFilterEnabled(true);

            }
        });
    }

    static final String[] COUNTRIES = new String[] {
        "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
        "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
        "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
        "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
        "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
        "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory",
        "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",
        "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
        "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
        "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
        "Cook Islands"
}
</code>```

screen2.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:text="Welcome to screen 2">

  <Button
    android:id="@+id/button02"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get back to screen 1."
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:clickable="true">
  </Button>

  <Button
    android:id="@+id/button03"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:text="Display countries."
    android:clickable="true">
  </Button>

  <ListView
    android:id="@+android:id/android:list"
    android:layout_height="fill_parent"
    android:layout_width="wrap_content"
    android:text="@id/text1">
  </ListView>

</RelativeLayout>
</code>```

listview.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<TextView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:id="@+id/text1">
</TextView>
</code>```

android-manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.screenchange"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ScreenChange"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".screen2"
            android:label="Screen 2 - New actvity.">
        </activity>
    </application>

</manifest>
</code>```

The problems I get are as follows:

1. The buttons on screen2 go unresponsive the moment I switch to screen2. No output on the logcat, no nothing.

2. There might even be errors in getting the listview to display, but I am not able to see any.

Any help is welcome,

Sriram.

答:
change your button2 code to this

```<code>button02.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Log.v(this.toString(), "Button02 clicked.");
            finish();
        }
    });
</code>```

there is no need of creating a new intent finish() will do the work

Body:
I have the following screen setup in android. A button on screen1 on clicking which you are taken to screen2. Screen2 has 2 buttons at the bottom of the screen. One button that displays a searchable listView and the other that takes you back to screen1. The code for screen1:

screen1.java

package com.example.screenchange;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class ScreenChange extends Activity {
    /** Called when the activity is first created. */

    private Button button01;

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

        button01 = (Button)findViewById(R.id.button01);
        button01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Log.v(this.toString(), "Inside on click listener for screen 2.");
                Intent intent = new Intent(v.getContext(), screen2.class);
                Log.v(this.toString(), "Intent created. Moving to start activity.");
                startActivity(intent);
            }
        });
    }
}

screen1.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <Button
        android:id="@+id/button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Move to screen 2"
        />

</LinearLayout>

Screen2.java:

package com.example.screenchange;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;

public class screen2 extends ListActivity {

    private Button button02;
    private Button button03;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen2);

        button02 = (Button)findViewById(R.id.button02);
        button02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Log.v(this.toString(), "Button02 clicked.");
                Intent intent = new Intent();   //takes control back to screen1.
                finish();
            }
        });

        button03 = (Button)findViewById(R.id.button03);
        button03.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Log.v(this.toString(), "Button03 clicked.");

                ArrayAdapter<String> listView = new ArrayAdapter<String>(v.getContext(), R.layout.listview, COUNTRIES);
                setListAdapter(listView);
                getListView().setTextFilterEnabled(true);

            }
        });
    }

    static final String[] COUNTRIES = new String[] {
        "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
        "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
        "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
        "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
        "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
        "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory",
        "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",
        "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
        "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
        "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
        "Cook Islands"
}

screen2.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:text="Welcome to screen 2">

  <Button
    android:id="@+id/button02"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get back to screen 1."
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:clickable="true">
  </Button>

  <Button
    android:id="@+id/button03"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:text="Display countries."
    android:clickable="true">
  </Button>

  <ListView
    android:id="@+android:id/android:list"
    android:layout_height="fill_parent"
    android:layout_width="wrap_content"
    android:text="@id/text1">
  </ListView>

</RelativeLayout>

listview.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:id="@+id/text1">
</TextView>

android-manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.screenchange"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ScreenChange"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".screen2"
            android:label="Screen 2 - New actvity.">
        </activity>
    </application>

</manifest>

The problems I get are as follows:

1. The buttons on screen2 go unresponsive the moment I switch to screen2. No output on the logcat, no nothing.

2. There might even be errors in getting the listview to display, but I am not able to see any.

Any help is welcome,

Sriram.

Body:
change your button2 code to this

button02.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Log.v(this.toString(), "Button02 clicked.");
            finish();
        }
    });

there is no need of creating a new intent finish() will do the work


问:
Calculate compounding factor
I have a set of data as follow and want to calculate the compounding factor for each of the items based on the Duration column.
The condition is that Duration is a multiple of 12, then I will apply a factor.
For example, item 2 has Duration starts from M34 to M37, I will apply a factor to M36.

However, the tricky part is I dont want to apply any factor if the first element in Duration vector for each item is a multiple of 12. For example, Item 1 starts from M24 to M27. Even though M24 is a multiple of 12, I dont want to apply any factor here.

This is my original dataset:

```<code>          ID               Rate.1    Duration
 1:       1                0.0200      M24
 2:       1                0.0200      M25
 3:       1                0.0200      M26
 4:       1                0.0200      M27
 5:       2                0.0200      M34
 6:       2                0.0200      M35
 7:       2                0.0200      M36
 8:       2                0.0200      M37
 9:       2                0.0200      M48
</code>```

What I want is Rate.2 col below:

```<code>          ID               Rate.1    Duration      Rate.2
 1:       1                0.0200      M24            1
 2:       1                0.0200      M25            1
 3:       1                0.0200      M26            1
 4:       1                0.0200      M27            1
 5:       2                0.0200      M34            1
 6:       2                0.0200      M35            1
 7:       2                0.0200      M36            1.2
 8:       2                0.0200      M37            1.2
 9:       2                0.0200      M48            1.44
</code>```

Is there a neat solution for this? Thanks

Title: Calculate compounding factor

Body:
I have a set of data as follow and want to calculate the compounding factor for each of the items based on the Duration column.
The condition is that Duration is a multiple of 12, then I will apply a factor.
For example, item 2 has Duration starts from M34 to M37, I will apply a factor to M36.

However, the tricky part is I dont want to apply any factor if the first element in Duration vector for each item is a multiple of 12. For example, Item 1 starts from M24 to M27. Even though M24 is a multiple of 12, I dont want to apply any factor here.

This is my original dataset:

          ID               Rate.1    Duration
 1:       1                0.0200      M24
 2:       1                0.0200      M25
 3:       1                0.0200      M26
 4:       1                0.0200      M27
 5:       2                0.0200      M34
 6:       2                0.0200      M35
 7:       2                0.0200      M36
 8:       2                0.0200      M37
 9:       2                0.0200      M48

What I want is Rate.2 col below:

          ID               Rate.1    Duration      Rate.2
 1:       1                0.0200      M24            1
 2:       1                0.0200      M25            1
 3:       1                0.0200      M26            1
 4:       1                0.0200      M27            1
 5:       2                0.0200      M34            1
 6:       2                0.0200      M35            1
 7:       2                0.0200      M36            1.2
 8:       2                0.0200      M37            1.2
 9:       2                0.0200      M48            1.44

Is there a neat solution for this? Thanks

Body:
It's not overly neat. Edited solution without loop:

df=data.frame("ID"=c(rep(1,4),rep(2,5)),
         "Rate.1"=rep(0.02,9),
         "Duration"=paste0("M",c(24:27,34:37,48))
  )

ids = which(as.numeric(sub("M","",df$Duration[-1]))%%12 == 0)+1
df$Rate.2 =  1
df$Rate.2[ids]=1.2
df$Rate.2=cumprod(df$Rate.2)

df
      ID Rate.1 Duration Rate.2
    1  1   0.02      M24   1.00
    2  1   0.02      M25   1.00
    3  1   0.02      M26   1.00
    4  1   0.02      M27   1.00
    5  2   0.02      M34   1.00
    6  2   0.02      M35   1.00
    7  2   0.02      M36   1.20
    8  2   0.02      M37   1.20
    9  2   0.02      M48   1.44

Previous solution with for loop:

df$Rate.2 =  1
    ids = which(as.numeric(sub("M","",df$Duration))%%12 == 0)
    for(i in 2:nrow(df)){
      if(i%in%ids){
        df$Rate.2[i:nrow(df)]=df$Rate.2[i:nrow(df)]*1.2
      }
    }


问:
I've been coding with notepad++ and now I'm getting into Eclipse IDE and I'm having trouble with my older projects
So,
I have been coding Java last semester (college) and we've always done it in Notepad++ , compile and execute by CMD (very simple programs though) and now I want to start codding in Eclipse, since I heard that it saves you a lot of time in syntax and gives you a heads up on typos and errors (Also I'm tired of compiling and executing by console). But the thing is that I usually have my code into two folders (model and interface) and use the

```<code>package modelo;
package interfaz;
</code>```

And now I execute eclipse and open these files, but it doesn't seem to work, I mean the code shows up and I can edit, but it wont show help or even let me execute the code. I know it must be a very noobie question but I can't seem to make it work.

Update:
This is what i get when i import my "project"
This is the error

答:
The project is not configured as Java project:

Create a Java project via File > Other...: Java > Java Project

Copy the content of the src folder into the src folder of the new project

In the new project, open the class that contains the main method and click the Run button

Body:
So,
I have been coding Java last semester (college) and we've always done it in Notepad++ , compile and execute by CMD (very simple programs though) and now I want to start codding in Eclipse, since I heard that it saves you a lot of time in syntax and gives you a heads up on typos and errors (Also I'm tired of compiling and executing by console). But the thing is that I usually have my code into two folders (model and interface) and use the

package modelo;
package interfaz;

And now I execute eclipse and open these files, but it doesn't seem to work, I mean the code shows up and I can edit, but it wont show help or even let me execute the code. I know it must be a very noobie question but I can't seem to make it work.

Update:
This is what i get when i import my "project"
This is the error


问:
How to Develop CXF webService deploy on Wildfly 10.0 server in Eclipse-maven project
Apache CXF library (cxf-api-3.2.0.jar) detected in ws endpoint deployment; either provide a proper deployment replacing embedded libraries with container module dependencies or disable the webservices subsystem for the current deployment adding a proper jboss-deployment-structure.xml</p>

答: Wildfly has it's own CXF integration therefore your deployment should not contain CXF libraries. If you want to use this, you'll have to disable Wildfly's CXF stuff as advised in the error message.</p>


问:
select specific element from List by using protractor
can any one suggest me how to select specific element from list by using below code</p>

 Select City   Customer Support </li> Feature Request    </li>Sales Enquiry  </li> Bug Report  </li> Payment Issue   </li>

答:
Please find a huge range of locator-possibilities on the official Protractortest API Page

Every element on a page needs to be uniquely identifiable... else the page wouldn't work, no matter which technology. Therefore with the help of any of the above provided locator-possibilities you'll always find the element you're looking for.

And there is never a need for XPath.

Body:
can any one suggest me how to select specific element from list by using below code

 Select City   Customer Support
 Feature Request
Sales Enquiry
 Bug Report
 Payment Issue


问:
Socket android client PC server
I have problem to connect my android client to my PC Server
here there are the codes

-->PC SERVER:

```<code>public class Server {

public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException
{

   ServerSocket server = new ServerSocket(4444);

   System.out.println("Waiting for clients to connect...");

   while (true)
   {
      Socket s = server.accept();
      InetAddress clientAddress = s.getInetAddress();
      System.out.println("Incoming connection from: " + clientAddress.getHostName() + "[" + clientAddress.getHostAddress() + "]");

      s.close();
   }
}
</code>```

}

--->ANDROID CLIENT:

```<code>public class Main extends Activity {

Button b;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b = (Button)findViewById(R.id.connect);
    b.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View arg0) {

            try {
                 Socket client = new Socket("10.0.2.2", 4444); //connect to server

                 client.close();   //closing the connection

                } catch (UnknownHostException e) {
                 e.printStackTrace();
                } catch (IOException e) {
                 e.printStackTrace();
            }

        }

    });

}
</code>```

When on my android device i click the button in my server program(PC) doesn't view device connect...why? i've tried to insert

```<code><uses-permission android:name="android.permission.INTERNET"></uses-permission>
</code>```

into my AndroidManifest but when i click on button program crash
Android device and PC are connected to same network(router DSL).

Help me please

答:
Your socket declaration should be as follow :</p>

```<code>Socket client = new Socket(10.0.2.2, 4444); //Quotes removed
</code>```

Title: Socket android client PC server

Body:
I have problem to connect my android client to my PC Server
here there are the codes

-->PC SERVER:

public class Server {

public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException
{

   ServerSocket server = new ServerSocket(4444);

   System.out.println("Waiting for clients to connect...");

   while (true)
   {
      Socket s = server.accept();
      InetAddress clientAddress = s.getInetAddress();
      System.out.println("Incoming connection from: " + clientAddress.getHostName() + "[" + clientAddress.getHostAddress() + "]");

      s.close();
   }
}

}

--->ANDROID CLIENT:

public class Main extends Activity {

Button b;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b = (Button)findViewById(R.id.connect);
    b.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View arg0) {

            try {
                 Socket client = new Socket("10.0.2.2", 4444); //connect to server

                 client.close();   //closing the connection

                } catch (UnknownHostException e) {
                 e.printStackTrace();
                } catch (IOException e) {
                 e.printStackTrace();
            }

        }

    });

}

When on my android device i click the button in my server program(PC) doesn't view device connect...why? i've tried to insert

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

into my AndroidManifest but when i click on button program crash
Android device and PC are connected to same network(router DSL).

Help me please

Body:
Your socket declaration should be as follow :

Socket client = new Socket(10.0.2.2, 4444); //Quotes removed


问:
elfutils compilation error implicit-function-declaration
I downloaded elfutils 0.170 and 0.169, but can't use gcc to compile either of them because of implicit-function-declaration. I can't find any place in elfutils makefile which specifies -Werror or -Werror=implicit-function-declaration.  Any idea to fix this compilation error?

https://sourceware.org/elfutils/ftp/0.170/
My steps

1: bzip2 -d elfutils-0.170.tar.bz2
2: tar -xvf elfutils-0.170.tar
3: ./configure

4: make

Then below errors show up.
elf_compress_gnu.c: In function 'elf_compress_gnu':
elf_compress_gnu.c:114:28: error: implicit declaration of function 'htobe64' [-Werror=implicit-function-declaration]
       uint64_t be64_size = htobe64 (orig_size);
                            ^
elf_compress_gnu.c:163:15: error: implicit declaration of function 'be64toh' [-Werror=implicit-function-declaration]
       gsize = be64toh (gsize);
               ^
cc1: all warnings being treated as errors

答:
elfutils incorrectly uses htobe64, which is not in any standard and only available in glibc and a subset of the BSDs.

Since you use GCC, you can use Ulf Hermann's patch to work around this issue:

Add replacement endian.h and byteswap.h to libgnu

It adds an implementation of htobe64 based on GCC built-in functions, so it is available when GCC is used as the compiler, independently of what the C library provides.


问:
jquery (this).parent.hasClass giving false positive while in animation
I use CSS animations and jQuery to open multiple flaps on a Calendar. That works great as long as the user waits for an animation to end and then clicks the next one. But the moment an opening animation is still running, and the user already starts the next, the script breaks and my class opend is removed from the .fenster div and window breaking the layout.

Does anybody see where my script is faulty?

$( document ).on("click" , '.flap' , function(){
    if ($(this).parent(".fenster").hasClass("opend")) {
     $(this).removeClass("flap_open" ).addClass("flap_close" );
  $(this).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {
      $(this).next().hide();
      $(this).removeClass("flap_close");
      $(this).parent(".fenster").removeClass("opend");
  });
 } else {
     $(this).addClass("flap_open" );
     $(this).parent(".fenster").addClass("opend");
     //$(this).removeClass("flap_close" );
     $(this).next().show();
 }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fenster {
 width: 30%;
 min-width: 130px;
 max-width: 300px;
 border: 1px solid rgba(212, 212, 212, 1);
 position: relative;
    left: 200px;
 z-index: 200;
 cursor: pointer;
}
.opend {
 perspective: 1500px;
 -webkit-perspective: 1500px;
 box-shadow: inset 0px 0px 5px #2e2d2e;
 cursor: auto;
 -webkit-backface-visibility: hidden;
}
.flap {
 width: 100%;
 height: 100%;
 z-index: 100;
  background-color: red;
}
.flap:before {
 content: "";
 display: block;
 padding-top: 75%;
}
.flap_open {
 transform-origin: 0 50%;
 -webkit-transform-origin: 0 50%;
 background-size: cover;
 width: 100%;
 height: 100%;
 z-index: 100;
 cursor: alias;
 animation: turn 4s forwards;
 -webkit-animation: turn 4s forwards;
 box-shadow:  5px 0px 5px 0px #2e2d2e;
}
.flap_close {
 transform-origin: 0 50%;
 -webkit-transform-origin: 0 50%;
 -webkit-animation: zumachen 4s forwards;
 animation: zumachen 4s forwards;
 opacity: 0.8;
 box-shadow:  5px 0px 5px 0px #2e2d2e;
 transform: rotateY(-100deg);
}
.button{
 position: absolute;
 bottom: 2%;
 left: 15%;
 width: 70%;
 height: 5vh;
 min-width: 80px;
 min-height: 28px;
 max-height: 20px;
 z-index: -1;
 text-align: center;
 display: table;
  background-color: grey;
}
@keyframes turn {
  to {
  transform: rotateY(-100deg);
  opacity: 0.8;
  box-shadow:  5px 0px 5px 0px #2e2d2e;
  visibility: visible;
  }
}
@-webkit-keyframes turn {
  to {
  -webkit-transform: rotateY(-100deg);
  -webkit-opacity: 0.8;
  box-shadow:  5px 0px 5px 0px #2e2d2e;
  visibility: visible;
  }
}
@keyframes zumachen {
  to {
  transform: rotateY(0deg);
  opacity: 1;
  box-shadow:  none;
  visibility: visible;
  }
}
@-webkit-keyframes zumachen {
  to {
  -webkit-transform: rotateY(0deg);
  -webkit-opacity: 1;
  box-shadow:  none;
  visibility: visible;
  }
}</code>```

Something

Something

```

答:
I think its because you tell program - "on click, if this has class opend, do some, time-taking, work and remove opend class" Because you remove class at the end program doesn't go to that point if clicked again earlier. Way around could be to use other indicator top check the state. For ex:

```<code>$( document ).on("click" , '.flap' , function(){
        if ($(this).parent(".fenster").hasClass("justEmptyClass")) {
            $(this).parent(".fenster").removeClass("justEmptyClass");
</code>```

Or use a variable - with false/rue to set and check state:

```<code>var open = true;
$( document ).on("click" , '.flap' , function(){
        if (open) {
            open = false;
</code>```

// and rest your code

Body:
I use CSS animations and jQuery to open multiple flaps on a Calendar. That works great as long as the user waits for an animation to end and then clicks the next one. But the moment an opening animation is still running, and the user already starts the next, the script breaks and my class opend is removed from the .fenster div and window breaking the layout.

Does anybody see where my script is faulty?

$( document ).on("click" , '.flap' , function(){
    if ($(this).parent(".fenster").hasClass("opend")) {
     $(this).removeClass("flap_open" ).addClass("flap_close" );
  $(this).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {
      $(this).next().hide();
      $(this).removeClass("flap_close");
      $(this).parent(".fenster").removeClass("opend");
  });
 } else {
     $(this).addClass("flap_open" );
     $(this).parent(".fenster").addClass("opend");
     //$(this).removeClass("flap_close" );
     $(this).next().show();
 }
});

.fenster {
 width: 30%;
 min-width: 130px;
 max-width: 300px;
 border: 1px solid rgba(212, 212, 212, 1);
 position: relative;
    left: 200px;
 z-index: 200;
 cursor: pointer;
}
.opend {
 perspective: 1500px;
 -webkit-perspective: 1500px;
 box-shadow: inset 0px 0px 5px #2e2d2e;
 cursor: auto;
 -webkit-backface-visibility: hidden;
}
.flap {
 width: 100%;
 height: 100%;
 z-index: 100;
  background-color: red;
}
.flap:before {
 content: "";
 display: block;
 padding-top: 75%;
}
.flap_open {
 transform-origin: 0 50%;
 -webkit-transform-origin: 0 50%;
 background-size: cover;
 width: 100%;
 height: 100%;
 z-index: 100;
 cursor: alias;
 animation: turn 4s forwards;
 -webkit-animation: turn 4s forwards;
 box-shadow:  5px 0px 5px 0px #2e2d2e;
}
.flap_close {
 transform-origin: 0 50%;
 -webkit-transform-origin: 0 50%;
 -webkit-animation: zumachen 4s forwards;
 animation: zumachen 4s forwards;
 opacity: 0.8;
 box-shadow:  5px 0px 5px 0px #2e2d2e;
 transform: rotateY(-100deg);
}
.button{
 position: absolute;
 bottom: 2%;
 left: 15%;
 width: 70%;
 height: 5vh;
 min-width: 80px;
 min-height: 28px;
 max-height: 20px;
 z-index: -1;
 text-align: center;
 display: table;
  background-color: grey;
}
@keyframes turn {
  to {
  transform: rotateY(-100deg);
  opacity: 0.8;
  box-shadow:  5px 0px 5px 0px #2e2d2e;
  visibility: visible;
  }
}
@-webkit-keyframes turn {
  to {
  -webkit-transform: rotateY(-100deg);
  -webkit-opacity: 0.8;
  box-shadow:  5px 0px 5px 0px #2e2d2e;
  visibility: visible;
  }
}
@keyframes zumachen {
  to {
  transform: rotateY(0deg);
  opacity: 1;
  box-shadow:  none;
  visibility: visible;
  }
}
@-webkit-keyframes zumachen {
  to {
  -webkit-transform: rotateY(0deg);
  -webkit-opacity: 1;
  box-shadow:  none;
  visibility: visible;
  }
}

Something

Something

Body:
I think its because you tell program - "on click, if this has class opend, do some, time-taking, work and remove opend class" Because you remove class at the end program doesn't go to that point if clicked again earlier. Way around could be to use other indicator top check the state. For ex:

$( document ).on("click" , '.flap' , function(){
        if ($(this).parent(".fenster").hasClass("justEmptyClass")) {
            $(this).parent(".fenster").removeClass("justEmptyClass");

Or use a variable - with false/rue to set and check state:

var open = true;
$( document ).on("click" , '.flap' , function(){
        if (open) {
            open = false;

// and rest your code


问:
What am I missing from my code to meet all the requirements of my program?
I have to design and implement a program that counts the number of integer values from user input. Produce a table listing the values you identify as integers from the input. Provide the sum and average of the numbers.This is what I have so far.</p>

```<code>public class Table {
public static void main(String [] strAng) {
    int sum = 0;
    double average;
    int min = 1;
    int max = 10;

    for(int number = min;
    number <= max; ++number) {
        sum += number;
    }

    System.out.print("Sum:" +sum);
    System.out.print("Average:" +average);
</code>```

答:
You have not get an input from user and also you do nothing to make average.

Try this code, and if you have other requirements, update the question.

```<code>    int sum = 0;
    double average;
    Scanner userInputScanner = new Scanner(System.in);

    System.out.println("Please enter the integers with space between each two integer: ");
    String inputNumberFilePath = userInputScanner.nextLine();

    String[] numStrArray = inputNumberFilePath.split(" ");

    for (String string : numStrArray) {
        sum += Integer.parseInt(string);
    }

    average = (double) sum / (double) numStrArray.length;
    System.out.println("Sum: " + sum);
    System.out.println("Average: " + average);
</code>```

output sample:

```<code>Please enter the integers with space between each two integer:
10 20 30 40 50
Sum: 150
Average: 30.0
</code>```

Body:
I have to design and implement a program that counts the number of integer values from user input. Produce a table listing the values you identify as integers from the input. Provide the sum and average of the numbers.This is what I have so far.

public class Table {
public static void main(String [] strAng) {
    int sum = 0;
    double average;
    int min = 1;
    int max = 10;

    for(int number = min;
    number <= max; ++number) {
        sum += number;
    }

    System.out.print("Sum:" +sum);
    System.out.print("Average:" +average);

Body:
You have not get an input from user and also you do nothing to make average.

Try this code, and if you have other requirements, update the question.

    int sum = 0;
    double average;
    Scanner userInputScanner = new Scanner(System.in);

    System.out.println("Please enter the integers with space between each two integer: ");
    String inputNumberFilePath = userInputScanner.nextLine();

    String[] numStrArray = inputNumberFilePath.split(" ");

    for (String string : numStrArray) {
        sum += Integer.parseInt(string);
    }

    average = (double) sum / (double) numStrArray.length;
    System.out.println("Sum: " + sum);
    System.out.println("Average: " + average);

output sample:

Please enter the integers with space between each two integer:
10 20 30 40 50
Sum: 150
Average: 30.0


问:
Context switch in Interrupt handlers
Why can't a context switch happen when an interrupt handler is executing ? More specifically, in the linux kernel, interrupt handlers run in the context of the process that was interrupted. Why is it not possible to do a context switch in the interrupt handler to schedule another process ?</p>

答:
A couple of reasons, I guess, depending on the meaning of your question:

Q: Why would context switching during an interrupt be bad?

A: Interrupts are generally for interacting with hardware. Hardware is typically time-sensitive so the OS can't just stop dealing with it in the middle of something and come back when it feels like it.

Q: What stops a context switch from happening during an interrupt?

A: An interrupt happens in a special interrupt context, not a regular process context. Since it's not in a process, it's not subject to context switching as a normal process would be.

There's probably a better, deeper explanation to be made, but that's the extent of my own understanding of the matter.

Title: Context switch in Interrupt handlers