问:
Serialize Object to to Application Settings in C#
I am trying to serialize an object into Application Settings.  I have a setting defined to be the object type already.  Here is the class I am trying to serialize.  I have to serialize an object to the application settings because the object type isn't known at runtime.

```<code>[Serializable]
[XmlInclude(typeof(TemplateGeneratorPreferences))]
public class MyPreferences
{
    [XmlElement(ElementName="GeneratorPreferences", Type=typeof(TemplateGeneratorPreferences))]
    public TemplateGeneratorPreferences FormSpecificPref{ get; set; }

    public MyPreferences()
    {
        GeneratorPreferences = new ScenarioTemplateGeneratorPreferences();
    }
}

[Serializable]
public class TemplateGeneratorPreferences
{
    [XmlAttribute("MyBool")]
    public bool MyBool { get; set; }

    public ScenarioTemplateGeneratorPreferences()
    {
        MyBool = true;
    }
}
</code>```

This simply won't serialize, I get the follow exception:

"The type MyPreferences was not expected. Use the XmlInclude or SoapInclude
  attribute to specify types that are not known statically."

I included the XmlInclude attribute so I'm a little stumped.

答:
From MSDN (the first link that pops up in google when searching for your errormessage) tells you that it's only the base type that needs be augmented with the attribute.

```<code>[System.Xml.Serialization.XmlInclude( typeof( Derived ) )]
public class Base
{
    // ...
}
</code>```

Attaching the XmlInclude attribute allows the XmlSerializer to serialize fields referencing objects of Derived type when a field or property is defined as type Base.

Body:
I am trying to serialize an object into Application Settings.  I have a setting defined to be the object type already.  Here is the class I am trying to serialize.  I have to serialize an object to the application settings because the object type isn't known at runtime.

[Serializable]
[XmlInclude(typeof(TemplateGeneratorPreferences))]
public class MyPreferences
{
    [XmlElement(ElementName="GeneratorPreferences", Type=typeof(TemplateGeneratorPreferences))]
    public TemplateGeneratorPreferences FormSpecificPref{ get; set; }

    public MyPreferences()
    {
        GeneratorPreferences = new ScenarioTemplateGeneratorPreferences();
    }
}

[Serializable]
public class TemplateGeneratorPreferences
{
    [XmlAttribute("MyBool")]
    public bool MyBool { get; set; }

    public ScenarioTemplateGeneratorPreferences()
    {
        MyBool = true;
    }
}

This simply won't serialize, I get the follow exception:

"The type MyPreferences was not expected. Use the XmlInclude or SoapInclude
  attribute to specify types that are not known statically."

I included the XmlInclude attribute so I'm a little stumped.

Body:
From MSDN (the first link that pops up in google when searching for your errormessage) tells you that it's only the base type that needs be augmented with the attribute.

[System.Xml.Serialization.XmlInclude( typeof( Derived ) )]
public class Base
{
    // ...
}

Attaching the XmlInclude attribute allows the XmlSerializer to serialize fields referencing objects of Derived type when a field or property is defined as type Base.


来源: stackexchange

问:
Is there a way to simplify OpenCl kernels usage ?
To use OpenCL kernel the following is needed:

Put the kernel code in a string

call clCreateProgramWithSource

call clBuildProgram

call clCreateKernel

call clSetKernelArg (x number of arguments)

call clEnqueueNDRangeKernel

This need to be done for each kernel. Is there a way to do this repeating less code for each kernel?

答:
You can have look at wrapper libraries
https://streamhpc.com/knowledge/for-developers/opencl-wrappers/</p>

ContentLicense: CC BY-SA 3.0


问:
When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id
I keep on getting this error. The place where it's throwing the error is:

```<code> var projectManagerList = gridReader.Read<ProjectResources, Employee, ProjectResources>((pr, e) =>
                    {
                        pr.Employee = e;
                        return pr;
                    }).ToList();
</code>```

The sql is:

```<code> SELECT DISTINCT
                             p_Resources.Empl_ID as EmployeeId
                            ,p_Resources.cRole
                            ,p_Empl.ID as Id
                            ,p_Empl.Title
                            ,p_Empl.First_Name as FirstName
                            ,p_Empl.MI as MiddleInitial
                            ,p_Empl.Last_Name as LastName
                            ,p_Empl.Phone
                            ,p_Empl.PWD as Password
                            ,p_Empl.email as Email
                            ,p_Empl.LoginName
                            ,p_Empl.Admin
                      FROM   p_Empl
                         LEFT OUTER JOIN
                          p_Resources on p_Resources.Empl_ID = p_Empl.ID
                     WHERE  p_Resources.cRole='Project Manager'
</code>```

I wrote "as Id" so why is it throwing the error? Thanks.

答:
It tells you to set the splitOn parameter. So you should set it to Id.

```<code>var projectManagerList = gridReader.Read<ProjectResources, Employee,
ProjectResources>((pr, e) =>
                {
                    pr.Employee = e;
                    return pr;
                },splitOn: "Id").ToList();
</code>```

It tells you the split between ProjectResources and Employee is the Id column.

Body:
I keep on getting this error. The place where it's throwing the error is:

 var projectManagerList = gridReader.Read<ProjectResources, Employee, ProjectResources>((pr, e) =>
                    {
                        pr.Employee = e;
                        return pr;
                    }).ToList();

The sql is:

 SELECT DISTINCT
                             p_Resources.Empl_ID as EmployeeId
                            ,p_Resources.cRole
                            ,p_Empl.ID as Id
                            ,p_Empl.Title
                            ,p_Empl.First_Name as FirstName
                            ,p_Empl.MI as MiddleInitial
                            ,p_Empl.Last_Name as LastName
                            ,p_Empl.Phone
                            ,p_Empl.PWD as Password
                            ,p_Empl.email as Email
                            ,p_Empl.LoginName
                            ,p_Empl.Admin
                      FROM   p_Empl
                         LEFT OUTER JOIN
                          p_Resources on p_Resources.Empl_ID = p_Empl.ID
                     WHERE  p_Resources.cRole='Project Manager'

I wrote "as Id" so why is it throwing the error? Thanks.

Body:
It tells you to set the splitOn parameter. So you should set it to Id.

var projectManagerList = gridReader.Read<ProjectResources, Employee,
ProjectResources>((pr, e) =>
                {
                    pr.Employee = e;
                    return pr;
                },splitOn: "Id").ToList();

It tells you the split between ProjectResources and Employee is the Id column.


问:
Null Pointer Exception when using KStream to change string to avro inKafka Streams
I'm stuck on this problem and I can't figure out what's going on. I am trying to use Kafka streams to write a log to a topic. On the other end, I have Kafka-connect entering the each entry into MySQL. So, basically what I need is a Kafka streams program which reads a topic as strings and parses it into Avro format and then enters it into a different topic.

Here's the code I wrote:

```<code>        //Define schema
        String userSchema = "{"
                + "\"type\":\"record\","
                + "\"name\":\"myrecord\","
                + "\"fields\":["
                + "  { \"name\":\"ID\", \"type\":\"int\" },"
                + "  { \"name\":\"COL_NAME_1\", \"type\":\"string\" },"
                + "  { \"name\":\"COL_NAME_2\", \"type\":\"string\" }"
    + "]}";

        String key = "key1";
        Schema.Parser parser = new Schema.Parser();
        Schema schema = parser.parse(userSchema);

//Settings
       System.out.println("Kafka Streams Demonstration");
        //Settings
        Properties settings = new Properties();
        // Set a few key parameters
        settings.put(StreamsConfig.APPLICATION_ID_CONFIG, APP_ID);
        // Kafka bootstrap server (broker to talk to); ubuntu is the host name for my VM running Kafka, port 9092 is where the (single) broker listens
        settings.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        // Apache ZooKeeper instance keeping watch over the Kafka cluster; ubuntu is the host name for my VM running Kafka, port 2181 is where the ZooKeeper listens
        settings.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181");
        // default serdes for serialzing and deserializing key and value from and to streams in case no specific Serde is specified
        settings.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
        settings.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
        settings.put(StreamsConfig.STATE_DIR_CONFIG ,"/tmp");
        // to work around exception Exception in thread "StreamThread-1" java.lang.IllegalArgumentException: Invalid timestamp -1
        // at org.apache.kafka.clients.producer.ProducerRecord.<init>(ProducerRecord.java:60)
        // see: https://groups.google.com/forum/#!topic/confluent-platform/5oT0GRztPBo

        // Create an instance of StreamsConfig from the Properties instance
        StreamsConfig config = new StreamsConfig(getProperties());
        final Serde < String > stringSerde = Serdes.String();
        final Serde < Long > longSerde = Serdes.Long();
        final Serde<byte[]> byteArraySerde = Serdes.ByteArray();

        // building Kafka Streams Model
        KStreamBuilder kStreamBuilder = new KStreamBuilder();
        // the source of the streaming analysis is the topic with country messages
        KStream<byte[], String> instream =
            kStreamBuilder.stream(byteArraySerde, stringSerde, "sqlin");

       final KStream<byte[], GenericRecord> outstream = instream.mapValues(new ValueMapper<String, GenericRecord>() {
            @Override
            public GenericRecord apply(final String record) {
                System.out.println(record);
                GenericRecord avroRecord = new GenericData.Record(schema);
                String[] array = record.split(" ", -1);
                for (int i = 0; i < array.length; i = i + 1) {
                    if (i == 0)
                        avroRecord.put("ID", Integer.parseInt(array[0]));
                    if (i == 1)
                        avroRecord.put("COL_NAME_1", array[1]);
                    if (i == 2)
                        avroRecord.put("COL_NAME_2", array[2]);
                }
                System.out.println(avroRecord);
                return avroRecord;
            }
          });
        outstream.to("sqlout");
</code>```

Here's the output after I get a Null Pointer Exception:

```<code>java -cp streams-examples-3.2.1-standalone.jar io.confluent.examples.streams.sql
Kafka Streams Demonstration
Start
Now started CountriesStreams Example
5 this is
{"ID": 5, "COL_NAME_1": "this", "COL_NAME_2": "is"}
Exception in thread "StreamThread-1" java.lang.NullPointerException
    at org.apache.kafka.streams.processor.internals.SinkNode.process(SinkNode.java:81)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:83)
    at org.apache.kafka.streams.kstream.internals.KStreamMapValues$KStreamMapProcessor.process(KStreamMapValues.java:42)
    at org.apache.kafka.streams.processor.internals.ProcessorNode$1.run(ProcessorNode.java:48)
    at org.apache.kafka.streams.processor.internals.StreamsMetricsImpl.measureLatencyNs(StreamsMetricsImpl.java:188)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:134)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:83)
    at org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:70)
    at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:197)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:627)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:361)
</code>```

