问:
understanding the usage of cattr_accessor in Rails Model Class
I am a newbie to ruby and rails.
In my Rails app, I am trying to use Wicked Wizard gem and need some help in Understanding about the cattr_accessor which I have come across in  the code

```<code>  create_table "pets", force: :cascade do |t|
            t.string   "name"
            t.string   "colour"
            t.string   "owner_name"
            t.text     "identifying_characteristics"
            t.text     "special_instructions"
            t.datetime "created_at"
            t.datetime "updated_at"
            t.string   "email"
            t.string   "password"
          end
</code>```

model

```<code> class Pet < ActiveRecord::Base
  has_many :pet_photos
  cattr_accessor :form_steps do
    %w(identity characteristics instructions)
  end

  attr_accessor :form_step
  validates :email, presence: true
  validates :name, :owner_name, presence: true, if: -> { required_for_step?(:identity) }
  validates :identifying_characteristics, :colour, presence: true, if: -> { required_for_step?(:characteristics) }
  validates :special_instructions, presence: true, if: -> { required_for_step?(:instructions) }

  def required_for_step?(step)
    return true if form_step.nil?
    return true if self.form_steps.index(step.to_s) <= self.form_steps.index(form_step)
  end

end
</code>```

and

```<code>      class Pet::StepsController < ApplicationController
        include Wicked::Wizard
        steps *Pet.form_steps

        def show
          @pet = Pet.find(params[:pet_id])
          render_wizard
        end

        def update
          @pet = Pet.find(params[:pet_id])
          @pet.update(pet_params(step))

            if params[:images]

                params[:images].each do |image|
                @pet.pet_photos.create(image: image)
              end
            end

          render_wizard @pet
        end

        private

        def pet_params(step)
          permitted_attributes = case step
                                 when "identity"
                                   [:name, :owner_name]
                                 when "characteristics"
                                   [:colour, :identifying_characteristics]
                                 when "instructions"
                                   [:special_instructions]
                                 end

          params.require(:pet).permit(permitted_attributes).merge(form_step: step)
        end

      end
</code>```

routes

```<code>  PetThing::Application.routes.draw do
          resources :pets, only: [:new, :create, :index, :destroy] do
            resources :steps, only: [:show, :update], controller: 'pet/steps'
          end

          root to: 'pets#index'
</code>```

Now my Questions are

1) what is the difference between the cattr_accessor and attr_accessor?

```<code>       cattr_accessor :form_steps do
       %w(identity characteristics instructions)
       end
       attr_accessor :form_step
</code>```

2) why two different symbols(:form_steps , :form_step) are used as method parameters for cattr_accessor and attr_accessor methods respectively?

3) why is a block passed as a parameter to cattr_accessor method?

Any Help is highly Appreciated.Thank you

答:
First of all, this method is deprecated or moved.
Which version do you use, Rails 4 or Rails ?

cattr_accessor > replaced for mattr_accessor(*syms, &blk) for Module which is the superclass of the class Class. I recomend to use attr_accessor, which is just a method to set attributes for the class, it works like a getter or a setter for the class but only works for an instance (in memory), the attribute is saved anywhere.

cattr_accessor is like the attr_* methods, but for the class level. One thing you wouldn't expect is because it uses a backing @@form_steps, the value shared between the class and all instances.

Api docs:

Defines both class and instance accessors for class attributes.

```<code>module HairColors
  mattr_accessor :hair_colors
end

class Person
  include HairColors
end

Person.hair_colors = [:brown, :black, :blonde, :red]
Person.hair_colors     # => [:brown, :black, :blonde, :red]
Person.new.hair_colors # => [:brown, :black, :blonde, :red]
</code>```

If a subclass changes the value then that would also change the value for parent class. Similarly if parent class changes the value then that would change the value of subclasses too.

```<code>class Male < Person
end

Male.hair_colors << :blue
Person.hair_colors # => [:brown, :black, :blonde, :red, :blue]
</code>```

To opt out of the instance writer method, pass instance_writer: false. To opt out of the instance reader method, pass instance_reader: false.

```<code>module HairColors
  mattr_accessor :hair_colors, instance_writer: false, instance_reader:             false
end

class Person
  include HairColors
end

Person.new.hair_colors = [:brown]  # => NoMethodError
Person.new.hair_colors             # => NoMethodError
</code>```

Or pass instance_accessor: false, to opt out both instance methods.

```<code>module HairColors
  mattr_accessor :hair_colors, instance_accessor: false
end

class Person
  include HairColors
end

Person.new.hair_colors = [:brown]  # => NoMethodError
Person.new.hair_colors             # => NoMethodError
</code>```

Also you can pass a block to set up the attribute with a default value.

```<code>module HairColors
  mattr_accessor :hair_colors do
[:brown, :black, :blonde, :red]
  end
end

class Person
  include HairColors
end

Person.class_variable_get("@@hair_colors") #=> [:brown, :black, :blonde, :red]
</code>```

1)

attr_accessor: is a ruby method that makes a getter and a setter

cattr_accessor:is a ruby method that makes a getter and a setter for the class (quite strange).

2)
Class variable have a tendency to wander from class to class. @@form_steps class variable can be exposed through inheritance tree.

3) To set which attributes will have this class. form_steps

```<code>p = Pet.new
p.form_steps = "var"
</code>```

and use the form_steps attribute inside your current instance Pet (like you do in the method required_for_step?).

Body:
I am a newbie to ruby and rails.
In my Rails app, I am trying to use Wicked Wizard gem and need some help in Understanding about the cattr_accessor which I have come across in  the code

  create_table "pets", force: :cascade do |t|
            t.string   "name"
            t.string   "colour"
            t.string   "owner_name"
            t.text     "identifying_characteristics"
            t.text     "special_instructions"
            t.datetime "created_at"
            t.datetime "updated_at"
            t.string   "email"
            t.string   "password"
          end

model

 class Pet < ActiveRecord::Base
  has_many :pet_photos
  cattr_accessor :form_steps do
    %w(identity characteristics instructions)
  end

  attr_accessor :form_step
  validates :email, presence: true
  validates :name, :owner_name, presence: true, if: -> { required_for_step?(:identity) }
  validates :identifying_characteristics, :colour, presence: true, if: -> { required_for_step?(:characteristics) }
  validates :special_instructions, presence: true, if: -> { required_for_step?(:instructions) }

  def required_for_step?(step)
    return true if form_step.nil?
    return true if self.form_steps.index(step.to_s) <= self.form_steps.index(form_step)
  end

end

and

      class Pet::StepsController < ApplicationController
        include Wicked::Wizard
        steps *Pet.form_steps

        def show
          @pet = Pet.find(params[:pet_id])
          render_wizard
        end

        def update
          @pet = Pet.find(params[:pet_id])
          @pet.update(pet_params(step))

            if params[:images]

                params[:images].each do |image|
                @pet.pet_photos.create(image: image)
              end
            end

          render_wizard @pet
        end

        private

        def pet_params(step)
          permitted_attributes = case step
                                 when "identity"
                                   [:name, :owner_name]
                                 when "characteristics"
                                   [:colour, :identifying_characteristics]
                                 when "instructions"
                                   [:special_instructions]
                                 end

          params.require(:pet).permit(permitted_attributes).merge(form_step: step)
        end

      end

routes

  PetThing::Application.routes.draw do
          resources :pets, only: [:new, :create, :index, :destroy] do
            resources :steps, only: [:show, :update], controller: 'pet/steps'
          end

          root to: 'pets#index'

Now my Questions are

1) what is the difference between the cattr_accessor and attr_accessor?

       cattr_accessor :form_steps do
       %w(identity characteristics instructions)
       end
       attr_accessor :form_step

2) why two different symbols(:form_steps , :form_step) are used as method parameters for cattr_accessor and attr_accessor methods respectively?

3) why is a block passed as a parameter to cattr_accessor method?

Any Help is highly Appreciated.Thank you

Body:
First of all, this method is deprecated or moved.
Which version do you use, Rails 4 or Rails ?

cattr_accessor > replaced for mattr_accessor(*syms, &blk) for Module which is the superclass of the class Class. I recomend to use attr_accessor, which is just a method to set attributes for the class, it works like a getter or a setter for the class but only works for an instance (in memory), the attribute is saved anywhere.

cattr_accessor is like the attr_* methods, but for the class level. One thing you wouldn't expect is because it uses a backing @@form_steps, the value shared between the class and all instances.

Api docs:

Defines both class and instance accessors for class attributes.

module HairColors
  mattr_accessor :hair_colors
end

class Person
  include HairColors
end

Person.hair_colors = [:brown, :black, :blonde, :red]
Person.hair_colors     # => [:brown, :black, :blonde, :red]
Person.new.hair_colors # => [:brown, :black, :blonde, :red]

If a subclass changes the value then that would also change the value for parent class. Similarly if parent class changes the value then that would change the value of subclasses too.

class Male < Person
end

Male.hair_colors << :blue
Person.hair_colors # => [:brown, :black, :blonde, :red, :blue]

To opt out of the instance writer method, pass instance_writer: false. To opt out of the instance reader method, pass instance_reader: false.

module HairColors
  mattr_accessor :hair_colors, instance_writer: false, instance_reader:             false
end

class Person
  include HairColors
end

Person.new.hair_colors = [:brown]  # => NoMethodError
Person.new.hair_colors             # => NoMethodError

Or pass instance_accessor: false, to opt out both instance methods.

module HairColors
  mattr_accessor :hair_colors, instance_accessor: false
end

class Person
  include HairColors
end

Person.new.hair_colors = [:brown]  # => NoMethodError
Person.new.hair_colors             # => NoMethodError

Also you can pass a block to set up the attribute with a default value.

module HairColors
  mattr_accessor :hair_colors do
[:brown, :black, :blonde, :red]
  end
end

class Person
  include HairColors
end

Person.class_variable_get("@@hair_colors") #=> [:brown, :black, :blonde, :red]

1)

attr_accessor: is a ruby method that makes a getter and a setter

cattr_accessor:is a ruby method that makes a getter and a setter for the class (quite strange).

2)
Class variable have a tendency to wander from class to class. @@form_steps class variable can be exposed through inheritance tree.

3) To set which attributes will have this class. form_steps

p = Pet.new
p.form_steps = "var"

and use the form_steps attribute inside your current instance Pet (like you do in the method required_for_step?).


来源: stackexchange

问:
How to redirect stdout with '\r' printed on the same line?
Check below the code snippet of using the character \r:

```<code>#include <stdio.h>
#include <unistd.h>
int main() {
    for(int i=1; i<=100; i++) {
        printf("%d%%\r", i);
        fflush(stdout);
        usleep(1e4);
    }
    printf("\n");
    return 0;
}
</code>```

