问:
How to use if-then-else in a recursive function
I am writing a function that will take a list of list and merge it into sorted pairs of list.  For example [[1],[9],[8],[7],[4],[5],[6]] would return [[1,9],[7,8],[4,5],[6]].  This is my first attempt at SML.  I keep getting this error: operator and operand don't agree [overload conflict].

```<code>    fun mergePass[] = []
    |   mergePass(x::[]) = x::[]
    |   mergePass(x::y::Z) =
        if x<y
        then (x @ y)::mergePass(Z)
        else (y @ x)::mergePass(Z);
</code>```

Edit:  If mergePass is called on [[1,9],[7,8],[4,5],[6]] I will need it to return [[1,7,8,9],[4,5,6]].

This merge function takes two sorted lists

```<code>   fun merge([],y) = y
   |   merge(x,[]) = x
   |   merge(a::x,b::y) =
   if a < b then a::merge(x,b::y)
   else b::merge(a::x,y);
</code>```

答:
You seem reasonably close. A few hints/remarks:

1) Aesthetically, using nil in one line and [] in others seems odd. Either use all nil or use all []

2) Since the input are lists of lists, in x::y::z, the identifiers x and y would be lists of integers, rather than individual integers. Thus, x<y wouldn't make sense. You can't compare lists of integers using <.

3) Your problem description strongly suggests that the inner-lists are all 1-element lists. Thus you could use the pattern [x]::[y]::z to allow you to compare x and y. In this case, x@y could be replaced by [x,y]

4) If the inner lists are allowed to be of arbitrary size, then your code needs major revision and would probably require a full-fledged sort function to sort the result of concatenating pairs of inner lists. Also, in this case, the single list in the one inner list case should probably be sorted.

5) You have a typo: mergeP isn't mergePass.

On Edit:

If the sublists are each sorted (and the name of the overall function perhaps suggests this) then you need a function called e.g. merge which will take two sorted lists and combine them into a single sorted list. If this is for a class and you have already seen a merge function as an example (perhaps in a discussion of merge-sort) -- just use that. Otherwise you will have to write your own before you write this function. Once you have the merge function, skip the part of comparing x and y and instead have something as simple as:

```<code>| mergePass (xs::ys::zss) = (merge xs ys) :: mergePass zss
</code>```

If the sublists are not merged, then you will need a full-fledged sort in which case you would use something like:

```<code>| mergePass (xs::ys::zss) = sort(xs @ ys) :: mergePass zss
</code>```

Body:
I am writing a function that will take a list of list and merge it into sorted pairs of list.  For example [[1],[9],[8],[7],[4],[5],[6]] would return [[1,9],[7,8],[4,5],[6]].  This is my first attempt at SML.  I keep getting this error: operator and operand don't agree [overload conflict].

    fun mergePass[] = []
    |   mergePass(x::[]) = x::[]
    |   mergePass(x::y::Z) =
        if x<y
        then (x @ y)::mergePass(Z)
        else (y @ x)::mergePass(Z);

Edit:  If mergePass is called on [[1,9],[7,8],[4,5],[6]] I will need it to return [[1,7,8,9],[4,5,6]].

This merge function takes two sorted lists

   fun merge([],y) = y
   |   merge(x,[]) = x
   |   merge(a::x,b::y) =
   if a < b then a::merge(x,b::y)
   else b::merge(a::x,y);

Body:
You seem reasonably close. A few hints/remarks:

1) Aesthetically, using nil in one line and [] in others seems odd. Either use all nil or use all []

2) Since the input are lists of lists, in x::y::z, the identifiers x and y would be lists of integers, rather than individual integers. Thus, x<y wouldn't make sense. You can't compare lists of integers using <.

3) Your problem description strongly suggests that the inner-lists are all 1-element lists. Thus you could use the pattern [x]::[y]::z to allow you to compare x and y. In this case, x@y could be replaced by [x,y]

4) If the inner lists are allowed to be of arbitrary size, then your code needs major revision and would probably require a full-fledged sort function to sort the result of concatenating pairs of inner lists. Also, in this case, the single list in the one inner list case should probably be sorted.

5) You have a typo: mergeP isn't mergePass.

On Edit:

If the sublists are each sorted (and the name of the overall function perhaps suggests this) then you need a function called e.g. merge which will take two sorted lists and combine them into a single sorted list. If this is for a class and you have already seen a merge function as an example (perhaps in a discussion of merge-sort) -- just use that. Otherwise you will have to write your own before you write this function. Once you have the merge function, skip the part of comparing x and y and instead have something as simple as:

| mergePass (xs::ys::zss) = (merge xs ys) :: mergePass zss

If the sublists are not merged, then you will need a full-fledged sort in which case you would use something like:

| mergePass (xs::ys::zss) = sort(xs @ ys) :: mergePass zss


来源: stackexchange

问:
a 3 level deep relationship in Ecto -- how to preload
I have quite a several level relationship  of models in my project. In a controller I have this:

```<code>var1 = Repo.get!(Model1, 123) |> Repo.preload([child_items1:  :child_items2])
</code>```

This works fine but I have to go one level deeper.

Namely each child_items2 many child_items3.  Now, how can I preload child_items3 for each child_items2?

答:
I usually use scopes. For example in my Model(1) I will have a with_model2 function that preloads the Model2. So to load 3 associations in a row, I'd have something like:

```<code>def with_model2(query \\ __MODULE__) do
  from query, preload: [model2: ^Model2.with_model3]
end
</code>```

for my Model(1). And then you get the idea, the Model2 would have

```<code>def with_model3(query \\ __MODULE__) do
  from query, preload: :model3
end
</code>```

I actually never went 3 level deep, but I just assume that would work.

ContentLicense: CC BY-SA 3.0

Body:
I have quite a several level relationship  of models in my project. In a controller I have this:

var1 = Repo.get!(Model1, 123) |> Repo.preload([child_items1:  :child_items2])

This works fine but I have to go one level deeper.

Namely each child_items2 many child_items3.  Now, how can I preload child_items3 for each child_items2?

Body:
I usually use scopes. For example in my Model(1) I will have a with_model2 function that preloads the Model2. So to load 3 associations in a row, I'd have something like:

def with_model2(query \\ __MODULE__) do
  from query, preload: [model2: ^Model2.with_model3]
end

for my Model(1). And then you get the idea, the Model2 would have

def with_model3(query \\ __MODULE__) do
  from query, preload: :model3
end

I actually never went 3 level deep, but I just assume that would work.


问:
How to output multiple numbers at once in a for loop using Java
I'm very new to Java programming (2 weeks in) and currently am practicing arrays.

My code is as follows:

```<code>import java.util.Scanner;

public class LA2_2_1 {
    public static void main (String[] args)
    {
        Scanner scan = new Scanner(System.in);
        int x;
        double avg;
        double num = 0;

        System.out.print("Enter the number of items: ");
        x = scan.nextInt();

        int [] numbers = new int [x];
        double sum = 0;
        sum = sum + num;

        for (int index = 0; index < numbers.length; index++)
        {
            System.out.print("Enter the numbers: ");
            num = scan.nextDouble();
            sum = sum + num;
            System.out.println(sum);
        }
        avg = sum/x;
        System.out.println("The average is " + avg);
    }
}
</code>```

Output:

```<code>Enter the number of items: 10

Enter the numbers: 3.4 5 6 1 6.5 7.8 3.5 8.5 6.3 9.5

3.4

Enter the numbers: 8.4

Enter the numbers: 14.4

Enter the numbers: 15.4

Enter the numbers: 21.9

Enter the numbers: 29.7

Enter the numbers: 33.2

Enter the numbers: 41.7

Enter the numbers: 48.0

Enter the numbers: 57.5

The average is 5.75
</code>```

My question is, how can I format the code so that I get "Enter the numbers" to appear only once? I just want the program to ask the user for the series of numbers they want to input. I do not want it to output multiple "Enter the numbers".

I think this may have to do with the output being within a for loop, but I am not too positive. I tried taking it out, and both the average and output for "Enter the numbers" turned to 0.0.

Any input would be helpful.

Thank you

答:
Just moving the print statement outside the loop works. Please try this working link as well http://rextester.com/live/ZDRYM2149</p>

```<code>class Rextester
{
    public static void main (String[] args)
    {
        Scanner scan = new Scanner(System.in);
        int x;
        double avg;
        double num = 0;

        System.out.print("Enter the number of items: ");
        x = scan.nextInt();

        int [] numbers = new int [x];
        double sum = 0;
        sum = sum + num;
        System.out.print("Enter the numbers: ");
        for (int index = 0; index < numbers.length; index++)
        {
            num = scan.nextDouble();
            sum = sum + num;
        }
        System.out.println("The sum is " + sum);
        avg = sum/x;
        System.out.println("The average is " + avg);

    }
}
</code>```

Body:
I'm very new to Java programming (2 weeks in) and currently am practicing arrays.

My code is as follows:

import java.util.Scanner;

public class LA2_2_1 {
    public static void main (String[] args)
    {
        Scanner scan = new Scanner(System.in);
        int x;
        double avg;
        double num = 0;

        System.out.print("Enter the number of items: ");
        x = scan.nextInt();

        int [] numbers = new int [x];
        double sum = 0;
        sum = sum + num;

        for (int index = 0; index < numbers.length; index++)
        {
            System.out.print("Enter the numbers: ");
            num = scan.nextDouble();
            sum = sum + num;
            System.out.println(sum);
        }
        avg = sum/x;
        System.out.println("The average is " + avg);
    }
}

Output:

Enter the number of items: 10

Enter the numbers: 3.4 5 6 1 6.5 7.8 3.5 8.5 6.3 9.5

3.4

Enter the numbers: 8.4

Enter the numbers: 14.4

Enter the numbers: 15.4

Enter the numbers: 21.9

Enter the numbers: 29.7

Enter the numbers: 33.2

Enter the numbers: 41.7

Enter the numbers: 48.0

Enter the numbers: 57.5

The average is 5.75

My question is, how can I format the code so that I get "Enter the numbers" to appear only once? I just want the program to ask the user for the series of numbers they want to input. I do not want it to output multiple "Enter the numbers".

I think this may have to do with the output being within a for loop, but I am not too positive. I tried taking it out, and both the average and output for "Enter the numbers" turned to 0.0.

Any input would be helpful.

Thank you

Body:
Just moving the print statement outside the loop works. Please try this working link as well http://rextester.com/live/ZDRYM2149

class Rextester
{
    public static void main (String[] args)
    {
        Scanner scan = new Scanner(System.in);
        int x;
        double avg;
        double num = 0;

        System.out.print("Enter the number of items: ");
        x = scan.nextInt();

        int [] numbers = new int [x];
        double sum = 0;
        sum = sum + num;
        System.out.print("Enter the numbers: ");
        for (int index = 0; index < numbers.length; index++)
        {
            num = scan.nextDouble();
            sum = sum + num;
        }
        System.out.println("The sum is " + sum);
        avg = sum/x;
        System.out.println("The average is " + avg);

    }
}


问:
Kubernetes delete secret docker-registry error Unable to connect to the server: x509
I have create two secret docker-registrys using with these step:

```<code>$ kubectl create secret docker-registry my-secret --docker-username=burak --docker-password=deniz --docker-email=burak@...

$ kubectl create secret docker-registry secret --docker-username=burak --docker-password=deniz --docker-email=burak@...
</code>```

After these step I tried to get deployment with using that:

```<code>$ kubectl get deployment
</code>```

and I have faced to that ERROR:

Unable to connect to the server: x509: certificate signed by unknown authority (possibly because of "crypto/rsa: verification error" while trying to verify candidate authority certificate "minikubeCA")

and When I have tried to delete or get these secret docker-registrys,I faced to same Error.

How Can I delete these docker-registrys. Can you help me?.

Thank you for your answers.

答: I recommend rebuilding your cluster and taking care to not disrupt the TLS tokens that you get for kubectl to function correctly.

Body:
I have create two secret docker-registrys using with these step:

$ kubectl create secret docker-registry my-secret --docker-username=burak --docker-password=deniz --docker-email=burak@...

$ kubectl create secret docker-registry secret --docker-username=burak --docker-password=deniz --docker-email=burak@...

