问:
Gradle play plugin property testClassesDirs missing in gradle 3.1
I want to use Gradle 3.1 and Gradle play plugin. I have to add a task.

Can you help me to parse below snippet from version 4.0 to 3.1?
I can't find the analogous property testClassesDirs in Gradle 3.1

```<code>task doesNotWorkIn3_1(type: Test) {

    dependsOn { tasks.compilePlayBinaryTests }
    testClassesDirs = project.files { [tasks.compilePlayBinaryTests.destinationDir] }
    classpath = project.files { testPlayBinary.classpath }
    include '**/SwaggerControllerJsonTest.class'
    outputs.upToDateWhen { false }
}
</code>```

答:
Like you said, the problem is with testClassesDirs, it exists in Gradle 4.x but not in Gradle 3.1.

So please update

testClassesDirs = project.files { [tasks.compilePlayBinaryTests.destinationDir] }

to

```<code>testClassesDir = tasks.compilePlayBinaryTests.destinationDir
</code>```

Let me know if this works.

Body:
I want to use Gradle 3.1 and Gradle play plugin. I have to add a task.

Can you help me to parse below snippet from version 4.0 to 3.1?
I can't find the analogous property testClassesDirs in Gradle 3.1

task doesNotWorkIn3_1(type: Test) {

    dependsOn { tasks.compilePlayBinaryTests }
    testClassesDirs = project.files { [tasks.compilePlayBinaryTests.destinationDir] }
    classpath = project.files { testPlayBinary.classpath }
    include '**/SwaggerControllerJsonTest.class'
    outputs.upToDateWhen { false }
}

Body:
Like you said, the problem is with testClassesDirs, it exists in Gradle 4.x but not in Gradle 3.1.

So please update

testClassesDirs = project.files { [tasks.compilePlayBinaryTests.destinationDir] }

to

testClassesDir = tasks.compilePlayBinaryTests.destinationDir

Let me know if this works.


来源: stackexchange

问:
Change highlighting of results in the FitNesse wiki
Currently the output looks like

Is there a way to make the comparison all or nothing without making some custom style or comparator or some other plugin?

答:
You can change the styles in fitnesse_wiki.css. The output is formatted with the classes fail and diff. Here's a sample of the output (not yours):

```<code>[10-Oct-197<span class="diff">4</span>] <span class="fail">expected [10-Oct-197</span><span class="diff">5</span><span class="fail">]</span>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can change the styles in fitnesse_wiki.css. The output is formatted with the classes fail and diff. Here's a sample of the output (not yours):

[10-Oct-197<span class="diff">4</span>] <span class="fail">expected [10-Oct-197</span><span class="diff">5</span><span class="fail">]</span>


问:
Import-Csv, Sort Imported Data and Counting Total Variables after Sort
I am attempting to write a powershell script importing a large csv of data. I am trying to sort the objects column by date range and counting the objects in the column. I imported the data and assigned values however when I ask for the count of the total value in the columns it counts each individual object rather than the sum of the remaining. I believe this is because it's within the foreach cmdlet.

Any ideas? I am newer to powershell.

```<code>CSV format,
ID FirstName LastName Date
1   jOHN      SMITH    8/8/2016

$users=Import-Csv data.csv

foreach ($user in $users) {

$FileID=$user.ID
$FileFIRST_NAME=$user.FIRST_NAME
$FileLAST_NAME=$user.LAST_NAME
$FileDATE=$user.DA

write-host $FileFIRST_NAME.count

}
</code>```

答:
Within the foreach loop (note that this is the foreach statement, not the cmdlet), each $user is a single row from within $users (which is an array of rows).

So asking for the .Count of any property (column) of a single row, will return 1. The loop will run that N times where N is the number of rows you have, so you will see 1 many times.

You don't need the loop at all to get a count of the rows:

```<code>$users=Import-Csv data.csv
$users.Count
</code>```

Since columns are a property of rows in this scenario, a count of any column will be the same as the count of the number of rows, so there's no reason to do so.

Body:
I am attempting to write a powershell script importing a large csv of data. I am trying to sort the objects column by date range and counting the objects in the column. I imported the data and assigned values however when I ask for the count of the total value in the columns it counts each individual object rather than the sum of the remaining. I believe this is because it's within the foreach cmdlet.

Any ideas? I am newer to powershell.

CSV format,
ID FirstName LastName Date
1   jOHN      SMITH    8/8/2016

$users=Import-Csv data.csv

foreach ($user in $users) {

$FileID=$user.ID
$FileFIRST_NAME=$user.FIRST_NAME
$FileLAST_NAME=$user.LAST_NAME
$FileDATE=$user.DA

write-host $FileFIRST_NAME.count

}

Body:
Within the foreach loop (note that this is the foreach statement, not the cmdlet), each $user is a single row from within $users (which is an array of rows).

So asking for the .Count of any property (column) of a single row, will return 1. The loop will run that N times where N is the number of rows you have, so you will see 1 many times.

You don't need the loop at all to get a count of the rows:

$users=Import-Csv data.csv
$users.Count

Since columns are a property of rows in this scenario, a count of any column will be the same as the count of the number of rows, so there's no reason to do so.


问:
Force system QT libraries to use openssl libraries shipped with the application
My application = libssl.so (1.0.2f) + libcrypto.so (1.0.2f) + my_app_exe

On Debian 9, QT version is 5.7 and openssl is 1.0.2l

my_app_exe returns 1.0.2l for QSslSocket::sslLibraryVersionString(), which means its using system openssl version.

Can I force QT libraries to somehow use openssl shipped along with my application?

I've tried setting library path using QCoreApplication::addLibraryPath(const QString &path), but QT library still picks up system openssl version.

Constraints:

Can't recompile QT library thats present on the system

Can't ship QT library along with the application

Can't change RPATH on system QT libraries

my_app_exe already uses RPATH which points to the current directory where shipped openssl resides.

答:
On Debian 9 I was able to get the correct SSL and Crypto libraries to load if I preload (load them as the first thing in the main()) using QLibrary calls. This is exactly what QT libraries are doing loadOpenSsl()

```<code>    int main()
    {
        QLibrary libcrypto, libssl;
        libcrypto.setFileNameAndVersion(QLatin1String("crypto"), QLatin1String(SHLIB_VERSION_NUMBER));
        libssl.setFileNameAndVersion(QLatin1String("ssl"), QLatin1String(SHLIB_VERSION_NUMBER));

        ...<snipped>...
        return 0;
     }
</code>```

Remember, I also have RPATH set on the application

```<code>$ objdump -x my_app_exe | grep -i RPATH
  RPATH                $ORIGIN/lib
</code>```

crypto libraries are stored in ./my_app_exe/lib/lib{ssl,crypto}.so

BTW, setting LD_LIBRARY_PATH didn't work for me.

Body:
On Debian 9 I was able to get the correct SSL and Crypto libraries to load if I preload (load them as the first thing in the main()) using QLibrary calls. This is exactly what QT libraries are doing loadOpenSsl()

    int main()
    {
        QLibrary libcrypto, libssl;
        libcrypto.setFileNameAndVersion(QLatin1String("crypto"), QLatin1String(SHLIB_VERSION_NUMBER));
        libssl.setFileNameAndVersion(QLatin1String("ssl"), QLatin1String(SHLIB_VERSION_NUMBER));

        ...<snipped>...
        return 0;
     }

Remember, I also have RPATH set on the application

$ objdump -x my_app_exe | grep -i RPATH
  RPATH                $ORIGIN/lib

crypto libraries are stored in ./my_app_exe/lib/lib{ssl,crypto}.so

BTW, setting LD_LIBRARY_PATH didn't work for me.


问:
How to change an int to a double in this while loop, C
I'm working with this code to calculate the square and cube of an input, and I added a third option to calculate the value divided by 2, so I had to change the result from an int to a double, but I don't think I did it right. Here's what I have so far:

```<code>#include <stdio.h>
// Function prototypes int Square(int value); int Cube(int value);