The output of this program on the console has only 1 line:

```<code>$ ./main
100%
</code>```

However if the output is redirected to a file ./main > main.log, the file has 100 lines:

```<code>1%
2%
3%
...
100%
</code>```

Question:

How do I keep only the last line of output to the log file?

答:
I am assuming this is part of a larger program where the "percentage" may or may not be 100% (otherwise, you could just print 100% right away).
So you could check if the output goes to a terminal using isatty. If not, print the "last percentage" value:

```<code>int main(void)
{
    int b = isatty(STDOUT_FILENO);
    int i;
    for(i=1; i<=100; i++) {
        if (b) printf("%d%%\r", i);
        fflush(stdout);
        usleep(1e4);
    }
    if (!b) printf("%d%%\r", i-1);
    printf("\n");
    return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Check below the code snippet of using the character \r:

#include <stdio.h>
#include <unistd.h>
int main() {
    for(int i=1; i<=100; i++) {
        printf("%d%%\r", i);
        fflush(stdout);
        usleep(1e4);
    }
    printf("\n");
    return 0;
}

The output of this program on the console has only 1 line:

$ ./main
100%

However if the output is redirected to a file ./main > main.log, the file has 100 lines:

1%
2%
3%
...
100%

Question:

How do I keep only the last line of output to the log file?

Body:
I am assuming this is part of a larger program where the "percentage" may or may not be 100% (otherwise, you could just print 100% right away).
So you could check if the output goes to a terminal using isatty. If not, print the "last percentage" value:

int main(void)
{
    int b = isatty(STDOUT_FILENO);
    int i;
    for(i=1; i<=100; i++) {
        if (b) printf("%d%%\r", i);
        fflush(stdout);
        usleep(1e4);
    }
    if (!b) printf("%d%%\r", i-1);
    printf("\n");
    return 0;
}


问:
How do I read .owl files in java and display its contents?
How do I read .owl files in java and display its contents?

答:
You have several options.

.owl files are text files, and you can display them that way.

.owl uses XML, so you can treat it like an XML document. Refer to http://www.w3.org/TR/owl-xmlsyntax/ and http://www.w3.org/TR/owl2-overview/ for a list of tags and what they represent.

Or you can use the OWL API. You can download it at: http://owlapi.sourceforge.net/index.html, and there are several examples at http://owlapi.sourceforge.net/documentation.html

Displaying and OWL ontology is somewhat challenging because the information you want to display can be highly linked, so its structure is that of a graph rather than sequential or tabular. It is possible for classes to be subclasses many other subclasses, and cyclical classification is possible. That is, A can be a subclass of B, which can be a subclass of C which can be a subclass of A.

ContentLicense: CC BY-SA 2.5


问:
Transposing SQL table
I have the following tables (tables below are simplification of more complex task):

abc.FirstTable

```<code>ID | Name
---------
10 | test
</code>```

abc.SecondTable

```<code>Id | RefId
----------
20 | 10
21 | 10
</code>```

What I want to have is:

```<code>Id | Name | RefId1 | RefId2
---------------------------
10 | test | 20     | 21
</code>```

I am stuck with:

```<code>select t1.id, t1.name, t2.ID from abc.FirstTable t1
left join abc.SecondTable t2 on t2.refid = t1.id;
</code>```

which produces two rows. Any tips on how to extend this query using joins? Thank you!

答:
```<code>with t as
(
  select t1.id id1, t1.name, t2.* from abc_FirstTable t1 join abc_SecondTable t2 on t2.refid = t1.id
)
select * from t
pivot
(
 min(id) min_id, max(id) max_id
 for (refid) in (10)
);
</code>```

Title: Transposing SQL table

Body:
I have the following tables (tables below are simplification of more complex task):

abc.FirstTable

ID | Name
---------
10 | test

abc.SecondTable

Id | RefId
----------
20 | 10
21 | 10

What I want to have is:

Id | Name | RefId1 | RefId2
---------------------------
10 | test | 20     | 21

I am stuck with:

select t1.id, t1.name, t2.ID from abc.FirstTable t1
left join abc.SecondTable t2 on t2.refid = t1.id;

which produces two rows. Any tips on how to extend this query using joins? Thank you!


问:
javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:""). Expected elements are
You can find a lot of questions like this in this site but none has solved my issue.

This is my XML :

```<code><?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<lookupInstances xmlns='http://www.pqr.com/awd/rest/v1' name='LKIMGR'>
<lookupParameters>
<lookupParameter name='businessArea'>PQAA</lookupParameter>
<lookupParameter name='MEMBERNUMBER'>ANTHONY1900</lookupParameter>
</lookupParameters>
</lookupInstances>
</code>```

I have created the Jaxb class using the XJC compiler and the file created is as :

```<code>//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.01.13 at 12:15:41 PM IST
//

package com.dsths.ga.awd.main;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 * <p>Java class for anonymous complex type.
 *
 * <p>The following schema fragment specifies the expected content contained within this class.
 *
 * ```
 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="lookupParameters">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <sequence>
 *                   <element name="lookupParameter">
 *                     <complexType>
 *                       <complexContent>
 *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                           <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
 *                         </restriction>
 *                       </complexContent>
 *                     </complexType>
 *                   </element>
 *                 </sequence>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *       </sequence>
 *       <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 * ```
 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "lookupParameters"
})
@XmlRootElement(name = "lookupInstances")
public class LookupInstances {

    @XmlElement(required = true)
    protected LookupInstances.LookupParameters lookupParameters;
    @XmlAttribute
    protected String name;

    /**
     * Gets the value of the lookupParameters property.
     *
     * @return
     *     possible object is
     *     {@link LookupInstances.LookupParameters }
     *
     */
    public LookupInstances.LookupParameters getLookupParameters() {
        return lookupParameters;
    }

    /**
     * Sets the value of the lookupParameters property.
     *
     * @param value
     *     allowed object is
     *     {@link LookupInstances.LookupParameters }
     *
     */
    public void setLookupParameters(LookupInstances.LookupParameters value) {
        this.lookupParameters = value;
    }

    /**
     * Gets the value of the name property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setName(String value) {
        this.name = value;
    }

    /**
     * <p>Java class for anonymous complex type.
     *
     * <p>The following schema fragment specifies the expected content contained within this class.
     *
     * ```
     * <complexType>
     *   <complexContent>
     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       <sequence>
     *         <element name="lookupParameter">
     *           <complexType>
     *             <complexContent>
     *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *                 <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
     *               </restriction>
     *             </complexContent>
     *           </complexType>
     *         </element>
     *       </sequence>
     *     </restriction>
     *   </complexContent>
     * </complexType>
     * ```
     *
     *
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "lookupParameter"
    })
    public static class LookupParameters {

        @XmlElement(required = true)
        protected LookupInstances.LookupParameters.LookupParameter lookupParameter;

        /**
         * Gets the value of the lookupParameter property.
         *
         * @return
         *     possible object is
         *     {@link LookupInstances.LookupParameters.LookupParameter }
         *
         */
        public LookupInstances.LookupParameters.LookupParameter getLookupParameter() {
            return lookupParameter;
        }

        /**
         * Sets the value of the lookupParameter property.
         *
         * @param value
         *     allowed object is
         *     {@link LookupInstances.LookupParameters.LookupParameter }
         *
         */
        public void setLookupParameter(LookupInstances.LookupParameters.LookupParameter value) {
            this.lookupParameter = value;
        }

        /**
         * <p>Java class for anonymous complex type.
         *
         * <p>The following schema fragment specifies the expected content contained within this class.
         *
         * ```
         * <complexType>
         *   <complexContent>
         *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
         *       <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
         *     </restriction>
         *   </complexContent>
         * </complexType>
         * ```
         *
         *
         */
        @XmlAccessorType(XmlAccessType.FIELD)
        @XmlType(name = "")
        public static class LookupParameter {

            @XmlAttribute
            protected String name;

            /**
             * Gets the value of the name property.
             *
             * @return
             *     possible object is
             *     {@link String }
             *
             */
            public String getName() {
                return name;
            }

            /**
             * Sets the value of the name property.
             *
             * @param value
             *     allowed object is
             *     {@link String }
             *
             */
            public void setName(String value) {
                this.name = value;
            }

        }

    }

}
</code>```

Unmarshal Code :

```<code>    public LookupInstances unmarshallXmlRequest(String xmlReq)
    {
        LookupInstances instances = null;
           try {
            JAXBContext jc = JAXBContext.newInstance( LookupInstances.class );
               Unmarshaller u = jc.createUnmarshaller();
               StringBuffer xmlStr = new StringBuffer( xmlReq );
               StringReader strReader = new StringReader( xmlStr.toString() );
               StreamSource strSource = new StreamSource(strReader);
               Object o = u.unmarshal( strSource );
               instances = (LookupInstances)o;
        } catch (JAXBException e) {

            e.printStackTrace();
        }
        return instances;
    }
</code>```

I got this error :

```<code>javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.pqr.com/awd/rest/v1", local:"lookupInstances"). Expected elements are <{}lookupInstances>
</code>```

Please help.

答:
```<code>@XmlSchema(namespace = "http://www.pqr.com/awd/rest/v1",
elementFormDefault = XmlNsForm.QUALIFIED) package your_package;

        import javax.xml.bind.annotation.XmlNsForm;
        import javax.xml.bind.annotation.XmlSchema;