After these step I tried to get deployment with using that:

$ kubectl get deployment

and I have faced to that ERROR:

Unable to connect to the server: x509: certificate signed by unknown authority (possibly because of "crypto/rsa: verification error" while trying to verify candidate authority certificate "minikubeCA")

and When I have tried to delete or get these secret docker-registrys,I faced to same Error.

How Can I delete these docker-registrys. Can you help me?.

Thank you for your answers.


问:
WordPress Ajax callback function from plugin - OOP
Using PluginBoilerplate to write a plugin.
I need to make an ajax call.

I added to main plugin.php file, class to register scripts and handle ajax calls.

```<code>if ( ! class_exists( 'PoorMansNameSpaceAJAX' ) ) {

class PoorMansNameSpaceAJAX{
    public static $instance = null;
    public $nonce = '';
    public $name = 'ajaxexample';
    public static function getInstance()
    {
        null === self::$instance AND self::$instance = new self;
        return self::$instance;
    }
    public function __construct(){
        # Could as well be: wp_enqueue_scripts or login_enqueue_scripts
        add_action( 'admin_enqueue_scripts', array( $this, 'scriptsEnqueue' ) );
        # Logged in users:
        add_action( 'wp_loaded', array( $this, 'scriptsRegister' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'scriptsLocalize' ) );
        add_action( 'admin_init', array( $this, 'ajaxRegister' ) );

    }
    public function scriptsRegister( $page ){
        $file = 'page-1.js';
        wp_register_script(
            $this->name ,
            WPBP_URLPATH . '/app/files/js/' . $file ,
            array('jquery')
        );
    }
    public function scriptsEnqueue( $page ){

        wp_enqueue_script( $this->name );
    }

    public function ajaxRegister() {
        add_action( "wp_ajax_{$this->name}_action",  array($this, 'ajaxexample'), '1' );
    }

    public function scriptsLocalize( $page ){
        wp_localize_script( $this->name, "{$this->name}Object", array(
            'ajaxurl'          => admin_url( 'admin-ajax.php' ),
            'action'           => "{$this->name}_action"
        ) );
    }

   public function ajaxexample(){
        ob_clean();

        echo json_encode( array(
            'success' => true
        ) );
        wp_die();
    }
}
}
</code>```

the class being called after vendor/autoload.php is included.

the main issue is that although the script is successfully registered, enqueued and localized, the ajax callback function is not taking action.

ajax call is returning empty response.

```<code>( function( $, plugin ) {
           $(document).ready( function() {

            $('#moreroles').on('click', function(event) {
                event.preventDefault();
                /* Act on the event */
                var data = plugin;
                $.ajax({
                    url: plugin.ajax_url,
                    data: data,
                    beforeSend : function( d ) {
                        console.log( 'Before send', d );
                     }
                })
                .done( function( response, textStatus, jqXHR ) {
                    console.log( 'AJAX done', textStatus, jqXHR, jqXHR.getAllResponseHeaders() );
                } )
                .fail( function( jqXHR, textStatus, errorThrown ) {
                    console.log( 'AJAX failed', jqXHR.getAllResponseHeaders(), textStatus, errorThrown );
                } )
                .then( function( jqXHR, textStatus, errorThrown ) {
                    console.log( 'AJAX after finished', jqXHR, textStatus, errorThrown );
                } );

            });
    } );
} )( jQuery, ajaxexampleObject || {});
</code>```

答:
PluginBoilerplate is missing the correct handling process for this kind of usage.
This OOP WP Plugin Boilerplate does it much better, and provides loader classes for admin and client.</p>

Body:
Using PluginBoilerplate to write a plugin.
I need to make an ajax call.

I added to main plugin.php file, class to register scripts and handle ajax calls.

if ( ! class_exists( 'PoorMansNameSpaceAJAX' ) ) {

class PoorMansNameSpaceAJAX{
    public static $instance = null;
    public $nonce = '';
    public $name = 'ajaxexample';
    public static function getInstance()
    {
        null === self::$instance AND self::$instance = new self;
        return self::$instance;
    }
    public function __construct(){
        # Could as well be: wp_enqueue_scripts or login_enqueue_scripts
        add_action( 'admin_enqueue_scripts', array( $this, 'scriptsEnqueue' ) );
        # Logged in users:
        add_action( 'wp_loaded', array( $this, 'scriptsRegister' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'scriptsLocalize' ) );
        add_action( 'admin_init', array( $this, 'ajaxRegister' ) );

    }
    public function scriptsRegister( $page ){
        $file = 'page-1.js';
        wp_register_script(
            $this->name ,
            WPBP_URLPATH . '/app/files/js/' . $file ,
            array('jquery')
        );
    }
    public function scriptsEnqueue( $page ){

        wp_enqueue_script( $this->name );
    }

    public function ajaxRegister() {
        add_action( "wp_ajax_{$this->name}_action",  array($this, 'ajaxexample'), '1' );
    }

    public function scriptsLocalize( $page ){
        wp_localize_script( $this->name, "{$this->name}Object", array(
            'ajaxurl'          => admin_url( 'admin-ajax.php' ),
            'action'           => "{$this->name}_action"
        ) );
    }

   public function ajaxexample(){
        ob_clean();

        echo json_encode( array(
            'success' => true
        ) );
        wp_die();
    }
}
}

the class being called after vendor/autoload.php is included.

the main issue is that although the script is successfully registered, enqueued and localized, the ajax callback function is not taking action.

ajax call is returning empty response.

( function( $, plugin ) {
           $(document).ready( function() {

            $('#moreroles').on('click', function(event) {
                event.preventDefault();
                /* Act on the event */
                var data = plugin;
                $.ajax({
                    url: plugin.ajax_url,
                    data: data,
                    beforeSend : function( d ) {
                        console.log( 'Before send', d );
                     }
                })
                .done( function( response, textStatus, jqXHR ) {
                    console.log( 'AJAX done', textStatus, jqXHR, jqXHR.getAllResponseHeaders() );
                } )
                .fail( function( jqXHR, textStatus, errorThrown ) {
                    console.log( 'AJAX failed', jqXHR.getAllResponseHeaders(), textStatus, errorThrown );
                } )
                .then( function( jqXHR, textStatus, errorThrown ) {
                    console.log( 'AJAX after finished', jqXHR, textStatus, errorThrown );
                } );

            });
    } );
} )( jQuery, ajaxexampleObject || {});


问:
joining two tables using CTE
I have two queries return following output: T1 and T2

Now I would like to join both tables on the T1.CMonth and T2.DueMonth fields.

The Final output should be as shown in the png.

The query for T1:

SELECT        WorkManagementAsset.AssetCategory, CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4), WorkItem.CompleteDate, 120) AS CMonth,
                           COUNT(CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4), WorkItem.CompleteDate, 120)) AS Total_Complete
  FROM            WorkManagementAsset INNER JOIN
                           WorkOrder ON WorkManagementAsset.Oid = WorkOrder.Asset INNER JOIN
                           WorkItem ON WorkOrder.Oid = WorkItem.WorkOrder INNER JOIN
                           InspectionDefectItem ON WorkItem.DefectItem = InspectionDefectItem.Oid AND WorkItem.Oid = InspectionDefectItem.WorkItem
  WHERE        (NOT (InspectionDefectItem.DefectGroupName LIKE N'Re%'))
  GROUP BY WorkManagementAsset.AssetCategory, CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4), WorkItem.CompleteDate, 120)
  HAVING        (WorkManagementAsset.AssetCategory = N'sealedroads') AND (NOT (CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4),
                           WorkItem.CompleteDate, 120) IS NULL))

The Query for T2:

SELECT        WorkManagementAsset.AssetCategory, CONVERT(CHAR(4),
  WorkItem.DueDate, 100) + CONVERT(CHAR(4), WorkItem.DueDate, 120) AS
  DueMonth,
                           COUNT(CONVERT(CHAR(4), WorkItem.DueDate, 100) + CONVERT(CHAR(4), WorkItem.DueDate, 120)) AS Total_DUE FROM            WorkManagementAsset INNER JOIN
                           WorkOrder ON WorkManagementAsset.Oid = WorkOrder.Asset INNER JOIN
                           WorkItem ON WorkOrder.Oid = WorkItem.WorkOrder INNER JOIN
                           InspectionDefectItem ON WorkItem.DefectItem = InspectionDefectItem.Oid AND WorkItem.Oid =
  InspectionDefectItem.WorkItem WHERE        (NOT
  (InspectionDefectItem.DefectGroupName LIKE N'Re%')) GROUP BY
  WorkManagementAsset.AssetCategory, CONVERT(CHAR(4), WorkItem.DueDate,
  100) + CONVERT(CHAR(4), WorkItem.DueDate, 120) HAVING

  (WorkManagementAsset.AssetCategory = N'sealedroads') AND
  (CONVERT(CHAR(4), WorkItem.DueDate, 100) + CONVERT(CHAR(4),
  WorkItem.DueDate, 120) <> '0')

Any help would be highly appreciated.
Thanks

Tables and Output

答:
This

```<code>WITH T1 AS
(
  SELECT
    WorkManagementAsset.AssetCategory,
    CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4), WorkItem.CompleteDate, 120) AS CMonth,
    COUNT(CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4), WorkItem.CompleteDate, 120)) AS Total_Complete
  FROM WorkManagementAsset
  INNER JOIN WorkOrder
    ON WorkManagementAsset.Oid = WorkOrder.Asset
  INNER JOIN WorkItem
    ON WorkOrder.Oid = WorkItem.WorkOrder
  INNER JOIN InspectionDefectItem
    ON WorkItem.DefectItem = InspectionDefectItem.Oid AND WorkItem.Oid = InspectionDefectItem.WorkItem
  WHERE (NOT (InspectionDefectItem.DefectGroupName LIKE N'Re%'))
  GROUP BY
    WorkManagementAsset.AssetCategory,
    CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4), WorkItem.CompleteDate, 120)
  HAVING (WorkManagementAsset.AssetCategory = N'sealedroads')
  AND (NOT (CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4), WorkItem.CompleteDate, 120) IS NULL))
),
T2 AS
(
  SELECT
    WorkManagementAsset.AssetCategory,
    CONVERT(CHAR(4), WorkItem.DueDate, 100) + CONVERT(CHAR(4), WorkItem.DueDate, 120) AS DueMonth,
    COUNT(CONVERT(CHAR(4), WorkItem.DueDate, 100) + CONVERT(CHAR(4), WorkItem.DueDate, 120)) AS Total_DUE
  FROM WorkManagementAsset
  INNER JOIN WorkOrder
    ON WorkManagementAsset.Oid = WorkOrder.Asset
  INNER JOIN WorkItem
    ON WorkOrder.Oid = WorkItem.WorkOrder
  INNER JOIN InspectionDefectItem
    ON WorkItem.DefectItem = InspectionDefectItem.Oid
    AND WorkItem.Oid = InspectionDefectItem.WorkItem
  WHERE (NOT (InspectionDefectItem.DefectGroupName LIKE N'Re%'))
  GROUP BY WorkManagementAsset.AssetCategory,
  CONVERT(CHAR(4), WorkItem.DueDate, 100) + CONVERT(CHAR(4), WorkItem.DueDate, 120)
  HAVING (WorkManagementAsset.AssetCategory = N'sealedroads')
  AND (CONVERT(CHAR(4), WorkItem.DueDate, 100) + CONVERT(CHAR(4), WorkItem.DueDate, 120) <> '0')
)
SELECT *
FROM T1
INNER JOIN T2 ON T1.CMonth = T2.DueMonth;
</code>```

Note that this is a horrifically inefficient query for numerous reasons.

Title: joining two tables using CTE

Body:
This