The topic sqlin contains a few message which consists of a digit followed by two words. Note the two print lines: The function gets one message, and successfully parses it before catching a null pointer. The problem is I am new to Java, Kafka, and Avro so I'm not sure where I'm going wrong. Did I set up the Avro Schema right? Or am using kstream wrong? Any help here would be greatly appreciated.

答:
I think the problem is the following line:

```<code>outstream.to("sqlout");
</code>```

Your application is configured to, by default, use a String serde for record keys and record values:

```<code>settings.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
settings.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
</code>```

Since outstream has type KStream<byte[], GenericRecord>, you must provide explicit serdes when calling to():

```<code>// sth like
outstream.to(Serdes.ByteArray(), yourGenericAvroSerde, "sqlout");
</code>```

FYI: The next version of Confluent Platform (ETA: this month = June
  2017) will ship with a ready-to-use generic + specific Avro
  serde
  that integrates with Confluent schema
  registry.  This
  should make your life easier.

See my answer at https://stackoverflow.com/a/44433098/1743580 for further details.

Body:
I'm stuck on this problem and I can't figure out what's going on. I am trying to use Kafka streams to write a log to a topic. On the other end, I have Kafka-connect entering the each entry into MySQL. So, basically what I need is a Kafka streams program which reads a topic as strings and parses it into Avro format and then enters it into a different topic.

Here's the code I wrote:

        //Define schema
        String userSchema = "{"
                + "\"type\":\"record\","
                + "\"name\":\"myrecord\","
                + "\"fields\":["
                + "  { \"name\":\"ID\", \"type\":\"int\" },"
                + "  { \"name\":\"COL_NAME_1\", \"type\":\"string\" },"
                + "  { \"name\":\"COL_NAME_2\", \"type\":\"string\" }"
    + "]}";

        String key = "key1";
        Schema.Parser parser = new Schema.Parser();
        Schema schema = parser.parse(userSchema);

//Settings
       System.out.println("Kafka Streams Demonstration");
        //Settings
        Properties settings = new Properties();
        // Set a few key parameters
        settings.put(StreamsConfig.APPLICATION_ID_CONFIG, APP_ID);
        // Kafka bootstrap server (broker to talk to); ubuntu is the host name for my VM running Kafka, port 9092 is where the (single) broker listens
        settings.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        // Apache ZooKeeper instance keeping watch over the Kafka cluster; ubuntu is the host name for my VM running Kafka, port 2181 is where the ZooKeeper listens
        settings.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181");
        // default serdes for serialzing and deserializing key and value from and to streams in case no specific Serde is specified
        settings.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
        settings.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
        settings.put(StreamsConfig.STATE_DIR_CONFIG ,"/tmp");
        // to work around exception Exception in thread "StreamThread-1" java.lang.IllegalArgumentException: Invalid timestamp -1
        // at org.apache.kafka.clients.producer.ProducerRecord.<init>(ProducerRecord.java:60)
        // see: https://groups.google.com/forum/#!topic/confluent-platform/5oT0GRztPBo

        // Create an instance of StreamsConfig from the Properties instance
        StreamsConfig config = new StreamsConfig(getProperties());
        final Serde < String > stringSerde = Serdes.String();
        final Serde < Long > longSerde = Serdes.Long();
        final Serde<byte[]> byteArraySerde = Serdes.ByteArray();

        // building Kafka Streams Model
        KStreamBuilder kStreamBuilder = new KStreamBuilder();
        // the source of the streaming analysis is the topic with country messages
        KStream<byte[], String> instream =
            kStreamBuilder.stream(byteArraySerde, stringSerde, "sqlin");

       final KStream<byte[], GenericRecord> outstream = instream.mapValues(new ValueMapper<String, GenericRecord>() {
            @Override
            public GenericRecord apply(final String record) {
                System.out.println(record);
                GenericRecord avroRecord = new GenericData.Record(schema);
                String[] array = record.split(" ", -1);
                for (int i = 0; i < array.length; i = i + 1) {
                    if (i == 0)
                        avroRecord.put("ID", Integer.parseInt(array[0]));
                    if (i == 1)
                        avroRecord.put("COL_NAME_1", array[1]);
                    if (i == 2)
                        avroRecord.put("COL_NAME_2", array[2]);
                }
                System.out.println(avroRecord);
                return avroRecord;
            }
          });
        outstream.to("sqlout");

Here's the output after I get a Null Pointer Exception:

java -cp streams-examples-3.2.1-standalone.jar io.confluent.examples.streams.sql
Kafka Streams Demonstration
Start
Now started CountriesStreams Example
5 this is
{"ID": 5, "COL_NAME_1": "this", "COL_NAME_2": "is"}
Exception in thread "StreamThread-1" java.lang.NullPointerException
    at org.apache.kafka.streams.processor.internals.SinkNode.process(SinkNode.java:81)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:83)
    at org.apache.kafka.streams.kstream.internals.KStreamMapValues$KStreamMapProcessor.process(KStreamMapValues.java:42)
    at org.apache.kafka.streams.processor.internals.ProcessorNode$1.run(ProcessorNode.java:48)
    at org.apache.kafka.streams.processor.internals.StreamsMetricsImpl.measureLatencyNs(StreamsMetricsImpl.java:188)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:134)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:83)
    at org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:70)
    at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:197)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:627)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:361)

The topic sqlin contains a few message which consists of a digit followed by two words. Note the two print lines: The function gets one message, and successfully parses it before catching a null pointer. The problem is I am new to Java, Kafka, and Avro so I'm not sure where I'm going wrong. Did I set up the Avro Schema right? Or am using kstream wrong? Any help here would be greatly appreciated.

Body:
I think the problem is the following line:

outstream.to("sqlout");

Your application is configured to, by default, use a String serde for record keys and record values:

settings.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
settings.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());

Since outstream has type KStream<byte[], GenericRecord>, you must provide explicit serdes when calling to():

// sth like
outstream.to(Serdes.ByteArray(), yourGenericAvroSerde, "sqlout");

FYI: The next version of Confluent Platform (ETA: this month = June
  2017) will ship with a ready-to-use generic + specific Avro
  serde
  that integrates with Confluent schema
  registry.  This
  should make your life easier.

See my answer at https://stackoverflow.com/a/44433098/1743580 for further details.


问:
Change all selections on the page using javascript
I want to change all selections on my page and set them to an index I define using javascript language.

Can you please advice on this ?

答:
Use the below code snippet:

```<code><select id="mySelect">
    <option>Apple</option>
    <option>Orange</option>
    <option>Pineapple</option>
    <option>Banana</option>
</select>
<button onclick="myFunction()">Try it</button>

<script>
    function myFunction() {
        document.getElementById("mySelect").selectedIndex = "2";
    }
</script>
</code>```

"2" represents index for the select element.

Body:
Use the below code snippet:

<select id="mySelect">
    <option>Apple</option>
    <option>Orange</option>
    <option>Pineapple</option>
    <option>Banana</option>
</select>
<button onclick="myFunction()">Try it</button>

<script>
    function myFunction() {
        document.getElementById("mySelect").selectedIndex = "2";
    }
</script>

"2" represents index for the select element.


问:
forbidden 403 error in 'PUT' request Ajax in django rest framwork
I am using django-rest framework while sending put ajax request got error 403 forbidden.

user-details.html

```<code>   <form action="{% url 'user-detail' pk=object.pk %}" id="use1">
        {% csrf_token %}
        {% for key,value in serializer.items %}
             {{key}} <input value="{{value}}" type="text" class="form-control" /><br>
        {% endfor %}

        <button class="btn btn-warning edit_record" type="button" >Update</button>
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#deleteModal">Delete</button>
    </form>
</code>```

when I click on update button ajax will call and here I got formdata with hidden field csrftoken and also other parameters but after run this ajax i got 403 forbidden error however "DELETE" method working fine here.

As far as I know  we get this error when csrftoken is missing but I have csrf_token in my form.