</code>```

This part is very important for JAXB generated classes, especially elementFormDefault = XmlNsForm.QUALIFIED will not automatically be added by the JAXB.

Thanks Blaise, your answer helped me.

Body:
You can find a lot of questions like this in this site but none has solved my issue.

This is my XML :

<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<lookupInstances xmlns='http://www.pqr.com/awd/rest/v1' name='LKIMGR'>
<lookupParameters>
<lookupParameter name='businessArea'>PQAA</lookupParameter>
<lookupParameter name='MEMBERNUMBER'>ANTHONY1900</lookupParameter>
</lookupParameters>
</lookupInstances>

I have created the Jaxb class using the XJC compiler and the file created is as :

//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.01.13 at 12:15:41 PM IST
//

package com.dsths.ga.awd.main;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="lookupParameters">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <sequence>
 *                   <element name="lookupParameter">
 *                     <complexType>
 *                       <complexContent>
 *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                           <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
 *                         </restriction>
 *                       </complexContent>
 *                     </complexType>
 *                   </element>
 *                 </sequence>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *       </sequence>
 *       <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "lookupParameters"
})
@XmlRootElement(name = "lookupInstances")
public class LookupInstances {

    @XmlElement(required = true)
    protected LookupInstances.LookupParameters lookupParameters;
    @XmlAttribute
    protected String name;

    /**
     * Gets the value of the lookupParameters property.
     *
     * @return
     *     possible object is
     *     {@link LookupInstances.LookupParameters }
     *
     */
    public LookupInstances.LookupParameters getLookupParameters() {
        return lookupParameters;
    }

    /**
     * Sets the value of the lookupParameters property.
     *
     * @param value
     *     allowed object is
     *     {@link LookupInstances.LookupParameters }
     *
     */
    public void setLookupParameters(LookupInstances.LookupParameters value) {
        this.lookupParameters = value;
    }

    /**
     * Gets the value of the name property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setName(String value) {
        this.name = value;
    }

    /**
     *
Java class for anonymous complex type.
     *
     *
The following schema fragment specifies the expected content contained within this class.
     *
     *

     * <complexType>
     *   <complexContent>
     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       <sequence>
     *         <element name="lookupParameter">
     *           <complexType>
     *             <complexContent>
     *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *                 <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
     *               </restriction>
     *             </complexContent>
     *           </complexType>
     *         </element>
     *       </sequence>
     *     </restriction>
     *   </complexContent>
     * </complexType>
     *

     *
     *
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "lookupParameter"
    })
    public static class LookupParameters {

        @XmlElement(required = true)
        protected LookupInstances.LookupParameters.LookupParameter lookupParameter;

        /**
         * Gets the value of the lookupParameter property.
         *
         * @return
         *     possible object is
         *     {@link LookupInstances.LookupParameters.LookupParameter }
         *
         */
        public LookupInstances.LookupParameters.LookupParameter getLookupParameter() {
            return lookupParameter;
        }

        /**
         * Sets the value of the lookupParameter property.
         *
         * @param value
         *     allowed object is
         *     {@link LookupInstances.LookupParameters.LookupParameter }
         *
         */
        public void setLookupParameter(LookupInstances.LookupParameters.LookupParameter value) {
            this.lookupParameter = value;
        }

        /**
         *
Java class for anonymous complex type.
         *
         *
The following schema fragment specifies the expected content contained within this class.
         *
         *

         * <complexType>
         *   <complexContent>
         *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
         *       <attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
         *     </restriction>
         *   </complexContent>
         * </complexType>
         *

         *
         *
         */
        @XmlAccessorType(XmlAccessType.FIELD)
        @XmlType(name = "")
        public static class LookupParameter {

            @XmlAttribute
            protected String name;

            /**
             * Gets the value of the name property.
             *
             * @return
             *     possible object is
             *     {@link String }
             *
             */
            public String getName() {
                return name;
            }

            /**
             * Sets the value of the name property.
             *
             * @param value
             *     allowed object is
             *     {@link String }
             *
             */
            public void setName(String value) {
                this.name = value;
            }

        }

    }

}

Unmarshal Code :

    public LookupInstances unmarshallXmlRequest(String xmlReq)
    {
        LookupInstances instances = null;
           try {
            JAXBContext jc = JAXBContext.newInstance( LookupInstances.class );
               Unmarshaller u = jc.createUnmarshaller();
               StringBuffer xmlStr = new StringBuffer( xmlReq );
               StringReader strReader = new StringReader( xmlStr.toString() );
               StreamSource strSource = new StreamSource(strReader);
               Object o = u.unmarshal( strSource );
               instances = (LookupInstances)o;
        } catch (JAXBException e) {

            e.printStackTrace();
        }
        return instances;
    }

I got this error :

javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.pqr.com/awd/rest/v1", local:"lookupInstances"). Expected elements are <{}lookupInstances>

Please help.

Body:
@XmlSchema(namespace = "http://www.pqr.com/awd/rest/v1",
elementFormDefault = XmlNsForm.QUALIFIED) package your_package;

        import javax.xml.bind.annotation.XmlNsForm;
        import javax.xml.bind.annotation.XmlSchema;

This part is very important for JAXB generated classes, especially elementFormDefault = XmlNsForm.QUALIFIED will not automatically be added by the JAXB.

Thanks Blaise, your answer helped me.


问:
Attachment in Corda :
I tried uploading zip files using uploadAttachemnt method where I got a secureHash as output.
I tried to download the same attachment using the hash as input to openAttachmnet method I got a InputStream.
When I tried to read the contents of the inputStream using BuffeReader it is encrypted. I realised I had to unzip the file and read it so I got this package "import java.util.zip.ZipEntry" to read a zip file content
I am unsure whether I can read the zip file contents using InputStream.
How should I read the zip file contents using the InputStream? If not should I unzip and upload the file ?  </p>

```<code>fun main(args: Array<String>) :String {
    require(args.isNotEmpty()) { "Usage: uploadBlacklist <node address>" }
    args.forEach { arg ->
        val nodeAddress = parse(args[0])
        val rpcConnection = CordaRPCClient(nodeAddress).start("user1", "test")
        val proxy = rpcConnection.proxy

         val attachmentInputStream = File(args[1]).inputStream()
        val attachmentHash = proxy.uploadAttachment(attachmentInputStream)
        print("AtachmentHash"+attachmentHash)

        // Download the attachment
        val inputString = proxy.openAttachment(attachmentHash).bufferedReader().use { it.readText() }
        println("The contents are ")
        print(inputString)

        val file = File("OutputFile.txt")
        file.writeText(inputString)
        rpcConnection.notifyServerAndClose()

    }

    return("File downloaded successfully in the path")
}
</code>```

答:
You need to convert the InputStream returned by openAttachment into a JarInputStream. You can then use the JarInputStream's methods to locate an entry and read its contents:

```<code>val attachmentDownloadInputStream = proxy.openAttachment(attachmentHash)
val attachmentJar = JarInputStream(attachmentDownloadInputStream)

while (attachmentJar.nextEntry.name != expectedFileName) {
    attachmentJar.nextEntry
}

val contents = attachmentJar.bufferedReader().readLines()
</code>```

For an example, take a look at the RPC client code of the Blacklist sample CorDapp here: https://github.com/corda/samples.

Title: Attachment in Corda :

Body:
I tried uploading zip files using uploadAttachemnt method where I got a secureHash as output.
I tried to download the same attachment using the hash as input to openAttachmnet method I got a InputStream.
When I tried to read the contents of the inputStream using BuffeReader it is encrypted. I realised I had to unzip the file and read it so I got this package "import java.util.zip.ZipEntry" to read a zip file content
I am unsure whether I can read the zip file contents using InputStream.
How should I read the zip file contents using the InputStream? If not should I unzip and upload the file ?

fun main(args: Array<String>) :String {
    require(args.isNotEmpty()) { "Usage: uploadBlacklist <node address>" }
    args.forEach { arg ->
        val nodeAddress = parse(args[0])
        val rpcConnection = CordaRPCClient(nodeAddress).start("user1", "test")
        val proxy = rpcConnection.proxy

         val attachmentInputStream = File(args[1]).inputStream()
        val attachmentHash = proxy.uploadAttachment(attachmentInputStream)
        print("AtachmentHash"+attachmentHash)

        // Download the attachment
        val inputString = proxy.openAttachment(attachmentHash).bufferedReader().use { it.readText() }
        println("The contents are ")
        print(inputString)

        val file = File("OutputFile.txt")
        file.writeText(inputString)
        rpcConnection.notifyServerAndClose()

    }

    return("File downloaded successfully in the path")
}

Body:
You need to convert the InputStream returned by openAttachment into a JarInputStream. You can then use the JarInputStream's methods to locate an entry and read its contents:

val attachmentDownloadInputStream = proxy.openAttachment(attachmentHash)
val attachmentJar = JarInputStream(attachmentDownloadInputStream)

while (attachmentJar.nextEntry.name != expectedFileName) {
    attachmentJar.nextEntry
}

val contents = attachmentJar.bufferedReader().readLines()

For an example, take a look at the RPC client code of the Blacklist sample CorDapp here: https://github.com/corda/samples.

ContentLicense: CC BY-SA 4.0


问:
Modifying a Nested JSON object
I have a json object that has encrypted values, I'll simplify this and pretend all values are numbers and i need the number x3 for this question. Is there a way to loop through the json object and update every value then return a decrypted version of the original object:

```<code>var encrypted = {
         a: 10,
         b: 4,
         c: {x:3, y:2, z:1},
 }

var decrypted = decryptJSON(encrypted) //<--- looking for this function

//decrypted = {
//         a: 30,
//         b: 12,
//         c: {x:9, y:6, z:3},
// }
</code>```

I've tried looping through the object using something like https://stackoverflow.com/a/29516227/620723 but this would only really work for a non nested json object.

Also the example I gave above is only nested one level in reality i may have nests inside nests inside nest inside....

答:
You could write a recursive function to traverse the object and update your values. Here is a quick example:

```<code>var encrypted = {
    a: 10,
    b: 4,
    c: {x: 3, y: 2, z: 1},
};

var updateObject = function (obj) {
    for (var key in obj) {
        obj[key] = updateValue(obj[key]);
    }
    return obj;
}

var updateValue = function(value) {
    if (typeof(value) === "object") {
        return updateObject(value);
    } else {
        return value * 3;
    }
}