int main ()
{
    /* variable definition: */
    int intValue, menuSelect,Results;
    double doubleValue, Resultsb;
    intValue = 1;
    doubleValue = intValue;
    // While a positive number
    while (intValue > 0)  {
        printf ("Enter a positive Integer\n: ");
        scanf("%d", &intValue);
        doubleValue=intValue;
        if (intValue > 0)  {
            printf ("Enter 1 to calculate Square, 2 to Calculate Cube, 3 to Shrink
                   value in half \n: ");
            scanf("%d", &menuSelect);
            if (menuSelect == 1)  {
                // Call the Square Function
                Results = Square(intValue);
                printf("Square of %d is %d\n",intValue,Results);
            }
            else if (menuSelect == 2)  {
                // Call the Cube function
                Results = Cube(intValue);
                printf("Cube of %d is %d\n",intValue,Results);
            }
            else if (menuSelect == 3) {
                Resultsb = Shrink(doubleValue);
                printf("%f shrunk in half is %f\n", doubleValue,Resultsb);
            }
            else
                printf("Invalid menu item, only 1, 2 or 3 is accepted\n");
        }
    }
    return 0;
}
/* function returning the Square of a number */
int Square(int value)
{
    return value*value;
}
/* function returning the Cube of a number */
int Cube(int value)
{     return value*value*value;
}
double Shrink(double value)
{   return value/2;
}
</code>```

If anyone can tell me what I'm doing wrong that would be amazing, thank you!

答:
As posted, your program does not compile because you omitted the protoptype for Shrink().

When it compiles the line Resultsb = Shrink(doubleValue);, the compiler infers that Shrink takes a double argument and returns an int (yes, it does that!).

When it later gets to the definition of Shrink(), the actual definition is incompatible with the previous inferred prototype.

You should move your functions before the main() function or at least provide proper prototypes for them.

In modern C (C99 and later), you must define all functions or provide prototypes for them before you call them.  The above behavior applies to old style C, which is still supported by many compilers out there.

Body:
I'm working with this code to calculate the square and cube of an input, and I added a third option to calculate the value divided by 2, so I had to change the result from an int to a double, but I don't think I did it right. Here's what I have so far:

#include <stdio.h>
// Function prototypes int Square(int value); int Cube(int value);

int main ()
{
    /* variable definition: */
    int intValue, menuSelect,Results;
    double doubleValue, Resultsb;
    intValue = 1;
    doubleValue = intValue;
    // While a positive number
    while (intValue > 0)  {
        printf ("Enter a positive Integer\n: ");
        scanf("%d", &intValue);
        doubleValue=intValue;
        if (intValue > 0)  {
            printf ("Enter 1 to calculate Square, 2 to Calculate Cube, 3 to Shrink
                   value in half \n: ");
            scanf("%d", &menuSelect);
            if (menuSelect == 1)  {
                // Call the Square Function
                Results = Square(intValue);
                printf("Square of %d is %d\n",intValue,Results);
            }
            else if (menuSelect == 2)  {
                // Call the Cube function
                Results = Cube(intValue);
                printf("Cube of %d is %d\n",intValue,Results);
            }
            else if (menuSelect == 3) {
                Resultsb = Shrink(doubleValue);
                printf("%f shrunk in half is %f\n", doubleValue,Resultsb);
            }
            else
                printf("Invalid menu item, only 1, 2 or 3 is accepted\n");
        }
    }
    return 0;
}
/* function returning the Square of a number */
int Square(int value)
{
    return value*value;
}
/* function returning the Cube of a number */
int Cube(int value)
{     return value*value*value;
}
double Shrink(double value)
{   return value/2;
}

If anyone can tell me what I'm doing wrong that would be amazing, thank you!


问:
Validation error with simple-schema
I'm trying to insert an array into an object and I'm not having any luck. I think the schema is rejecting it based on validation but I'm not sure why. If I console.log(this.state.typeOfWork) and check typeof it states its an Object which contains:

```<code>(2) ["Audit - internal", "Audit - external"]
0: "Audit - internal"
1: "Audit - external"
</code>```

My collection after an update contains:

```<code>"roleAndSkills": {
    "typeOfWork": []
  }
</code>```

Example: Schema

```<code>roleAndSkills: { type: Object, optional: true },
  'roleAndSkills.typeOfWork': { type: Array, optional: true },
  'roleAndSkills.typeOfWork.$': { type: String, optional: true }
</code>```

Example: update

```<code>ProfileCandidate.update(this.state.profileCandidateCollectionId, {
      $set: {
        roleAndSkills: {
          typeOfWork: [this.state.typeOfWork]
        }
      }
    });
</code>```

答:
You state that this.state.typeOfWork is an array (of strings) but then when you .update() your document you are enclosing it in square brackets:

```<code>ProfileCandidate.update(this.state.profileCandidateCollectionId, {
  $set: {
    roleAndSkills: {
      typeOfWork: [this.state.typeOfWork]
    }
  }
});
</code>```

Simply remove the redundant square brackets:

```<code>ProfileCandidate.update(this.state.profileCandidateCollectionId, {
  $set: {
    roleAndSkills: {
      typeOfWork: this.state.typeOfWork
    }
  }
});
</code>```

Also since your array is just an array of strings you can simplify your schema a bit by declaring it as such with [String] for the type:

```<code>'roleAndSkills.typeOfWork': { type: [String] }
</code>```

Note furthermore that objects and arrays are by default optional so you can even omit the optional flag.

Title: Validation error with simple-schema

Body:
I'm trying to insert an array into an object and I'm not having any luck. I think the schema is rejecting it based on validation but I'm not sure why. If I console.log(this.state.typeOfWork) and check typeof it states its an Object which contains:

(2) ["Audit - internal", "Audit - external"]
0: "Audit - internal"
1: "Audit - external"

My collection after an update contains:

"roleAndSkills": {
    "typeOfWork": []
  }

Example: Schema

roleAndSkills: { type: Object, optional: true },
  'roleAndSkills.typeOfWork': { type: Array, optional: true },
  'roleAndSkills.typeOfWork.$': { type: String, optional: true }

Example: update

ProfileCandidate.update(this.state.profileCandidateCollectionId, {
      $set: {
        roleAndSkills: {
          typeOfWork: [this.state.typeOfWork]
        }
      }
    });

Body:
You state that this.state.typeOfWork is an array (of strings) but then when you .update() your document you are enclosing it in square brackets:

ProfileCandidate.update(this.state.profileCandidateCollectionId, {
  $set: {
    roleAndSkills: {
      typeOfWork: [this.state.typeOfWork]
    }
  }
});

Simply remove the redundant square brackets:

ProfileCandidate.update(this.state.profileCandidateCollectionId, {
  $set: {
    roleAndSkills: {
      typeOfWork: this.state.typeOfWork
    }
  }
});

Also since your array is just an array of strings you can simplify your schema a bit by declaring it as such with [String] for the type:

'roleAndSkills.typeOfWork': { type: [String] }

Note furthermore that objects and arrays are by default optional so you can even omit the optional flag.


问:
start Android gps service
is there any way to turn on gps service through code?</p>

答:
No.

Turning on GPS is a user's choice. It would be unethical to force it.

ContentLicense: CC BY-SA 2.5

Title: start Android gps service


答:
You need a prototype for the function before you call it. Otherwise, the default return type is int. So put:

```<code>int Square(int value);
int Cube(int value);
double Shrink(double value);
</code>```

before main(), or move the function definitions to the top.

You also don't need the doubleValue variable. Passing intValue to the function will automatically convert it, based on the prototype.

Here's the working program.

```<code>#include <stdio.h>
// Function prototypes
int Square(int value);
int Cube(int value);
double Shrink(double value);

int main ()
{
    /* variable definition: */
    int intValue, menuSelect,Results;
    double Resultsb;
    intValue = 1;
    // While a positive number
    while (intValue > 0)  {
        printf ("Enter a positive Integer\n: ");
        scanf("%d", &intValue);
        if (intValue > 0)  {
            printf ("Enter 1 to calculate Square, 2 to Calculate Cube, 3 to Shrink value in half \n: ");
            scanf("%d", &menuSelect);

            if (menuSelect == 1)  {
                // Call the Square Function
                Results = Square(intValue);
                printf("Square of %d is %d\n",intValue,Results);
            }
            else if (menuSelect == 2)  {
                // Call the Cube function
                Results = Cube(intValue);
                printf("Cube of %d is %d\n",intValue,Results);
            }
            else if (menuSelect == 3) {
                Resultsb = Shrink(intValue);
                printf("%d shrunk in half is %f\n", intValue,Resultsb);
            }
            else
                printf("Invalid menu item, only 1, 2 or 3 is accepted\n");
        }
    }
    return 0;
}
/* function returning the Square of a number */
int Square(int value)
{
    return value*value;
}
/* function returning the Cube of a number */
int Cube(int value)
{     return value*value*value;
}
double Shrink(double value)
{   return value/2;
}
</code>```

Title: How to change an int to a double in this while loop, C

Body:
You need a prototype for the function before you call it. Otherwise, the default return type is int. So put:

int Square(int value);
int Cube(int value);
double Shrink(double value);

before main(), or move the function definitions to the top.

You also don't need the doubleValue variable. Passing intValue to the function will automatically convert it, based on the prototype.

Here's the working program.

#include <stdio.h>
// Function prototypes
int Square(int value);
int Cube(int value);
double Shrink(double value);

int main ()
{
    /* variable definition: */
    int intValue, menuSelect,Results;
    double Resultsb;
    intValue = 1;
    // While a positive number
    while (intValue > 0)  {
        printf ("Enter a positive Integer\n: ");
        scanf("%d", &intValue);
        if (intValue > 0)  {
            printf ("Enter 1 to calculate Square, 2 to Calculate Cube, 3 to Shrink value in half \n: ");
            scanf("%d", &menuSelect);

            if (menuSelect == 1)  {
                // Call the Square Function
                Results = Square(intValue);
                printf("Square of %d is %d\n",intValue,Results);
            }
            else if (menuSelect == 2)  {
                // Call the Cube function
                Results = Cube(intValue);
                printf("Cube of %d is %d\n",intValue,Results);
            }
            else if (menuSelect == 3) {
                Resultsb = Shrink(intValue);
                printf("%d shrunk in half is %f\n", intValue,Resultsb);
            }
            else
                printf("Invalid menu item, only 1, 2 or 3 is accepted\n");
        }
    }
    return 0;
}
/* function returning the Square of a number */
int Square(int value)
{
    return value*value;
}
/* function returning the Cube of a number */
int Cube(int value)
{     return value*value*value;
}
double Shrink(double value)
{   return value/2;
}


问:
Group objects sharing same key and cast them in another object
These are my classes:

```<code>class Schedule
{
    Int32 Id {get; set;}
    String CustomerName {get; set;}
    DateTime SchedStartDate {get; set;}
    DateTime SchedEndDate {get; set;}
    List<Body> Body {get; set;}
}

class Body
{
    Int32 Id {get; set;}
    String ProductBarcode {get; set;}
    Int32 ProductItemId {get; set;}
    DateTime DtEvaluation {get; set;}
    List<History> History {get; set;}
}

class History
{
    Int32 ActionId { get; set; }
    String Description { get; set; }
    String Picture { get; set; }
    String Observation { get; set; }
    Int32 EvalItemId { get; set; }
    Int32 EvalCriteriaId { get; set; }
}
</code>```

I have an Schedule object and the string Body.ProductBarcode is repeated on the Schedule.Body list. Also, sometimes the list Body.History is empty and sometimes it is not.

The Body.ProductBarcode repetition is correct from the application's point of view, but it is giving  me some trouble when I try to consolidate the data, as I want it to be cast the Schedule object in another class (that I find easier to work with):

```<code>class EmailSchedule
{
    String Id { get; set; }
    Int32 ProductId { get; set; }
    DateTime DtEvaluation { get; set; }
    List<EmailHistory> History { get; set; }
}
class EmailHistory
{
    Int32 ActionId { get; set; }
    String Description { get; set; }
    String Picture { get; set; }
    String Observation { get; set; }
    String EvalItemId { get; set; }
    Int32 EvalCriteriaId { get; set; }
}
</code>```

Keep in mind that, at this point, the only thing that interests me is the Body.ProductBarcode key and each of it's Body.History lists. Schedules's properties are already safe and sound and the other Body's properties are useless.

This is an example of a JSON that will be converted into the Schedule object

My problem is that, as there are repeated Body.ProductBarcode I need to group the occurrences where the Body.ProductBarcode match and, after that bring all the Body.History lists to the same EmailSchedule.History list.

I've tried to use LINQ, but as I'm not familiar with it, I wasn't able to make it work.

答:
I assume you don't care about any of the EmailSchedule properties since you said the other Body properties are useless besides History. You can copy the other History properties to EmailHistory in the same way I did here if you need all of them.

Here is the mixed query/method syntax:

```<code>var ans = from b in bodies
          group b by b.ProductBarcode into bg
          let bgf = bg.First()
          select new EmailSchedule {
              History = bg.SelectMany(b => b.History, (b, h) => new EmailHistory { ActionId = h.ActionId, Description = h.Description }).ToList()
          };
</code>```

and here is query syntax:

```<code>var ans = from b in bodies
          group b by b.ProductBarcode into bg
          let bgf = bg.First()
           select new EmailSchedule {
               History = (from b in bg from h in b.History select new EmailHistory { ActionId = h.ActionId, Description = h.Description }).ToList()
          };
</code>```

Body:
These are my classes:

class Schedule
{
    Int32 Id {get; set;}
    String CustomerName {get; set;}
    DateTime SchedStartDate {get; set;}
    DateTime SchedEndDate {get; set;}
    List Body {get; set;}
}

class Body
{
    Int32 Id {get; set;}
    String ProductBarcode {get; set;}
    Int32 ProductItemId {get; set;}
    DateTime DtEvaluation {get; set;}
    List<History> History {get; set;}
}

class History
{
    Int32 ActionId { get; set; }
    String Description { get; set; }
    String Picture { get; set; }
    String Observation { get; set; }
    Int32 EvalItemId { get; set; }
    Int32 EvalCriteriaId { get; set; }
}

I have an Schedule object and the string Body.ProductBarcode is repeated on the Schedule.Body list. Also, sometimes the list Body.History is empty and sometimes it is not.

The Body.ProductBarcode repetition is correct from the application's point of view, but it is giving  me some trouble when I try to consolidate the data, as I want it to be cast the Schedule object in another class (that I find easier to work with):

class EmailSchedule
{
    String Id { get; set; }
    Int32 ProductId { get; set; }
    DateTime DtEvaluation { get; set; }
    List<EmailHistory> History { get; set; }
}
class EmailHistory
{
    Int32 ActionId { get; set; }
    String Description { get; set; }
    String Picture { get; set; }
    String Observation { get; set; }
    String EvalItemId { get; set; }
    Int32 EvalCriteriaId { get; set; }
}

Keep in mind that, at this point, the only thing that interests me is the Body.ProductBarcode key and each of it's Body.History lists. Schedules's properties are already safe and sound and the other Body's properties are useless.

This is an example of a JSON that will be converted into the Schedule object

My problem is that, as there are repeated Body.ProductBarcode I need to group the occurrences where the Body.ProductBarcode match and, after that bring all the Body.History lists to the same EmailSchedule.History list.

I've tried to use LINQ, but as I'm not familiar with it, I wasn't able to make it work.

Body:
I assume you don't care about any of the EmailSchedule properties since you said the other Body properties are useless besides History. You can copy the other History properties to EmailHistory in the same way I did here if you need all of them.

Here is the mixed query/method syntax:

var ans = from b in bodies
          group b by b.ProductBarcode into bg
          let bgf = bg.First()
          select new EmailSchedule {
              History = bg.SelectMany(b => b.History, (b, h) => new EmailHistory { ActionId = h.ActionId, Description = h.Description }).ToList()
          };

and here is query syntax:

var ans = from b in bodies
          group b by b.ProductBarcode into bg
          let bgf = bg.First()
           select new EmailSchedule {
               History = (from b in bg from h in b.History select new EmailHistory { ActionId = h.ActionId, Description = h.Description }).ToList()
          };


问:
Ansible custom nested looping
I have to process output from CloudFormation Outputs that is:

Ansible code that produces this output:

```<code>- debug:
  var: stack.stack_outputs
</code>```

Output:

```<code>ok: [localhost] => {
  "stack.stack_outputs": {
    "Roles": "webserver balancer dbserver",
    "dbserver": "54.0.1.1 54.0.1.2",
    "balancer": "54.0.2.3",
    "webserver": "54.0.2.5 54.0.2.7 54.0.3.1"
}}
</code>```

With that, I want to create 3 (dynamic number!) groups named accordingly filled with appropriate IPs.

Ansible code that I want to HELP WITH:

```<code>- name: fill roles with proper hosts
  local_action: add_host hostname={{item}} groupname={{role}}
  with_whatever: ?...?
</code>```

In pseudo ansible python it would look like this:

```<code>for role in stack.stack_outputs.Roles.split():                           # Python
  for ip in stack.stack_outputs[role].split():                           # Python
    local_action: add_host hostname={{ip}} groupname={{role}}            # Ansible
</code>```

Note:

The way to do it for these three roles statically is obviously:

```<code>- name: fill role WEBSERVER
  local_action: add_host hostname={{item}} groupname=webserver
  with_items: stack.stack_outputs.webserver.split()
- name: fill role DBSERVER
  local_action: add_host hostname={{item}} groupname=dbserver
  with_items: stack.stack_outputs.dbserver.split()
- name: fill role BALANCER
  local_action: add_host hostname={{item}} groupname=balancer
  with_items: stack.stack_outputs.balancer.split()
</code>```

I want to do it dynamically, is it even possible in Ansible?

Yes, I can use shell module to hack it putting everything in temporary file and then looping over that; but is there a better solution?

Thanks for any suggestions.

答:
For anyone that comes asking without reading the documentation first. Ansible has been updated to support nested indexing:

http://docs.ansible.com/ansible/playbooks_loops.html#nested-loops

Cheers!

Title: Ansible custom nested looping

Body:
I have to process output from CloudFormation Outputs that is:

Ansible code that produces this output:

- debug:
  var: stack.stack_outputs

Output:

ok: [localhost] => {
  "stack.stack_outputs": {
    "Roles": "webserver balancer dbserver",
    "dbserver": "54.0.1.1 54.0.1.2",
    "balancer": "54.0.2.3",
    "webserver": "54.0.2.5 54.0.2.7 54.0.3.1"
}}

With that, I want to create 3 (dynamic number!) groups named accordingly filled with appropriate IPs.

Ansible code that I want to HELP WITH:

- name: fill roles with proper hosts
  local_action: add_host hostname={{item}} groupname={{role}}
  with_whatever: ?...?

In pseudo ansible python it would look like this:

for role in stack.stack_outputs.Roles.split():                           # Python
  for ip in stack.stack_outputs[role].split():                           # Python
    local_action: add_host hostname={{ip}} groupname={{role}}            # Ansible

Note:

The way to do it for these three roles statically is obviously:

- name: fill role WEBSERVER
  local_action: add_host hostname={{item}} groupname=webserver
  with_items: stack.stack_outputs.webserver.split()
- name: fill role DBSERVER
  local_action: add_host hostname={{item}} groupname=dbserver
  with_items: stack.stack_outputs.dbserver.split()
- name: fill role BALANCER
  local_action: add_host hostname={{item}} groupname=balancer
  with_items: stack.stack_outputs.balancer.split()

I want to do it dynamically, is it even possible in Ansible?

Yes, I can use shell module to hack it putting everything in temporary file and then looping over that; but is there a better solution?

Thanks for any suggestions.


问:
OnClickListener isn't working for ImageView
I'm pretty sure everything is right but the log isn't showing up in the console area of Eclipse when I click any of the images.

Ultimately, I want to have a popup menu appear when these images are clicked but right now I'm just trying to get the onclick events working correctly and then I'll add those in later.

My code:

Java

```<code>public class SecondScreen extends HelloAndroid {
    public void onCreate(Bundle savedInstanceState) {

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

           super.onCreate(savedInstanceState);
           setContentView(R.layout.main2);

           // initialize header
           ImageView header = (ImageView) findViewById(R.id.header_image);
           header.setOnClickListener(headerClick);

           // Make sure vitals and details are same size
           LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
           params.weight = 0.5f;

           // initialize vitals image
           ImageView vitals = (ImageView) findViewById(R.id.vitalsigns_image);
           vitals.setLayoutParams(params);
           vitals.setOnClickListener(vitalsClick);

           // initialize details image
           ImageView details = (ImageView) findViewById(R.id.details_image);
           details.setLayoutParams(params);
           details.setOnClickListener(detailsClick);

       }

        private OnClickListener headerClick = new OnClickListener() {

            public void onClick(View view) {
                Log.d("Clicked", "Header Clicked!");

            }
       };

        private OnClickListener vitalsClick = new OnClickListener() {

             public void onClick(View view) {
                Log.d("Clicked", "Vitals Clicked!");

             }
        };

        private OnClickListener detailsClick = new OnClickListener() {

             public void onClick(View view) {
                Log.d("Clicked", "Details Click!");

             }
        };
}
</code>```

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">

    <!-- HEADER -->

    <ImageView
       android:id="@+id/header_image"
       android:src="@drawable/header"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentTop="true"
    />

<!-- FOOTER -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#000000"
    android:layout_alignParentBottom="true">
    >

    <ImageView
        android:id="@+id/vitalsigns_image"
        android:src="@drawable/vitalsigns"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_alignParentBottom="true"
    />

    <ImageView
        android:id="@+id/details_image"
        android:src="@drawable/details"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_alignParentBottom="true"
    />

</LinearLayout>
</code>```

What am I doing wrong?

答:
I had this issue and fixed in by adding android:layout_width="44dp" to make sure user would have enough area to click on. Then, you can align image content the way you wannt. In my case:

```<code>    <ImageView
    android:id="@+id/locationImageView"
    android:layout_width="44dp"
    android:layout_height="16dp"
    android:layout_centerVertical="true"
    android:layout_marginStart="4dp"
    android:layout_toEndOf="@id/locationText"
    android:adjustViewBounds="true"
    android:scaleType="fitStart"
    android:src="@drawable/icn_edit_small_white"/>
</code>```

Body:
I'm pretty sure everything is right but the log isn't showing up in the console area of Eclipse when I click any of the images.

Ultimately, I want to have a popup menu appear when these images are clicked but right now I'm just trying to get the onclick events working correctly and then I'll add those in later.

My code:

Java

public class SecondScreen extends HelloAndroid {
    public void onCreate(Bundle savedInstanceState) {

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

           super.onCreate(savedInstanceState);
           setContentView(R.layout.main2);

           // initialize header
           ImageView header = (ImageView) findViewById(R.id.header_image);
           header.setOnClickListener(headerClick);

           // Make sure vitals and details are same size
           LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
           params.weight = 0.5f;

           // initialize vitals image
           ImageView vitals = (ImageView) findViewById(R.id.vitalsigns_image);
           vitals.setLayoutParams(params);
           vitals.setOnClickListener(vitalsClick);

           // initialize details image
           ImageView details = (ImageView) findViewById(R.id.details_image);
           details.setLayoutParams(params);
           details.setOnClickListener(detailsClick);

       }

        private OnClickListener headerClick = new OnClickListener() {

            public void onClick(View view) {
                Log.d("Clicked", "Header Clicked!");

            }
       };

        private OnClickListener vitalsClick = new OnClickListener() {

             public void onClick(View view) {
                Log.d("Clicked", "Vitals Clicked!");

             }
        };

        private OnClickListener detailsClick = new OnClickListener() {

             public void onClick(View view) {
                Log.d("Clicked", "Details Click!");

             }
        };
}

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">

    <ImageView
       android:id="@+id/header_image"
       android:src="@drawable/header"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentTop="true"
    />

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#000000"
    android:layout_alignParentBottom="true">
    >

    <ImageView
        android:id="@+id/vitalsigns_image"
        android:src="@drawable/vitalsigns"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_alignParentBottom="true"
    />

    <ImageView
        android:id="@+id/details_image"
        android:src="@drawable/details"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_alignParentBottom="true"
    />

</LinearLayout>

What am I doing wrong?

Body:
I had this issue and fixed in by adding android:layout_width="44dp" to make sure user would have enough area to click on. Then, you can align image content the way you wannt. In my case:

    <ImageView
    android:id="@+id/locationImageView"
    android:layout_width="44dp"
    android:layout_height="16dp"
    android:layout_centerVertical="true"
    android:layout_marginStart="4dp"
    android:layout_toEndOf="@id/locationText"
    android:adjustViewBounds="true"
    android:scaleType="fitStart"
    android:src="@drawable/icn_edit_small_white"/>


问:
Blackberry eclipse debugger not reflecting code changes
I've been struggling with this for the past day. I seem to be stuck with a weird bug in Eclipse where it decides to step through and exec sections that I've entirely deleted or commented. It also chooses to ignore all the instructions that I've actually added today. I've tried removing all breakpoints, clearing my bin directory, resetting my emulator, but nothing works.

Any help is much appreciated!

Thanks,

Teja.

答: try to clean your emulator if you haven't done this yet. Go to emulator folder and use clean.bat to clean the emulator this will remove all applications you installed on emulator. </p>


问:
swift/scenekit problems getting touch events from SCNScene and overlaySKScene
Good afternoon, I'm trying to figure out how to get touch notifications from an SCNNode & a SKSpriteNode from an SCNScene overlayed with a SKScene.

```<code>import UIKit
import SceneKit
class GameViewController: UIViewController {
var scnView:SCNView!
var scnScene:SCNScene!
var sprite: spritekitHUD!
var cameraNode: SCNNode!
var shape: SCNNode!

override func viewDidLoad() {
    super.viewDidLoad()
    setupScene()
     }

func setupScene() {
    scnView = self.view as! SCNView
    scnView.delegate = self
    scnView.allowsCameraControl = true
    scnScene = SCNScene(named: "art.scnassets/scene.scn")
    scnView.scene = scnScene
    sprite=spritekitHUD(size: self.view.bounds.size, game: self)
    scnView.overlaySKScene=sprite
    cameraNode = scnScene.rootNode.childNode(withName: "camera",
                                              recursively: true)!
    shape=scnScene.rootNode.childNode(withName: "shape", recursively: true)
    shape.name="ThreeDShape"
    }

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
 let touch = touches.first!
 let location = touch.location(in: scnView)
 let hitResults = scnView.hitTest(location, options: nil)
 if let result = hitResults.first {
      handleTouchFor(node: result.node)
     }
  }

func handleTouchFor(node: SCNNode) {
  if node.name == "ThreeDShape" {
         print("SCNNode Touched")
    }
  }
}
</code>```

This is my Spritekit overlay scene

```<code>import Foundation
import SpriteKit

class spritekitHUD: SKScene{

var game:GameViewController!
var shapeNode: SKSpriteNode!

init(size: CGSize, game: GameViewController){
    super.init(size: size)
    self.backgroundColor = UIColor.white

    let spriteSize = size.width/12
    self.shapeNode= SKSpriteNode(imageNamed: "shapeNode")
    self.shapeNode.size = CGSize(width: spriteSize, height: spriteSize)
    self.shapeNode.position = CGPoint(x: spriteSize + 8, y: spriteSize + 8)
    self.shapeNode.name="test"
    self.game=game

    self.addChild(self.pauseNode)

}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let touch=touches.first else{
        return
    }
    let location=touch.location(in: self)
    if self.atPoint(location).name=="test" {
     print("Spritekit node pressed")
    }
 }
}
</code>```

so with this I can successfully get notifications that my spritenode has been touched on my overlaySKScene but I cant figure out how to get a notification that my SCNode has been touched. If you cant have 2 touchesbegan functions does anyone have any ideas how I can handle the 3d events with 2d events at the same time?

Thanks for your help!!

答:
If you want to use an SKScene overlay of an SCNView for user controls, (eg you want to implement a button in the SKScene overlay that "consumes" the touch), but also have touches that don't hit the controls to pass through and register in the underlying SCNView, you have to do this: set isUserInteractionEnabled to false on the SKScene overlay itself, but then to true on any individual elements within that overlay that you'd like to act as buttons.

```<code>let overlay = SKScene(fileNamed: "overlay")
overlay?.isUserInteractionEnabled = false
let pauseButton = overlay?.childNode(withName: "pauseButton") as? Button
// Button is a subclass of SKSpriteNode that overrides touchesEnded
pauseButton?.isUserInteractionEnabled = true
sceneView.overlaySKScene = overlay
</code>```

If the user touches a button, the button's touch events (touchesBegan, touchesEnded etc) will fire and consume the touch (underlying gesture recognizers will still fire though). If they touch outside of a button however, the touch will pass through to the underlying SCNView.

Body:
Good afternoon, I'm trying to figure out how to get touch notifications from an SCNNode & a SKSpriteNode from an SCNScene overlayed with a SKScene.

import UIKit
import SceneKit
class GameViewController: UIViewController {
var scnView:SCNView!
var scnScene:SCNScene!
var sprite: spritekitHUD!
var cameraNode: SCNNode!
var shape: SCNNode!

override func viewDidLoad() {
    super.viewDidLoad()
    setupScene()
     }

func setupScene() {
    scnView = self.view as! SCNView
    scnView.delegate = self
    scnView.allowsCameraControl = true
    scnScene = SCNScene(named: "art.scnassets/scene.scn")
    scnView.scene = scnScene
    sprite=spritekitHUD(size: self.view.bounds.size, game: self)
    scnView.overlaySKScene=sprite
    cameraNode = scnScene.rootNode.childNode(withName: "camera",
                                              recursively: true)!
    shape=scnScene.rootNode.childNode(withName: "shape", recursively: true)
    shape.name="ThreeDShape"
    }

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
 let touch = touches.first!
 let location = touch.location(in: scnView)
 let hitResults = scnView.hitTest(location, options: nil)
 if let result = hitResults.first {
      handleTouchFor(node: result.node)
     }
  }

func handleTouchFor(node: SCNNode) {
  if node.name == "ThreeDShape" {
         print("SCNNode Touched")
    }
  }
}