```<code>$(".edit_record").on("click",function() {
        var url = document.location.pathname
        form = $(this).closest("form")[0],
        formData = new FormData(form);
         $.ajax({
             type:'PUT',
             url: url,
             data: formData,
             success: function (data) {

            },
              headers: {'X_METHODOVERRIDE': 'PUT'},

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

I used ModelViewset in views.py

```<code> class UserViewSet(viewsets.ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserProfileSerializer

        def update(self, request, *args, **kwargs):
            import pdb;pdb.set_trace()
            response = super(UserViewSet, self).update(request, *args, **kwargs)
            success =  True if response.status_code in [200,201] else False
            return Response({'object':response.data, 'success':success})

        def partial_update(self, request, *args, **kwargs):
            import pdb;pdb.set_trace()

        def destroy(self, request,*args, **kwargs):
            response = super(UserViewSet, self).destroy(request, *args, **kwargs)
            success =  True if response.status_code == 204 else False
            return Response({'data':success})
</code>```

答:
try this,

```<code>    $.ajax({
        type:"DELETE",
        data:{},
        url:"{{ category_update }}",
        beforeSend:function(xhr){
            xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
        },
        success:function(data,textStatus){
            location.replace(location.href);
        },
        error:function(XMLHttpRequest, textStatus, errorThrown){
           document.write(XMLHttpRequest.responseText);
        }
    });
</code>```

the point is :

```<code>beforeSend:function(xhr){
     xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
},
</code>```

Body:
I am using django-rest framework while sending put ajax request got error 403 forbidden.

user-details.html

   <form action="{% url 'user-detail' pk=object.pk %}" id="use1">
        {% csrf_token %}
        {% for key,value in serializer.items %}
             {{key}} <input value="{{value}}" type="text" class="form-control" />

        {% endfor %}

        <button class="btn btn-warning edit_record" type="button" >Update</button>
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#deleteModal">Delete</button>
    </form>

when I click on update button ajax will call and here I got formdata with hidden field csrftoken and also other parameters but after run this ajax i got 403 forbidden error however "DELETE" method working fine here.

As far as I know  we get this error when csrftoken is missing but I have csrf_token in my form.

$(".edit_record").on("click",function() {
        var url = document.location.pathname
        form = $(this).closest("form")[0],
        formData = new FormData(form);
         $.ajax({
             type:'PUT',
             url: url,
             data: formData,
             success: function (data) {

            },
              headers: {'X_METHODOVERRIDE': 'PUT'},

         });
    });

I used ModelViewset in views.py

 class UserViewSet(viewsets.ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserProfileSerializer

        def update(self, request, *args, **kwargs):
            import pdb;pdb.set_trace()
            response = super(UserViewSet, self).update(request, *args, **kwargs)
            success =  True if response.status_code in [200,201] else False
            return Response({'object':response.data, 'success':success})

        def partial_update(self, request, *args, **kwargs):
            import pdb;pdb.set_trace()

        def destroy(self, request,*args, **kwargs):
            response = super(UserViewSet, self).destroy(request, *args, **kwargs)
            success =  True if response.status_code == 204 else False
            return Response({'data':success})

Body:
try this,

    $.ajax({
        type:"DELETE",
        data:{},
        url:"{{ category_update }}",
        beforeSend:function(xhr){
            xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
        },
        success:function(data,textStatus){
            location.replace(location.href);
        },
        error:function(XMLHttpRequest, textStatus, errorThrown){
           document.write(XMLHttpRequest.responseText);
        }
    });

the point is :

beforeSend:function(xhr){
     xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
},


问:
Parameterized JUnit Test
QUESTION:
After putting my initialization into the actual @Parameters I no longer have a NullPointerException, is it possiuble that @Before isn't actually invoked before?!
Is there a solution so I don't have to put it into my Paramters?

Solution:

```<code>@RunWith(value = Parameterized.class)
public class XQTest4Test {
    static XQueryTestHelper buildTest;
    static HeaderBodyPayloadTestcase[] arrayHdrInbPayTestcases;

    @Before
    public void initialize() throws Exception {
        buildTest = new XQueryTestHelper();
        buildTest.initialization();

        arrayHdrInbPayTestcases = buildTest.getHdrInbPayTestcases();
        System.out.println(arrayHdrInbPayTestcases[0].a);
    }

        @Parameter
        public HeaderBodyPayloadTestcase testcase;

        @Parameters(name = "{index}: pew")
        public static Iterable<? extends HeaderBodyPayloadTestcase> data() throws Exception {
            buildTest = new XQueryTestHelper();
            buildTest.initialization();

            arrayHdrInbPayTestcases = buildTest.getHdrInbPayTestcases();
            return Arrays.asList(arrayHdrInbPayTestcases);
        }

    @Test
    public void someTest() throws Exception{
    //  System.out.println(xq.toString());
        System.out.println(testcase.a);
        if(testcase.c.contains("HDR")){
            assertTrue(new XQueryTester(testcase.a,testcase.b).testHeader(testcase.c,testcase.d));
        }
        else if (testcase.c.contains("PAY")){
            assertTrue(new XQueryTester(testcase.a,testcase.b).testBody(testcase.c,testcase.d));

        }
        else {
            assertTrue(new XQueryTester(testcase.a,testcase.b).testInbound(testcase.c,testcase.d));
        }
    }

}
</code>```

答:
I think @Parameter annotation should help you. In this way you do not need a constructor with parameters.

```<code>@RunWith(Parameterized.class)
public class XQTest4Test {
    static XQueryTestHelper buildTest;
    static HeaderBodyPayloadTestcase[] arrayHdrInbPayTestcases;

    @Parameter
    public HeaderBodyPayloadTestcase testcase;

    @Parameters(name = "{index}: pew")
    public static Iterable<Object[]> data() {
        return Arrays.asList(new HeaderBodyPayloadTestcase[][]{arrayHdrInbPayTestcases});
    }

    // ...

}
</code>```

And ensure that access modifier of field marked as @Parameter is public.

I would recommend you to do all the initialization in @Before or @BeforeClass methods. Depends on you logic.

This feature is well-documented on JUnit4 wiki

Title: Parameterized JUnit Test

Body:
QUESTION:
After putting my initialization into the actual @Parameters I no longer have a NullPointerException, is it possiuble that @Before isn't actually invoked before?!
Is there a solution so I don't have to put it into my Paramters?

Solution:

@RunWith(value = Parameterized.class)
public class XQTest4Test {
    static XQueryTestHelper buildTest;
    static HeaderBodyPayloadTestcase[] arrayHdrInbPayTestcases;

    @Before
    public void initialize() throws Exception {
        buildTest = new XQueryTestHelper();
        buildTest.initialization();

        arrayHdrInbPayTestcases = buildTest.getHdrInbPayTestcases();
        System.out.println(arrayHdrInbPayTestcases[0].a);
    }

        @Parameter
        public HeaderBodyPayloadTestcase testcase;

        @Parameters(name = "{index}: pew")
        public static Iterable<? extends HeaderBodyPayloadTestcase> data() throws Exception {
            buildTest = new XQueryTestHelper();
            buildTest.initialization();

            arrayHdrInbPayTestcases = buildTest.getHdrInbPayTestcases();
            return Arrays.asList(arrayHdrInbPayTestcases);
        }

    @Test
    public void someTest() throws Exception{
    //  System.out.println(xq.toString());
        System.out.println(testcase.a);
        if(testcase.c.contains("HDR")){
            assertTrue(new XQueryTester(testcase.a,testcase.b).testHeader(testcase.c,testcase.d));
        }
        else if (testcase.c.contains("PAY")){
            assertTrue(new XQueryTester(testcase.a,testcase.b).testBody(testcase.c,testcase.d));

        }
        else {
            assertTrue(new XQueryTester(testcase.a,testcase.b).testInbound(testcase.c,testcase.d));
        }
    }

}

Body:
I think @Parameter annotation should help you. In this way you do not need a constructor with parameters.

@RunWith(Parameterized.class)
public class XQTest4Test {
    static XQueryTestHelper buildTest;
    static HeaderBodyPayloadTestcase[] arrayHdrInbPayTestcases;

    @Parameter
    public HeaderBodyPayloadTestcase testcase;

    @Parameters(name = "{index}: pew")
    public static Iterable<Object[]> data() {
        return Arrays.asList(new HeaderBodyPayloadTestcase[][]{arrayHdrInbPayTestcases});
    }

    // ...

}

And ensure that access modifier of field marked as @Parameter is public.

I would recommend you to do all the initialization in @Before or @BeforeClass methods. Depends on you logic.

This feature is well-documented on JUnit4 wiki


问:
Parameters in ActionResult
In migrating a Vanilla MVC project to a Vanilla Umbraco project, i am facing a couple of issues. One of them is with the query parameters, and transferring them to my Index.

Old ActionResult from working MVC project:

```<code>public ActionResult Index(int value1, int value2, bool value3 = false)
{...}
</code>```

New ActionResult, working in a Vanilla Umbraco project

```<code>public override ActionResult Index(RenderModel model)
{...}
</code>```

But i need the parameters (coming from querystring) from the original project.
I tried simply adding them:

```<code>public override ActionResult Index(RenderModel model, int value1, int value2, bool value3 = false)
{...}
</code>```

But when i do the latter, i get the error 'Controller.Index(RenderModel, int, int, bool): no suitable method found to override'

What am i missing?

答:
You can not pass those values as parameters. You should extract them from query string instead. </p>

```<code>public override ActionResult Index(RenderModel model)
{
     var value1 = Request["value1"];
     var value2 = Request["value2"];
     var value3 = Request["value3"];
     ...
}
</code>```

Title: Parameters in ActionResult

Body:
In migrating a Vanilla MVC project to a Vanilla Umbraco project, i am facing a couple of issues. One of them is with the query parameters, and transferring them to my Index.

Old ActionResult from working MVC project:

public ActionResult Index(int value1, int value2, bool value3 = false)
{...}

New ActionResult, working in a Vanilla Umbraco project

public override ActionResult Index(RenderModel model)
{...}

But i need the parameters (coming from querystring) from the original project.
I tried simply adding them:

public override ActionResult Index(RenderModel model, int value1, int value2, bool value3 = false)
{...}

But when i do the latter, i get the error 'Controller.Index(RenderModel, int, int, bool): no suitable method found to override'

What am i missing?

Body:
You can not pass those values as parameters. You should extract them from query string instead.

public override ActionResult Index(RenderModel model)
{
     var value1 = Request["value1"];
     var value2 = Request["value2"];
     var value3 = Request["value3"];
     ...
}


问:
Add column to table and then update it inside transaction
I am creating a script that will be run in a MS SQL server. This script will run multiple statements and needs to be transactional, if one of the statement fails the overall execution is stopped and any changes are rolled back.

I am having trouble creating this transactional model when issuing ALTER TABLE statements to add columns to a table and then updating the newly added column. In order to access the newly added column right away, I use a GO command to execute the ALTER TABLE statement, and then call my UPDATE statement. The problem I am facing is that I cannot issue a GO command inside an IF statement. The IF statement is important within my transactional model. This is a sample code of the script I am trying to run. Also notice that issuing a  GO command, will discard the @errorCode variable, and will need to be declared down in the code before being used (This is not in the code below).

```<code>BEGIN TRANSACTION

DECLARE @errorCode INT
SET @errorCode = @@ERROR

-- **********************************
-- * Settings
-- **********************************
IF @errorCode = 0
BEGIN
 BEGIN TRY
  ALTER TABLE Color ADD [CodeID] [uniqueidentifier] NOT NULL DEFAULT ('{00000000-0000-0000-0000-000000000000}')
  GO
 END TRY
 BEGIN CATCH
  SET @errorCode = @@ERROR
 END CATCH
END

IF @errorCode = 0
BEGIN
 BEGIN TRY
  UPDATE Color
  SET CodeID= 'B6D266DC-B305-4153-A7AB-9109962255FC'
  WHERE [Name] = 'Red'
 END TRY
 BEGIN CATCH
  SET @errorCode = @@ERROR
 END CATCH
END

-- **********************************
-- * Check @errorCode to issue a COMMIT or a ROLLBACK
-- **********************************
IF @errorCode = 0
BEGIN
 COMMIT
 PRINT 'Success'
END
ELSE
BEGIN
 ROLLBACK
 PRINT 'Failure'
END
</code>```

So what I would like to know is how to go around this problem, issuing ALTER TABLE statements to add a column and then updating that column, all within a script executing as a transactional unit.

答:
Have you tried it without the GO?

Normally you should not mix table changes and data changes in the same script.

Body:
I am creating a script that will be run in a MS SQL server. This script will run multiple statements and needs to be transactional, if one of the statement fails the overall execution is stopped and any changes are rolled back.

I am having trouble creating this transactional model when issuing ALTER TABLE statements to add columns to a table and then updating the newly added column. In order to access the newly added column right away, I use a GO command to execute the ALTER TABLE statement, and then call my UPDATE statement. The problem I am facing is that I cannot issue a GO command inside an IF statement. The IF statement is important within my transactional model. This is a sample code of the script I am trying to run. Also notice that issuing a  GO command, will discard the @errorCode variable, and will need to be declared down in the code before being used (This is not in the code below).

BEGIN TRANSACTION

DECLARE @errorCode INT
SET @errorCode = @@ERROR

-- **********************************
-- * Settings
-- **********************************
IF @errorCode = 0
BEGIN
 BEGIN TRY
  ALTER TABLE Color ADD [CodeID] [uniqueidentifier] NOT NULL DEFAULT ('{00000000-0000-0000-0000-000000000000}')
  GO
 END TRY
 BEGIN CATCH
  SET @errorCode = @@ERROR
 END CATCH
END

IF @errorCode = 0
BEGIN
 BEGIN TRY
  UPDATE Color
  SET CodeID= 'B6D266DC-B305-4153-A7AB-9109962255FC'
  WHERE [Name] = 'Red'
 END TRY
 BEGIN CATCH
  SET @errorCode = @@ERROR
 END CATCH
END

-- **********************************
-- * Check @errorCode to issue a COMMIT or a ROLLBACK
-- **********************************
IF @errorCode = 0
BEGIN
 COMMIT
 PRINT 'Success'
END
ELSE
BEGIN
 ROLLBACK
 PRINT 'Failure'
END

So what I would like to know is how to go around this problem, issuing ALTER TABLE statements to add a column and then updating that column, all within a script executing as a transactional unit.

ContentLicense: CC BY-SA 2.5


问:
Simple ajax post call in Play framework
Hi I'm trying to simply send a string once a button is pressed in my website using ajax to my java code in Play framework. I can't find a simple tutorial which simply explains how to do this. They are all using templates.
Lets say my java method is:

```<code>  public static Result upload() { }
</code>```

and my button is calling a javascript method which gets a String from another input when clicked:

```<code><input id="submit" type="submit" onclick="send();">
</code>```

答:
```<code>POST        /home/testPost                               controllers.Application.testPost

//Server Side.
def testPost = Action { request =>

    println("testPost Called");
    println(request.body.asFormUrlEncoded.get("name").head);
    Ok("Succeeded");

}

Client Side:

public static testPost(){
$.ajax({
url:"/dialog/testPost",
type:"POST",
data:{
name:"Varadharajan R"
},
success:function(response){
alert(response);
}
});
}
</code>```

Title: Simple ajax post call in Play framework

Body:
Hi I'm trying to simply send a string once a button is pressed in my website using ajax to my java code in Play framework. I can't find a simple tutorial which simply explains how to do this. They are all using templates.
Lets say my java method is:

  public static Result upload() { }

and my button is calling a javascript method which gets a String from another input when clicked:

<input id="submit" type="submit" onclick="send();">


问:
Getting access denied issue after site moving to live server in magento?
I have moved the magento website to my live server.

But When i try to open it gives me error like  "http://prntscr.com/ff3yp2".

Can you please help me to fix this issue?

Thanks

答:
This issue occur because of 2 reasons.

Incorrect database connection details are mention in app/etc/local.xml file.

Mention user don't have all the privileges of that database.

You can check host as well.


问:
The React way to retrieve (some) DOM values
My react Menu component renders a list of links. Other parts need to animate (width and x/y pos) depending on the width of the Menu component's link's widths so all this needs to happen after all has rendered, and I need to read values from the DOM.

I'm looking for a proper way, no react anti-pattern, to handle this scenario but can't really sort it out in a way I'm happy with.

Here's an explanatory flow.

1) User clicks a link in the menu.

2) Activate that link.

```<code>this.setState({link: {active: true}});
</code>```

3) Look up and store what width the clicked element has.

```<code>let w = this.myLink.offsetWidth; // myLink from refs.
</code>```

4) Update state with new width

```<code>this.setState({styleState: { width: w }}); // Styles used in component elsewhere.
</code>```

OK! This works fairly well, now I want to do the same for pos X/Y which makes things more complicated. Now I'll need to getBoundingClientRect() and take consideration to this element's parents to get the correct position etc.

I keep wishing for a sensible DOM API where I can grab values from the DOM (yep, jQuery style - like jqLite), then with values I update my state and thus re-render the component. I realize it wouldn't make sense to manipulate the DOM this way so I'm not trying to, but in this specific case the truth is actually in the DOM already and I need to extract it.

Is there a lib ppl use for these things, just to get a couple of getter methods like el.width(), el.left() for convenience?

答:
I don't think its bad style to read size/styles of the dom after rendering. Just be sure to not modify the dom directly. The reason is that the real dom should always be in sync with the virtual dom.

I would encapsulate this behaviour in a custom Link component that receives an onClick:

//untested pseudocode
class Link extends Component {

  handleRendered = (el) => {
    this.width = el.clientWidth;
    ....
  }

  handleClick = (ev) => {
    this.props.onClick({
      width: this.width,
      x: this.x,
      ...
    })
  }

  render = () => {
    return (

 this.handleRendered(el)} onClick={this.handleClick}>
        {this.props.children}

    );

  }
}

class MyPage extends Component {

  handleClick = ({width, ....}) => {
    this.setState({
      otherElementStyle: {
        width: width
      }
    })
  }

  render = () => {
    return (
      <Link onClick={this.handleClick}>
        Menu1
      </Link>
    );

  }
}
```

Concerning your requested library, I'm not aware of any but I bet there is one.

Body:
My react Menu component renders a list of links. Other parts need to animate (width and x/y pos) depending on the width of the Menu component's link's widths so all this needs to happen after all has rendered, and I need to read values from the DOM.

I'm looking for a proper way, no react anti-pattern, to handle this scenario but can't really sort it out in a way I'm happy with.

Here's an explanatory flow.

1) User clicks a link in the menu.