updateObject(encrypted);
console.log(encrypted);
</code>```

Please note that this will only work as long as you only have objects and numeric values in your object. You will definitely need to adjust the functions if your data is more dynamic.

This should get you started though!

Title: Modifying a Nested JSON object

Body:
I have a json object that has encrypted values, I'll simplify this and pretend all values are numbers and i need the number x3 for this question. Is there a way to loop through the json object and update every value then return a decrypted version of the original object:

var encrypted = {
         a: 10,
         b: 4,
         c: {x:3, y:2, z:1},
 }

var decrypted = decryptJSON(encrypted) //<--- looking for this function

//decrypted = {
//         a: 30,
//         b: 12,
//         c: {x:9, y:6, z:3},
// }

I've tried looping through the object using something like https://stackoverflow.com/a/29516227/620723 but this would only really work for a non nested json object.

Also the example I gave above is only nested one level in reality i may have nests inside nests inside nest inside....

Body:
You could write a recursive function to traverse the object and update your values. Here is a quick example:

var encrypted = {
    a: 10,
    b: 4,
    c: {x: 3, y: 2, z: 1},
};

var updateObject = function (obj) {
    for (var key in obj) {
        obj[key] = updateValue(obj[key]);
    }
    return obj;
}

var updateValue = function(value) {
    if (typeof(value) === "object") {
        return updateObject(value);
    } else {
        return value * 3;
    }
}

updateObject(encrypted);
console.log(encrypted);

Please note that this will only work as long as you only have objects and numeric values in your object. You will definitely need to adjust the functions if your data is more dynamic.

This should get you started though!


问:
Python: Keeping leading zeros when open txt with pandas
I have this txt file:

```<code>Tu 11:44:00 119 52913161 DETECTOR STATE 0001
Tu 11:44:00 119 52913161 DETECTOR STATE 1100
Tu 11:44:02 119 52913161 DETECTOR STATE 0000
Tu 11:44:02 119 52913161 DETECTOR STATE 1110
Tu 11:44:04 119 52913161 DETECTOR STATE 0000
Tu 11:44:04 119 52913161 DETECTOR STATE 0011
</code>```

Which I open in Python (Jupyter Notebook) using this code:

```<code>import pandas as pd
data= pd.read_csv('EXPORT20171205114501_1.txt', sep=" ", header=None)
data.columns = ["day", "time", "street", "sensor", "type", "state", "bits"]
</code>```

I get this output:

```<code>    day time    street  sensor  type    state   bits
0   Tu  11:44:00    119 52913161    DETECTOR    STATE      1
1   Tu  11:44:00    119 52913161    DETECTOR    STATE   1100
2   Tu  11:44:02    119 52913161    DETECTOR    STATE      0
3   Tu  11:44:02    119 52913161    DETECTOR    STATE   1110
4   Tu  11:44:04    119 52913161    DETECTOR    STATE      0
5   Tu  11:44:04    119 52913161    DETECTOR    STATE     11
</code>```

How can keep the leading zeros?

I've tried the following options:

```<code> data = pd.read_csv('EXPORT20171205114501_1.txt', sep=" ", header=None, dtype={'column': object})

 data = pd.read_csv('EXPORT20171205114501_1.txt', sep=" ", header=None).astype(str)

 data = pd.read_csv('EXPORT20171205114501_1.txt', sep=" ", header=None, converters={'ColName': str})
</code>```

None of the above options work. I've updated pandas to the latest version. Any idea?

答:
Use parameter names for columns names by list and then is possible define column for parse to string by dtype parameter with dictionary:

```<code>names = ["day", "time", "street", "sensor", "type", "state", "bits"]
df = pd.read_csv('EXPORT20171205114501_1.txt', sep="\s+", names=names, dtype={'bits':str})
print (df)
  day      time  street    sensor      type  state  bits
0  Tu  11:44:00     119  52913161  DETECTOR  STATE  0001
1  Tu  11:44:00     119  52913161  DETECTOR  STATE  1100
2  Tu  11:44:02     119  52913161  DETECTOR  STATE  0000
3  Tu  11:44:02     119  52913161  DETECTOR  STATE  1110
4  Tu  11:44:04     119  52913161  DETECTOR  STATE  0000
5  Tu  11:44:04     119  52913161  DETECTOR  STATE  0011
</code>```

And if need all columns as strings:

```<code>names = ["day", "time", "street", "sensor", "type", "state", "bits"]
df = pd.read_csv('EXPORT20171205114501_1.txt', sep="\s+", names=names, dtype=str)
print (df)
  day      time  street    sensor      type  state  bits
0  Tu  11:44:00     119  52913161  DETECTOR  STATE  0001
1  Tu  11:44:00     119  52913161  DETECTOR  STATE  1100
2  Tu  11:44:02     119  52913161  DETECTOR  STATE  0000
3  Tu  11:44:02     119  52913161  DETECTOR  STATE  1110
4  Tu  11:44:04     119  52913161  DETECTOR  STATE  0000
5  Tu  11:44:04     119  52913161  DETECTOR  STATE  0011
</code>```

Body:
I have this txt file:

Tu 11:44:00 119 52913161 DETECTOR STATE 0001
Tu 11:44:00 119 52913161 DETECTOR STATE 1100
Tu 11:44:02 119 52913161 DETECTOR STATE 0000
Tu 11:44:02 119 52913161 DETECTOR STATE 1110
Tu 11:44:04 119 52913161 DETECTOR STATE 0000
Tu 11:44:04 119 52913161 DETECTOR STATE 0011

Which I open in Python (Jupyter Notebook) using this code:

import pandas as pd
data= pd.read_csv('EXPORT20171205114501_1.txt', sep=" ", header=None)
data.columns = ["day", "time", "street", "sensor", "type", "state", "bits"]

I get this output:

    day time    street  sensor  type    state   bits
0   Tu  11:44:00    119 52913161    DETECTOR    STATE      1
1   Tu  11:44:00    119 52913161    DETECTOR    STATE   1100
2   Tu  11:44:02    119 52913161    DETECTOR    STATE      0
3   Tu  11:44:02    119 52913161    DETECTOR    STATE   1110
4   Tu  11:44:04    119 52913161    DETECTOR    STATE      0
5   Tu  11:44:04    119 52913161    DETECTOR    STATE     11

How can keep the leading zeros?

I've tried the following options:

 data = pd.read_csv('EXPORT20171205114501_1.txt', sep=" ", header=None, dtype={'column': object})

 data = pd.read_csv('EXPORT20171205114501_1.txt', sep=" ", header=None).astype(str)

 data = pd.read_csv('EXPORT20171205114501_1.txt', sep=" ", header=None, converters={'ColName': str})

None of the above options work. I've updated pandas to the latest version. Any idea?

Body:
Use parameter names for columns names by list and then is possible define column for parse to string by dtype parameter with dictionary:

names = ["day", "time", "street", "sensor", "type", "state", "bits"]
df = pd.read_csv('EXPORT20171205114501_1.txt', sep="\s+", names=names, dtype={'bits':str})
print (df)
  day      time  street    sensor      type  state  bits
0  Tu  11:44:00     119  52913161  DETECTOR  STATE  0001
1  Tu  11:44:00     119  52913161  DETECTOR  STATE  1100
2  Tu  11:44:02     119  52913161  DETECTOR  STATE  0000
3  Tu  11:44:02     119  52913161  DETECTOR  STATE  1110
4  Tu  11:44:04     119  52913161  DETECTOR  STATE  0000
5  Tu  11:44:04     119  52913161  DETECTOR  STATE  0011

And if need all columns as strings:

names = ["day", "time", "street", "sensor", "type", "state", "bits"]
df = pd.read_csv('EXPORT20171205114501_1.txt', sep="\s+", names=names, dtype=str)
print (df)
  day      time  street    sensor      type  state  bits
0  Tu  11:44:00     119  52913161  DETECTOR  STATE  0001
1  Tu  11:44:00     119  52913161  DETECTOR  STATE  1100
2  Tu  11:44:02     119  52913161  DETECTOR  STATE  0000
3  Tu  11:44:02     119  52913161  DETECTOR  STATE  1110
4  Tu  11:44:04     119  52913161  DETECTOR  STATE  0000
5  Tu  11:44:04     119  52913161  DETECTOR  STATE  0011


问:
DAX - PARALLELPERIOD() to get the previous minute
In DAX, I want to get the value for a previous minute.

I know the PARALLELPERIOD function can do this for the date and year, but does not allow this to be done by minute.

Is there an easy way I can write the below:

[DateTime]     = [DateTime]  - ( 1 / 24 / 60 )

I'm new to DAX and therefore aren't sure how to alias the two "DateTime"s in my filter condition (one for the universe of the calculate function, the other referring to the row in my original query)

I know of the EARLIER () function, but I don't understand how to define the order, to be my time column.

Edit:

My measure looks like the below:

```<code>Total:= SUM('Table'[CountColumn])
</code>```

I've started to write a measure to try and  get the previous minute:

```<code>PreviousMinuteTotal:= CALCULATE (
    SUM ( 'Table'[CountColumn] ),
    'Table'[DateTime]
            = 'Table'[DateTime]  - ( 1 / 24 / 60 ) )
</code>```

Obviously this is a contradiction as a date cannot be both itself and equal to the previous value, so I'm trying to work out how add a filter in calculate that looks back by one minute.

答:
Try something like this:

```<code>PreviousMinuteTotal =
    VAR PreviousMinute = MAX('Table'[DateTime]) - TIME(0,1,0)
    RETURN CALCULATE(SUM('Table'[CountColumn]), 'Table'[DateTime] = PreviousMinute)
</code>```

I had a bit of trouble (due to rounding maybe?) using this, so you might need to try this for the return line instead. (I added a second of wiggle room.)

```<code>RETURN CALCULATE(SUM('Table'[CountColumn]),
           'Table'[DateTime] > PreviousMinute - TIME(0,0,1),
           'Table'[DateTime] < PreviousMinute + TIME(0,0,1))
</code>```

Body:
In DAX, I want to get the value for a previous minute.

I know the PARALLELPERIOD function can do this for the date and year, but does not allow this to be done by minute.

Is there an easy way I can write the below:

[DateTime]     = [DateTime]  - ( 1 / 24 / 60 )

I'm new to DAX and therefore aren't sure how to alias the two "DateTime"s in my filter condition (one for the universe of the calculate function, the other referring to the row in my original query)

I know of the EARLIER () function, but I don't understand how to define the order, to be my time column.

Edit:

My measure looks like the below:

Total:= SUM('Table'[CountColumn])

I've started to write a measure to try and  get the previous minute:

PreviousMinuteTotal:= CALCULATE (
    SUM ( 'Table'[CountColumn] ),
    'Table'[DateTime]
            = 'Table'[DateTime]  - ( 1 / 24 / 60 ) )

Obviously this is a contradiction as a date cannot be both itself and equal to the previous value, so I'm trying to work out how add a filter in calculate that looks back by one minute.

Body:
Try something like this:

PreviousMinuteTotal =
    VAR PreviousMinute = MAX('Table'[DateTime]) - TIME(0,1,0)
    RETURN CALCULATE(SUM('Table'[CountColumn]), 'Table'[DateTime] = PreviousMinute)

I had a bit of trouble (due to rounding maybe?) using this, so you might need to try this for the return line instead. (I added a second of wiggle room.)

RETURN CALCULATE(SUM('Table'[CountColumn]),
           'Table'[DateTime] > PreviousMinute - TIME(0,0,1),
           'Table'[DateTime] < PreviousMinute + TIME(0,0,1))


问:
Read data from a local JSON file with data binding in ngOnInit() results in undefined variable
I am trying to get a data from json file in the assets folder, and then assign this data to a variable that will be binded to another @Input variable of a child componenet.

Code

Based on multiple solutions on the net, I retrieve my JSON data this way:

```<code>@Injectable()
export class JSONService {

    constructor(private http: HttpClient) { }