WITH T1 AS
(
  SELECT
    WorkManagementAsset.AssetCategory,
    CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4), WorkItem.CompleteDate, 120) AS CMonth,
    COUNT(CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4), WorkItem.CompleteDate, 120)) AS Total_Complete
  FROM WorkManagementAsset
  INNER JOIN WorkOrder
    ON WorkManagementAsset.Oid = WorkOrder.Asset
  INNER JOIN WorkItem
    ON WorkOrder.Oid = WorkItem.WorkOrder
  INNER JOIN InspectionDefectItem
    ON WorkItem.DefectItem = InspectionDefectItem.Oid AND WorkItem.Oid = InspectionDefectItem.WorkItem
  WHERE (NOT (InspectionDefectItem.DefectGroupName LIKE N'Re%'))
  GROUP BY
    WorkManagementAsset.AssetCategory,
    CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4), WorkItem.CompleteDate, 120)
  HAVING (WorkManagementAsset.AssetCategory = N'sealedroads')
  AND (NOT (CONVERT(CHAR(4), WorkItem.CompleteDate, 100) + CONVERT(CHAR(4), WorkItem.CompleteDate, 120) IS NULL))
),
T2 AS
(
  SELECT
    WorkManagementAsset.AssetCategory,
    CONVERT(CHAR(4), WorkItem.DueDate, 100) + CONVERT(CHAR(4), WorkItem.DueDate, 120) AS DueMonth,
    COUNT(CONVERT(CHAR(4), WorkItem.DueDate, 100) + CONVERT(CHAR(4), WorkItem.DueDate, 120)) AS Total_DUE
  FROM WorkManagementAsset
  INNER JOIN WorkOrder
    ON WorkManagementAsset.Oid = WorkOrder.Asset
  INNER JOIN WorkItem
    ON WorkOrder.Oid = WorkItem.WorkOrder
  INNER JOIN InspectionDefectItem
    ON WorkItem.DefectItem = InspectionDefectItem.Oid
    AND WorkItem.Oid = InspectionDefectItem.WorkItem
  WHERE (NOT (InspectionDefectItem.DefectGroupName LIKE N'Re%'))
  GROUP BY WorkManagementAsset.AssetCategory,
  CONVERT(CHAR(4), WorkItem.DueDate, 100) + CONVERT(CHAR(4), WorkItem.DueDate, 120)
  HAVING (WorkManagementAsset.AssetCategory = N'sealedroads')
  AND (CONVERT(CHAR(4), WorkItem.DueDate, 100) + CONVERT(CHAR(4), WorkItem.DueDate, 120) <> '0')
)
SELECT *
FROM T1
INNER JOIN T2 ON T1.CMonth = T2.DueMonth;

Note that this is a horrifically inefficient query for numerous reasons.


问:
Linking CSS to HTML background color
I am using node.js to run a local website and am having trouble linking the css to html.

The html is:

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

<head>
    <title> Name </title>
    <meta charset="utf-8"/>
    <link rel="stylesheet" type="text/css" href="style.css" />

</head>

<body id="background">
    <h1> My Website </h1>
    <span style="float:right">
    <a href = "https://google.com/"> Google </a>
    </span>
</body>
</code>```

and css is:

```<code>#background {
  background-color: #0099FF;
}
</code>```

I have not been able to view the effects of the css on the website and am not able to change the background color.

I have checked online resources and it seems as if the syntax is correct. The css file style.css is in the same directory as the html. The html is working on the local website but not the css.

update: i am adding the app.js file

```<code>var http = require('http'),
    fs = require('fs');

fs.readFile('./header.html', function (err, html) {
    if (err) {
        throw err;
    }
    http.createServer(function(request, response) {
        response.writeHeader(200, {"Content-Type": "text/html"});
        response.write(html);
        response.end();
    }).listen(8080);
});
</code>```

答:
Try putting this code at the line under your title tag

```<code><base href="/">
</code>```

This thread might help you more

Title: Linking CSS to HTML background color

Body:
I am using node.js to run a local website and am having trouble linking the css to html.

The html is:

<!DOCTYPE html>

    <title> Name </title>
    <meta charset="utf-8"/>
    <link rel="stylesheet" type="text/css" href="style.css" />

 My Website

     Google

and css is:

#background {
  background-color: #0099FF;
}

I have not been able to view the effects of the css on the website and am not able to change the background color.

I have checked online resources and it seems as if the syntax is correct. The css file style.css is in the same directory as the html. The html is working on the local website but not the css.

update: i am adding the app.js file

var http = require('http'),
    fs = require('fs');

fs.readFile('./header.html', function (err, html) {
    if (err) {
        throw err;
    }
    http.createServer(function(request, response) {
        response.writeHeader(200, {"Content-Type": "text/html"});
        response.write(html);
        response.end();
    }).listen(8080);
});

Body:
Try putting this code at the line under your title tag

<base href="/">

This thread might help you more


问:
How do you quickly identify object structure in node?
Is there a way to quickly identify object structure in Node?  I have the following code below, which uses the spotify npm package

```<code>// *****************  Code for SPOTIFY  *************************

// Return Artist, Song Name, a preview link of the song from Spotify, and the albumn the song is from

//  Search for text variable on spotify.  Console log data

if (nodeArgs=="spotify-this-song") {

spotify.search({ type: 'track', query: text }, function(err, data) {
    if ( err ) {
        console.log('Error occurred: ' + err);
        return;
    }
    console.log(JSON.stringify(data, null, 2));
});

};
</code>```

This returns the data, but it's difficult for me (a new coder) to determine the object levels and to output the information I'm looking for (Artist, Song Name, a preview link of the song from Spotify, the albumn, etc)

Is there an easier way to graphically see the object structure?

Thanks in advance for your help!

答:
There are a couple of different console commands that format the data differently.  A couple that might be useful for an object are:

```<code>console.dir(data);

console.table(data);
</code>```

If you're using node version 6.3 or greater you can use the --inspect parameter to debug the app in your browser: $ node --inspect index.js and then set a break-point to take a closer look at the variable.

Body:
Is there a way to quickly identify object structure in Node?  I have the following code below, which uses the spotify npm package

// *****************  Code for SPOTIFY  *************************

// Return Artist, Song Name, a preview link of the song from Spotify, and the albumn the song is from

//  Search for text variable on spotify.  Console log data

if (nodeArgs=="spotify-this-song") {

spotify.search({ type: 'track', query: text }, function(err, data) {
    if ( err ) {
        console.log('Error occurred: ' + err);
        return;
    }
    console.log(JSON.stringify(data, null, 2));
});

};

This returns the data, but it's difficult for me (a new coder) to determine the object levels and to output the information I'm looking for (Artist, Song Name, a preview link of the song from Spotify, the albumn, etc)

Is there an easier way to graphically see the object structure?

Thanks in advance for your help!

Body:
There are a couple of different console commands that format the data differently.  A couple that might be useful for an object are:

console.dir(data);

console.table(data);

If you're using node version 6.3 or greater you can use the --inspect parameter to debug the app in your browser: $ node --inspect index.js and then set a break-point to take a closer look at the variable.


问:
PHP Remove empty value from array with unset not working correctly
I have a string containing sentences. I wish to break these sentences into an array, then modify each array item, including removing any array items that are empty.

Here's what I have:

```<code>//Explode string by dot
$items_array = explode(".", $raw_data);

//Loop through the array
foreach ($items_array as $i => $item) {

  //Remove any whitespace at front of item
  $item= ltrim($item);

  //Check if array item is empty and unset
  if($item === NULL){
    unset($items_array[$i]);
  }

  //Reinstate the dot
  $item .= '.';
}
</code>```

However, this does not work. I see extra '.' and if I put a print(strlen($item)); within the loop (after the unset) I see a few 0 results.

I know the if condition is being met because if I put a print in there it will trigger the same amount of times a 0 appears, eg:

```<code> if($item === NULL){
      print("no value");
      unset($raw_inclusions[$i]);
    }
</code>```

Have I done something wrong here?

Example $raw_data string. Assume I have no control over what is placed here.

```<code>$raw_data = "Brown fox. Lazy dog."
</code>```

Expected/desired result:

```<code>$items_array = array("Brown fox.", "Lazy dog.");
</code>```

Current result:

```<code>$items_array = array("Brown fox.", "Lazy dog.", ".");
</code>```

答:
It is unclear what you want to achieve, but following may help you further.

```<code>$raw_data = "Brown fox. Lazy dog.";
$items_array = preg_split('/(?<=[.?!])\s+(?=[a-z0-9])/i', $raw_data);

$sentences = new ArrayIterator($items_array);
for ($sentences->rewind(); $sentences->valid(); $sentences->next()) {
  // Do something with sentence
  print $sentences->current() . "\n";
}
</code>```

And your approach to work it should look something like

```<code>//Explode string by dot
$items_array = explode(".", $raw_data);

//Loop through the array and pass sentence by reference
foreach ($items_array as $i => &$item) {

  //Remove any whitespace at front of item
  $item = ltrim($item);

  //Check if array item is empty and unset (and continue)
  if(empty($item)){
    unset($items_array[$i]);
    continue;
  }
  // Reinstate the dot
  $item .= '.';
}
</code>```

Body:
I have a string containing sentences. I wish to break these sentences into an array, then modify each array item, including removing any array items that are empty.

Here's what I have:

//Explode string by dot
$items_array = explode(".", $raw_data);

//Loop through the array
foreach ($items_array as $i => $item) {

  //Remove any whitespace at front of item
  $item= ltrim($item);

  //Check if array item is empty and unset
  if($item === NULL){
    unset($items_array[$i]);
  }

  //Reinstate the dot
  $item .= '.';
}

However, this does not work. I see extra '.' and if I put a print(strlen($item)); within the loop (after the unset) I see a few 0 results.

I know the if condition is being met because if I put a print in there it will trigger the same amount of times a 0 appears, eg:

 if($item === NULL){
      print("no value");
      unset($raw_inclusions[$i]);
    }

Have I done something wrong here?

Example $raw_data string. Assume I have no control over what is placed here.

$raw_data = "Brown fox. Lazy dog."

Expected/desired result:

$items_array = array("Brown fox.", "Lazy dog.");

Current result:

$items_array = array("Brown fox.", "Lazy dog.", ".");

Body:
It is unclear what you want to achieve, but following may help you further.

$raw_data = "Brown fox. Lazy dog.";
$items_array = preg_split('/(?<=[.?!])\s+(?=[a-z0-9])/i', $raw_data);

$sentences = new ArrayIterator($items_array);
for ($sentences->rewind(); $sentences->valid(); $sentences->next()) {
  // Do something with sentence
  print $sentences->current() . "\n";
}

And your approach to work it should look something like

//Explode string by dot
$items_array = explode(".", $raw_data);

//Loop through the array and pass sentence by reference
foreach ($items_array as $i => &$item) {

  //Remove any whitespace at front of item
  $item = ltrim($item);

  //Check if array item is empty and unset (and continue)
  if(empty($item)){
    unset($items_array[$i]);
    continue;
  }
  // Reinstate the dot
  $item .= '.';
}


问:
translate category attributes in magento backend
I can translate product attributes in the backend by editing the attribute label.
Is it possible to do the same for category attributes?
Is there another way to translate them?

Thanks

答:
You can edit the value of a category's attributes for one store at a time by picking that store from the "Choose Store View" drop-down. This restricts your changes to the store you are editing.

Many things can be translated on both the frontend and backend with inline translation.

ContentLicense: CC BY-SA 2.5


问:
API Gateway CLI Lambda permission (add-permission)
After going to tons of pages (including some SO ones) suggesting some advice (see list below), I am still not able to give my APIGateway access to execute a newly added Lambda function via the AWS CLI Command Line tool.

i.e. I'm trying to replicate this:

I've created a new endpoint, with the following integration setup:

As soon as I try and test it (from within the API Gateway Console), I get this

```<code><AccessDeniedException>
  <Message>Unable to determine service/operation name to be authorized</Message>