2) Activate that link.

this.setState({link: {active: true}});

3) Look up and store what width the clicked element has.

let w = this.myLink.offsetWidth; // myLink from refs.

4) Update state with new width

this.setState({styleState: { width: w }}); // Styles used in component elsewhere.

OK! This works fairly well, now I want to do the same for pos X/Y which makes things more complicated. Now I'll need to getBoundingClientRect() and take consideration to this element's parents to get the correct position etc.

I keep wishing for a sensible DOM API where I can grab values from the DOM (yep, jQuery style - like jqLite), then with values I update my state and thus re-render the component. I realize it wouldn't make sense to manipulate the DOM this way so I'm not trying to, but in this specific case the truth is actually in the DOM already and I need to extract it.

Is there a lib ppl use for these things, just to get a couple of getter methods like el.width(), el.left() for convenience?

Body:
I don't think its bad style to read size/styles of the dom after rendering. Just be sure to not modify the dom directly. The reason is that the real dom should always be in sync with the virtual dom.

I would encapsulate this behaviour in a custom Link component that receives an onClick:

//untested pseudocode
class Link extends Component {

  handleRendered = (el) => {
    this.width = el.clientWidth;
    ....
  }

  handleClick = (ev) => {
    this.props.onClick({
      width: this.width,
      x: this.x,
      ...
    })
  }

  render = () => {
    return (
      <div ref={(el) => this.handleRendered(el)} onClick={this.handleClick}>
        {this.props.children}
      </div>
    );

  }
}

class MyPage extends Component {

  handleClick = ({width, ....}) => {
    this.setState({
      otherElementStyle: {
        width: width
      }
    })
  }

  render = () => {
    return (
      <Link onClick={this.handleClick}>
        Menu1
      </Link>
    );

  }
}

Concerning your requested library, I'm not aware of any but I bet there is one.


问:
How to Update a column in all rows of a table based on a function call with existing value in that same column
I have a column in my user_table called password.
Now I want to update all password fields in all rows by passing the existing value of password field and update it using the return value from the function. How to achieve it?

```<code>╔════╦══════════════╦══════╗
║ id ║  username    ║ pwd  ║
╠════╬══════════════╬══════╣
║  1 ║ Jeff Atwood  ║ 5636 ║
║  2 ║ Geoff Dalgas ║  148 ║
║  3 ║ Jarrod Dixon ║  101 ║
║  4 ║ Joel Spolsky ║  959 ║
╚════╩══════════════╩══════╝
</code>```

my function is as follows:

```<code>function encryptPassword(password)
{
// $new password = my encryption logic here
   return $password;
}
</code>```

How can I update all password cloumn in every row one by one?

答:
```<code>DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `ITERATEALLTABLE_PWD`()
BEGIN
DECLARE VAR_OLD_PASS varchar(100);
DECLARE VAR_NEW_PASS varchar(100);
DECLARE VAR_QRY varchar(100);
DECLARE VAR_FINISHED INT(11) DEFAULT 0;
DECLARE VAR_ID INT(11) ;
DECLARE DATABASE_CURSOR CURSOR FOR
                SELECT pwd ,ID
                FROM TABLENAME;

                DECLARE CONTINUE HANDLER FOR NOT FOUND SET VAR_FINISHED = 1;

                OPEN DATABASE_CURSOR;
                GET_NEXTRECORD: LOOP

                        FETCH DATABASE_CURSOR INTO VAR_OLD_PASS,VAR_ID;

                           IF VAR_FINISHED = 1 THEN
                        LEAVE GET_NEXTRECORD;
                        END IF;

                            SET VAR_NEW_PASS =CONCAT(VAR_OLD_PASS,'ABC'); <-------Here you have to implement your crypto operation!>
                            SET @VAR_QRY = CONCAT("UPDATE TABLENAME SET PWD=" , VAR_NEW_PASS , " WHERE ID = ",VAR_ID);

                            PREPARE stmt FROM @VAR_QRY;
                            EXECUTE stmt;

                END LOOP GET_NEXTRECORD;

                CLOSE DATABASE_CURSOR;

END
</code>```