    public fromJSON(jsonFileName: string): Observable<any[]> {
      let result: any[] = new Array();
      let pathToJson: string = "assets/" + jsonFileName + ".json";

      return this.http.get(pathToJson).map(data => {
        let result: any[] = new Array();
        // Apply some treatment on data and push it to the result array
        return result;
      });
    }
}
</code>```

I then call my service in the ngOnInit() method of the parent component:

```<code>ngOnInit() {
    this.jsonService.fromJSON("users.json").subscribe(fields => {
      this.fields= fields;
      console.log(this.fields); // Log (I): this.fields is well defined
    });
    console.log(this.fields); // Log (II): this.fields is undefined
}
</code>```

Where the variable fields is binded to a child component:

```<code><child-component [childFields] = "fields"></child-component>
</code>```

Problem

The problem that I am facing is that the asynchronous call to the fromJSON method causes this.fields to be undefined at some point of the lifecycle of the page execution (Log (II) from the code above), and this causes to send an undefined value of the this.fields variable to the child component.

How to avoid to have an undefined value of the fields variable, and make sure that the child component is always loaded with the data from the json file?

答:
Assuming your component is somewhat like below

```<code>export class SomeComponent implements OnInit {
  public fields: any[];

  ngOnInit() {
    this.jsonService.fromJSON("users.json").subscribe(fields => {
      this.fields = fields;
      console.log(this.fields); // Log (I): this.fields is well defined
    });
    console.log(this.fields); // Log (II): this.fields is undefined
  }
}
</code>```

Then you can either initialize fields with an empty array

```<code>public fields: any[] = [];
</code>```

OR in template

```<code><child-component *ngIf="fields" [childFields]="fields"></child-component>
</code>```

Body:
I am trying to get a data from json file in the assets folder, and then assign this data to a variable that will be binded to another @Input variable of a child componenet.

Code

Based on multiple solutions on the net, I retrieve my JSON data this way:

@Injectable()
export class JSONService {

    constructor(private http: HttpClient) { }

    public fromJSON(jsonFileName: string): Observable<any[]> {
      let result: any[] = new Array();
      let pathToJson: string = "assets/" + jsonFileName + ".json";

      return this.http.get(pathToJson).map(data => {
        let result: any[] = new Array();
        // Apply some treatment on data and push it to the result array
        return result;
      });
    }
}

I then call my service in the ngOnInit() method of the parent component:

ngOnInit() {
    this.jsonService.fromJSON("users.json").subscribe(fields => {
      this.fields= fields;
      console.log(this.fields); // Log (I): this.fields is well defined
    });
    console.log(this.fields); // Log (II): this.fields is undefined
}

Where the variable fields is binded to a child component:

<child-component [childFields] = "fields"></child-component>

Problem

The problem that I am facing is that the asynchronous call to the fromJSON method causes this.fields to be undefined at some point of the lifecycle of the page execution (Log (II) from the code above), and this causes to send an undefined value of the this.fields variable to the child component.

How to avoid to have an undefined value of the fields variable, and make sure that the child component is always loaded with the data from the json file?

Body:
Assuming your component is somewhat like below

export class SomeComponent implements OnInit {
  public fields: any[];

  ngOnInit() {
    this.jsonService.fromJSON("users.json").subscribe(fields => {
      this.fields = fields;
      console.log(this.fields); // Log (I): this.fields is well defined
    });
    console.log(this.fields); // Log (II): this.fields is undefined
  }
}

Then you can either initialize fields with an empty array

public fields: any[] = [];

OR in template

<child-component *ngIf="fields" [childFields]="fields"></child-component>


问:
Turn id back into a reference object in AppScript objective-c
I'm writing an app that talks to Mail using Objective-C-appscript (objc-appscript). I want to make a copy of the currently selected mail messages and perform some processing on it at a later -- at which time the current selection may have changed.

```<code>MLApplication *mail = [[MLApplication alloc] initWithBundleID: @"com.apple.mail"];
MLReference *ref = [mail selection];
id theSelection = [[ref getItem] copy];

// Do something here, which may change the contents of ref,
// but that's okay since I made a copy in theSelection

MLMoveCommand *cmd = [[theSelection move] to: [[mail mailboxes] byName:@"test"]];

// This command should move the selected messages to the mailbox but fails
// because theSelection

MLReference *ref2 = nil; // Need to turn theSelection into an MLReference *
MLMoveCommand *cmd = [[ref2 move] to: [[mail mailboxes] byName:@"test"]];
</code>```

I need to turn theSelection back into an MLReference *. I'm sure this should be a simple operation, but I am new to appscript and require some guidance. Thanks!

答:
You can always cast theSelection to whatever type you want it to be.  You can also query it and find out what type it thinks it is using the class method.  You probably don't have to do this though.

For example,

NSString *something = [(MLReference *)theSelection someFuncIMadeUp];

You can read all about the runtime stuff (like the class method) in the apple doc:

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html

Body:
I'm writing an app that talks to Mail using Objective-C-appscript (objc-appscript). I want to make a copy of the currently selected mail messages and perform some processing on it at a later -- at which time the current selection may have changed.

MLApplication *mail = [[MLApplication alloc] initWithBundleID: @"com.apple.mail"];
MLReference *ref = [mail selection];
id theSelection = [[ref getItem] copy];

// Do something here, which may change the contents of ref,
// but that's okay since I made a copy in theSelection

MLMoveCommand *cmd = [[theSelection move] to: [[mail mailboxes] byName:@"test"]];

// This command should move the selected messages to the mailbox but fails
// because theSelection

MLReference *ref2 = nil; // Need to turn theSelection into an MLReference *
MLMoveCommand *cmd = [[ref2 move] to: [[mail mailboxes] byName:@"test"]];

I need to turn theSelection back into an MLReference *. I'm sure this should be a simple operation, but I am new to appscript and require some guidance. Thanks!


问:
why does it only add 2 when passed by reference?
How come only when its passed by reference does the value of age change? why doesn't it work when passed by value?

```<code>    #include<stdio.h>
struct employee{
char name[20];
int age;
};
void modify_byVal(struct employee v){
    v.age=v.age+2;
    }
    void modify_byRef(struct employee *p){
 p ->age=p->age+2;
 }
 void main(){
     struct employee Sam = {"Sam", 35};
     struct employee Mary = {"Mary", 25};
     modify_byVal(Sam);
     modify_byRef(&Mary);
     printf("%s %d", Sam.name, Sam.age);
     printf(" ");
     printf("%s %d", Mary.name, Mary.age);
     }
</code>```

Output of code

答:
Because the change you made when you passed the value is on the copy of the variable passed. This is completely unrelated with the variable in main().

On the second case when you passed the address as an value, you dereferenced it and made changes to that address's variable. That's why the change retained.

There is no pass by reference in C.

Body:
How come only when its passed by reference does the value of age change? why doesn't it work when passed by value?

    #include<stdio.h>
struct employee{
char name[20];
int age;
};
void modify_byVal(struct employee v){
    v.age=v.age+2;
    }
    void modify_byRef(struct employee *p){
 p ->age=p->age+2;
 }
 void main(){
     struct employee Sam = {"Sam", 35};
     struct employee Mary = {"Mary", 25};
     modify_byVal(Sam);
     modify_byRef(&Mary);
     printf("%s %d", Sam.name, Sam.age);
     printf(" ");
     printf("%s %d", Mary.name, Mary.age);
     }

Output of code


问:
Dynamic Parameter cannot be specified in parameter set '__AllParameterSets'

Hello, I am trying to create a dynamic ValidateSet that is based on the contents of a simple text file for one of my cmdlet parameters.  I followed this blog post https://blogs.technet.microsoft.com/pstips/2014/06/09/dynamic-validateset-in-a-dynamic-parameter/, and I came up with the following:

```<code>function Remove-NetScalerWhiteListItem
{
[CmdletBinding()]
Param
(
)
DynamicParam
{
    $ParameterName = "ServiceGroup"

    $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]

    $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
    $ParameterAttribute.Mandatory = $true
    $ParameterAttribute.Position = 0
    $ParameterAttribute.DontShow = $false

    $serviceGroups = Get-NetScalerWhiteList

    $ValidateSetAtrribute = New-Object System.Management.Automation.ValidateSetAttribute($serviceGroups)

    $AttributeCollection.Add($ValidateSetAtrribute)

    $RunTimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)

    $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
    $RuntimeParameterDictionary.Add($ParameterName, $RunTimeParameter)

    $RuntimeParameterDictionary

}
Begin
{
    $ServiceGroup = $PSBoundParameters[$ParameterName]
}
Process
{
    Copy-Item "$masterIgnoreFilePath\ingnore.txt" "$masterIgnoreFilePath\ingnore.bak"
    $serviceGroups = Get-NetScalerWhiteList
    $serviceGroups.Remove($serviceGroup)
    Write-Host $serviceGroups

}

}
</code>```

This partially works, if I begin by typing Remove-NetScalerWhiteListItem -ServiceGroup my validation set is there and working, however when I select one of the items and run the command I get the following error:

```<code>Remove-NetScalerWhiteListItem : Parameter 'ServiceGroup' cannot be specified
in parameter set '__AllParameterSets'.
At line:1 char:1
+ Remove-NetScalerWhiteListItem -servicegroup servicegroupname
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Remove-
NetScalerWhiteListItem], ParameterBindingException
    + FullyQualifiedErrorId : ParameterNotInParameterSet,Remove-