This is my Spritekit overlay scene

import Foundation
import SpriteKit

class spritekitHUD: SKScene{

var game:GameViewController!
var shapeNode: SKSpriteNode!

init(size: CGSize, game: GameViewController){
    super.init(size: size)
    self.backgroundColor = UIColor.white

    let spriteSize = size.width/12
    self.shapeNode= SKSpriteNode(imageNamed: "shapeNode")
    self.shapeNode.size = CGSize(width: spriteSize, height: spriteSize)
    self.shapeNode.position = CGPoint(x: spriteSize + 8, y: spriteSize + 8)
    self.shapeNode.name="test"
    self.game=game

    self.addChild(self.pauseNode)

}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let touch=touches.first else{
        return
    }
    let location=touch.location(in: self)
    if self.atPoint(location).name=="test" {
     print("Spritekit node pressed")
    }
 }
}

so with this I can successfully get notifications that my spritenode has been touched on my overlaySKScene but I cant figure out how to get a notification that my SCNode has been touched. If you cant have 2 touchesbegan functions does anyone have any ideas how I can handle the 3d events with 2d events at the same time?

Thanks for your help!!

Body:
If you want to use an SKScene overlay of an SCNView for user controls, (eg you want to implement a button in the SKScene overlay that "consumes" the touch), but also have touches that don't hit the controls to pass through and register in the underlying SCNView, you have to do this: set isUserInteractionEnabled to false on the SKScene overlay itself, but then to true on any individual elements within that overlay that you'd like to act as buttons.