</AccessDeniedException>
</code>```

I know that this is because, although I have added the lambda function to  the method, the APIGateway policy has still not been updated (image 1), hence, there are permission issues.

If I re-add the function and allow the permissions automatically (via the AWS GUI) the testing and execution works fine.

My current CLI command I am trying to execute is this (through PS):

```<code>aws lambda add-permission --function-name xx-url --statement-id apigateway-perm-1 --action lambda:InvokeFunction --principal apigateway.amazonaws.com --s
ource-arn "arn:aws:execute-api:{REGION}:{AWS_ACCOUNT_ID}:{API_ID}/*/*"
</code>```

I have tried multiple versions of the above arn address (including /*/* | /{STAGE}/{METHOD} | /{STAGE}/{METHOD}/{RESOURCE})

I've also tried deploying the API before and after these changes, with no effect?

PS - I've also read the suggestion of changing the integration type of the function to a POST (see this URL), but my requirement is to have a GET method, also - adding this GET method manually through the console works fine, hence, so should doing the same through the CLI tool.

URL list (if anyone else is look for some resources on this issue / topic):

http://interworks.com.mk

docs AWS

docs AWS #2

remove-permission

UPDATE #1

I can also confirm that, after comparing the newly created get-policy against an existing, working one - they seem almost identical (just named differently):

AWS CLI command used: aws lambda get-policy --function-name {FunctionName}

Result of already working policy vs. the newly created one:

This makes me suspect it could be an additional step I'm missing.

EDIT (per request)

Test screenshot - this log goes on to display the AccessDeniedException error.

Log as text (made a little shorter for readability):

Execution log for request test-request
  Tue Mar 28 22:59:40 UTC 2017 : Starting execution for request: test-invoke-request
  Tue Mar 28 22:59:40 UTC 2017 : HTTP Method: GET, Resource Path: /api/v1/{path}
  Tue Mar 28 22:59:40 UTC 2017 : Method request path: {}
  Tue Mar 28 22:59:40 UTC 2017 : Method request query string: {fileName=x.doc}
  Tue Mar 28 22:59:40 UTC 2017 : Method request headers: {}
  Tue Mar 28 22:59:40 UTC 2017 : Method request body before transformations:
  Tue Mar 28 22:59:40 UTC 2017 : Endpoint request URI: https://lambda.ap-southeast-2.amazonaws.com/2015-03-31/functions/arn:aws:lambda:ap-southeast-2:{accountid}:function:xx-url/invocations
  Tue Mar 28 22:59:40 UTC 2017 : Endpoint request headers: {X-Amz-Date=20170328T240Z, x-amzn-apigateway-api-id={resouceId}, Accept=application/json, Access-Control-Allow-Origin=*, User-Agent=AmazonAPIGateway_f, Host=lambda.ap-southeast-2.amazonaws.com, X-Amz-Content-Sha256=93438097f7627fe6203432b05e2257de86b32f74f8306, X-Amzn-Trace-Id=Root=1-58daeadc-bdd8f80d35834164c70, x-amzn-lambda-integration-tag=test-request, Authorization=*********************************************d309e7, X-Amz-Source-Arn=arn:aws:execute-api:ap-southeast-2:{AccountId}:{resourceId}/null/GET/api/v1/{path}, X-Amz-Security-Token=FQoDYXdzEDcaDAzSjIbAbD9j0wBjWFBxP++dR0+CGiK3flLOatlCr2 [TRUNCATED]
  Tue Mar 28 22:59:40 UTC 2017 : Endpoint request body after transformations: {"resource":"/api/v1/{path}","path":"/api/v1/{path}","httpMethod":"GET","headers":null,"queryStringParameters":{"fileName":"x.doc"},"pathParameters":null,"stageVariables":null,"requestContext":{"accountId":"{AccountId}","resourceId":"{AccountId}:{resourceId}","stage":"test-invoke-stage","requestId":"test-invoke-request","identity":{"cognitoIdentityPoolId":null,"accountId""{resourceId}","cognitoIdentityId":null,"caller":"ABPPLGO4:","apiKey":"test-invoke-api-key","sourceIp":"test-invoke-source-ip","accessKey":"ASHYYQ","cognitoAuthenticationType":null,"cognitoAuthenticationProvider":null,"userArn":"arn:aws:sts::111:assumed-role/AWS-Admins/{name}","userAgent":"Apache-HttpClient/4.5.x (Java/1.8.0_112)","user":"AROZBPPLGO4:{name}"},"resourcePath":"/api/v1/{path}","httpMethod":"GET","apiId":"{resourceId}"},"body":null,"isBase64Encoded":false}
  Tue Mar 28 22:59:40 UTC 2017 : Endpoint response body before transformations:

<AccessDeniedException>
  <Message>Unable to determine service/operation name to be authorized</Message>
</AccessDeniedException>

Tue Mar 28 22:59:40 UTC 2017 : Endpoint response headers: {x-amzn-RequestId=39398a3e-140a-11e7-92a3-3fdc0fbb61c2, Connection=keep-alive, Content-Length=130, Date=Tue, 28 Mar 2017 22:59:39 GMT}
  Tue Mar 28 22:59:40 UTC 2017 : Execution failed due to configuration error: Malformed Lambda proxy response
  Tue Mar 28 22:59:40 UTC 2017 : Method completed with status: 502

The fact that this ends up reading Malformed Lambda proxy response is not the issue - I have proven it by re-selecting the lambda function manually, letting the permissions be applied, retest immediately and all works fine, the Lambda is not even getting invoked.

答:
To summarize the debugging from the chat:

The GET method was created with the incorrect http method for Lambda, GET. This caused Lambda to not be able to interpret the request from API Gateway, generating the XML error response. The XML error response is not a valid JSON proxy response, and generated a 502 as a result.

The console is adding the necessary permissions and resetting the http method to POST, hence why it is successful after using the console.

Body:
After going to tons of pages (including some SO ones) suggesting some advice (see list below), I am still not able to give my APIGateway access to execute a newly added Lambda function via the AWS CLI Command Line tool.

i.e. I'm trying to replicate this:

I've created a new endpoint, with the following integration setup:

As soon as I try and test it (from within the API Gateway Console), I get this

<AccessDeniedException>
  <Message>Unable to determine service/operation name to be authorized</Message>
</AccessDeniedException>

I know that this is because, although I have added the lambda function to  the method, the APIGateway policy has still not been updated (image 1), hence, there are permission issues.

If I re-add the function and allow the permissions automatically (via the AWS GUI) the testing and execution works fine.

My current CLI command I am trying to execute is this (through PS):

aws lambda add-permission --function-name xx-url --statement-id apigateway-perm-1 --action lambda:InvokeFunction --principal apigateway.amazonaws.com --s
ource-arn "arn:aws:execute-api:{REGION}:{AWS_ACCOUNT_ID}:{API_ID}/*/*"

I have tried multiple versions of the above arn address (including /*/* | /{STAGE}/{METHOD} | /{STAGE}/{METHOD}/{RESOURCE})

I've also tried deploying the API before and after these changes, with no effect?

PS - I've also read the suggestion of changing the integration type of the function to a POST (see this URL), but my requirement is to have a GET method, also - adding this GET method manually through the console works fine, hence, so should doing the same through the CLI tool.

URL list (if anyone else is look for some resources on this issue / topic):

http://interworks.com.mk

docs AWS

docs AWS #2

remove-permission

UPDATE #1

I can also confirm that, after comparing the newly created get-policy against an existing, working one - they seem almost identical (just named differently):

AWS CLI command used: aws lambda get-policy --function-name {FunctionName}

Result of already working policy vs. the newly created one:

This makes me suspect it could be an additional step I'm missing.

EDIT (per request)

Test screenshot - this log goes on to display the AccessDeniedException error.

Log as text (made a little shorter for readability):

Execution log for request test-request
  Tue Mar 28 22:59:40 UTC 2017 : Starting execution for request: test-invoke-request
  Tue Mar 28 22:59:40 UTC 2017 : HTTP Method: GET, Resource Path: /api/v1/{path}
  Tue Mar 28 22:59:40 UTC 2017 : Method request path: {}
  Tue Mar 28 22:59:40 UTC 2017 : Method request query string: {fileName=x.doc}
  Tue Mar 28 22:59:40 UTC 2017 : Method request headers: {}
  Tue Mar 28 22:59:40 UTC 2017 : Method request body before transformations:
  Tue Mar 28 22:59:40 UTC 2017 : Endpoint request URI: https://lambda.ap-southeast-2.amazonaws.com/2015-03-31/functions/arn:aws:lambda:ap-southeast-2:{accountid}:function:xx-url/invocations
  Tue Mar 28 22:59:40 UTC 2017 : Endpoint request headers: {X-Amz-Date=20170328T240Z, x-amzn-apigateway-api-id={resouceId}, Accept=application/json, Access-Control-Allow-Origin=*, User-Agent=AmazonAPIGateway_f, Host=lambda.ap-southeast-2.amazonaws.com, X-Amz-Content-Sha256=93438097f7627fe6203432b05e2257de86b32f74f8306, X-Amzn-Trace-Id=Root=1-58daeadc-bdd8f80d35834164c70, x-amzn-lambda-integration-tag=test-request, Authorization=*********************************************d309e7, X-Amz-Source-Arn=arn:aws:execute-api:ap-southeast-2:{AccountId}:{resourceId}/null/GET/api/v1/{path}, X-Amz-Security-Token=FQoDYXdzEDcaDAzSjIbAbD9j0wBjWFBxP++dR0+CGiK3flLOatlCr2 [TRUNCATED]
  Tue Mar 28 22:59:40 UTC 2017 : Endpoint request body after transformations: {"resource":"/api/v1/{path}","path":"/api/v1/{path}","httpMethod":"GET","headers":null,"queryStringParameters":{"fileName":"x.doc"},"pathParameters":null,"stageVariables":null,"requestContext":{"accountId":"{AccountId}","resourceId":"{AccountId}:{resourceId}","stage":"test-invoke-stage","requestId":"test-invoke-request","identity":{"cognitoIdentityPoolId":null,"accountId""{resourceId}","cognitoIdentityId":null,"caller":"ABPPLGO4:","apiKey":"test-invoke-api-key","sourceIp":"test-invoke-source-ip","accessKey":"ASHYYQ","cognitoAuthenticationType":null,"cognitoAuthenticationProvider":null,"userArn":"arn:aws:sts::111:assumed-role/AWS-Admins/{name}","userAgent":"Apache-HttpClient/4.5.x (Java/1.8.0_112)","user":"AROZBPPLGO4:{name}"},"resourcePath":"/api/v1/{path}","httpMethod":"GET","apiId":"{resourceId}"},"body":null,"isBase64Encoded":false}
  Tue Mar 28 22:59:40 UTC 2017 : Endpoint response body before transformations:

<AccessDeniedException>
  <Message>Unable to determine service/operation name to be authorized</Message>
</AccessDeniedException>

Tue Mar 28 22:59:40 UTC 2017 : Endpoint response headers: {x-amzn-RequestId=39398a3e-140a-11e7-92a3-3fdc0fbb61c2, Connection=keep-alive, Content-Length=130, Date=Tue, 28 Mar 2017 22:59:39 GMT}
  Tue Mar 28 22:59:40 UTC 2017 : Execution failed due to configuration error: Malformed Lambda proxy response
  Tue Mar 28 22:59:40 UTC 2017 : Method completed with status: 502

The fact that this ends up reading Malformed Lambda proxy response is not the issue - I have proven it by re-selecting the lambda function manually, letting the permissions be applied, retest immediately and all works fine, the Lambda is not even getting invoked.


问:
JQuery get checkbox id
I'm trying to get an id of a checkbox.
There are several checkboxes on a page that have ids like: channel_left_restream_ids_42, channel_left_restream_ids_44, etc. I need to handle an event when one of those checked and get an id of the checked.

So for checkbox with code <input type="checkbox" value="42" checked="checked" name="channel[left_restream_ids][]" id="channel_left_restream_ids_42"> and coffescript like this:

```<code>$("input[id*=channel_left_restream_ids]").change (e) =>
  alert($(this).attr("id"))