NetScalerWhiteListItem
</code>```

As for the line $serviceGroups = Get-NetScalerWhiteList that is just a wrapper around a Get-Content call to a specific file.

答:
I think you need one more line. You never add the $ParameterAttribute to the $AttributeCollection. You can do so by using this line $AttributeCollection.Add($ParameterAttribute).

```<code>function Remove-NetScalerWhiteListItem
{
[CmdletBinding()]
Param
(
)
DynamicParam
{
    $ParameterName = "ServiceGroup"

    $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]

    $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
    $ParameterAttribute.Mandatory = $true
    $ParameterAttribute.Position = 0
    $ParameterAttribute.DontShow = $false

    $serviceGroups = Get-NetScalerWhiteList

    $ValidateSetAtrribute = New-Object System.Management.Automation.ValidateSetAttribute($serviceGroups)

    $AttributeCollection.Add($ValidateSetAtrribute)
    $AttributeCollection.Add($ParameterAttribute)

    $RunTimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)

    $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
    $RuntimeParameterDictionary.Add($ParameterName, $RunTimeParameter)

    $RuntimeParameterDictionary

}
Begin
{
    $ServiceGroup = $PSBoundParameters[$ParameterName]
}
Process
{
    Copy-Item "$masterIgnoreFilePath\ingnore.txt" "$masterIgnoreFilePath\ingnore.bak"
    $serviceGroups = Get-NetScalerWhiteList
    $serviceGroups.Remove($serviceGroup)
    Write-Host $serviceGroups

}

}
</code>```

Body:
Hello, I am trying to create a dynamic ValidateSet that is based on the contents of a simple text file for one of my cmdlet parameters.  I followed this blog post https://blogs.technet.microsoft.com/pstips/2014/06/09/dynamic-validateset-in-a-dynamic-parameter/, and I came up with the following:

function Remove-NetScalerWhiteListItem
{
[CmdletBinding()]
Param
(
)
DynamicParam
{
    $ParameterName = "ServiceGroup"

    $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]

    $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
    $ParameterAttribute.Mandatory = $true
    $ParameterAttribute.Position = 0
    $ParameterAttribute.DontShow = $false

    $serviceGroups = Get-NetScalerWhiteList

    $ValidateSetAtrribute = New-Object System.Management.Automation.ValidateSetAttribute($serviceGroups)

    $AttributeCollection.Add($ValidateSetAtrribute)

    $RunTimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)

    $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
    $RuntimeParameterDictionary.Add($ParameterName, $RunTimeParameter)

    $RuntimeParameterDictionary

}
Begin
{
    $ServiceGroup = $PSBoundParameters[$ParameterName]
}
Process
{
    Copy-Item "$masterIgnoreFilePath\ingnore.txt" "$masterIgnoreFilePath\ingnore.bak"
    $serviceGroups = Get-NetScalerWhiteList
    $serviceGroups.Remove($serviceGroup)
    Write-Host $serviceGroups

}

}

This partially works, if I begin by typing Remove-NetScalerWhiteListItem -ServiceGroup my validation set is there and working, however when I select one of the items and run the command I get the following error:

Remove-NetScalerWhiteListItem : Parameter 'ServiceGroup' cannot be specified
in parameter set '__AllParameterSets'.
At line:1 char:1
+ Remove-NetScalerWhiteListItem -servicegroup servicegroupname
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Remove-
NetScalerWhiteListItem], ParameterBindingException
    + FullyQualifiedErrorId : ParameterNotInParameterSet,Remove-
NetScalerWhiteListItem

As for the line $serviceGroups = Get-NetScalerWhiteList that is just a wrapper around a Get-Content call to a specific file.

Body:
I think you need one more line. You never add the $ParameterAttribute to the $AttributeCollection. You can do so by using this line $AttributeCollection.Add($ParameterAttribute).

function Remove-NetScalerWhiteListItem
{
[CmdletBinding()]
Param
(
)
DynamicParam
{
    $ParameterName = "ServiceGroup"

    $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]

    $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
    $ParameterAttribute.Mandatory = $true
    $ParameterAttribute.Position = 0
    $ParameterAttribute.DontShow = $false

    $serviceGroups = Get-NetScalerWhiteList

    $ValidateSetAtrribute = New-Object System.Management.Automation.ValidateSetAttribute($serviceGroups)

    $AttributeCollection.Add($ValidateSetAtrribute)
    $AttributeCollection.Add($ParameterAttribute)

    $RunTimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)

    $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
    $RuntimeParameterDictionary.Add($ParameterName, $RunTimeParameter)

    $RuntimeParameterDictionary

}
Begin
{
    $ServiceGroup = $PSBoundParameters[$ParameterName]
}
Process
{
    Copy-Item "$masterIgnoreFilePath\ingnore.txt" "$masterIgnoreFilePath\ingnore.bak"
    $serviceGroups = Get-NetScalerWhiteList
    $serviceGroups.Remove($serviceGroup)
    Write-Host $serviceGroups

}

}


问:
TensorFlow on Windows: "Couldn't open CUDA library cudnn64_5.dll"
Tensorflow just released windows support. I installed the gpu version and CUDA 8.0 and python 3.5. However, after I import the tensorflow I got the following error:

```<code>>>> import tensorflow
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\dso_loader.cc:128] successfully opened CUDA library cublas64_80.dll locally
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\dso_loader.cc:119] Couldn't open CUDA library cudnn64_5.dll
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\cuda\cuda_dnn.cc:3459] Unable to load cuDNN DSO
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\dso_loader.cc:128] successfully opened CUDA library cufft64_80.dll locally
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\dso_loader.cc:128] successfully opened CUDA library nvcuda.dll locally
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\dso_loader.cc:128] successfully opened CUDA library curand64_80.dll locally
</code>```

Can someone help? Thanks!

答:
Tried pip3 install --upgrade tensorflow after tensorflow-gpu and it worked fine.

I think it's an issue only when trying pip3 install --upgrade tensorflow-gpu directly.

Body:
Tensorflow just released windows support. I installed the gpu version and CUDA 8.0 and python 3.5. However, after I import the tensorflow I got the following error:

>>> import tensorflow
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\dso_loader.cc:128] successfully opened CUDA library cublas64_80.dll locally
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\dso_loader.cc:119] Couldn't open CUDA library cudnn64_5.dll
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\cuda\cuda_dnn.cc:3459] Unable to load cuDNN DSO
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\dso_loader.cc:128] successfully opened CUDA library cufft64_80.dll locally
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\dso_loader.cc:128] successfully opened CUDA library nvcuda.dll locally
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\dso_loader.cc:128] successfully opened CUDA library curand64_80.dll locally

Can someone help? Thanks!


问:
Event handle on customized ListView
```<code>public class ActivityForShow extends Activity

{
     //have a ListView layout
     ListView.setAdapter(SingleRowAdapter);
}

public class SingleRowAdapter extends ArrayAdapter
{
    //every row has a CheckBox ,a TextView and a Button
}
</code>```

Now I want to handle CheckBox and Button events,do some background work and show result in a dialog.

But how to getRefences of Checkbox and Button in ActivityForShow?

findViewById() will cause Exception.

答: I don't think you want to do that in the ActivityForShow class. Instead, register all event handlers inside of your SingleRowAdapter#getItem(int) method (you will have have to override this). In that method you create the view for the given row, so you know what the row is (position) and you can register event handlers for the CheckBox, Button, etc</p>

Title: Event handle on customized ListView

Body:
public class ActivityForShow extends Activity

{
     //have a ListView layout
     ListView.setAdapter(SingleRowAdapter);
}

public class SingleRowAdapter extends ArrayAdapter
{
    //every row has a CheckBox ,a TextView and a Button
}

Now I want to handle CheckBox and Button events,do some background work and show result in a dialog.

But how to getRefences of Checkbox and Button in ActivityForShow?

findViewById() will cause Exception.


问:
Which JS benchmark site is correct?
I created a benchmark on both jsperf.com and jsben.ch, however, they're giving substantially different results.

JSPerf: https://jsperf.com/join-vs-template-venryx

JSBench: http://jsben.ch/9DaxR

Note that the code blocks are exactly the same.

On jsperf, block 1 is "61% slower" than the fastest:

On jsbench, block 1 is only 32% slower than the fastest: ((99 - 75) / 75)

What gives? I would expect benchmark sites to give the same results, at least within a few percent.

As it stands, I'm unable to make a conclusion on which option is fastest because of the inconsistency.

EDIT

Extended list of benchmarks:

https://jsperf.com/join-vs-template-venryx

https://jsbench.me/f3k3g71sg9

http://jsbench.github.io/#7f03c3d3fdc9ae3a399d0f2d6de3d69f

https://run.perf.zone/view/Join-vs-Template-Venryx-1512492228976

http://jsben.ch/9DaxR

Not sure which is the best, but I'd skip jsben.ch (the last one) for the reasons Job mentions: it doesn't display the number of runs, the error margin, or the  number of operations per second -- which is important for estimating absolute performance impact, and enabling stable comparison between benchmark sites and/or browsers and browser versions.

(At the moment http://jsbench.me is my favorite.)

答:
March 2019 Update: results are inconsistent between Firefox and Chrome - perf.zone behave anomalously on Chrome, jsben.ch behaves anomalously on Firefox. Until we know exactly why, the best you can do is benchmark on multiple websites (but I'd still skip jsben.ch, the others give you a least some error margin and stats on how many runs were taken, and so on)

TL;DR: <s>running your code on perf.zone and on jsbench.github.io (see here and here), the results closely match jsperf.</s> Personally, and for other reasons than just these results, I trust these three websites more than jsben.ch.

Recently, I tried benchmarking the performance of string concatenation too, but in my case it's building one string out of 1000000+ single character strings (join('') wins for numbers this large and up, btw). On my machine the jsben.ch timed out instead of giving a result at all. Perhaps it works better on yours, but for me that's a big warning sign:

http://jsben.ch/mYaJk

http://jsbench.github.io/#26d1f3705b3340ace36cbad7b24055fb

https://run.perf.zone/view/join-vs-concat-when-dealing-with-very-long-lists-of-single-character-strings-1512490506658

(I can't be bothered to ever have to deal with jsperf's not all tests inserted again, sorry)

At the moment I suspect but can't prove that perf.zone has slightly more reliable benchmark numbers:

when optimising lz-string I used jsbench.github.io for a very long time, but at some point I noticed there were impossibly large error margins for certain types of code, over 100%.

running benchmarks on mobile is fine with jsperf.com and perf.zone, but jsbench.github.io is kinda janky and the CSS breaks while running tests.

Perhaps these two things are related: perhaps the method that jsbench.github.io uses to update the DOM introduces some kind of overhead that affects the benchmarks (they should meta-benchmark that...).

Note: perf.zone is not without its flaws. It sometimes times out when trying to save a benchmark (the worst time to do so...) and you can only fork your own code, not edit it. But the output still seems to be more in line with jsperf, and it has a really nice "quick" mode for throwaway benchmarking

Title: Which JS benchmark site is correct?


问:
How to set a different color for ListViewItem based on value?
I'm trying to set a different color based on the item value of a ListView, what I did so far:

```<code><ListView ItemsSource="{Binding Collections}">
   <ListView.Resources>
       <Style TargetType="{x:Type ListViewItem}">
            <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource SignColorConverter}}" />
       </Style>
   </ListView.Resources>
   <ListView.View>
        <GridView>
            <GridView.Columns>
                 <GridViewColumn Header="Item1" DisplayMemberBinding="{Binding Item1}"/>
                 <GridViewColumn Header="Item2" DisplayMemberBinding="{Binding Item2}"/>
</code>```

the converter:

```<code>public class SignColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var input = System.Convert.ToInt32(value as string);

        //this method simply check if the value is between a range.
        if (GeneralUtility.IsInRange(input, 0, 20))
        {
            return Brushes.Red;
        }
        else
        {
            return DependencyProperty.UnsetValue;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
</code>```

the problem's that the input value in the converter is even 0. What am I doing wrong?

Thanks for any help.

UPDATE

The Collection property contains these values:

```<code>public List<Collection> Collection
{
     public Item1 { get; set; }
     public Item2 { get; set; }
}
</code>```

so essentially I need to pass in the style:

```<code> <Style TargetType="{x:Type ListViewItem}">
            <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource SignColorConverter}}" />
       </Style>