Try above code;

And make changes accordingly for new password,here i had just appending ABC with OLD PASSWORD.

Hope this help.

Body:
I have a column in my user_table called password.
Now I want to update all password fields in all rows by passing the existing value of password field and update it using the return value from the function. How to achieve it?

╔════╦══════════════╦══════╗
║ id ║  username    ║ pwd  ║
╠════╬══════════════╬══════╣
║  1 ║ Jeff Atwood  ║ 5636 ║
║  2 ║ Geoff Dalgas ║  148 ║
║  3 ║ Jarrod Dixon ║  101 ║
║  4 ║ Joel Spolsky ║  959 ║
╚════╩══════════════╩══════╝

my function is as follows:

function encryptPassword(password)
{
// $new password = my encryption logic here
   return $password;
}

How can I update all password cloumn in every row one by one?

Body:
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `ITERATEALLTABLE_PWD`()
BEGIN
DECLARE VAR_OLD_PASS varchar(100);
DECLARE VAR_NEW_PASS varchar(100);
DECLARE VAR_QRY varchar(100);
DECLARE VAR_FINISHED INT(11) DEFAULT 0;
DECLARE VAR_ID INT(11) ;
DECLARE DATABASE_CURSOR CURSOR FOR
                SELECT pwd ,ID
                FROM TABLENAME;

                DECLARE CONTINUE HANDLER FOR NOT FOUND SET VAR_FINISHED = 1;

                OPEN DATABASE_CURSOR;
                GET_NEXTRECORD: LOOP

                        FETCH DATABASE_CURSOR INTO VAR_OLD_PASS,VAR_ID;

                           IF VAR_FINISHED = 1 THEN
                        LEAVE GET_NEXTRECORD;
                        END IF;

                            SET VAR_NEW_PASS =CONCAT(VAR_OLD_PASS,'ABC'); <-------Here you have to implement your crypto operation!>
                            SET @VAR_QRY = CONCAT("UPDATE TABLENAME SET PWD=" , VAR_NEW_PASS , " WHERE ID = ",VAR_ID);

                            PREPARE stmt FROM @VAR_QRY;
                            EXECUTE stmt;

                END LOOP GET_NEXTRECORD;

                CLOSE DATABASE_CURSOR;

END

Try above code;

And make changes accordingly for new password,here i had just appending ABC with OLD PASSWORD.

Hope this help.


问:
Offload App remove what in iOS 11
I just installed iOS 11 beta and I noticed that Offload App, By offloading app what will be remove Shared Directory or User Default or remove both or other than this ?

Looking for suggestions.

Thanks

答: There is no official document(technical) available for offloading apps till the date but as the description(in setting app) says that your documents and data will be saved then I think it will save user defaults , document directories and core data - I mean all kind of data that can be stored!

Title: Offload App remove what in iOS 11


问:
SCVMM PowerShell commands not working in Task Scheduler when account is not logged in
I am trying to run a script with the Task Scheduler.
It works just fine when the user is logged in, but when I try to run it when the user is not logged in, the command Get-SCVirtualMachine returns null.

The script does run, but just that command doesnt return any value when I am running it without the service account being logged in.

Of course I have the "Run wether user is logged on or not" flag set to true. And as I said, the script gets executed, just that SCVMM cmdlet isn't working.

答: The Solution was to add the service account as a local administrator. Somehow i totally forgot that. Therefore it could'nt load the needed PS Modules.</p>


问:
JUnit: compare two beans that contain a List regardless of list order
I have found a lot of questions and answers about comparing List objects regardless of the order of their elements, but my problem is more complex: I have two beans that contain, among other properties, a List.  I want to perform an assertEquals of the two beans regardless of the order of the elements in the inner lists.  Is there a simple way to do this?</p>

答:
When you do assertEquals(expectedObject, actualObject) Behind the scene the junit actually call object's equal method.So my suggestion will be if you override your equal method then you can achieve what you are expecting.

Logic behind assertEqual.

```<code>String expectedString = String.valueOf(expected);
String actualString = String.valueOf(actual);
 if (expectedString.equals(actualString)) {
            return formatted + "expected: "
                    + formatClassAndValue(expected, expectedString)
                    + " but was: " + formatClassAndValue(actual, actualString);
        } else {
            return formatted + "expected:<" + expectedString + "> but was:<"
                    + actualString + ">";
        }
</code>```

Or Apache util available to check two object without equal method overiding

```<code><dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>
</code>```

API

```<code>EqualsBuilder.reflectionEquals( obj1, obj2 )
</code>```

Body:
When you do assertEquals(expectedObject, actualObject) Behind the scene the junit actually call object's equal method.So my suggestion will be if you override your equal method then you can achieve what you are expecting.

Logic behind assertEqual.

String expectedString = String.valueOf(expected);
String actualString = String.valueOf(actual);
 if (expectedString.equals(actualString)) {
            return formatted + "expected: "
                    + formatClassAndValue(expected, expectedString)
                    + " but was: " + formatClassAndValue(actual, actualString);
        } else {
            return formatted + "expected:<" + expectedString + "> but was:<"
                    + actualString + ">";
        }

Or Apache util available to check two object without equal method overiding

<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>

API

EqualsBuilder.reflectionEquals( obj1, obj2 )


问:
How do I encode URI parameter values?
I want to send a URI as the value of a query/matrix parameter. Before I can append it to an existing URI, I need to encode it according to RFC 2396. For example, given the input:

http://google.com/resource?key=value1 & value2

I expect the output:

http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue1%2520%26%2520value2

Neither java.net.URLEncoder nor java.net.URI will generate the right output. URLEncoder is meant for HTML form encoding which is not the same as RFC 2396. URI has no mechanism for encoding a single value at a time so it has no way of knowing that value1 and value2 are part of the same key.

答: It seems that CharEscapers from Google GData-java-client has what you want. It has uriPathEscaper method, uriQueryStringEscaper, and generic uriEscaper. (All return Escaper object which does actual escaping). Apache License.</p>

OwnerDisplayName: Gili

Title: How do I encode URI parameter values?

LastEditorDisplayName: Gili

OwnerDisplayName: Peter Štibraný


问:
Cross-domain AJAX request behaving oddly on Android phone's native browser
My setup is like so:

An SQLite database sits in one of my Apache folders

A Perl cgi script sits in the same folder, with public permissions, so that it can handle database interactions

A C program, running on the same machine, listens on a specific port for specific JSON requests and responds with specifically-formatted JSON data

A webpage, written primarily in jQuery and HTML, must access both the SQLite database and the C program somewhat constantly. It does so using AJAX requests -- here's an example from the code:

```<code>function sendCommand(cmd, callback) {
$.ajax({url: "http://192.168.42.90:6112/?cmd=" + cmd,
    dataType: "jsonp",
    success: function(d,s,x) {
          callback(d);
    },
    jsonpCallback: "json",
    error: function(xhr) {
         alert('Error: ' + xhr.status);
    }
});
}
</code>```

So I might invoke it with something like sendCommand("get_x", updatePosition) -- so that it'd send the get_x command along to the C program, and, if it got good feedback, run said feedback through the updatePosition function.

So all of this works SPLENDIDLY if I'm running on a webpage on the same machine. If I move to another machine -- in this case, specifically, an Android phone, doing tethered IP over USB, it ... sort of works. This is what's puzzling me -- it doesn't silently fail, like I'm used to JavaScript doing. Instead, as far as I can tell, it sends the request out, claims that it got data back, and runs the callback function -- only, according to the C program, nothing ever happened; according to Wireshark, no packets were sent; and the "data" that it gets back is an empty, specially-formatted string. If I'm expecting "(5,5)" as output from C, it's getting "(0,0)" -- why is it getting anything at all? Much less filling "(,)" with 0s?

Very strange. I've tried various little things, like changing the dataType to "json", making sure all my permissions are set up right, etc. I'm fairly sure that Apache isn't interfering, since there's nothing in the logs -- what gets me is that I don't see anything on Wireshark, of all things. It's like the phone just plain isn't trying to make the request.

答: maybe it is caching the ajax requests?  try setting cache:false in your jquery ajax requests.</p>

Body:
My setup is like so:

An SQLite database sits in one of my Apache folders

A Perl cgi script sits in the same folder, with public permissions, so that it can handle database interactions

A C program, running on the same machine, listens on a specific port for specific JSON requests and responds with specifically-formatted JSON data

A webpage, written primarily in jQuery and HTML, must access both the SQLite database and the C program somewhat constantly. It does so using AJAX requests -- here's an example from the code:

function sendCommand(cmd, callback) {
$.ajax({url: "http://192.168.42.90:6112/?cmd=" + cmd,
    dataType: "jsonp",
    success: function(d,s,x) {
          callback(d);
    },
    jsonpCallback: "json",
    error: function(xhr) {
         alert('Error: ' + xhr.status);
    }
});
}

So I might invoke it with something like sendCommand("get_x", updatePosition) -- so that it'd send the get_x command along to the C program, and, if it got good feedback, run said feedback through the updatePosition function.

So all of this works SPLENDIDLY if I'm running on a webpage on the same machine. If I move to another machine -- in this case, specifically, an Android phone, doing tethered IP over USB, it ... sort of works. This is what's puzzling me -- it doesn't silently fail, like I'm used to JavaScript doing. Instead, as far as I can tell, it sends the request out, claims that it got data back, and runs the callback function -- only, according to the C program, nothing ever happened; according to Wireshark, no packets were sent; and the "data" that it gets back is an empty, specially-formatted string. If I'm expecting "(5,5)" as output from C, it's getting "(0,0)" -- why is it getting anything at all? Much less filling "(,)" with 0s?

Very strange. I've tried various little things, like changing the dataType to "json", making sure all my permissions are set up right, etc. I'm fairly sure that Apache isn't interfering, since there's nothing in the logs -- what gets me is that I don't see anything on Wireshark, of all things. It's like the phone just plain isn't trying to make the request.


问:
Image didn't load in JPanel
I have a JPanel name "imagePanel" and a button name "browseBtn". All contained in a JFrame class. When pressing the browseBtn, a file chooser will open up and after choosing a PNG image file, the image will appear directly in the imagePanel.

This is the action event for the browseBtn