let overlay = SKScene(fileNamed: "overlay")
overlay?.isUserInteractionEnabled = false
let pauseButton = overlay?.childNode(withName: "pauseButton") as? Button
// Button is a subclass of SKSpriteNode that overrides touchesEnded
pauseButton?.isUserInteractionEnabled = true
sceneView.overlaySKScene = overlay

If the user touches a button, the button's touch events (touchesBegan, touchesEnded etc) will fire and consume the touch (underlying gesture recognizers will still fire though). If they touch outside of a button however, the touch will pass through to the underlying SCNView.


问:
change() jQuery not working
I'm having some trouble getting my change() event working in jQuery. I am making a small program that converts temperatures to Kelvin, and I want the span that holds my value after conversion to update 1) every time the temperature to convert changes and 2) every time a different temperature scale is selected from the radio buttons.

Relevant Code:

$(document).ready(function() {
  $('input[type=radio]').checkboxradio();
  var temp = parseFloat()
  $('input.listener').change(function() {
    var name = $(this).attr("name");
    var val = $(this).val();

    switch (name) {
      case 'unit':
        var temperature = $('input#temp').val();
        switch (val) {
          case 'f':
            $('span#output').html(((temperature - 32) / 1.8) + 273.15);
            break;
          case 'c':
            $('span#output').html(temperature + 273.15);
            break;
          case 'r':
            $('span#output').html(temperature / 1.8);
            break;
        }
      case 'temp':
        var u = $('input[name=unit]:checked').val();
        switch (u) {
          case 'f':
            $('span#output').html(((val - 32) / 1.8) + 273.15);
            break;
          case 'c':
            $('span#output').html(val + 273.15);
            break;
          case 'r':
            $('span#output').html(val / 1.8);
            break;
        }
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget">
  <fieldset>
    <legend>Select a Unit to Convert to Kelvin: </legend>
    <label for="fRadio">Fahrenheit</label>
    <input id="fRadio" class="listener" type="radio" name="unit" value="f">
    <label for="cRadio">Celsius</label>
    <input id="cRadio" class="listener" type="radio" name="unit" value="c">
    <label for="rRadio">Rankine</label>
    <input id="rRadio" class="listener" type="radio" name="unit" value="r">
  </fieldset>
</div>
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert the value to Kelvin:</p>

<p>
  <label>Temperature</label>
  <input id="temp" class="listener" type="number" value="32">
</p>
<p>Kelvin: <span id="output"></span></p></code>```

My guess is I'm making a pretty dumb small mistake, but I can't seem to figure it out. Thanks for any and all help, suggestions, and solutions.

答:
Two mistakes with your code:

Forgetting breaks; for the parent switch statement.

Forgetting name="temp" on the temperature field.

I changed the final temperature to a variable and made that the text of the output just so that there would be so many $('span#output').html(temperature);

Also, you should use the oninput event to detect a change for the number field.

$(document).ready(function() {
  //$('input[type=radio]').checkboxradio();
  var temp = parseFloat();
  $('input.listener').on('change', updateTemp);
  $('input.listener').on('input', updateTemp);

  function updateTemp() {
    var name = $(this).attr("name");
    var val = $(this).val();
    var final;

    switch (name) {
      case 'unit':
        var temperature = $('input#temp').val();
        switch (val) {
          case 'f':
            final = ((temperature - 32) / 1.8) + 273.15;
            break;
          case 'c':
            final = temperature + 273.15;
            break;
          case 'r':
            final = temperature / 1.8;
            break;
        }
      break;
      case 'temp':
        var u = $('input[name=unit]:checked').val();
        switch (u) {
          case 'f':
            final = ((val - 32) / 1.8) + 273.15;
            break;
          case 'c':
            final = val + 273.15;
            break;
          case 'r':
            final = val / 1.8;
            break;
        }
      break;
    }
    $("#output").text(final);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget">
  <fieldset>
    <legend>Select a Unit to Convert to Kelvin: </legend>
    <label for="fRadio">Fahrenheit</label>
    <input id="fRadio" class="listener" type="radio" name="unit" value="f">
    <label for="cRadio">Celsius</label>
    <input id="cRadio" class="listener" type="radio" name="unit" value="c">
    <label for="rRadio">Rankine</label>
    <input id="rRadio" class="listener" type="radio" name="unit" value="r">
  </fieldset>
</div>
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert the value to Kelvin:</p>

<p>
  <label>Temperature</label>
  <input id="temp" class="listener" type="number" name="temp" value="32">
</p>
<p>Kelvin: <span id="output"></span></p></code>```

Title: change() jQuery not working

Body:
I'm having some trouble getting my change() event working in jQuery. I am making a small program that converts temperatures to Kelvin, and I want the span that holds my value after conversion to update 1) every time the temperature to convert changes and 2) every time a different temperature scale is selected from the radio buttons.

Relevant Code:

$(document).ready(function() {
  $('input[type=radio]').checkboxradio();
  var temp = parseFloat()
  $('input.listener').change(function() {
    var name = $(this).attr("name");
    var val = $(this).val();

    switch (name) {
      case 'unit':
        var temperature = $('input#temp').val();
        switch (val) {
          case 'f':
            $('span#output').html(((temperature - 32) / 1.8) + 273.15);
            break;
          case 'c':
            $('span#output').html(temperature + 273.15);
            break;
          case 'r':
            $('span#output').html(temperature / 1.8);
            break;
        }
      case 'temp':
        var u = $('input[name=unit]:checked').val();
        switch (u) {
          case 'f':
            $('span#output').html(((val - 32) / 1.8) + 273.15);
            break;
          case 'c':
            $('span#output').html(val + 273.15);
            break;
          case 'r':
            $('span#output').html(val / 1.8);
            break;
        }
    }
  });
});

  <fieldset>
    <legend>Select a Unit to Convert to Kelvin: </legend>
    Fahrenheit
    <input id="fRadio" class="listener" type="radio" name="unit" value="f">
    Celsius
    <input id="cRadio" class="listener" type="radio" name="unit" value="c">
    Rankine
    <input id="rRadio" class="listener" type="radio" name="unit" value="r">
  </fieldset>

Temperature Converter

Type a value in the Fahrenheit field to convert the value to Kelvin:

  Temperature
  <input id="temp" class="listener" type="number" value="32">

Kelvin:

My guess is I'm making a pretty dumb small mistake, but I can't seem to figure it out. Thanks for any and all help, suggestions, and solutions.

Body:
Two mistakes with your code:

Forgetting breaks; for the parent switch statement.

Forgetting name="temp" on the temperature field.

I changed the final temperature to a variable and made that the text of the output just so that there would be so many $('span#output').html(temperature);

Also, you should use the oninput event to detect a change for the number field.

$(document).ready(function() {
  //$('input[type=radio]').checkboxradio();
  var temp = parseFloat();
  $('input.listener').on('change', updateTemp);
  $('input.listener').on('input', updateTemp);

  function updateTemp() {
    var name = $(this).attr("name");
    var val = $(this).val();
    var final;

    switch (name) {
      case 'unit':
        var temperature = $('input#temp').val();
        switch (val) {
          case 'f':
            final = ((temperature - 32) / 1.8) + 273.15;
            break;
          case 'c':
            final = temperature + 273.15;
            break;
          case 'r':
            final = temperature / 1.8;
            break;
        }
      break;
      case 'temp':
        var u = $('input[name=unit]:checked').val();
        switch (u) {
          case 'f':
            final = ((val - 32) / 1.8) + 273.15;
            break;
          case 'c':
            final = val + 273.15;
            break;
          case 'r':
            final = val / 1.8;
            break;
        }
      break;
    }
    $("#output").text(final);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget">
  <fieldset>
    <legend>Select a Unit to Convert to Kelvin: </legend>
    <label for="fRadio">Fahrenheit</label>
    <input id="fRadio" class="listener" type="radio" name="unit" value="f">
    <label for="cRadio">Celsius</label>
    <input id="cRadio" class="listener" type="radio" name="unit" value="c">
    <label for="rRadio">Rankine</label>
    <input id="rRadio" class="listener" type="radio" name="unit" value="r">
  </fieldset>
</div>
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert the value to Kelvin:</p>

<p>
  <label>Temperature</label>
  <input id="temp" class="listener" type="number" name="temp" value="32">
</p>
<p>Kelvin: <span id="output"></span></p>


问:
"Add to Homescreen" Banner in Rails PWA
I've made a small PWA in RoR; following and I followed Google's guide on having "Add to Homescreen" banners. Everything in devtools is fine: the service worker is registered, the manifest.json is found, the "Add to Homescreen" link is displayed and runs in the tool drawer.

I even installed Lighthouse like they said and ran the report; it says everything should work. However, I have yet to see the banner (yes, it isn't already on my homescreen; yes, I visited at least five minutes apart).

Does anyone have an idea on what the threshold is WRT users activity to make the banner appear?

(ps. does anyone want to try it out here?)

答: thanks for the responses; I waited like a day, cleared my caches completely, and got the banner. I still don't know the threshold for how many times you have to visit, but at least it works.</p>

Title: "Add to Homescreen" Banner in Rails PWA


问:
Download file with curl on Mac
I want to download a file in a shell-script using curl on my Mac:

```<code>http://dumps.wikimedia.org/barwiki/latest/barwiki-latest-pages-articles.xml.bz2
</code>```

However, I always get:

```<code><html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.11.6</center>
</body>
</html>
</code>```

Why and what can I do?

答:
with php i check url rediect first and then try to get </p>

```<code>    <?
$url='http://xxxx/';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE); // We'll parse redirect url from header.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE); // We want to just get redirect url but not to follow it.
$response = curl_exec($ch);
preg_match_all('/^Location:(.*)$/mi', $response, $matches);
$data = curl_close($ch);
$turl= !empty($matches[1]) ? trim($matches[1][0]) : 'No redirect found';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $turl);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$homepage=$data = curl_exec($ch);
</code>```

<p>i can't help you with ssh but if poosible use it with php  </p>

Title: Download file with curl on Mac

Body:
I want to download a file in a shell-script using curl on my Mac:

http://dumps.wikimedia.org/barwiki/latest/barwiki-latest-pages-articles.xml.bz2

However, I always get:

<title>301 Moved Permanently</title>

301 Moved Permanently

nginx/1.11.6

Why and what can I do?

Body:
with php i check url rediect first and then try to get

    <?
$url='http://xxxx/';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE); // We'll parse redirect url from header.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE); // We want to just get redirect url but not to follow it.
$response = curl_exec($ch);
preg_match_all('/^Location:(.*)$/mi', $response, $matches);
$data = curl_close($ch);
$turl= !empty($matches[1]) ? trim($matches[1][0]) : 'No redirect found';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $turl);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$homepage=$data = curl_exec($ch);

i can't help you with ssh but if poosible use it with php


问:
Qml - Exchange date between c++ class and class created by QmlRegisterType
I have the following question regards qml object loaded with qml Loader (setSource("qmlObject.qml")).

In qmlObject.qml I have imported objectClass(.h/.cpp) created with qmlRegisterType, thus when I launch loader.setSource("qmlObject.qml") command an instance of objectClass(.h/.cpp) is created.

I have other main class named coreClass(.h/.cpp) and I should exchange data between objectClass(.h/.cpp) and coreClass(.h/.cpp).

What's the best practice to implement this feature in my simple qt application?

答:
You can easily exchange data between c++ classes with SIGNAL and SLOT mechanism.
just pass pointer of coreClass to objectClass and connect signal and slots.</p>


答:
You should set one of the radio buttons as default with checked="checked". Then try following: </p>

```<code>   $(document).ready(function () {
        $('input.listener').change(function () {
          if ($(this).attr("type") == 'radio') {
            //radio button changed
            var u = $(this).val();
          } else {
            var u = $("input[type='radio']:checked").val();
          }
          var temperature = $('#temp').val();

          switch (u) {
            case 'f':
              $('span#output').html(((temperature - 32) / 1.8) + 273.15);
              break;
            case 'c':
              $('span#output').html(temperature + 273.15);
              break;
            case 'r':
              $('span#output').html(temperature / 1.8);
              break;
          }
        });
      });
</code>```

Title: change() jQuery not working

Body:
You should set one of the radio buttons as default with checked="checked". Then try following:

   $(document).ready(function () {
        $('input.listener').change(function () {
          if ($(this).attr("type") == 'radio') {
            //radio button changed
            var u = $(this).val();
          } else {
            var u = $("input[type='radio']:checked").val();
          }
          var temperature = $('#temp').val();

          switch (u) {
            case 'f':
              $('span#output').html(((temperature - 32) / 1.8) + 273.15);
              break;
            case 'c':
              $('span#output').html(temperature + 273.15);
              break;
            case 'r':
              $('span#output').html(temperature / 1.8);
              break;
          }
        });
      });


问:
React: Nested onclick also triggers parent
I used the react version of the slick carousel to make a Netflix like carousel.
You can click on a tile and that tile then expands to show the details of that tile.

Example:

This works great thanks to Slicks ability to handle dynamic heights.
I want to add a close button the expanded section (as seen in the far right). But that is where I have an issue.

If I add a close button with a onClick handler, it will always trigger the parent Onclick which shows the expanded section.

The showExpanded onclick function just sets a showDetails state.

So my question is:

How can I set a state by clicking on the close button, without also triggering the wrapping parent.

I tried event.preventDefault() and event.stopPropagation() but that didn't do the trick.

Tile click looks like this:

```<code>expandTile(){
  this.setState({
    showDetails: true,
    closeTile: false
  });
}
</code>```

Close button click function as I have it now:

```<code>closeTile(e){
   e.preventDefault();
   e.stopPropagation();
   const showDetails = this.state.showDetails;
   if(showDetails){
      this.setState({
        showDetails: false,
        closeTile: true
      });
   }
}
</code>```

Update: added JSX:

```<code>  return (
    <div className={s.itemPreWrapper} key={`${el.title}-item-${index}`}>
      <div className={`${s.item} ${showDetails ? s.showDetails : ''}`}
           onClick={self.state.expandItem}
           data-index={index}
        <div className={s.itemCaret}></div>
        <div className={s.imgWrapper}>
          <img src={el.itemImage}/>
        </div>
        <div className={s.overlay}>
          {el.title}
        </div>
        <div className={s.expandedTile} style={{left: '-'+offset+'px'}}>
          <div className={s.etItem}>
           <div key={`subitem-${index}`} ref="subItem">
            <div className="row">
              <div className={`${s.etClose}`} onClick={self.state.closeTile}><span></span></div>
              <div className="col-xs-12 col-sm-3">
                <div className={`${s.etImage}`}>
                  <img src={el.itemImage} alt="product image" className="img-responsive"/>
                </div>
              </div>
              <div className="col-xs-12 col-sm-9">
                <div className="row">
                  <div className={`${s.etContent} col-xs-12 col-sm-6 col-lg-8`}>
                    <h2>{itemTitle}</h2>
                    <p> {el.description}</p>
                  </div>
                  <div className={`${s.etMedia} col-xs-12 hidden-sm col-sm-5 col-lg-3`}>
                    {media}
                  </div>
                </div>
            </div>
            <div className="col-xs-12 col-md-11">
              {optionsElem}
            </div>
          </div>
          </div>
        </div>
      </div>
    </div>
  );
</code>```

答: The solution that worked for me was to place a call to event.stopPropagation() in your child onClick method. This will prevent the parent from being called.

Body:
I used the react version of the slick carousel to make a Netflix like carousel.
You can click on a tile and that tile then expands to show the details of that tile.

Example:

This works great thanks to Slicks ability to handle dynamic heights.
I want to add a close button the expanded section (as seen in the far right). But that is where I have an issue.

If I add a close button with a onClick handler, it will always trigger the parent Onclick which shows the expanded section.

The showExpanded onclick function just sets a showDetails state.

So my question is:

How can I set a state by clicking on the close button, without also triggering the wrapping parent.

I tried event.preventDefault() and event.stopPropagation() but that didn't do the trick.

Tile click looks like this:

expandTile(){
  this.setState({
    showDetails: true,
    closeTile: false
  });
}

Close button click function as I have it now:

closeTile(e){
   e.preventDefault();
   e.stopPropagation();
   const showDetails = this.state.showDetails;
   if(showDetails){
      this.setState({
        showDetails: false,
        closeTile: true
      });
   }
}

Update: added JSX:

  return (
    <div className={s.itemPreWrapper} key={`${el.title}-item-${index}`}>
      <div className={`${s.item} ${showDetails ? s.showDetails : ''}`}
           onClick={self.state.expandItem}
           data-index={index}

          {el.title}

           <div key={`subitem-${index}`} ref="subItem">

              <div className={`${s.etClose}`} onClick={self.state.closeTile}>

                <div className={`${s.etImage}`}>

                  <div className={`${s.etContent} col-xs-12 col-sm-6 col-lg-8`}>

{itemTitle}

 {el.description}

                  <div className={`${s.etMedia} col-xs-12 hidden-sm col-sm-5 col-lg-3`}>
                    {media}

              {optionsElem}

  );


问:
Reading a hash from a file on disk
Here is a hash that I save to a file to later be read.

```<code>my_hash = {-1 => 20, -2 => 30, -3 => 40}
File.open("my_file.txt", "w") { |f| f.write my_hash }
#how it looks opening the text file
{-1 => 20, -2 => 30, -3 => 40}
</code>```

When I go to read it, is where my problem is. (following code is separate from top)

```<code>my_hash = File.foreach("my_file.txt") { |f| print f }
p my_hash
#=> {-1 => 20, -2 => 30, -3 => 40}nil
</code>```

that nil messes up the rest of my code..not sure how to get rid of if. Just for clarity the rest of the code...

```<code>back_up_hash = {-1 => 20}
if my_hash.nil?
  my_hash = back_up_hash
end
</code>```

That little nil always makes my_hash equal to back_up_hash. I need that .nil? just in case the file is doesn't have the hash, otherwise the problem just gets pushed further down.

I also tried to read (slurp?..it's a small file) the file like this....

```<code>my_hash = File.read("my_file.txt") { |f| print f }
p my_hash
=> "{-1 => 20, -2 => 30, -3 => 40}"
# not sure how to get it out of string form...and I have searched for it.
</code>```

答:
The proper way to save simple data structures to a file is to serialize them. In this particular case, using JSON is probably a good choice:

```<code># save hash to file:
f.write MultiJson.dump(my_hash)

# load it back:
p MultiJson.load(file_contents)
</code>```

Keep in mind that JSON is only able to serialize simple, built-in data types (strings, numbers, arrays, hashes and the like). You will not be able to serialize and deserialize custom objects this way without some additional work.

If you don't have MultiJson, try it with JSON instead.

Title: Reading a hash from a file on disk

Body:
Here is a hash that I save to a file to later be read.

my_hash = {-1 => 20, -2 => 30, -3 => 40}
File.open("my_file.txt", "w") { |f| f.write my_hash }
#how it looks opening the text file
{-1 => 20, -2 => 30, -3 => 40}

When I go to read it, is where my problem is. (following code is separate from top)

my_hash = File.foreach("my_file.txt") { |f| print f }
p my_hash
#=> {-1 => 20, -2 => 30, -3 => 40}nil

that nil messes up the rest of my code..not sure how to get rid of if. Just for clarity the rest of the code...

back_up_hash = {-1 => 20}
if my_hash.nil?
  my_hash = back_up_hash
end

That little nil always makes my_hash equal to back_up_hash. I need that .nil? just in case the file is doesn't have the hash, otherwise the problem just gets pushed further down.

I also tried to read (slurp?..it's a small file) the file like this....

my_hash = File.read("my_file.txt") { |f| print f }
p my_hash
=> "{-1 => 20, -2 => 30, -3 => 40}"
# not sure how to get it out of string form...and I have searched for it.

Body:
The proper way to save simple data structures to a file is to serialize them. In this particular case, using JSON is probably a good choice:

# save hash to file:
f.write MultiJson.dump(my_hash)

# load it back:
p MultiJson.load(file_contents)

Keep in mind that JSON is only able to serialize simple, built-in data types (strings, numbers, arrays, hashes and the like). You will not be able to serialize and deserialize custom objects this way without some additional work.

If you don't have MultiJson, try it with JSON instead.


问:
Facebook random metadata website
Hello im trying to make a random metadata website but om a little comfused on how the coding works. I think it uses Javascript.
Example :
https://i.stack.imgur.com/p03MG.jpg

答:
Yes you could use JavaScript for this. You can just put all the "img src values" into an array, then use the Math.random() function to generate a random number to address the "img src values" in the array whenever the page loads. You can then change the "src" attribute of the image to one of the values in the array.

Here are the basics of what I mean (I won't hold your hand though):

```<code>var yourImage = document.getElementById("yourImgElementsId");
var imgSrcArray = [imgSrc1, imgSrc2, imgSrc3, imgSrc4];
var randomNumber = Math.random() * (max - min) + min;

yourImage.src = imgSrcArray[randomNumber];
</code>```

I would suggest learning JavaScript basics before attempting to finish this, then look at these sources when you're more confident:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

Title: Facebook random metadata website

Body:
Yes you could use JavaScript for this. You can just put all the "img src values" into an array, then use the Math.random() function to generate a random number to address the "img src values" in the array whenever the page loads. You can then change the "src" attribute of the image to one of the values in the array.

Here are the basics of what I mean (I won't hold your hand though):

var yourImage = document.getElementById("yourImgElementsId");
var imgSrcArray = [imgSrc1, imgSrc2, imgSrc3, imgSrc4];
var randomNumber = Math.random() * (max - min) + min;

yourImage.src = imgSrcArray[randomNumber];

I would suggest learning JavaScript basics before attempting to finish this, then look at these sources when you're more confident:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random


问:
Mailgun Mailing List Address Bounced
I have setup a mailing list via Mailgun, newsletter@example.com. When I send a message to this address with my Mailgun API key, the message is delivered to all of the members of the mailing list.

Core Issue: Mailgun also attempts to deliver the message to newsletter@example.com itself, which is an email address that doesn't exist, resulting in the below error in our logs each day

```<code>Failed: morningalert@example.com → newsletter@example.com 'Morning Report: 2017-05-12' Not delivering to previously bounced address
</code>```

I could simply ignore this, but it does put a skew on our analytics and makes it difficult for us to notice meaningful errors since it shows a bounce every time. How can I address this so we do not cause this bounce error when sending to our mailing list? My (poorly written) Python code is below. Thank you!

```<code>def standard_message(key, to, from_email, from_name, subject, body, delivery_time=False, replyto=False):
    url = "https://api.mailgun.net/v3/tradedefender.com/messages"
    auth = ("api", key)
    data =  {"from": from_name + " <" + from_email + ">",
            "to": to,
            "subject": subject,
            "text": body}

    if(delivery_time != False):
        data["o:deliverytime"] = delivery_time

    if(replyto != False):
        data["h:Reply-To"] = replyto

    response = requests.post(url, auth=auth, data=data)

    if("200" in str(response)):
        return(True)
    else:
        raise Exception(response)
</code>```

答:
Have you double checked you don't have that email address in your database as a subscriber? I don't see why Mailgun would be trying to deliver to newsletter@example.com.

Failing that, you could try the “Suppressions” tab of the Control Panel to manually unsubscribe the email address:

https://app.mailgun.com/app/suppressions/tradedefender.com/unsubscribes

Title: Mailgun Mailing List Address Bounced

Body:
I have setup a mailing list via Mailgun, newsletter@example.com. When I send a message to this address with my Mailgun API key, the message is delivered to all of the members of the mailing list.

Core Issue: Mailgun also attempts to deliver the message to newsletter@example.com itself, which is an email address that doesn't exist, resulting in the below error in our logs each day

Failed: morningalert@example.com → newsletter@example.com 'Morning Report: 2017-05-12' Not delivering to previously bounced address

I could simply ignore this, but it does put a skew on our analytics and makes it difficult for us to notice meaningful errors since it shows a bounce every time. How can I address this so we do not cause this bounce error when sending to our mailing list? My (poorly written) Python code is below. Thank you!

def standard_message(key, to, from_email, from_name, subject, body, delivery_time=False, replyto=False):
    url = "https://api.mailgun.net/v3/tradedefender.com/messages"
    auth = ("api", key)
    data =  {"from": from_name + " <" + from_email + ">",
            "to": to,
            "subject": subject,
            "text": body}

    if(delivery_time != False):
        data["o:deliverytime"] = delivery_time

    if(replyto != False):
        data["h:Reply-To"] = replyto

    response = requests.post(url, auth=auth, data=data)

    if("200" in str(response)):
        return(True)
    else:
        raise Exception(response)


问:
Can't get search box to center in bootstrap navbar
I have static bootstrap navbar and am trying to center a search box in it. Everything I've tried is not working. Either get it below the navbar or not at all. I now have it showing, but it is displaying above the navbar title on the left, and not at the same vertical position as the rest of the navbar items. I've tried using just form, navbar-center and now a div. None of them work. There must be some simple bootstrap class or css I'm missing.

```<code>    <nav class="navbar navbar-default ">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button>
            <a class="navbar-brand" href="index.html"><img src="static/img/CAP-Seal-75x75.png" width=50 height=50 ></a>
            <p style="padding-top:25px;width:120%;"></span>CAWG (TRACS) </p>
        </div>
        <div id="search" class="nav navbar-nav navbar-center">
        <form class="nav navbar-nav navbar-center" role="search">
            <input type="text" class="search form-control input-sm" placeholder="Search" id="sitesearch">
                <button type="submit" class="btn btn-xs"><span class="glyphicon glyphicon-search"></span></button>
                </form>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
            <ul class="nav navbar-nav navbar-right" style="padding-right:20px;">
            <ul class="nav navbar-nav">
                <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <span class="glyphicon glyphicon-th-list" aria-hidden="true" style="font-size:1.5em;"></span><i class="icon-angle-down"> </i></a>
                    <ul class="dropdown-menu">
                        <li><a href="#track_modal_realtime"  data-toggle="modal">Real Time Tracking</a></li>
                        <li><a id="stop_tracking" href="#">Stop Tracking</a></li>
                        <li><a href="#track_modal_historical"  data-toggle="modal">Historical Tracking</a></li>
                        <li><a href="#send_message_modal"  data-toggle="modal">Communications</a></li>
                    </ul>
                </li>
                <li>
                    <a class="navbar-brand" href="#menu-toggle" id="menu-toggle"><span class="glyphicon glyphicon-resize-full" aria-hidden="true" id="sizeIcon" style="font-size:1.5em;"></span></a></li><!---->
                <li><a href="#settings_modal" data-toggle="modal"><span class="glyphicon glyphicon-cog" style="font-size:1.5em;" aria-hidden="true"></span></a></li>
            </ul>

        </div>
    </nav>
</code>```

Any suggestions?

Thanks

答:
Hopefully I have read your question right. If so, you could always do something like this:

```<code>   <nav class="navbar navbar-default ">
 <div class="row">
   <div class="col-sm-4">
    <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar">                   </span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button>
        <a class="navbar-brand" href="index.html"><img src="static/img/CAP-Seal-75x75.png" width=50 height=50 ></a>
        <p style="padding-top:25px;width:120%;"></span>CAWG (TRACS) </p>
    </div>
  </div>
  <div class="col-sm-4">
    <div id="search" class="nav navbar-nav navbar-center">
      <form class="nav navbar-nav navbar-center" role="search">
        <div class="input-group">
          <input type="text" class="search form-control input-sm" placeholder="Search" id="sitesearch">
          <span class="input-group-addon" id="basic-addon2"><span class="glyphicon glyphicon-search"></span></span>
        </div>
      </form>
    </div>
  </div>
  <div class="col-sm-4">
    <div id="navbar" class="navbar-collapse collapse">
      <ul class="nav navbar-nav navbar-right" style="padding-right:20px;">
        <ul class="nav navbar-nav">
          <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <span class="glyphicon glyphicon-th-list" aria-hidden="true" style="font-size:1.5em;"></span><i class="icon-angle-down"> </i></a>
            <ul class="dropdown-menu">
              <li><a href="#track_modal_realtime"  data-toggle="modal">Real Time Tracking</a></li>
              <li><a id="stop_tracking" href="#">Stop Tracking</a></li>
              <li><a href="#track_modal_historical"  data-toggle="modal">Historical Tracking</a></li>
              <li><a href="#send_message_modal"  data-toggle="modal">Communications</a></li>
            </ul>
          </li>
          <li>
            <a class="navbar-brand" href="#menu-toggle" id="menu-toggle"><span class="glyphicon glyphicon-resize-full" aria-hidden="true" id="sizeIcon" style="font-size:1.5em;"></span></a></li><!---->
          <li><a href="#settings_modal" data-toggle="modal"><span class="glyphicon glyphicon-cog" style="font-size:1.5em;" aria-hidden="true"></span></a></li>
        </ul>
        </div>
    </div>
  </div>
</nav>
</code>```

By using bootstraps build in cols you can easily center elements by simply splitting your nav into 3 parts.

Hopefully this is what you are after :)

Working example here - https://codepen.io/anon/pen/ZyMZrY

Body:
I have static bootstrap navbar and am trying to center a search box in it. Everything I've tried is not working. Either get it below the navbar or not at all. I now have it showing, but it is displaying above the navbar title on the left, and not at the same vertical position as the rest of the navbar items. I've tried using just form, navbar-center and now a div. None of them work. There must be some simple bootstrap class or css I'm missing.

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> Toggle navigation    </button>

CAWG (TRACS)

        <form class="nav navbar-nav navbar-center" role="search">
            <input type="text" class="search form-control input-sm" placeholder="Search" id="sitesearch">
                <button type="submit" class="btn btn-xs"></button>
                </form>

Real Time Tracking

Stop Tracking

Historical Tracking

Communications

Any suggestions?

Thanks

Body:
Hopefully I have read your question right. If so, you could always do something like this:

   <nav class="navbar navbar-default ">
 <div class="row">
   <div class="col-sm-4">
    <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar">                   </span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button>
        <a class="navbar-brand" href="index.html"><img src="static/img/CAP-Seal-75x75.png" width=50 height=50 ></a>
        <p style="padding-top:25px;width:120%;"></span>CAWG (TRACS) </p>
    </div>
  </div>
  <div class="col-sm-4">
    <div id="search" class="nav navbar-nav navbar-center">
      <form class="nav navbar-nav navbar-center" role="search">
        <div class="input-group">
          <input type="text" class="search form-control input-sm" placeholder="Search" id="sitesearch">
          <span class="input-group-addon" id="basic-addon2"><span class="glyphicon glyphicon-search"></span></span>
        </div>
      </form>
    </div>
  </div>
  <div class="col-sm-4">
    <div id="navbar" class="navbar-collapse collapse">
      <ul class="nav navbar-nav navbar-right" style="padding-right:20px;">
        <ul class="nav navbar-nav">
          <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <span class="glyphicon glyphicon-th-list" aria-hidden="true" style="font-size:1.5em;"></span><i class="icon-angle-down"> </i></a>
            <ul class="dropdown-menu">
              <li><a href="#track_modal_realtime"  data-toggle="modal">Real Time Tracking</a></li>
              <li><a id="stop_tracking" href="#">Stop Tracking</a></li>
              <li><a href="#track_modal_historical"  data-toggle="modal">Historical Tracking</a></li>
              <li><a href="#send_message_modal"  data-toggle="modal">Communications</a></li>
            </ul>
          </li>
          <li>
            <a class="navbar-brand" href="#menu-toggle" id="menu-toggle"><span class="glyphicon glyphicon-resize-full" aria-hidden="true" id="sizeIcon" style="font-size:1.5em;"></span></a></li><!---->
          <li><a href="#settings_modal" data-toggle="modal"><span class="glyphicon glyphicon-cog" style="font-size:1.5em;" aria-hidden="true"></span></a></li>
        </ul>
        </div>
    </div>
  </div>
</nav>

By using bootstraps build in cols you can easily center elements by simply splitting your nav into 3 parts.

Hopefully this is what you are after :)

Working example here - https://codepen.io/anon/pen/ZyMZrY


问:
Embed file after codesign signature is created
I create a macOS bundle and codesign it. Post codesigning I want to sign app binary and put the resulting signature inside the bundle.
My research says its not possible, is there slight chance that its possible to do so? Mavericks and older you could exclude files from bundle signature but not sure if its possible in Sierra/Yosemite/El Capitan.</p>

答:
From Code Signing In Depth Document

I exclude files so I can fix my bundle after I build it?

This is no longer allowed. If you must modify your bundle, do it before signing. If you modify a signed bundle, you must re-sign it afterwards.

Codesigning recursively goes to the sub directories and include all the code while generating signature and modifying the bundle (removing file, adding new file or changing even 1 bit in the files included in the signature) will invalidate the bundle.


问:
RESTFUL Web Service - List
I have a client application requesting a list of channels from a webservice. Is it possible to take the "response" from the web service and store it in an ArrayList?

Meaning if I wanted to store a list of channels for example, it would normally come from the web service as a response, typically from ResponseBuilder.

And I want to store it in an ArrayList from the client, like List.

How would I go about doing that?

答:
You can use TypeReference to instantiate your Channel object list, here is an example:

```<code>import com.fasterxml.jackson.core.type.TypeReference;

public class ChannelClient {

  public void getChannels() {
    Response serviceResponse = client.target("http://your_service_url/channels/").
                request(MediaType.APPLICATION_JSON).get(Response.class);
    String responseString = serviceResponse.readEntity(String.class);
    List<Channel> list = new ObjectMapper().readerFor(new TypeReference<List<Channel>>() {
        }).readValue(responseString);
  }
}
</code>```

Make sure to have Jersey JSON Jackson jar in your dependencies, you can get it from here

https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-json-jackson/2.26-b07

EDIT: In case you want to consume MediaType.TEXT_PLAIN response, you will just change the request method argument to your specified type like this:

```<code> Response serviceResponse = client.target("http://your_service_url/channels/").
            request(MediaType.TEXT_PLAIN).get(Response.class);
</code>```

Title: RESTFUL Web Service - List

Body:
You can use TypeReference to instantiate your Channel object list, here is an example:

import com.fasterxml.jackson.core.type.TypeReference;

public class ChannelClient {

  public void getChannels() {
    Response serviceResponse = client.target("http://your_service_url/channels/").
                request(MediaType.APPLICATION_JSON).get(Response.class);
    String responseString = serviceResponse.readEntity(String.class);
    List<Channel> list = new ObjectMapper().readerFor(new TypeReference<List<Channel>>() {
        }).readValue(responseString);
  }
}

Make sure to have Jersey JSON Jackson jar in your dependencies, you can get it from here

https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-json-jackson/2.26-b07

EDIT: In case you want to consume MediaType.TEXT_PLAIN response, you will just change the request method argument to your specified type like this:

 Response serviceResponse = client.target("http://your_service_url/channels/").
            request(MediaType.TEXT_PLAIN).get(Response.class);


问:
multiple aggregations on multiple variable on groups
I have a data.table and would like to run multiple aggregations on multiple columns while the table is grouped on another variable. I have tried the following:

```<code>library(data.table)

DT <- data.table(a = 1:10,
                 b = 10:1,
                 group = rep(1:2, each=5))

aggs <- function(x) list(mean = mean(x), sd = sd(x))

DT[, lapply(.SD, aggs), .(group), .SDcols = c('a', 'b')]
</code>```

This doesn't quite work as I would either need the names() as a column or for the output to be split into columns - say a.mean, b.mean, etc.:

```<code>   group        a        b
1:     1        3        8
2:     1 1.581139 1.581139
3:     2        8        3
4:     2 1.581139 1.581139
</code>```

答:
You were close, missing an extra data.frame to cast the results the way you want:

```<code>DT[, data.frame(lapply(.SD, aggs)), by=group, .SDcols = c('a', 'b')]
</code>```

giving:

```<code>   group a.mean     a.sd b.mean     b.sd
1:     1      3 1.581139      8 1.581139
2:     2      8 1.581139      3 1.581139
</code>```

Body:
I have a data.table and would like to run multiple aggregations on multiple columns while the table is grouped on another variable. I have tried the following:

library(data.table)

DT <- data.table(a = 1:10,
                 b = 10:1,
                 group = rep(1:2, each=5))

aggs <- function(x) list(mean = mean(x), sd = sd(x))

DT[, lapply(.SD, aggs), .(group), .SDcols = c('a', 'b')]

This doesn't quite work as I would either need the names() as a column or for the output to be split into columns - say a.mean, b.mean, etc.:

   group        a        b
1:     1        3        8
2:     1 1.581139 1.581139
3:     2        8        3
4:     2 1.581139 1.581139

Body:
You were close, missing an extra data.frame to cast the results the way you want:

DT[, data.frame(lapply(.SD, aggs)), by=group, .SDcols = c('a', 'b')]

giving:

   group a.mean     a.sd b.mean     b.sd
1:     1      3 1.581139      8 1.581139
2:     2      8 1.581139      3 1.581139


问:
ImageView onClickListener is not working
I have two ImageViews, one text field and one WebView in a LinearLayout. My ImageView listener is not working. Here is my XML:

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

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="back"
        android:adjustViewBounds="true"
        android:clickable="true"
        android:src="@drawable/back_icon" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:clickable="true"
        android:contentDescription="forward"
        android:src="@drawable/back_icon"/>
    <EditText
        android:id="@+id/adressBar"
        android:imeOptions="actionDone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:ems="10" >
    </EditText>

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
</code>```

Here is my Java code. I should point out that the Log.d statement is not firing, so it is definitely not getting called:

```<code>public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    if (savedInstanceState == null) {
        L.d(">>onCreateView", "savedInstanceState null");
    }
    View v = inflater.inflate(R.layout.browser,null);
    mWebView = (WebView) v.findViewById(R.id.webView);
    back =(ImageView) v.findViewById(R.id.imageView1);
    back.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("backkkkkkkkkkkkkkkk", "msg");

        }
    });
    return v;
}
</code>```

答:
I had a similar issue and fixed it by adding android:layout_width="44dp" to make sure user would have enough area to click on. Then, you can align image content the way you wannt. In my case:

```<code><ImageView
    android:id="@+id/locationImageView"
    android:layout_width="44dp"
    android:layout_height="16dp"
    android:layout_centerVertical="true"
    android:layout_marginStart="4dp"
    android:layout_toEndOf="@id/locationText"
    android:adjustViewBounds="true"
    android:scaleType="fitStart"
    android:src="@drawable/icn_edit_small_white"/>
</code>```

Body:
I have two ImageViews, one text field and one WebView in a LinearLayout. My ImageView listener is not working. Here is my XML:

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

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="back"
        android:adjustViewBounds="true"
        android:clickable="true"
        android:src="@drawable/back_icon" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:clickable="true"
        android:contentDescription="forward"
        android:src="@drawable/back_icon"/>
    <EditText
        android:id="@+id/adressBar"
        android:imeOptions="actionDone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:ems="10" >
    </EditText>

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Here is my Java code. I should point out that the Log.d statement is not firing, so it is definitely not getting called:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    if (savedInstanceState == null) {
        L.d(">>onCreateView", "savedInstanceState null");
    }
    View v = inflater.inflate(R.layout.browser,null);
    mWebView = (WebView) v.findViewById(R.id.webView);
    back =(ImageView) v.findViewById(R.id.imageView1);
    back.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("backkkkkkkkkkkkkkkk", "msg");

        }
    });
    return v;
}

Body:
I had a similar issue and fixed it by adding android:layout_width="44dp" to make sure user would have enough area to click on. Then, you can align image content the way you wannt. In my case:

<ImageView
    android:id="@+id/locationImageView"
    android:layout_width="44dp"
    android:layout_height="16dp"
    android:layout_centerVertical="true"
    android:layout_marginStart="4dp"
    android:layout_toEndOf="@id/locationText"
    android:adjustViewBounds="true"
    android:scaleType="fitStart"
    android:src="@drawable/icn_edit_small_white"/>

ContentLicense: CC BY-SA 4.0


问:
How to force redirect to https when user changes the url to be http://whatever?
I'm using play framework 2.3 and I've got to the point where redirecting to https is working but if I change the https in the url to http, the request never makes it to the server. Any thoughts?</p>

答:
use two server config first one with port 80 any one open it will redirect to only https </p>

```<code>    server {
listen       80;
        server_name  domain   www.doman ;
return         301 https://www.doman.com$request_uri;
}
################################################
server {
    location ~ /\. { deny  all; }
listen              443 ssl;
server_name        domain   www.doman  ;
</code>```

Body:
use two server config first one with port 80 any one open it will redirect to only https

    server {
listen       80;
        server_name  domain   www.doman ;
return         301 https://www.doman.com$request_uri;
}
################################################
server {
    location ~ /\. { deny  all; }
listen              443 ssl;
server_name        domain   www.doman  ;


问:
How to make text field like this in swift?
I want to make this kind of text field in my application. Could you guys suggest how to create a text field like the ones shown in this picture?

答:
Use Eureka! It's an open source library available on Github - https://github.com/EurekaCommunity

It's really useful for creating form-based table views like the one you've described above.


问:
How can I convert a date from the format "dd/mm/yyyy" to "yyyy/dd/mm"?
I have a Textbox in which the user is supposed to enter a date in the format dd/mm/yyyy, this date is stored as yyyy/mm/dd in the database.

So I want the user to enter the date in dd/mm/yyyy format and later I want to convert to yyyy/mm/dd so that I can query database.

How can I convert the user input date dd/mm/yyyy to yyyy/mm/dd?

答:
```<code>string input = "20/12/2010"; // dd/mm/yyyy
DateTime d;
if (DateTime.TryParseExact(input, "dd/mm/yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out d))
{
    string result = d.ToString("yyyy/mm/dd");
}
</code>```