</code>```

each Item value of Collection, and evaluate the value on the converter.

答:
Your XAML binds the ListViewItem to the setter. When your IValueConverter converts the ListViewItem type, it returns 0 (if you used int.TryParse(), it would return false). What you are missing is that you have to bind the setter to a property in the ListViewItem. For example, if your ListViewItem is:

```<code>class item
{
    public object Item1 {get;set;}
    public object Item2 {get;set;}
    public int Color {get;set;}
}
</code>```

Then your XAML can be:

```<code><ListView ItemsSource="{Binding Collections}">
    <ListView.Resources>
        <local:SignColorConverter x:Key="SignColorConverter"/>
        <Style TargetType="{x:Type ListViewItem}">
            <Setter Property="Background" Value="{Binding Color, Converter={StaticResource SignColorConverter}}"/>
        </Style>
    </ListView.Resources>
    <ListView.View>
        <GridView>
            <GridView.Columns>
                <GridViewColumn Header="Item1" DisplayMemberBinding="{Binding Item1}"/>
                    <GridViewColumn Header="Item2" DisplayMemberBinding="{Binding Item2}"/>
...
</code>```

Or if you have to evaluate multiple item properties, your XAML can stay the same as OP:

```<code>...
    <Style TargetType="{x:Type ListViewItem}">
        <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}}, Converter={StaticResource SignColorConverter}}"/>
    </Style>