</code>```

I can't get it work. It says undefined. I've tried a lot of alternatives, none worked. Where am I doing a mistake?

JSFiddle is here

答:
Unexpectedly, the problem was not in jQuery or smth like this.
That was simply a problem of a bold array in my Coffee.
Replacing $("input[id*=channel_left_restream_ids]").change (e) => with $("input[id*=channel_left_restream_ids]").change (e) -> (difference is only with an array at the end of the line) did the trick.

Title: JQuery get checkbox id

Body:
I'm trying to get an id of a checkbox.
There are several checkboxes on a page that have ids like: channel_left_restream_ids_42, channel_left_restream_ids_44, etc. I need to handle an event when one of those checked and get an id of the checked.

So for checkbox with code <input type="checkbox" value="42" checked="checked" name="channel[left_restream_ids][]" id="channel_left_restream_ids_42"> and coffescript like this:

$("input[id*=channel_left_restream_ids]").change (e) =>
  alert($(this).attr("id"))

I can't get it work. It says undefined. I've tried a lot of alternatives, none worked. Where am I doing a mistake?

JSFiddle is here


问:
Pushing icon to the right of text in Bootstrap
Using Bootstrap 3.3.7, I'm trying to create a two-column row with the following content and characteristics:

Left column (col-sm-9) that contains text

Right column (col-sm-3) that contains one horizontally and vertically centered image

Non-full-height vertical divider in between those two divs

I am having trouble getting the entire row to display with a minimum of 980 pixels and created a fiddle here:

Originally, the image div container on the right was only as tall as the image itself, so I added the following code to force same heights, but that caused the width to be reduced to the size of the contents within each div:

```<code>[class*="ccol-"] {
float: none;
display: table-cell;
vertical-align: middle;
}
</code>```

I was wondering how other Bootstrappers might code out a simple row with text on the left, a vertical divider, and an image on the right.

答:
I'd recommend flexbox to center vertically.

@media (min-width: 768px) {
  .previewWrapper .row {
    display: flex;
  }
  .previewWrapper .row > * {
    flex-grow: 1;
    display: flex;
    flex-direction:column;
    justify-content: center;
  }
}
```

Updated snippet. Don't forget to autoprefix. Please note I made it 9-3, as you requested in question. If you want to keep it 10-2, here it is.

Body:
Using Bootstrap 3.3.7, I'm trying to create a two-column row with the following content and characteristics:

Left column (col-sm-9) that contains text

Right column (col-sm-3) that contains one horizontally and vertically centered image

Non-full-height vertical divider in between those two divs

I am having trouble getting the entire row to display with a minimum of 980 pixels and created a fiddle here:

Originally, the image div container on the right was only as tall as the image itself, so I added the following code to force same heights, but that caused the width to be reduced to the size of the contents within each div:

[class*="ccol-"] {
float: none;
display: table-cell;
vertical-align: middle;
}

I was wondering how other Bootstrappers might code out a simple row with text on the left, a vertical divider, and an image on the right.

Body:
I'd recommend flexbox to center vertically.

@media (min-width: 768px) {
  .previewWrapper .row {
    display: flex;
  }
  .previewWrapper .row > * {
    flex-grow: 1;
    display: flex;
    flex-direction:column;
    justify-content: center;
  }
}

Updated snippet. Don't forget to autoprefix. Please note I made it 9-3, as you requested in question. If you want to keep it 10-2, here it is.


问:
Android, java rx, asynchronous
I have a screen that shows a list of items.

First I want to show the elements from the local database.

After the  user is viewing the local elements, check the internet and
update  them (if the device has internet).

I have the following code fragments

```<code>Observable<Data> fetchFromdisk = ...;
Observable<Data> fetchFromNetwork = ...;

Observable<Data>  fetchData= Observable.concat (fetchFromdisk ,fetchFromNetwork);
</code>```

Then I'm doing the following

```<code>mSubscriptions.clear();
Subscription subscription = fetchData
        .subscribeOn(mSchedulerProvider.computation())
        .observeOn(mSchedulerProvider.ui())
        .subscribe(
                new Subscriber<List<Data>>() {
                    @Override
                    public void onCompleted() {
                        view.setLoadingIndicator(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        processError(e);
                    }

                    @Override
                    public void onNext(List<Data> data) {
                        processData(data);
                    }
                }

        );
mSubscriptions.add(subscription);
</code>```

But what is happening is that fetchFromdisk is first run, then FetchFromNetwork is executed. Once emitting elements ends the execution of ProcessData begins.

That is quite the opposite of what I want to achieve.
I want to prioritize the user to see the data quickly and then go to the internet.
what am I doing wrong?

答:
It might be because your subscriber returns a List rather than Data?

Are you sure you are using the right observer? The concat operator should return a Observer with the same element.

```<code>    Observable<String> a = Observable.just("a");
    Observable<String> b = Observable.just("b");

    Observable<String> ab = Observable.concat(a,b);

    ab.subscribe(new Subscriber<String>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onNext(String s) {
            Log.d("onNext", s);
        }
    });
</code>```

Title: Android, java rx, asynchronous

Body:
I have a screen that shows a list of items.

First I want to show the elements from the local database.

After the  user is viewing the local elements, check the internet and
update  them (if the device has internet).

I have the following code fragments

Observable<Data> fetchFromdisk = ...;
Observable<Data> fetchFromNetwork = ...;

Observable<Data>  fetchData= Observable.concat (fetchFromdisk ,fetchFromNetwork);

Then I'm doing the following

mSubscriptions.clear();
Subscription subscription = fetchData
        .subscribeOn(mSchedulerProvider.computation())
        .observeOn(mSchedulerProvider.ui())
        .subscribe(
                new Subscriber<List<Data>>() {
                    @Override
                    public void onCompleted() {
                        view.setLoadingIndicator(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        processError(e);
                    }

                    @Override
                    public void onNext(List<Data> data) {
                        processData(data);
                    }
                }

        );
mSubscriptions.add(subscription);

But what is happening is that fetchFromdisk is first run, then FetchFromNetwork is executed. Once emitting elements ends the execution of ProcessData begins.

That is quite the opposite of what I want to achieve.
I want to prioritize the user to see the data quickly and then go to the internet.
what am I doing wrong?

Body:
It might be because your subscriber returns a List rather than Data?

Are you sure you are using the right observer? The concat operator should return a Observer with the same element.

    Observable<String> a = Observable.just("a");
    Observable<String> b = Observable.just("b");

    Observable<String> ab = Observable.concat(a,b);

    ab.subscribe(new Subscriber<String>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onNext(String s) {
            Log.d("onNext", s);
        }
    });


问:
Converting scraped text into Pandas data frame with BeautifulSoup
I am extracting some text from a website using the code below. I have it in the form of a string.

```<code>import requests
URL = 'https://www.instituteforsupplymanagement.org/about/MediaRoom/newsreleasedetail.cfm?ItemNumber=30655&SSO=1'
r = requests.get(URL)
page = r.text

from bs4 import BeautifulSoup
soup = BeautifulSoup(page, 'lxml')
import re

strong_el = soup.find('strong',text='WHAT RESPONDENTS ARE SAYING …')

ul_tag = strong_el.find_next_sibling('ul')
LI_TAG =''
for li_tag in ul_tag.children:

    LI_TAG += li_tag.string

print LI_TAG
</code>```

I am trying to create a data frame with 2 columns: 1) Comments 2) Industry (sub-string within the brackets).
Getting some error when I tried to use StringIO as follows: 'TypeError: data argument can't be an iterator'. How can I convert these comments into a data frame?

```<code>import sys
if sys.version_info[0] < 3:
    from StringIO import StringIO
else:
    from io import StringIO

import pandas as pd

LI_TAG = StringIO(LI_TAG)
df = pd.DataFrame(LI_TAG)
</code>```

答:
It seems like the LI_TAG variable is just a long string - so you're going to have to split it up to store it in a dataframe.

```<code>import requests
URL = 'https://www.instituteforsupplymanagement.org/about/MediaRoom/newsreleasedetail.cfm?ItemNumber=30655&SSO=1'
r = requests.get(URL)
page = r.text

from bs4 import BeautifulSoup
soup = BeautifulSoup(page, 'lxml')
import re

strong_el = soup.find('strong',text='WHAT RESPONDENTS ARE SAYING …')

ul_tag = strong_el.find_next_sibling('ul')
LI_TAG =''
for li_tag in ul_tag.children:

    LI_TAG += li_tag.string

# Convert to unicode to remove quotation marks \u201c and \u201d
LI_TAG_U = unicode(LI_TAG)
comments=[]
industries=[]
for string in LI_TAG.strip().split('\n'):
    comment, industry =  string.split(u'\u201d')
    comments.append(comment.strip(u'\u201c'))
    industries.append(industry.strip(' (').strip(')'))

import pandas as pd

data = pd.DataFrame()

data['Comment']=comments
data['Industry']=industries
</code>```

Hope this works for you!

ContentLicense: CC BY-SA 4.0

Body:
I am extracting some text from a website using the code below. I have it in the form of a string.

import requests
URL = 'https://www.instituteforsupplymanagement.org/about/MediaRoom/newsreleasedetail.cfm?ItemNumber=30655&SSO=1'
r = requests.get(URL)
page = r.text

from bs4 import BeautifulSoup
soup = BeautifulSoup(page, 'lxml')
import re

strong_el = soup.find('strong',text='WHAT RESPONDENTS ARE SAYING …')

ul_tag = strong_el.find_next_sibling('ul')
LI_TAG =''
for li_tag in ul_tag.children:

    LI_TAG += li_tag.string

print LI_TAG

I am trying to create a data frame with 2 columns: 1) Comments 2) Industry (sub-string within the brackets).
Getting some error when I tried to use StringIO as follows: 'TypeError: data argument can't be an iterator'. How can I convert these comments into a data frame?

import sys
if sys.version_info[0] < 3:
    from StringIO import StringIO
else:
    from io import StringIO

import pandas as pd

LI_TAG = StringIO(LI_TAG)
df = pd.DataFrame(LI_TAG)

Body:
It seems like the LI_TAG variable is just a long string - so you're going to have to split it up to store it in a dataframe.

import requests
URL = 'https://www.instituteforsupplymanagement.org/about/MediaRoom/newsreleasedetail.cfm?ItemNumber=30655&SSO=1'
r = requests.get(URL)
page = r.text

from bs4 import BeautifulSoup
soup = BeautifulSoup(page, 'lxml')
import re

strong_el = soup.find('strong',text='WHAT RESPONDENTS ARE SAYING …')

ul_tag = strong_el.find_next_sibling('ul')
LI_TAG =''
for li_tag in ul_tag.children:

    LI_TAG += li_tag.string

# Convert to unicode to remove quotation marks \u201c and \u201d
LI_TAG_U = unicode(LI_TAG)
comments=[]
industries=[]
for string in LI_TAG.strip().split('\n'):
    comment, industry =  string.split(u'\u201d')
    comments.append(comment.strip(u'\u201c'))
    industries.append(industry.strip(' (').strip(')'))

import pandas as pd

data = pd.DataFrame()

data['Comment']=comments
data['Industry']=industries

Hope this works for you!


问:
What is the correct setting for pandas.read_csv to read a very raw CSV file with first three numbers compiled into datetime.datetime object?
To be more explicit, I have this type of data

```<code>2011,1,14, Orange  ,Buy,1500,
2011,1,19, Apple   ,Sell,1500,
2011,1,19, Banana  ,Buy,4000,
</code>```

I am trying to read it directly into DataFrame with a columns=['date','fruit', 'trade','quantity'] shape like this.

```<code>print df_grocer.date
2011-01-14 16:00:00
2011-01-19 16:00:00
2011-01-19 16:00:00
</code>```

and

```<code>print df_grocer.fruit
Orange
Apple
Banana
</code>```

Thanks in advance

答:
pd.read_csv

parse_dates : boolean or list of ints or names or list of lists or dict, default False

boolean. If True -> try parsing the index.

list of ints or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column.

list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as
  a single date column.

dict, e.g. {‘foo’ : [1, 3]} -> parse columns 1, 3 as date and call result ‘foo’

Note: A fast-path exists for iso8601-formatted dates.

```<code>from io import StringIO
import pandas as pd

txt = """2011,1,14, Orange  ,Buy,1500,
2011,1,19, Apple   ,Sell,1500,
2011,1,19, Banana  ,Buy,4000,"""

df = pd.read_csv(
    StringIO(txt),
    skipinitialspace=True,
    header=None,
    parse_dates=dict(date=[0, 1, 2]),
    usecols=[0, 1, 2, 3, 4, 5],
    names=['_', '_', '_', 'fruit', 'trade', 'quantity']
)

print(df)

        date     fruit trade  quantity
0 2011-01-14  Orange     Buy      1500
1 2011-01-19  Apple     Sell      1500
2 2011-01-19  Banana     Buy      4000
</code>```