```<code>private void browseBtnActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
      JFileChooser fc = new JFileChooser();
    int result = fc.showOpenDialog(null);
    if (result == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        if (accept(file)) {
            try {
                ImageIcon image = new ImageIcon(file.getPath());
                JLabel l = new JLabel(image);
                imagePanel.add(l);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "Error reading file !");
            }
        }
        else {
            JOptionPane.showMessageDialog(this, "Choose png file only !");
        }
    }

}

public boolean accept(File file) {
    return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
</code>```

I have choose the correct .png file but i don't understand why the image didn't show up in the imagePanel. Can you guy explain on that ?
Cheers.

答:
You should avoid creating new objects everytime you want to display your image, imagine if you change it 5 times, you're creating 5 times an object while you display only one !

Like said in the comments, your best shot would be to create your label when you create your panel, add it to said panel, then simply change the icon of this label when you load your image.

```<code>        browseBtn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fc = new JFileChooser();
            int result = fc.showOpenDialog(null);
            if (result == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                if (accept(file)) {
                    try {
                        ImageIcon image = new ImageIcon(file.getPath());
                        label.setIcon(image);
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(this, "Error reading file !");
                    }
                }
                else {
                    JOptionPane.showMessageDialog(this, "Choose png file only !");
                }
            }
        }

        public boolean accept(File file) {
            return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
        }

    });
</code>```

Assuming label is the reference to said JLabel, created on components initialisation.

Title: Image didn't load in JPanel

Body:
I have a JPanel name "imagePanel" and a button name "browseBtn". All contained in a JFrame class. When pressing the browseBtn, a file chooser will open up and after choosing a PNG image file, the image will appear directly in the imagePanel.

This is the action event for the browseBtn

private void browseBtnActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
      JFileChooser fc = new JFileChooser();
    int result = fc.showOpenDialog(null);
    if (result == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        if (accept(file)) {
            try {
                ImageIcon image = new ImageIcon(file.getPath());
                JLabel l = new JLabel(image);
                imagePanel.add(l);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "Error reading file !");
            }
        }
        else {
            JOptionPane.showMessageDialog(this, "Choose png file only !");
        }
    }

}

public boolean accept(File file) {
    return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}

I have choose the correct .png file but i don't understand why the image didn't show up in the imagePanel. Can you guy explain on that ?
Cheers.

Body:
You should avoid creating new objects everytime you want to display your image, imagine if you change it 5 times, you're creating 5 times an object while you display only one !

Like said in the comments, your best shot would be to create your label when you create your panel, add it to said panel, then simply change the icon of this label when you load your image.

        browseBtn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fc = new JFileChooser();
            int result = fc.showOpenDialog(null);
            if (result == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                if (accept(file)) {
                    try {
                        ImageIcon image = new ImageIcon(file.getPath());
                        label.setIcon(image);
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(this, "Error reading file !");
                    }
                }
                else {
                    JOptionPane.showMessageDialog(this, "Choose png file only !");
                }
            }
        }

        public boolean accept(File file) {
            return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
        }

    });

Assuming label is the reference to said JLabel, created on components initialisation.


问:
Conditional Tooltip Based On Checkbox WPF
I've got a checkbox and a button in my WPF MVVM app. If the checkbox is checked I want a tooltip on the button that says "x" and if it's unchecked the tooltip should say "y".

Anyone know the best way to do this? I think it could be done with a separate property in my view model, but maybe there's an easier way to do this in just the xaml?

Thanks in advance.

答:
You could use a Style with a DataTrigger that binds to the IsChecked property of the CheckBox:

```<code><CheckBox x:Name="chk" Content="CheckBox" />
<Button Content="Button">
    <Button.Style>
        <Style TargetType="Button">
            <Setter Property="ToolTip" Value="y" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsChecked, ElementName=chk}" Value="True">
                    <Setter Property="ToolTip" Value="x" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>
</code>```

Body:
You could use a Style with a DataTrigger that binds to the IsChecked property of the CheckBox:

<CheckBox x:Name="chk" Content="CheckBox" />
<Button Content="Button">
    <Button.Style>
        <Style TargetType="Button">
            <Setter Property="ToolTip" Value="y" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsChecked, ElementName=chk}" Value="True">
                    <Setter Property="ToolTip" Value="x" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>


问:
Facebook like button not working in android app
There is a Facebook like button in my android app. But when clicking on that I got this error.

```<code>java.lang.NullPointerException: Argument 'activity' cannot be null
                  at com.facebook.internal.Validate.notNull(Validate.java:36)
                  at com.facebook.internal.FacebookDialogBase.<init>(FacebookDialogBase.java:53)
                  at com.facebook.share.internal.LikeDialog.<init>(LikeDialog.java:67)
                  at com.facebook.share.internal.LikeActionController.presentLikeDialog(LikeActionController.java:824)
                  at com.facebook.share.internal.LikeActionController.toggleLike(LikeActionController.java:698)
                  at com.facebook.share.widget.LikeView.toggleLike(LikeView.java:569)
                  at com.facebook.share.widget.LikeView.access$300(LikeView.java:52)
                  at com.facebook.share.widget.LikeView$1.onClick(LikeView.java:519)
                  at com.facebook.FacebookButtonBase$1.onClick(FacebookButtonBase.java:312)
                  at android.view.View.performClick(View.java:4496)
                  at android.view.View$PerformClick.run(View.java:18603)
                  at android.os.Handler.handleCallback(Handler.java:733)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:136)
                  at android.app.ActivityThread.main(ActivityThread.java:5433)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
                  at dalvik.system.NativeStart.main(Native Method)
</code>```

Here is my code for Facebook like button

```<code>LikeView likeView = (LikeView) findViewById(R.id.likeView);
likeView.setLikeViewStyle(LikeView.Style.STANDARD);
likeView.setAuxiliaryViewPosition(LikeView.AuxiliaryViewPosition.INLINE);
likeView.setObjectIdAndType(
    "http://inthecheesefactory.com/blog/understand-android-activity-
     launchmode/en",
      LikeView.ObjectType.OPEN_GRAPH)
</code>```

This is code for like button in xml file.

```<code><com.facebook.share.widget.LikeView
                android:id="@+id/likeView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"/>
</code>```

How can I solve it

答:
Try to change

```<code>likeView.setObjectIdAndType(
"http://inthecheesefactory.com/blog/understand-android-activity-
 launchmode/en",
  LikeView.ObjectType.OPEN_GRAPH)
</code>```

with

```<code>likeView.setObjectIdAndType(
"http://inthecheesefactory.com/blog/understand-android-activity-
 launchmode/en",
  LikeView.ObjectType.PAGE
</code>```

)

Body:
There is a Facebook like button in my android app. But when clicking on that I got this error.

java.lang.NullPointerException: Argument 'activity' cannot be null
                  at com.facebook.internal.Validate.notNull(Validate.java:36)
                  at com.facebook.internal.FacebookDialogBase.<init>(FacebookDialogBase.java:53)
                  at com.facebook.share.internal.LikeDialog.<init>(LikeDialog.java:67)
                  at com.facebook.share.internal.LikeActionController.presentLikeDialog(LikeActionController.java:824)
                  at com.facebook.share.internal.LikeActionController.toggleLike(LikeActionController.java:698)
                  at com.facebook.share.widget.LikeView.toggleLike(LikeView.java:569)
                  at com.facebook.share.widget.LikeView.access$300(LikeView.java:52)
                  at com.facebook.share.widget.LikeView$1.onClick(LikeView.java:519)
                  at com.facebook.FacebookButtonBase$1.onClick(FacebookButtonBase.java:312)
                  at android.view.View.performClick(View.java:4496)
                  at android.view.View$PerformClick.run(View.java:18603)
                  at android.os.Handler.handleCallback(Handler.java:733)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:136)
                  at android.app.ActivityThread.main(ActivityThread.java:5433)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
                  at dalvik.system.NativeStart.main(Native Method)

Here is my code for Facebook like button

LikeView likeView = (LikeView) findViewById(R.id.likeView);
likeView.setLikeViewStyle(LikeView.Style.STANDARD);
likeView.setAuxiliaryViewPosition(LikeView.AuxiliaryViewPosition.INLINE);
likeView.setObjectIdAndType(
    "http://inthecheesefactory.com/blog/understand-android-activity-
     launchmode/en",
      LikeView.ObjectType.OPEN_GRAPH)

This is code for like button in xml file.

<com.facebook.share.widget.LikeView
                android:id="@+id/likeView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"/>

How can I solve it

Body:
Try to change

likeView.setObjectIdAndType(
"http://inthecheesefactory.com/blog/understand-android-activity-
 launchmode/en",
  LikeView.ObjectType.OPEN_GRAPH)

with

likeView.setObjectIdAndType(
"http://inthecheesefactory.com/blog/understand-android-activity-
 launchmode/en",
  LikeView.ObjectType.PAGE

)


问:
App crashes at startActivity(intent)
this app crashes when i push over botonRegistro. The intent is created but i think is saved as null and i don´t know why. This is the code:

```<code>import com.example.pestanasholacampus.R;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.app.Activity;
import android.content.Intent;

public class InitActivity extends Activity {

protected EditText usuarioIntroducido;
protected EditText pwdIntroducida;
protected Button botonEntrada;
protected Button botonRegistro;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_acceso);
    System.out.println("Contenido enlazado");

    // obtenemos los recursos de la clase R para la activity_main
    usuarioIntroducido = (EditText) findViewById(R.id.usuarioIntroducido);
    pwdIntroducida = (EditText) findViewById(R.id.contrasenaIntroducida);
    botonEntrada = (Button) findViewById(R.id.botonEntrar);
    botonRegistro = (Button) findViewById(R.id.BotonRegistro);
    System.out.println("Variables asociadas");

    botonRegistro.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intentRegistro = new Intent(getBaseContext(), // I think intentRegistro is saved as null
                    RegistroActivity.class);
            startActivity(intentRegistro); //NullpointerException at this point
        }
    });
    botonEntrada.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            /*
             * String usuario = usuarioIntroducido.getText().toString();
             * String clave = pwdIntroducida.getText().toString();
             * compruebaUsuario(v);
             */
            Intent intentEntrar = new Intent(getBaseContext(),
                    MainActivity.class);
            System.out.println("Boton entrar pulsado.");
            startActivity(intentEntrar);
        }
    });

    // Enlace al activity de registro mediante el boton

}

public void compruebaUsuario(View view) {// La entrada es desde la view que
                                            // se ha llamado (los botones
                                            // son views)
    Intent intent = new Intent(getBaseContext(), MainActivity.class);
    intent.putExtra("user", usuarioIntroducido.getText());
    intent.putExtra("pwd", pwdIntroducida.getText());
    // El start Activity iría despues de comprobar el usuario con la BDD.
    startActivity(intent);
}
</code>```

}