...
</code>```

And then you have to evaluate the ListViewItem as the appropriate type in the IValueConverter:

```<code>public class SignColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var input = (item)value;
        if (input != null)
        {
            int item1 = int.Parse(input.Item1);
            int item2 = int.Parse(input.Item2);
            //Your logic here
            return Brushes.Red;
        }
        else
        {
            return DependencyProperty.UnsetValue;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
</code>```

Body:
I'm trying to set a different color based on the item value of a ListView, what I did so far:

<ListView ItemsSource="{Binding Collections}">
   <ListView.Resources>

   </ListView.Resources>
   <ListView.View>
        <GridView>
            <GridView.Columns>
                 <GridViewColumn Header="Item1" DisplayMemberBinding="{Binding Item1}"/>
                 <GridViewColumn Header="Item2" DisplayMemberBinding="{Binding Item2}"/>

the converter:

public class SignColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var input = System.Convert.ToInt32(value as string);

        //this method simply check if the value is between a range.
        if (GeneralUtility.IsInRange(input, 0, 20))
        {
            return Brushes.Red;
        }
        else
        {
            return DependencyProperty.UnsetValue;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

the problem's that the input value in the converter is even 0. What am I doing wrong?

Thanks for any help.

UPDATE

The Collection property contains these values:

public List<Collection> Collection
{
     public Item1 { get; set; }
     public Item2 { get; set; }
}

so essentially I need to pass in the style:

each Item value of Collection, and evaluate the value on the converter.

Body:
Your XAML binds the ListViewItem to the setter. When your IValueConverter converts the ListViewItem type, it returns 0 (if you used int.TryParse(), it would return false). What you are missing is that you have to bind the setter to a property in the ListViewItem. For example, if your ListViewItem is:

class item
{
    public object Item1 {get;set;}
    public object Item2 {get;set;}
    public int Color {get;set;}
}

Then your XAML can be:

<ListView ItemsSource="{Binding Collections}">
    <ListView.Resources>
        <local:SignColorConverter x:Key="SignColorConverter"/>
        <Style TargetType="{x:Type ListViewItem}">
            <Setter Property="Background" Value="{Binding Color, Converter={StaticResource SignColorConverter}}"/>
        </Style>
    </ListView.Resources>
    <ListView.View>
        <GridView>
            <GridView.Columns>
                <GridViewColumn Header="Item1" DisplayMemberBinding="{Binding Item1}"/>
                    <GridViewColumn Header="Item2" DisplayMemberBinding="{Binding Item2}"/>
...

Or if you have to evaluate multiple item properties, your XAML can stay the same as OP:

...
    <Style TargetType="{x:Type ListViewItem}">
        <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}}, Converter={StaticResource SignColorConverter}}"/>
    </Style>
...

And then you have to evaluate the ListViewItem as the appropriate type in the IValueConverter:

public class SignColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var input = (item)value;
        if (input != null)
        {
            int item1 = int.Parse(input.Item1);
            int item2 = int.Parse(input.Item2);
            //Your logic here
            return Brushes.Red;
        }
        else
        {
            return DependencyProperty.UnsetValue;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}


问:
How to efficiently alias a float as both a named member and an element of an array?
I am implementing a particle-based fluid simulation. To represent vectors such as velocity, acceleration etc I have defined a class that looks like this

```<code>class Vec3f {
public:
    float x, y, z;

    // ... bunch of constructors, operators and utility functions
}
</code>```

I'm using the library nanoflann for kd-tree searches. To accommodate for arbitrary class designs, nanoflann requires a user-defined adaptor class that the kd-tree class then queries to get info about the particle dataset. One function that the adaptor has to offer, as described in the nanoflann documentation is the following.

```<code>// Must return the dim'th component of the idx'th point in the class:
inline T kdtree_get_pt(const size_t idx, int dim) const { ... }
</code>```

The problem is that this interface does not work seamlessly with the x, y, z representation. Naively, it would need to do something like this

```<code>inline float kdtree_get_pt(const size_t idx, int dim) const {
    switch(dim) {
    case 0:
        return particlearray[idx].x;
    case 1:
        return particlearray[idx].y;
    case 2:
        return particlearray[idx].z;
    }
}
</code>```

Building and querying the kd-tree consumes a significant portion of my app's runtime and kd_tree_get_pt gets queried multiple times in the process so I need it to be optimized. The following solution should be faster.

```<code>class Vec3f {
public:
    float values[3];
    // ...
}

// Then inside the adaptor class
inline float kdtree_get_pt(const size_t idx, int dim) const {
    return particlearrray[idx].values[dim];
}
</code>```

However, I much prefer the x, y, z interface for my equations. Now that the problem is clear, my question is how can I keep the x, y, z notation for my equations without making kdtree_get_pt suboptimal.

Solutions I have considered:

Vec3f has member float values[3] and getters in the form of float& x(). The function call should be optimized away completely so this almost works but I do not want to have to add the parentheses in my equations if I can avoid it. eg I want to be able to write vec1.x - vec2.x instead of vec1.x() - vec2.x(). As far as I know, C++ does not offer a way to "disguise" a function call as a member variable, excluding preprocessor macros which I do not consider a safe solution.

Vec3f has members float values[3] and float& x, y, z where the latter are initialized to point to the corresponding floats in the array. I thought they would be optimized away as they are known at compile time and obviously cannot change value after initialization, but even with optimizations on, MSVC++ seems to actually store the float&s as can be seen by sizeof(Vec3f) growing by 12 bytes after their addition. This doubles the storage size of my dataset which raises a concern for cache misses when working with arbitrarily large datasets.

kdtree_get_pt uses float& values[3] to point to x, y, z. This might eliminate the branching cost, but I don't believe the extra level of indirection, nor the need to initialize all 3 references can be optimized away so it is presumably slower than the return particlearrray[idx][dim]` version.

kdtree_get_pt uses reinterpret_cast or pointer magic to directly point into Vec3f's members. Given a Vec3f object's address, I believe x, y, z are guaranteed to be stored in that order with the first one stored at the same address as the one given by the & operator on the Vec3f object, but even so I'm confused as to whether there exists a well-defined way to observe them.

答:
You should always check if the switch statements will really introduce branchings in the final compiled output. A tool that might help you there is godbolt.

For both of those code snippets (random and cout have been added to prevent complete removeal of the code):

```<code>#include<cstddef>
#include<array>
#include<iostream>
#include <ctime>

class Vec3f {
public:
    float values[3];
};

struct Test {
    std::array<Vec3f,100> particlearray;

    float kdtree_get_pt(const size_t idx, int dim) const {
        return particlearray[idx].values[dim];
    }
};

int main() {
   Test t;

   std::srand(std::time(0));
   int random_variable = std::rand();

   std::cout << t.kdtree_get_pt(random_variable,0);
   std::cout << t.kdtree_get_pt(random_variable,1);
   std::cout << t.kdtree_get_pt(random_variable,2) << std::endl;

   return 0;
}
</code>```

and

```<code>#include<iostream>
#include<array>
#include<ctime>
#include<cstdlib>
#include<cstddef>

class Vec3f {
public:
    float x, y, z;
};

struct Test {
    std::array<Vec3f,100> particlearray;

    float kdtree_get_pt(const size_t idx, int dim) const {
        switch(dim) {
        case 0:
            return particlearray[idx].x;
        case 1:
            return particlearray[idx].y;
        case 2:
            return particlearray[idx].z;
        }
    }
};

int main() {
   Test t;

   std::srand(std::time(0));
   int random_variable = std::rand();

   std::cout << t.kdtree_get_pt(random_variable,0);
   std::cout << t.kdtree_get_pt(random_variable,1);
   std::cout << t.kdtree_get_pt(random_variable,2) << std::endl;

   return 0;
}
</code>```

The access to x, y and z or values[dim] will be compiled (by gcc 7) to:

```<code>cvtss2sd xmm0, DWORD PTR [rsp+rbx]
cvtss2sd xmm0, DWORD PTR [rsp+4+rbx]
cvtss2sd xmm0, DWORD PTR [rsp+8+rbx]
</code>```

Without any branching.

Body:
I am implementing a particle-based fluid simulation. To represent vectors such as velocity, acceleration etc I have defined a class that looks like this

class Vec3f {
public:
    float x, y, z;

    // ... bunch of constructors, operators and utility functions
}

I'm using the library nanoflann for kd-tree searches. To accommodate for arbitrary class designs, nanoflann requires a user-defined adaptor class that the kd-tree class then queries to get info about the particle dataset. One function that the adaptor has to offer, as described in the nanoflann documentation is the following.

// Must return the dim'th component of the idx'th point in the class:
inline T kdtree_get_pt(const size_t idx, int dim) const { ... }

The problem is that this interface does not work seamlessly with the x, y, z representation. Naively, it would need to do something like this

inline float kdtree_get_pt(const size_t idx, int dim) const {
    switch(dim) {
    case 0:
        return particlearray[idx].x;
    case 1:
        return particlearray[idx].y;
    case 2:
        return particlearray[idx].z;
    }
}

Building and querying the kd-tree consumes a significant portion of my app's runtime and kd_tree_get_pt gets queried multiple times in the process so I need it to be optimized. The following solution should be faster.

class Vec3f {
public:
    float values[3];
    // ...
}

// Then inside the adaptor class
inline float kdtree_get_pt(const size_t idx, int dim) const {
    return particlearrray[idx].values[dim];
}

However, I much prefer the x, y, z interface for my equations. Now that the problem is clear, my question is how can I keep the x, y, z notation for my equations without making kdtree_get_pt suboptimal.

Solutions I have considered:

Vec3f has member float values[3] and getters in the form of float& x(). The function call should be optimized away completely so this almost works but I do not want to have to add the parentheses in my equations if I can avoid it. eg I want to be able to write vec1.x - vec2.x instead of vec1.x() - vec2.x(). As far as I know, C++ does not offer a way to "disguise" a function call as a member variable, excluding preprocessor macros which I do not consider a safe solution.

Vec3f has members float values[3] and float& x, y, z where the latter are initialized to point to the corresponding floats in the array. I thought they would be optimized away as they are known at compile time and obviously cannot change value after initialization, but even with optimizations on, MSVC++ seems to actually store the float&s as can be seen by sizeof(Vec3f) growing by 12 bytes after their addition. This doubles the storage size of my dataset which raises a concern for cache misses when working with arbitrarily large datasets.

kdtree_get_pt uses float& values[3] to point to x, y, z. This might eliminate the branching cost, but I don't believe the extra level of indirection, nor the need to initialize all 3 references can be optimized away so it is presumably slower than the return particlearrray[idx][dim]` version.

kdtree_get_pt uses reinterpret_cast or pointer magic to directly point into Vec3f's members. Given a Vec3f object's address, I believe x, y, z are guaranteed to be stored in that order with the first one stored at the same address as the one given by the & operator on the Vec3f object, but even so I'm confused as to whether there exists a well-defined way to observe them.

Body:
You should always check if the switch statements will really introduce branchings in the final compiled output. A tool that might help you there is godbolt.

For both of those code snippets (random and cout have been added to prevent complete removeal of the code):

#include<cstddef>
#include<array>
#include<iostream>
#include <ctime>

class Vec3f {
public:
    float values[3];
};

struct Test {
    std::array<Vec3f,100> particlearray;

    float kdtree_get_pt(const size_t idx, int dim) const {
        return particlearray[idx].values[dim];
    }
};

int main() {
   Test t;

   std::srand(std::time(0));
   int random_variable = std::rand();

   std::cout << t.kdtree_get_pt(random_variable,0);
   std::cout << t.kdtree_get_pt(random_variable,1);
   std::cout << t.kdtree_get_pt(random_variable,2) << std::endl;

   return 0;
}

and

#include<iostream>
#include<array>
#include<ctime>
#include<cstdlib>
#include<cstddef>

class Vec3f {
public:
    float x, y, z;
};

struct Test {
    std::array<Vec3f,100> particlearray;

    float kdtree_get_pt(const size_t idx, int dim) const {
        switch(dim) {
        case 0:
            return particlearray[idx].x;
        case 1:
            return particlearray[idx].y;
        case 2:
            return particlearray[idx].z;
        }
    }
};

int main() {
   Test t;

   std::srand(std::time(0));
   int random_variable = std::rand();

   std::cout << t.kdtree_get_pt(random_variable,0);
   std::cout << t.kdtree_get_pt(random_variable,1);
   std::cout << t.kdtree_get_pt(random_variable,2) << std::endl;

   return 0;
}

The access to x, y and z or values[dim] will be compiled (by gcc 7) to:

cvtss2sd xmm0, DWORD PTR [rsp+rbx]
cvtss2sd xmm0, DWORD PTR [rsp+4+rbx]
cvtss2sd xmm0, DWORD PTR [rsp+8+rbx]

Without any branching.


问:
Query and regex find data

Hello guys! I try to accomplish the following.
I have a string which is a query string like:

```<code>let query = "?course_subject=Robotica&course_type=%20C&course_location=%20VIV7&course_teacher=%20Pozna_C_R&course_start_hour=14:00%20&course_end_hour=%2015:50"
</code>```

Which I get with:window.location.search

What I try to get back is all the pairs name - value in an array like:

```<code>output_array = [["course_subject","Robotia"],["course_type","C"]]
</code>```

And so on.
But I can not figure out how to write the code using regex.
Can someone help me with the code?
I mention that I do not know the query string which it will come, so I can not search using a name,like:course_subject or course_type

答:
You can first decode your url using decodeURI and then array#split on & and then use array#map to arrayp#split each string on =.

let query = "course_subject=Robotica&course_type=%20C&course_location=%20VIV7&course_teacher=%20Pozna_C_R&course_start_hour=14:00%20&course_end_hour=%2015:50";
var result = decodeURI(query).split('&').map(str => str.split('='));
console.log(result);```

Title: Query and regex find data

Body:
Hello guys! I try to accomplish the following.
I have a string which is a query string like:

let query = "?course_subject=Robotica&course_type=%20C&course_location=%20VIV7&course_teacher=%20Pozna_C_R&course_start_hour=14:00%20&course_end_hour=%2015:50"

Which I get with:window.location.search

What I try to get back is all the pairs name - value in an array like:

output_array = [["course_subject","Robotia"],["course_type","C"]]

And so on.
But I can not figure out how to write the code using regex.
Can someone help me with the code?
I mention that I do not know the query string which it will come, so I can not search using a name,like:course_subject or course_type


问:
Find closest value to determined multiplicated value
I have two values. One is static and equals 24

```<code>int A = 24;
</code>```

and I have entries list :

```<code>[0, 21, 45, 76, 98]
</code>```

All of occurences comes in loop and I want to get closest value which divides on A :

```<code>0 - 24
21 - 24
45 - 48
76 - 72
98 - 96
</code>```

How to calculate this?

答:
You could divide each value by a using floating point division, round it to the closest int and then multiply it back again by a:

```<code>int a = 24;
int[] values = new int[]{0, 21, 45, 76, 98};

int[] result =
    Arrays.stream(values).map(v -> a * (int) Math.round(v / (double) a)).toArray();
</code>```

Body:
I have two values. One is static and equals 24

int A = 24;

and I have entries list :

[0, 21, 45, 76, 98]

All of occurences comes in loop and I want to get closest value which divides on A :

0 - 24
21 - 24
45 - 48
76 - 72
98 - 96

How to calculate this?

Body:
You could divide each value by a using floating point division, round it to the closest int and then multiply it back again by a:

int a = 24;
int[] values = new int[]{0, 21, 45, 76, 98};

int[] result =
    Arrays.stream(values).map(v -> a * (int) Math.round(v / (double) a)).toArray();


问:
Specify an output message for successful test case
Each Assert allow to define error message which will be printed out in case of assert failure but can I somehow provide a message which will be outputed in case of successful test run?

答:
You should handle the NUnit.Framework.SuccessException and print the message:

try
{
    // assert
    Assert.Pass(sOutput);
}
catch (SuccessException ex)
{
    Console.WriteLine(ex.Message);
    return;
}
```

As a result you should get the output message under clicking Output:

Body:
You should handle the NUnit.Framework.SuccessException and print the message:

try
{
    // assert
    Assert.Pass(sOutput);
}
catch (SuccessException ex)
{
    Console.WriteLine(ex.Message);
    return;
}

As a result you should get the output message under clicking Output:


问:
Comments field in SharePoint Issue Tracking list
I've created a list using the SharePoint (MOSS 2007) Issue Tracking List.  A "Comments" field is automatically created in this list.  The Comments column has extra functionality that provides a sort of history/log whenever an edit is made to a list item.  Unfortunately, a comment entry is created even when an insignificant edit is made.  For example, I could edit the title of the list item and leave the comment field blank.  This results in a blank entry being saved for the Comments field (except the date/time of the edit and the person making it).  If there are several edits made (with the Comments field left empty), then several blank entries appear to be stored in the data (for the Comment field).  Is there a way to not save a comment entry if it's blank?

Also, is there a way to have a Comments field in a Custom List?  This column seems to only be available in the Issues Tracking List.

答:
i managed to remove the blank comments by changing it to plain text. see this blog

http://mekalikot.blogspot.com/2011/01/how-to-remove-blank-comments-on-append.html


问:
Add img tag to a button rendered by php function
I'm trying to add an  tag to a button (inside the button) that is created/rendered by a php function.

Inside that function, in the end, I have this:

```<code>return $environment->render('WizardBundle:Participation:ssa.html.twig', $parameters);
</code>```

ssa.html.twig has:

```<code>{% if url is defined %}
    <a href="{{ url }}" {{ attributes|raw }}><img src="{{ asset(assetsPath ~ '/images/image.png') }}">{{ label|trans({}, 'wizard') }}</a>
{% else %}
    <p>{{ label }}</p>
{% endif %}
</code>```

I tried to add the tag inside the , but nothing shows up.
Do I need to modify anything in that php function (can post if needed)?

答:
This works fine for me:

```<code>$parameters = [
    'url' => 'http://google.es',
    'attributes' => 'target="_blank"',
    'label' => 'button',
    'assetsPath' => ''
];
</code>```

on template:

```<code>{% if url is defined %}
    <a href="{{ url }}" {{ attributes|raw }}>
        <button><img src="{{ asset(assetsPath ~ '/images/image.png') }}"> {{ label }}</a></button>
    </a>
{% else %}
    <p>{{ label }}</p>
{% endif %}
</code>```

If don't work for you, can you put the full code?

Body:
I'm trying to add an  tag to a button (inside the button) that is created/rendered by a php function.

Inside that function, in the end, I have this:

return $environment->render('WizardBundle:Participation:ssa.html.twig', $parameters);

ssa.html.twig has:

{% if url is defined %}
    {{ label|trans({}, 'wizard') }}
{% else %}

{{ label }}

{% endif %}

I tried to add the tag inside the , but nothing shows up.
Do I need to modify anything in that php function (can post if needed)?

Body:
This works fine for me:

$parameters = [
    'url' => 'http://google.es',
    'attributes' => 'target="_blank"',
    'label' => 'button',
    'assetsPath' => ''
];

on template:

{% if url is defined %}
    <a href="{{ url }}" {{ attributes|raw }}>
        <button><img src="{{ asset(assetsPath ~ '/images/image.png') }}"> {{ label }}</a></button>
    </a>
{% else %}
    <p>{{ label }}</p>
{% endif %}

If don't work for you, can you put the full code?