Body:
To be more explicit, I have this type of data

2011,1,14, Orange  ,Buy,1500,
2011,1,19, Apple   ,Sell,1500,
2011,1,19, Banana  ,Buy,4000,

I am trying to read it directly into DataFrame with a columns=['date','fruit', 'trade','quantity'] shape like this.

print df_grocer.date
2011-01-14 16:00:00
2011-01-19 16:00:00
2011-01-19 16:00:00

and

print df_grocer.fruit
Orange
Apple
Banana

Thanks in advance

Body:
pd.read_csv

parse_dates : boolean or list of ints or names or list of lists or dict, default False

boolean. If True -> try parsing the index.

list of ints or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column.

list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as
  a single date column.

dict, e.g. {‘foo’ : [1, 3]} -> parse columns 1, 3 as date and call result ‘foo’

Note: A fast-path exists for iso8601-formatted dates.

from io import StringIO
import pandas as pd

txt = """2011,1,14, Orange  ,Buy,1500,
2011,1,19, Apple   ,Sell,1500,
2011,1,19, Banana  ,Buy,4000,"""

df = pd.read_csv(
    StringIO(txt),
    skipinitialspace=True,
    header=None,
    parse_dates=dict(date=[0, 1, 2]),
    usecols=[0, 1, 2, 3, 4, 5],
    names=['_', '_', '_', 'fruit', 'trade', 'quantity']
)

print(df)

        date     fruit trade  quantity
0 2011-01-14  Orange     Buy      1500
1 2011-01-19  Apple     Sell      1500
2 2011-01-19  Banana     Buy      4000


问:
Replacing one url base with another in php
I'm trying to figure out how to replace one url base with another within php.

So a function that takes "http://www.website1.com/test" and replaces the "http://www.website1.com" to make it "http://www.website2.com/test" .

This is probably a very easy quick function but i'm having trouble finding the right str_replace() to get this done.

```<code><?php
$pre_replace = "http://www.website1.com/test";
$post_replace = str_replace(
  'http://www.website1.com',
  'http://www.website2.com',
  $pre_replace);
echo $post_replace;
?>
</code>```

isn't quite working for some reason

答:
For the most reliable solution, I'd probably break the URL up using parse_url(), edit the host portion as necessary, and then put it back together.

That way, you can rely on any bugfixes that have made it into parse_url() over the years rather than reinventing the parser wheel.

Body:
I'm trying to figure out how to replace one url base with another within php.

So a function that takes "http://www.website1.com/test" and replaces the "http://www.website1.com" to make it "http://www.website2.com/test" .

This is probably a very easy quick function but i'm having trouble finding the right str_replace() to get this done.

<?php
$pre_replace = "http://www.website1.com/test";
$post_replace = str_replace(
  'http://www.website1.com',
  'http://www.website2.com',
  $pre_replace);
echo $post_replace;
?>

isn't quite working for some reason


问:
Can I display a million record in a html table in one go?
I'm currently creating a web-based system that would have a millions of data after some years (3 years = 1 million record, just guessing).

Now I have a webpage where I display all records in a html table dynamically.

If the time comes can it display these amount of data?
What are the things I need to consider?

What about hardware requirements (for the server probably)?

The set up would be a LAN set up to be use by 7 users simultaneously.

Any help would be appreciated.

Here is a my php code:
my php code

and this is the result:
Result

答:
it's not a human readable ,
you can get all data from the database is possible and saved it in an array
then make search in array and get the result what you want </p>


问:
Python asynchronous request handling while calling subprocess
I have a REST API written in Flask and using the Tornado web server.

When a request comes in, I execute a long running shell command using tornado.process.Subprocess.

Is there a way to keep handling new requests while the shell command is running, and return the result after the shell command is complete.

I am thinking

```<code>from tornado import gen
from tornado.process import Subprocess

@gen.coroutine
def callSubProcess(commandString):
    p = Subprocess(commandString)
    yield p.wait_for_exit()
    raise gen.Return(someResult)

@app.route(url, methods=['POST'])
@gen.coroutine
def process():
    result = yield callSubProcess(commandString)
    raise gen.Return(result)

http_server = HTTPServer(WSGIContainer(app))
http_server.listen(5000)
IOLoop.instance().start()
</code>```

But this doesn't seem to work:
I just get 'Future' object is not callable when making a request.  What is the problem here?

答: To use coroutines, you must use tornado.web.Application, not tornado.wsgi.WSGIContainer. Tornado does not magically give WSGI frameworks like Flask the ability to handle asynchronous operations and coroutines.

Body:
I have a REST API written in Flask and using the Tornado web server.

When a request comes in, I execute a long running shell command using tornado.process.Subprocess.

Is there a way to keep handling new requests while the shell command is running, and return the result after the shell command is complete.

I am thinking

from tornado import gen
from tornado.process import Subprocess

@gen.coroutine
def callSubProcess(commandString):
    p = Subprocess(commandString)
    yield p.wait_for_exit()
    raise gen.Return(someResult)

@app.route(url, methods=['POST'])
@gen.coroutine
def process():
    result = yield callSubProcess(commandString)
    raise gen.Return(result)

http_server = HTTPServer(WSGIContainer(app))
http_server.listen(5000)
IOLoop.instance().start()

But this doesn't seem to work:
I just get 'Future' object is not callable when making a request.  What is the problem here?


问:
Recommended DNS setup for one service running in multiple clusters?
I was reading through the external-dns proposal here https://docs.google.com/document/d/1qaTGTLpPRMqMFZo17J169BsqIfY652Miqc_xXVCYm1Y

This made me wonder about our plan for setting up DNS records for a service running in multiple kubernetes clusters.  So i wanted to solicit feedback from other cluster operators about what they are doing and see if my process is needlessly complicated or lacking.

One of the reasons for our approach is that we plan on running a given service in multiple kubernetes clusters.  For example let's say we have 2 production kubernetes clusters one in us-east-1 and one in us-west-2 and we have deployed a service named 'service' to both of these clusters (today manually in the future through federation).

Here is an image that articulates our DNS setup

Do people have other approaches for running services that span multiple clusters?   I'm hoping this will dovetail with deploying federated services and would be keen if anyone knows why this won't?

答:
I think some of this could be addressed with GEO features of Route53

https://aws.amazon.com/route53/faqs/#what_is_geo_dns


问:
Framework7 - SearchBar close keyboard
I am trying to create a custom search searchBar element using framework7. The code I have so far works and when the search button is pressed the app is redirected  to another page. The problem I have is that when the app opens the page the keyboard remains open.

Is there a way to force the keyboard to close when the button Search is pressed?
HTML:

```<code><form class="searchbar">
    <div class="searchbar-input">
        <input type="search" placeholder="Search" style=" background-image: url(img/search.png);">
        <a href="#" class="searchbar-clear"></a>
    </div>
</form>
</code>```

JS

```<code> $$('.searchbar').on("search", function (e) {
            //close the keyboard
            mainView.router.load({
                url: 'productlist.html'
            });
        });
</code>```

答: disable the searchbar before loading new page</p>

Title: Framework7 - SearchBar close keyboard

Body:
I am trying to create a custom search searchBar element using framework7. The code I have so far works and when the search button is pressed the app is redirected  to another page. The problem I have is that when the app opens the page the keyboard remains open.

Is there a way to force the keyboard to close when the button Search is pressed?
HTML:

<form class="searchbar">

        <input type="search" placeholder="Search" style=" background-image: url(img/search.png);">

</form>

JS

 $$('.searchbar').on("search", function (e) {
            //close the keyboard
            mainView.router.load({
                url: 'productlist.html'
            });
        });


问:
show only one li item when sliding list items from left to right
I am trying to make a text slider and I want to show only one li item per slide. The data in li items is being fetched from DB and inserted to DOM by JS. The problem right now is that all of the li items are showing while sliding, current elem shows at top. How I can make sure that only one li item shows per slide with css?

I tried to make the li items display: inline and float but it did not help.

```<code>#slider ul li{display: inline}
</code>```

Here is the website where I am testing. Please help me understand how I can do this or what I am doing wrong here.

答:
If you're talking about the text in the main body that rotates, you can hide all but the first li with

```<code>#slider li:not(:first-child) {
    display: none;
}
</code>```

Body:
I am trying to make a text slider and I want to show only one li item per slide. The data in li items is being fetched from DB and inserted to DOM by JS. The problem right now is that all of the li items are showing while sliding, current elem shows at top. How I can make sure that only one li item shows per slide with css?

I tried to make the li items display: inline and float but it did not help.

#slider ul li{display: inline}

Here is the website where I am testing. Please help me understand how I can do this or what I am doing wrong here.

Body:
If you're talking about the text in the main body that rotates, you can hide all but the first li with

#slider li:not(:first-child) {
    display: none;
}


问:
How do I get the name from a named tuple in python?
I create a named tuple like this:

```<code>from collections import namedtuple
spam = namedtuple('eggs', 'x, y, z')
ham = spam(1,2,3)
</code>```

Then I can access elements of ham with e.g.

```<code>>>> ham.x
1
>>> ham.z
3
</code>```

In the interpreter,

```<code>>>> ham
eggs(x=1, y=2, z=3)
</code>```

But what if I just want to get 'eggs'? The only way I've been able to think of is

```<code>>>> ham.__repr__.split('(')[0]
'eggs'
</code>```

but this seems a bit messy. Is there a cleaner way of doing it?

Why do named tuples have this 'eggs' aspect to them if it isn't possible to access it without resorting to a private method?

答:
On the topic of namedtuple attributes:

```<code> >>> ham._fields
    ('x', 'y', 'z')
</code>```

is sometimes useful to know

Body:
I create a named tuple like this:

from collections import namedtuple
spam = namedtuple('eggs', 'x, y, z')
ham = spam(1,2,3)

Then I can access elements of ham with e.g.

>>> ham.x
1
>>> ham.z
3

In the interpreter,

>>> ham
eggs(x=1, y=2, z=3)

But what if I just want to get 'eggs'? The only way I've been able to think of is

>>> ham.__repr__.split('(')[0]
'eggs'

but this seems a bit messy. Is there a cleaner way of doing it?

Why do named tuples have this 'eggs' aspect to them if it isn't possible to access it without resorting to a private method?

Body:
On the topic of namedtuple attributes:

 >>> ham._fields
    ('x', 'y', 'z')

is sometimes useful to know


问:
How can I achieve noSmooth() with the P3D renderer?
I'd like to render basic 3D shapes without any aliasing/smoothing with a PGraphics instance using the P3D renderer, but noSmooth() doesn't seem to work.

In OF I remember calling setTextureMinMagFilter(GL_NEAREST,GL_NEAREST); on a texture.

What would be the equivalent in Processing ?

I tried to use PGL:

```<code>PGL.TEXTURE_MIN_FILTER = PGL.NEAREST;
PGL.TEXTURE_MAG_FILTER = PGL.NEAREST;
</code>```

but I get a black image as the result.
If I comment PGL.TEXTURE_MIN_FILTER = PGL.NEAREST;  I can see the render, but it's interpolated, not sharp.

Here'a basic test sketch with a few things I've tried:

```<code>PGraphics buffer;
PGraphicsOpenGL pgl;

void setup() {
  size(320, 240, P3D);
  noSmooth();
  //hint(DISABLE_TEXTURE_MIPMAPS);

  //((PGraphicsOpenGL)g).textureSampling(0);

  //PGL pgl = beginPGL();
  //PGL.TEXTURE_MIN_FILTER = PGL.NEAREST;
  //PGL.TEXTURE_MAG_FILTER = PGL.NEAREST;
  //endPGL();

  buffer=createGraphics(width/8, height/8, P3D);
  buffer.noSmooth();
  buffer.beginDraw();
  //buffer.hint(DISABLE_TEXTURE_MIPMAPS);
  //((PGraphicsOpenGL)buffer).textureSampling(0);
  PGL bpgl = buffer.beginPGL();
  //PGL.TEXTURE_MIN_FILTER = PGL.NEAREST;//commenting this back in results in a blank buffer
  PGL.TEXTURE_MAG_FILTER = PGL.NEAREST;
  buffer.endPGL();
  buffer.background(0);
  buffer.stroke(255);
  buffer.line(0, 0, buffer.width, buffer.height);
  buffer.endDraw();
}
void draw() {

  image(buffer, 0, 0, width, height);
}
</code>```