The debugger error is: Unable to start activity ComponentInfo {com.example.pestanasholacampus/com.example.pestanasholacampus.RegistroActivity}: java.lang.NullPointerException

Edit:This is my RegistroActivity

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

import com.example.pestanasholacampus.GestionRegistros;
import com.example.pestanasholacampus.R;
import com.example.pestanasholacampus.Usuario;
import com.example.pestanasholacampus.R.id;
import com.example.pestanasholacampus.R.layout;
import com.example.pestanasholacampus.R.menu;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
</code>```

public class RegistroActivity extends Activity{

```<code>private EditText nombre= (EditText)findViewById(R.id.pideNombre);
private EditText apellido1= (EditText)findViewById(R.id.pideAp1);
private EditText apellido2= (EditText)findViewById(R.id.pideAp2);
private EditText universidad= (EditText)findViewById(R.id.pideCampus);
private EditText telefono= (EditText)findViewById(R.id.pideTelefono);
private EditText mail= (EditText)findViewById(R.id.pideEmail);
private EditText clave= (EditText)findViewById(R.id.pideClave);

private Button botonReg= (Button)findViewById(R.id.BotonRegistro);

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.actividad_registro);
    botonReg.setOnClickListener(new View.OnClickListener() {
        Usuario usuario= new Usuario();
        @Override
        public void onClick(View v) {
            //Obtenemos los datos introducidos y los almacenamos en la clase usuario
            usuario.setNombre(nombre.getText().toString());
            usuario.setApellido1(apellido1.getText().toString());
            usuario.setApellido2(apellido2.getText().toString());
            usuario.setCampus(universidad.getText().toString());
            usuario.setClave(clave.getText().toString());
            usuario.setTelefono(telefono.getText().toString());
            usuario.setEmail(mail.getText().toString());

            GestionRegistros gestor= new GestionRegistros();

        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
</code>```

}

Thanks.

答:
Nice explanation.. I have faced the same problem, just want to add that initialization of components have to be after oncreate() -> setContentView() in source activity as well as in target activity also.

Otherwise the app will keep on crashing.

The problem here was NullPointerException.

Title: App crashes at startActivity(intent)

Body:
this app crashes when i push over botonRegistro. The intent is created but i think is saved as null and i don´t know why. This is the code:

import com.example.pestanasholacampus.R;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.app.Activity;
import android.content.Intent;

public class InitActivity extends Activity {

protected EditText usuarioIntroducido;
protected EditText pwdIntroducida;
protected Button botonEntrada;
protected Button botonRegistro;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_acceso);
    System.out.println("Contenido enlazado");

    // obtenemos los recursos de la clase R para la activity_main
    usuarioIntroducido = (EditText) findViewById(R.id.usuarioIntroducido);
    pwdIntroducida = (EditText) findViewById(R.id.contrasenaIntroducida);
    botonEntrada = (Button) findViewById(R.id.botonEntrar);
    botonRegistro = (Button) findViewById(R.id.BotonRegistro);
    System.out.println("Variables asociadas");

    botonRegistro.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intentRegistro = new Intent(getBaseContext(), // I think intentRegistro is saved as null
                    RegistroActivity.class);
            startActivity(intentRegistro); //NullpointerException at this point
        }
    });
    botonEntrada.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            /*
             * String usuario = usuarioIntroducido.getText().toString();
             * String clave = pwdIntroducida.getText().toString();
             * compruebaUsuario(v);
             */
            Intent intentEntrar = new Intent(getBaseContext(),
                    MainActivity.class);
            System.out.println("Boton entrar pulsado.");
            startActivity(intentEntrar);
        }
    });

    // Enlace al activity de registro mediante el boton

}

public void compruebaUsuario(View view) {// La entrada es desde la view que
                                            // se ha llamado (los botones
                                            // son views)
    Intent intent = new Intent(getBaseContext(), MainActivity.class);
    intent.putExtra("user", usuarioIntroducido.getText());
    intent.putExtra("pwd", pwdIntroducida.getText());
    // El start Activity iría despues de comprobar el usuario con la BDD.
    startActivity(intent);
}

}

The debugger error is: Unable to start activity ComponentInfo {com.example.pestanasholacampus/com.example.pestanasholacampus.RegistroActivity}: java.lang.NullPointerException

Edit:This is my RegistroActivity

package com.example.pestanasholacampus;

import com.example.pestanasholacampus.GestionRegistros;
import com.example.pestanasholacampus.R;
import com.example.pestanasholacampus.Usuario;
import com.example.pestanasholacampus.R.id;
import com.example.pestanasholacampus.R.layout;
import com.example.pestanasholacampus.R.menu;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class RegistroActivity extends Activity{

private EditText nombre= (EditText)findViewById(R.id.pideNombre);
private EditText apellido1= (EditText)findViewById(R.id.pideAp1);
private EditText apellido2= (EditText)findViewById(R.id.pideAp2);
private EditText universidad= (EditText)findViewById(R.id.pideCampus);
private EditText telefono= (EditText)findViewById(R.id.pideTelefono);
private EditText mail= (EditText)findViewById(R.id.pideEmail);
private EditText clave= (EditText)findViewById(R.id.pideClave);

private Button botonReg= (Button)findViewById(R.id.BotonRegistro);

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.actividad_registro);
    botonReg.setOnClickListener(new View.OnClickListener() {
        Usuario usuario= new Usuario();
        @Override
        public void onClick(View v) {
            //Obtenemos los datos introducidos y los almacenamos en la clase usuario
            usuario.setNombre(nombre.getText().toString());
            usuario.setApellido1(apellido1.getText().toString());
            usuario.setApellido2(apellido2.getText().toString());
            usuario.setCampus(universidad.getText().toString());
            usuario.setClave(clave.getText().toString());
            usuario.setTelefono(telefono.getText().toString());
            usuario.setEmail(mail.getText().toString());

            GestionRegistros gestor= new GestionRegistros();

        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

Thanks.


问:
How to retrieve the latest eventName (latest by date)
I have two arrays

```<code>var events=["DELIVERED", "OUT TO DELEVERY", "REACHED WAREHOUSE", "DEPARTED"];

var eventDetails= [{
"source" : "application"
"DateTime": "2016-05-12 11:20:00",
"eventName" : "DELIVERED"
},
{
"source" : "application"
"DateTime": "2017-06-07 00:00:00",
"eventName" : "OUT TO DELEVERY"
},
{
"source" : "application"
"DateTime": "2016-11-05 11:20:00",
"eventNname" : "CUSTOM CLEARANCE"
}];
</code>```

I need to display the latest eventName (latest by date and time) from eventDetails array, if the latest eventName is present in "events" Array. Else it should return null( if eventName in latest updated record doesn't contain any of the value from event array).

答:
You can do this in a few different ways. A simple solution to this would be sorting the events by date and then grabbing the one you need (the first in this case):

```<code>var eventDetails= [{
  "source" : "application",
  "DateTime": "2016-05-12 11:20:00",
  "eventName" : "DELIVERED"
}, {
  "source" : "application",
  "DateTime": "2017-06-07 00:00:00",
  "eventName" : "OUT TO DELEVERY"
}, {
  "source" : "application",
  "DateTime": "2016-11-05 11:20:00",
  "eventNname" : "CUSTOM CLEARANCE"
}];

var last = eventDetails.sort(function(prev, next) {
    return new Date(next.DateTime) - new Date(prev.DateTime);
})[0];

var lastEventName = last.eventName;

if (events.indexOf(lastEventName) >= 0) {
  // Return true
} else {
  // Return false
}
</code>```

Option 2:

You can also loop through all events and keep track of the latest:

```<code>var last = eventDetails[0];
for (var i = 1; i < eventDetails.length; i++) {
  if (eventDetails[i].DateTime > last.DateTime) {
    last = eventDetails[i];
  }
}
var lastEventName = last.eventName;

if (events.indexOf(lastEventName) >= 0) {
  // Return true
} else {
  // Return false
}
</code>```

Body:
I have two arrays

var events=["DELIVERED", "OUT TO DELEVERY", "REACHED WAREHOUSE", "DEPARTED"];

var eventDetails= [{
"source" : "application"
"DateTime": "2016-05-12 11:20:00",
"eventName" : "DELIVERED"
},
{
"source" : "application"
"DateTime": "2017-06-07 00:00:00",
"eventName" : "OUT TO DELEVERY"
},
{
"source" : "application"
"DateTime": "2016-11-05 11:20:00",
"eventNname" : "CUSTOM CLEARANCE"
}];

I need to display the latest eventName (latest by date and time) from eventDetails array, if the latest eventName is present in "events" Array. Else it should return null( if eventName in latest updated record doesn't contain any of the value from event array).

Body:
You can do this in a few different ways. A simple solution to this would be sorting the events by date and then grabbing the one you need (the first in this case):

var eventDetails= [{
  "source" : "application",
  "DateTime": "2016-05-12 11:20:00",
  "eventName" : "DELIVERED"
}, {
  "source" : "application",
  "DateTime": "2017-06-07 00:00:00",
  "eventName" : "OUT TO DELEVERY"
}, {
  "source" : "application",
  "DateTime": "2016-11-05 11:20:00",
  "eventNname" : "CUSTOM CLEARANCE"
}];

var last = eventDetails.sort(function(prev, next) {
    return new Date(next.DateTime) - new Date(prev.DateTime);
})[0];

var lastEventName = last.eventName;

if (events.indexOf(lastEventName) >= 0) {
  // Return true
} else {
  // Return false
}

Option 2:

You can also loop through all events and keep track of the latest:

var last = eventDetails[0];
for (var i = 1; i < eventDetails.length; i++) {
  if (eventDetails[i].DateTime > last.DateTime) {
    last = eventDetails[i];
  }
}
var lastEventName = last.eventName;

if (events.indexOf(lastEventName) >= 0) {
  // Return true
} else {
  // Return false
}


问:
Magento error : SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded;
i have the following problem and i dont know how to solve it. Frontend and Backend dont work. Has anyone an idear ?

a:5:{i:0;s:458:"SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction, query was: UPDATE `catalogrule` SET `name` = ?, `description` = ?, `from_date` = ?, `to_date` = '2017-07-30', `is_active` = ?, `conditions_serialized` = ?, `actions_serialized` = ?, `stop_rules_processing` = ?, `sort_order` = ?, `simple_action` = ?, `discount_amount` = ?, `sub_is_enable` = ?, `sub_simple_action` = ?, `sub_discount_amount` = ? WHERE (rule_id='17')";i:1;s:3033:"#0 /is/htdocs/wp1158418_XAIH5ALR0L/www/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
#1 /is/htdocs/wp1158418_XAIH5ALR0L/www/app/code/core/Zend/Db/Statement.php(291): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
#2 /is/htdocs/wp1158418_XAIH5ALR0L/www/lib/Zend/Db/Adapter/Abstract.php(480): Zend_Db_Statement->execute(Array)
#3 /is/htdocs/wp1158418_XAIH5ALR0L/www/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('UPDATE `catalog...', Array)
#4 /is/htdocs/wp1158418_XAIH5ALR0L/www/lib/Varien/Db/Adapter/Pdo/Mysql.php(504): Zend_Db_Adapter_Pdo_Abstract->query('UPDATE `catalog...', Array)
#5 /is/htdocs/wp1158418_XAIH5ALR0L/www/lib/Zend/Db/Adapter/Abstract.php(635): Varien_Db_Adapter_Pdo_Mysql->query('UPDATE `catalog...', Array)
#6 /is/htdocs/wp1158418_XAIH5ALR0L/www/app/code/core/Mage/Core/Model/Resource/Db/Abstract.php(433): Zend_Db_Adapter_Abstract->update('catalogrule', Array, 'rule_id='17'')
#7 /is/htdocs/wp1158418_XAIH5ALR0L/www/app/code/core/Mage/Core/Model/Abstract.php(318): Mage_Core_Model_Resource_Db_Abstract->save(Object(Mage_CatalogRule_Model_Rule))
#8 /is/htdocs/wp1158418_XAIH5ALR0L/www/app/code/local/Mirasvit/Action/Model/Observer.php(51): Mage_Core_Model_Abstract->save()
#9 /is/htdocs/wp1158418_XAIH5ALR0L/www/app/code/local/Mirasvit/Action/Model/Observer.php(24): Mirasvit_Action_Model_Observer->updateStatus()
#10 /is/htdocs/wp1158418_XAIH5ALR0L/www/app/code/core/Mage/Core/Model/App.php(1357): Mirasvit_Action_Model_Observer->onControllerActionLayoutRenderBefore(Object(Varien_Event_Observer))
#11 /is/htdocs/wp1158418_XAIH5ALR0L/www/app/code/core/Mage/Core/Model/App.php(1336): Mage_Core_Model_App->_callObserverMethod(Object(Mirasvit_Action_Model_Observer), 'onControllerAct...', Object(Varien_Event_Observer))
#12 /is/htdocs/wp1158418_XAIH5ALR0L/www/app/Mage.php(448): Mage_Core_Model_App->dispatchEvent('controller_acti...', Array)
#13 /is/htdocs/wp1158418_XAIH5ALR0L/www/app/code/core/Mage/Core/Controller/Varien/Action.php(384): Mage::dispatchEvent('controller_acti...')
#14 /is/htdocs/wp1158418_XAIH5ALR0L/www/app/code/core/Mage/Adminhtml/controllers/IndexController.php(82): Mage_Core_Controller_Varien_Action->renderLayout()
#15 /is/htdocs/wp1158418_XAIH5ALR0L/www/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Adminhtml_IndexController->loginAction()
#16 /is/htdocs/wp1158418_XAIH5ALR0L/www/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(254): Mage_Core_Controller_Varien_Action->dispatch('login')
#17 /is/htdocs/wp1158418_XAIH5ALR0L/www/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#18 /is/htdocs/wp1158418_XAIH5ALR0L/www/app/code/core/Mage/Core/Model/App.php(365): Mage_Core_Controller_Varien_Front->dispatch()
#19 /is/htdocs/wp1158418_XAIH5ALR0L/www/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#20 /is/htdocs/wp1158418_XAIH5ALR0L/www/index.php(83): Mage::run('', 'store')
#21 {main}";s:3:"url";s:17:"/index.php/admin/";s:11:"script_name";s:10:"/index.php";s:4:"skin";s:5:"admin";}```

答:
Delete Cache

Follow below directory,

var/cache

The problem will be resolved.


问:
forbidden 403 error in 'PUT' request Ajax in django rest framwork
I am using django-rest framework while sending put ajax request got error 403 forbidden.

user-details.html

```<code>   <form action="{% url 'user-detail' pk=object.pk %}" id="use1">
        {% csrf_token %}
        {% for key,value in serializer.items %}
             {{key}} <input value="{{value}}" type="text" class="form-control" /><br>
        {% endfor %}

        <button class="btn btn-warning edit_record" type="button" >Update</button>
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#deleteModal">Delete</button>
    </form>
</code>```

when I click on update button ajax will call and here I got formdata with hidden field csrftoken and also other parameters but after run this ajax i got 403 forbidden error however "DELETE" method working fine here.

As far as I know  we get this error when csrftoken is missing but I have csrf_token in my form.

```<code>$(".edit_record").on("click",function() {
        var url = document.location.pathname
        form = $(this).closest("form")[0],
        formData = new FormData(form);
         $.ajax({
             type:'PUT',
             url: url,
             data: formData,
             success: function (data) {

            },
              headers: {'X_METHODOVERRIDE': 'PUT'},

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

I used ModelViewset in views.py

```<code> class UserViewSet(viewsets.ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserProfileSerializer

        def update(self, request, *args, **kwargs):
            import pdb;pdb.set_trace()
            response = super(UserViewSet, self).update(request, *args, **kwargs)
            success =  True if response.status_code in [200,201] else False
            return Response({'object':response.data, 'success':success})

        def partial_update(self, request, *args, **kwargs):
            import pdb;pdb.set_trace()

        def destroy(self, request,*args, **kwargs):
            response = super(UserViewSet, self).destroy(request, *args, **kwargs)
            success =  True if response.status_code == 204 else False
            return Response({'data':success})
</code>```

答:
I think It is a Problem with Django Security and your Cookies. You need to configure your Middleware. Please take a look at this SO solution and this piece of Django Documentation.

What you could try is adding this to your Ajax Call and I would change the type to POST instead of PUT.

```<code>$.ajaxSetup({
  data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
  type: "POST",
  .....
 });
</code>```

What worked for me is implementing this into my JS:

```<code>function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
        }
    }
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
   return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
       if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
           xhr.setRequestHeader("X-CSRFToken", csrftoken);
     }
  }
});
</code>```

Body:
I am using django-rest framework while sending put ajax request got error 403 forbidden.

user-details.html

   <form action="{% url 'user-detail' pk=object.pk %}" id="use1">
        {% csrf_token %}
        {% for key,value in serializer.items %}
             {{key}} <input value="{{value}}" type="text" class="form-control" />

        {% endfor %}

        <button class="btn btn-warning edit_record" type="button" >Update</button>
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#deleteModal">Delete</button>
    </form>

when I click on update button ajax will call and here I got formdata with hidden field csrftoken and also other parameters but after run this ajax i got 403 forbidden error however "DELETE" method working fine here.

As far as I know  we get this error when csrftoken is missing but I have csrf_token in my form.

$(".edit_record").on("click",function() {
        var url = document.location.pathname
        form = $(this).closest("form")[0],
        formData = new FormData(form);
         $.ajax({
             type:'PUT',
             url: url,
             data: formData,
             success: function (data) {

            },
              headers: {'X_METHODOVERRIDE': 'PUT'},

         });
    });

I used ModelViewset in views.py

 class UserViewSet(viewsets.ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserProfileSerializer

        def update(self, request, *args, **kwargs):
            import pdb;pdb.set_trace()
            response = super(UserViewSet, self).update(request, *args, **kwargs)
            success =  True if response.status_code in [200,201] else False
            return Response({'object':response.data, 'success':success})

        def partial_update(self, request, *args, **kwargs):
            import pdb;pdb.set_trace()

        def destroy(self, request,*args, **kwargs):
            response = super(UserViewSet, self).destroy(request, *args, **kwargs)
            success =  True if response.status_code == 204 else False
            return Response({'data':success})

Body:
I think It is a Problem with Django Security and your Cookies. You need to configure your Middleware. Please take a look at this SO solution and this piece of Django Documentation.

What you could try is adding this to your Ajax Call and I would change the type to POST instead of PUT.

$.ajaxSetup({
  data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
  type: "POST",
  .....
 });

What worked for me is implementing this into my JS:

function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
        }
    }
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
   return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
       if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
           xhr.setRequestHeader("X-CSRFToken", csrftoken);
     }
  }
});


问:
How to manage front-end dependencies with bower in Angular 4.x app
I had worked on angular 1.x project before where we used bower to manage and install front-end dependencies. We used a gulp build system, in which we used gulp-wiredep to wire up all dependencies in index.html.

Just recently, I have started working on Angular 4.x project and planning out to create a build system with gulp. Is that even possible? I know there are other options available like webpack, angular-cli etc... but is wish to create it using gulp.

My questions is:

How to manage the front-end dependencies?

Earlier when we used gulp, front-end dependencies were managed by bower and we used gulp-wiredep to wire all those up in index.html. But when I searched for Angular 4.x package in bower, I did't find one.

If I use SystemJs as a module loader, do I still have to reference all the js (ts->js) in index.html?

Earlier we had a gulp task which picked up all the js file referenced in index.html and bundled it into one app.js file.

Please help! I understand angular 4.x but I am finding a hard time with a build system.

答:
How to manage the front-end dependencies?

Use npm for that. Bower is dying.

If I use SystemJs as a module loader, do I still have to reference all
  the js (ts->js) in index.html?

No, you just have to reference the starting module, usually main.js. Read more here.

But I would strongly recommend to consider webpack/angular-cli for your build system.


答: It will save Shared Directory & User Defaults. Everything else will be deleted.</p>

Title: Offload App remove what in iOS 11

Body:
I just installed iOS 11 beta and I noticed that Offload App, By offloading app what will be remove Shared Directory or User Default or remove both or other than this ?

Looking for suggestions.

Thanks