(I've also posted on the Processing Forum, but no luck so far)

答:
You were actually on the right track. You were just passing the wrong value to textureSampling().

Since the documentation on PGraphicsOpenGL::textureSampling()
is a bit scarce to say the least.
I decided to peak into it using a decompiler, which lead me to
Texture::usingMipmaps().
There I was able to see the values and what they reflected (in the decompiled code).

```<code>2 = POINT
3 = LINEAR
4 = BILINEAR
5 = TRILINEAR
</code>```

Where PGraphicsOpenGL's default textureSampling is 5 (TRILINEAR).

I also later found this old comment on an issue equally confirming it.

So to get point/nearest filtering you only need to call noSmooth() on the application itself, and call textureSampling() on your PGraphics.

```<code>size(320, 240, P3D);
noSmooth();

buffer = createGraphics(width/8, height/8, P3D);
((PGraphicsOpenGL) buffer).textureSampling(2);
</code>```

So considering the above, and only including the code you used to draw the line and drawing buffer to the application. Then that gives the following desired result.

Body:
I'd like to render basic 3D shapes without any aliasing/smoothing with a PGraphics instance using the P3D renderer, but noSmooth() doesn't seem to work.

In OF I remember calling setTextureMinMagFilter(GL_NEAREST,GL_NEAREST); on a texture.

What would be the equivalent in Processing ?

I tried to use PGL:

PGL.TEXTURE_MIN_FILTER = PGL.NEAREST;
PGL.TEXTURE_MAG_FILTER = PGL.NEAREST;

but I get a black image as the result.
If I comment PGL.TEXTURE_MIN_FILTER = PGL.NEAREST;  I can see the render, but it's interpolated, not sharp.

Here'a basic test sketch with a few things I've tried:

PGraphics buffer;
PGraphicsOpenGL pgl;

void setup() {
  size(320, 240, P3D);
  noSmooth();
  //hint(DISABLE_TEXTURE_MIPMAPS);

  //((PGraphicsOpenGL)g).textureSampling(0);

  //PGL pgl = beginPGL();
  //PGL.TEXTURE_MIN_FILTER = PGL.NEAREST;
  //PGL.TEXTURE_MAG_FILTER = PGL.NEAREST;
  //endPGL();

  buffer=createGraphics(width/8, height/8, P3D);
  buffer.noSmooth();
  buffer.beginDraw();
  //buffer.hint(DISABLE_TEXTURE_MIPMAPS);
  //((PGraphicsOpenGL)buffer).textureSampling(0);
  PGL bpgl = buffer.beginPGL();
  //PGL.TEXTURE_MIN_FILTER = PGL.NEAREST;//commenting this back in results in a blank buffer
  PGL.TEXTURE_MAG_FILTER = PGL.NEAREST;
  buffer.endPGL();
  buffer.background(0);
  buffer.stroke(255);
  buffer.line(0, 0, buffer.width, buffer.height);
  buffer.endDraw();
}
void draw() {

  image(buffer, 0, 0, width, height);
}

(I've also posted on the Processing Forum, but no luck so far)

Body:
You were actually on the right track. You were just passing the wrong value to textureSampling().

Since the documentation on PGraphicsOpenGL::textureSampling()
is a bit scarce to say the least.
I decided to peak into it using a decompiler, which lead me to
Texture::usingMipmaps().
There I was able to see the values and what they reflected (in the decompiled code).

2 = POINT
3 = LINEAR
4 = BILINEAR
5 = TRILINEAR

Where PGraphicsOpenGL's default textureSampling is 5 (TRILINEAR).

I also later found this old comment on an issue equally confirming it.

So to get point/nearest filtering you only need to call noSmooth() on the application itself, and call textureSampling() on your PGraphics.

size(320, 240, P3D);
noSmooth();

buffer = createGraphics(width/8, height/8, P3D);
((PGraphicsOpenGL) buffer).textureSampling(2);

So considering the above, and only including the code you used to draw the line and drawing buffer to the application. Then that gives the following desired result.


问:
R- Autoplot function
Hi I am running a ggfortify package in R, that allows customisation of time series plots in R.

See link https://cran.r-project.org/web/packages/ggfortify/vignettes/basics.html.

The Link shows the example change of color on the plot:

```<code>library(ggfortify)
autoplot(AirPassengers, ts.colour = 'blue')
</code>```

In my code I have installed the packaged and loaded the library for ggfortify, however it doesn't display this ts.colour function as I type it.

My code:

```<code>autoplot(sales, ts.colour = 'blue')
</code>```

resembles the above, but displays it in black, with the background the style should include but no difference to plot colour or thickness.

many thanks.

答:
The ts.colour argument will only work on a time-series object. If you run str(sales) it should return something like: "Time-Series [1:144] ..."

If it doesn't then you can try to convert it with:

ts(sales, start = c(2012, 1), end = c(2016, 2), 2)

ggfortify tries to infer a lot of things from the plotted object, sales, so focus your attention there.  Good luck!

Title: R- Autoplot function

Body:
Hi I am running a ggfortify package in R, that allows customisation of time series plots in R.

See link https://cran.r-project.org/web/packages/ggfortify/vignettes/basics.html.

The Link shows the example change of color on the plot:

library(ggfortify)
autoplot(AirPassengers, ts.colour = 'blue')

In my code I have installed the packaged and loaded the library for ggfortify, however it doesn't display this ts.colour function as I type it.

My code:

autoplot(sales, ts.colour = 'blue')

resembles the above, but displays it in black, with the background the style should include but no difference to plot colour or thickness.

many thanks.


问:
Is there a native way to convert to UTC time in UniVerse 11.2.4+?
The release notes for UniVerse version 11.2.4 mention local time zone configuration, but it is in the context of auditing. This is the quote:

Local time zone configuration

Prior to UniVerse 11.2.4, the date and time data stored in the audit log records was based on UTC only.
  Beginning at UniVerse 11.2.4, UniVerse adds the date and time data
  based on local timezone to audit log records. The data is stored in
  location 19 for each record. The dictionary name for this data field
  is TZINFO. For more information, see UniVerse Security Features.

Since UniVerse seems capable of working with time zones natively, does this mean there might be a way to easily generate UTC-formatted date/time stamps from my EST/EDT values?

I am sending data to a system that wants dates formatted in ISO-8601 Date/Time format yyyy-MMddTHH:mm:ssZ, like 2015-06-02T15:55:22Z, with the time zone and Daylight Saving Time offsets accounted for.

I dug through the Security Features guide, and found this:

UniVerse also adds a globally cataloged program to help users to
  obtain date and time information from the audit log (which is called
  by the above two I-descriptor fields):

```<code>SUBROUTINE GETLOCALTIME
(
RESULT ;* OUT: output
TZOFF ;* IN: time zone offset
DATE ;* IN: UTC date
TIME ;* IN: UTC time
OP ;* IN: operation
;* 1: get local date
;* 2: get local time
;* 3: get local timezone id
;* 4: get local timezone daylight saving flag
)
</code>```

(Since I'm not using the auditing capabilities of UniVerse, I don't think I can do much with this, nor could I locate the subroutine.)

I have also played with the popular(?) DATE.UTILITY program from PickWiki, but its calculation of Daylight Saving Time start/end dates seem off. I will save those issues for another question.

This is getting long-winded but I'm hoping someone can point me in the right direction if there's a new OCONV() parameter or something I could use.

Just in case it matters, I'm running on Windows Server 2008 R2.

Thanks!

答:
Thanks for the clues.  Here's my implementation:

```<code>  SUBROUTINE FORMAT.ISO.8601 (IDATE, ITIME, RESULT, ERR.TEXT)

  * Don't step on the caller's variables.
  IN.DATE = IDATE
  IN.TIME = ITIME

  * Initialize the outbound variable.
  RESULT = ''

  IF NOT(NUM(IN.DATE)) THEN
     ERR.TEXT = 'Non-numeric internal date ' : DQUOTE(IN.DATE) : ' when numeric required.'
     RETURN
  END

  IF NOT(NUM(IN.DATE)) THEN
     ERR.TEXT = 'Non-numeric internal time ' : DQUOTE(IN.TIME) : ' when numeric required.'
     RETURN
  END

  * SYSTEM(99) is based on 1/1/1970.
  SECONDS.SINCE.GMT.01.01.1970 = SYSTEM(99)

  * Day 0 in Pick is 12/31/1967
  * Subtract 732 to equalize the starting dates.
  NUMBER.OF.DAYS.SINCE.01.01.1970 = DATE() - 732

  SECONDS.SINCE.MIDNIGHT.LOCAL= TIME()
  SECS.PER.DAY = 24 * 60 * 60
  LOCAL.SECONDS.SINCE.GMT.01.01.1970 = NUMBER.OF.DAYS.SINCE.01.01.1970 * SECS.PER.DAY + FIELD(SECONDS.SINCE.MIDNIGHT.LOCAL,".",1)

  OFFSET = LOCAL.SECONDS.SINCE.GMT.01.01.1970 - SECONDS.SINCE.GMT.01.01.1970

  OFFSET = INT((OFFSET / 60 )/ 60)

  OTIME = OCONV(IN.TIME, 'MTS')
  IF OTIME = '' THEN
     ERR.TEXT = 'Bad internal time ' : DQUOTE(IN.TIME) : '.'
     RETURN
  END

  HOURS = FIELD(OTIME, ':', 1)
  MINUTES = FIELD(OTIME, ':', 2)
  SECONDS = FIELD(OTIME, ':', 3)

  HOURS -= OFFSET
  IF HOURS >= 24 THEN
     IN.DATE += 1
     HOURS = HOURS - 24
  END
  HOURS = HOURS 'R%2'

  ODATE = OCONV(IN.DATE, 'D4/')
  IF ODATE = '' THEN
     ERR.TEXT = 'Bad internal date ' : DQUOTE(IN.DATE) : '.'
     RETURN
  END

  DMONTH = FIELD(ODATE, '/', 1)
  DDAY = FIELD(ODATE, '/',2)
  DYEAR = FIELD(ODATE, '/',3)

  RESULT = DYEAR : '-' : DMONTH : '-' : DDAY : 'T' : HOURS : ':' : MINUTES : ':' : SECONDS : 'Z'

  RETURN

END
</code>```

Here's my test harness:

```<code>  CRT 'Testing right now.'
  IDATE = DATE()
  ITIME = TIME()
  CALL FORMAT.ISO.8601 (IDATE, ITIME, RESULT, ERR.TEXT)
  IF ERR.TEXT THEN
     CRT 'ERR.TEXT: ' : ERR.TEXT
  END ELSE
     CRT 'RESULT: ' : RESULT
  END

  CRT
  CRT 'Testing an hour ago.'
  IDATE = DATE()
  ITIME = TIME()
  ITIME = ITIME - (60*60)
  IF ITIME < 0 THEN
     ITIME += (24*60*60)
     IDATE -= 1
  END
  CALL FORMAT.ISO.8601 (IDATE, ITIME, RESULT, ERR.TEXT)
  IF ERR.TEXT THEN
     CRT 'ERR.TEXT: ' : ERR.TEXT
  END ELSE
     CRT 'RESULT: ' : RESULT
  END

  CRT
  CRT 'Testing an hour from now.'
  IDATE = DATE()
  ITIME = TIME()
  ITIME = ITIME + (60*60)
  IF ITIME > (24*60*60) THEN
     ITIME -= (24*60*60)
     IDATE += 1
  END
  CALL FORMAT.ISO.8601 (IDATE, ITIME, RESULT, ERR.TEXT)
  IF ERR.TEXT THEN
     CRT 'ERR.TEXT: ' : ERR.TEXT
  END ELSE
     CRT 'RESULT: ' : RESULT
  END

END
</code>```

Here's my test run:

```<code>  >T$FORMAT.ISO.8601
  Testing right now.
  RESULT: 2017-03-29T00:47:22Z

  Testing an hour ago.
  RESULT: 2017-03-28T23:47:22Z

  Testing an hour from now.
  RESULT: 2017-03-29T01:47:22Z
</code>```

Body:
The release notes for UniVerse version 11.2.4 mention local time zone configuration, but it is in the context of auditing. This is the quote:

Local time zone configuration

Prior to UniVerse 11.2.4, the date and time data stored in the audit log records was based on UTC only.
  Beginning at UniVerse 11.2.4, UniVerse adds the date and time data
  based on local timezone to audit log records. The data is stored in
  location 19 for each record. The dictionary name for this data field
  is TZINFO. For more information, see UniVerse Security Features.

Since UniVerse seems capable of working with time zones natively, does this mean there might be a way to easily generate UTC-formatted date/time stamps from my EST/EDT values?

I am sending data to a system that wants dates formatted in ISO-8601 Date/Time format yyyy-MMddTHH:mm:ssZ, like 2015-06-02T15:55:22Z, with the time zone and Daylight Saving Time offsets accounted for.

I dug through the Security Features guide, and found this:

UniVerse also adds a globally cataloged program to help users to
  obtain date and time information from the audit log (which is called
  by the above two I-descriptor fields):

SUBROUTINE GETLOCALTIME
(
RESULT ;* OUT: output
TZOFF ;* IN: time zone offset
DATE ;* IN: UTC date
TIME ;* IN: UTC time
OP ;* IN: operation
;* 1: get local date
;* 2: get local time
;* 3: get local timezone id
;* 4: get local timezone daylight saving flag
)

(Since I'm not using the auditing capabilities of UniVerse, I don't think I can do much with this, nor could I locate the subroutine.)

I have also played with the popular(?) DATE.UTILITY program from PickWiki, but its calculation of Daylight Saving Time start/end dates seem off. I will save those issues for another question.

This is getting long-winded but I'm hoping someone can point me in the right direction if there's a new OCONV() parameter or something I could use.

Just in case it matters, I'm running on Windows Server 2008 R2.

Thanks!

Body:
Thanks for the clues.  Here's my implementation:

  SUBROUTINE FORMAT.ISO.8601 (IDATE, ITIME, RESULT, ERR.TEXT)

  * Don't step on the caller's variables.
  IN.DATE = IDATE
  IN.TIME = ITIME

  * Initialize the outbound variable.
  RESULT = ''

  IF NOT(NUM(IN.DATE)) THEN
     ERR.TEXT = 'Non-numeric internal date ' : DQUOTE(IN.DATE) : ' when numeric required.'
     RETURN
  END

  IF NOT(NUM(IN.DATE)) THEN
     ERR.TEXT = 'Non-numeric internal time ' : DQUOTE(IN.TIME) : ' when numeric required.'
     RETURN
  END

  * SYSTEM(99) is based on 1/1/1970.
  SECONDS.SINCE.GMT.01.01.1970 = SYSTEM(99)

  * Day 0 in Pick is 12/31/1967
  * Subtract 732 to equalize the starting dates.
  NUMBER.OF.DAYS.SINCE.01.01.1970 = DATE() - 732

  SECONDS.SINCE.MIDNIGHT.LOCAL= TIME()
  SECS.PER.DAY = 24 * 60 * 60
  LOCAL.SECONDS.SINCE.GMT.01.01.1970 = NUMBER.OF.DAYS.SINCE.01.01.1970 * SECS.PER.DAY + FIELD(SECONDS.SINCE.MIDNIGHT.LOCAL,".",1)

  OFFSET = LOCAL.SECONDS.SINCE.GMT.01.01.1970 - SECONDS.SINCE.GMT.01.01.1970

  OFFSET = INT((OFFSET / 60 )/ 60)

  OTIME = OCONV(IN.TIME, 'MTS')
  IF OTIME = '' THEN
     ERR.TEXT = 'Bad internal time ' : DQUOTE(IN.TIME) : '.'
     RETURN
  END

  HOURS = FIELD(OTIME, ':', 1)
  MINUTES = FIELD(OTIME, ':', 2)
  SECONDS = FIELD(OTIME, ':', 3)

  HOURS -= OFFSET
  IF HOURS >= 24 THEN
     IN.DATE += 1
     HOURS = HOURS - 24
  END
  HOURS = HOURS 'R%2'

  ODATE = OCONV(IN.DATE, 'D4/')
  IF ODATE = '' THEN
     ERR.TEXT = 'Bad internal date ' : DQUOTE(IN.DATE) : '.'
     RETURN
  END

  DMONTH = FIELD(ODATE, '/', 1)
  DDAY = FIELD(ODATE, '/',2)
  DYEAR = FIELD(ODATE, '/',3)

  RESULT = DYEAR : '-' : DMONTH : '-' : DDAY : 'T' : HOURS : ':' : MINUTES : ':' : SECONDS : 'Z'

  RETURN

END

Here's my test harness:

  CRT 'Testing right now.'
  IDATE = DATE()
  ITIME = TIME()
  CALL FORMAT.ISO.8601 (IDATE, ITIME, RESULT, ERR.TEXT)
  IF ERR.TEXT THEN
     CRT 'ERR.TEXT: ' : ERR.TEXT
  END ELSE
     CRT 'RESULT: ' : RESULT
  END

  CRT
  CRT 'Testing an hour ago.'
  IDATE = DATE()
  ITIME = TIME()
  ITIME = ITIME - (60*60)
  IF ITIME < 0 THEN
     ITIME += (24*60*60)
     IDATE -= 1
  END
  CALL FORMAT.ISO.8601 (IDATE, ITIME, RESULT, ERR.TEXT)
  IF ERR.TEXT THEN
     CRT 'ERR.TEXT: ' : ERR.TEXT
  END ELSE
     CRT 'RESULT: ' : RESULT
  END

  CRT
  CRT 'Testing an hour from now.'
  IDATE = DATE()
  ITIME = TIME()
  ITIME = ITIME + (60*60)
  IF ITIME > (24*60*60) THEN
     ITIME -= (24*60*60)
     IDATE += 1
  END
  CALL FORMAT.ISO.8601 (IDATE, ITIME, RESULT, ERR.TEXT)
  IF ERR.TEXT THEN
     CRT 'ERR.TEXT: ' : ERR.TEXT
  END ELSE
     CRT 'RESULT: ' : RESULT
  END

END

Here's my test run:

  >T$FORMAT.ISO.8601
  Testing right now.
  RESULT: 2017-03-29T00:47:22Z

  Testing an hour ago.
  RESULT: 2017-03-28T23:47:22Z

  Testing an hour from now.
  RESULT: 2017-03-29T01:47:22Z


问:
while loop which executes five times and each time displaying a random digit
I'm trying to create program segment that uses a single while loop which executes its loop body five times, each time displaying a random digit from this set of values. { 1 , 2 , 3 , 4 , 5 , 6 }
The while loop executes only once enter code here

```<code>public static void main(String[] args){
        int num = 0;
        int count = 0;
        while (count < 5)
            count ++;
        num = (int)(Math.random()* 6);

    System.out.println(num);
</code>```

I also tried to do that with arrays.

```<code> public static void main(String[] args){
            int[] num = { 1 , 2 , 3 , 4 , 5 , 6 };
            int count = 0;
            while (count < 5)
                count++;
            num [count] = (int)(Math.random()* 6);
            System.out.println(num);
</code>```

Any tips will be helpful.

答:
The while loop has no braces, so the body is only the next statement. Which increments count. Add braces.

```<code>while (count < 5) {
    count ++;
    num = (int) (Math.random() * 6);
    System.out.println(num);
}
</code>```

Or, in Java 8+, with an IntStream like

```<code>IntStream.generate(() -> (int) (Math.random() * 6))
        .limit(5).forEachOrdered(System.out::println);
</code>```

Body:
I'm trying to create program segment that uses a single while loop which executes its loop body five times, each time displaying a random digit from this set of values. { 1 , 2 , 3 , 4 , 5 , 6 }
The while loop executes only once enter code here

public static void main(String[] args){
        int num = 0;
        int count = 0;
        while (count < 5)
            count ++;
        num = (int)(Math.random()* 6);

    System.out.println(num);

I also tried to do that with arrays.

 public static void main(String[] args){
            int[] num = { 1 , 2 , 3 , 4 , 5 , 6 };
            int count = 0;
            while (count < 5)
                count++;
            num [count] = (int)(Math.random()* 6);
            System.out.println(num);

Any tips will be helpful.

Body:
The while loop has no braces, so the body is only the next statement. Which increments count. Add braces.

while (count < 5) {
    count ++;
    num = (int) (Math.random() * 6);
    System.out.println(num);
}

Or, in Java 8+, with an IntStream like

IntStream.generate(() -> (int) (Math.random() * 6))
        .limit(5).forEachOrdered(System.out::println);


问:
Neural Network with my own dataset
I have downloaded many face images from web. In order to learn Tensorflow I want to feed those images to a simple fully-connected neural network with a single hidden layer. I have found an example code in here.

Since I am a beginner, I don't know how to train, evaluate, and test the network with the downloaded images. The code owner used a '.mat' file and a .pkl file. I don't understand how he organized training and test set.

In order to run the code with my images;
Do I need to divide my images into training, test, and validation folders and turn each folder into a mat file? How am I going to provide labels for the training?

Besides, I don't understand why he used a '.pkl' file?

All in all, I would like to change this code so that I can find test, training , and validation set classification performance with my image dataset.

It might be an easy question, but it is important for me as it is a starting step. Thanks for your understanding.

答:
First, you don't have to use .mat files nor pickles. Tensorflow expects numpy array.

For instance, let's say you have 70000 images of size 28x28 (=784 dimensions) belonging to 10 classes. Let's also assume that you'd like to train a simple feedforward neural network to classify the images.

The first step would be to split the images between train and test (and validation, but let's put this aside for the sake of simplicity). For the sake of the example, let's imagine that you chose randomly 60000 images for your training set and 10000 for your test set.

The second step would be to ensure that your data has the right format. Here, you'd like your training set to consist in one numpy array of shape (60000, 784) for the images and another one of shape (60000, 10) for the labels (if you use one-hot encoding to represent your classes). As for your test set, you should have an array of shape (10000, 784) for the images and one of shape (10000, 10) for the labels.

Once you have these big numpy arrays, you should define placeholders that will allow you to feed data to you network during training and evaluation.

```<code>images = tf.placeholder(tf.float32, shape=[None, 784])
labels = tf.placeholder(tf.int64, shape=[None, 10])
</code>```

The None here means that you can feed a batch of any size, i.e. as many images as you want, as long as you numpy array is of shape (anything, 784).

The third step consists in defining your model as well as the loss function and the optimizer.

The fourth step consists in training your network by feeding it with random batches of data using the placeholders created above. As your network is training, you can periodically print its performance like the training loss/accuracy as well as the test loss/accuracy.

You can find a complete and very simple example here.

Title: Neural Network with my own dataset

Body:
First, you don't have to use .mat files nor pickles. Tensorflow expects numpy array.

For instance, let's say you have 70000 images of size 28x28 (=784 dimensions) belonging to 10 classes. Let's also assume that you'd like to train a simple feedforward neural network to classify the images.

The first step would be to split the images between train and test (and validation, but let's put this aside for the sake of simplicity). For the sake of the example, let's imagine that you chose randomly 60000 images for your training set and 10000 for your test set.

The second step would be to ensure that your data has the right format. Here, you'd like your training set to consist in one numpy array of shape (60000, 784) for the images and another one of shape (60000, 10) for the labels (if you use one-hot encoding to represent your classes). As for your test set, you should have an array of shape (10000, 784) for the images and one of shape (10000, 10) for the labels.

Once you have these big numpy arrays, you should define placeholders that will allow you to feed data to you network during training and evaluation.

images = tf.placeholder(tf.float32, shape=[None, 784])
labels = tf.placeholder(tf.int64, shape=[None, 10])

The None here means that you can feed a batch of any size, i.e. as many images as you want, as long as you numpy array is of shape (anything, 784).

The third step consists in defining your model as well as the loss function and the optimizer.

The fourth step consists in training your network by feeding it with random batches of data using the placeholders created above. As your network is training, you can periodically print its performance like the training loss/accuracy as well as the test loss/accuracy.

You can find a complete and very simple example here.