问:
Select items from List of objects that are tuples
I have a class that looks like so;

```<code>class MessageEntry
{
    public Tuple<bool, int> MessageId;

    public Tuple<bool, DateTime> MessageDate { get; internal set; }
    public Tuple<bool, String> Subject { get; internal set; }
    public Tuple<bool, String> EmailFrom { get; internal set; }
    public Tuple<bool, String> EmailTo { get; internal set; }
    public Tuple<bool, String> EmailCC { get; internal set; }
    public Tuple<bool, String> EmailBCC { get; internal set; }
    public Tuple<bool, String> EmailDateSent { get; internal set; }
    public Tuple<bool, String> BodyHTML { get; internal set; }
}
</code>```

I then have a List<MessageEntry> - List<MessageEntry> test = new List<MessageEntry>.

How can I select all items frrom test where Item1 of the tuples is true?

答:
I do not quite understand how you plan to use the code from the question.
But I think this code can help you if you change it to your own needs.

EDIT (I extract check method in extension method, for using in LINQ like style):

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var test = new List<MessageEntry>();

            var result = test
                .Where(entry => entry.IsAllTuplePropertiesIsTrue())
                .Aggregate(
                    string.Empty,
                    (s, entry) => s + $"value is {entry.IsAllTuplePropertiesIsTrue()}"
                    );

            Console.WriteLine(result);
            Console.ReadLine();
        }
    }

    public static class MessageEntryExtension
    {
        private const BindingFlags BindingFlags =
            System.Reflection.BindingFlags.GetProperty
            | System.Reflection.BindingFlags.Public
            | System.Reflection.BindingFlags.Instance;

        /// <summary>
        /// Method check all <see cref="Tuple" /> properties
        /// in instance of <see cref="MessageEntry" /> class.
        /// </summary>
        /// <param name="messageEntry"></param>
        /// <returns>If one of several Tuple.Item1 value is not bool false not equal
        /// false - return false. Any way - true</returns>
        public static bool IsAllTuplePropertiesIsTrue(this MessageEntry messageEntry)
        {
            var props = typeof (MessageEntry).GetProperties(BindingFlags);

            foreach (var value in props.Select(p => p.GetValue(messageEntry)))
            {
                if (value == null)
                    return false;

                if (typeof (Tuple<,>) == value.GetType())
                    return false;

                var item1Type = value.GetType().GetProperty("Item1", BindingFlags);
                var item1Value = item1Type?.GetValue(value);

                if (!(item1Value is bool))
                    return false;

                if (!(bool) item1Value)
                    return false;
            }

            return true;
        }
    }

    public class MessageEntry
    {
        public MessageEntry()
        {
            MessageId = new Tuple<bool, int>(true, 1);
            MessageDate = new Tuple<bool, DateTime>(false, DateTime.Now);
            Subject = new Tuple<bool, string>(true, "Hello, World!");
        }

        // Pay attention, I changed this place,
        // so as not to duplicate the reflection code.
        // For properties and field, it is similar, but still disconnects
        public Tuple<bool, int> MessageId { get; internal set; }

        public Tuple<bool, DateTime> MessageDate { get; internal set; }
        public Tuple<bool, string> Subject { get; internal set; }
        public Tuple<bool, string> EmailFrom { get; internal set; }
        public Tuple<bool, string> EmailTo { get; internal set; }
        public Tuple<bool, string> EmailCC { get; internal set; }
        public Tuple<bool, string> EmailBCC { get; internal set; }
        public Tuple<bool, string> EmailDateSent { get; internal set; }
        public Tuple<bool, string> BodyHTML { get; internal set; }
    }
}
</code>```

Body:
I have a class that looks like so;

class MessageEntry
{
    public Tuple<bool, int> MessageId;

    public Tuple<bool, DateTime> MessageDate { get; internal set; }
    public Tuple<bool, String> Subject { get; internal set; }
    public Tuple<bool, String> EmailFrom { get; internal set; }
    public Tuple<bool, String> EmailTo { get; internal set; }
    public Tuple<bool, String> EmailCC { get; internal set; }
    public Tuple<bool, String> EmailBCC { get; internal set; }
    public Tuple<bool, String> EmailDateSent { get; internal set; }
    public Tuple<bool, String> BodyHTML { get; internal set; }
}

I then have a List<MessageEntry> - List<MessageEntry> test = new List<MessageEntry>.

How can I select all items frrom test where Item1 of the tuples is true?

Body:
I do not quite understand how you plan to use the code from the question.
But I think this code can help you if you change it to your own needs.

EDIT (I extract check method in extension method, for using in LINQ like style):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var test = new List<MessageEntry>();

            var result = test
                .Where(entry => entry.IsAllTuplePropertiesIsTrue())
                .Aggregate(
                    string.Empty,
                    (s, entry) => s + $"value is {entry.IsAllTuplePropertiesIsTrue()}"
                    );

            Console.WriteLine(result);
            Console.ReadLine();
        }
    }

    public static class MessageEntryExtension
    {
        private const BindingFlags BindingFlags =
            System.Reflection.BindingFlags.GetProperty
            | System.Reflection.BindingFlags.Public
            | System.Reflection.BindingFlags.Instance;

        /// <summary>
        /// Method check all <see cref="Tuple" /> properties
        /// in instance of <see cref="MessageEntry" /> class.
        /// </summary>
        /// <param name="messageEntry"></param>
        /// <returns>If one of several Tuple.Item1 value is not bool false not equal
        /// false - return false. Any way - true</returns>
        public static bool IsAllTuplePropertiesIsTrue(this MessageEntry messageEntry)
        {
            var props = typeof (MessageEntry).GetProperties(BindingFlags);

            foreach (var value in props.Select(p => p.GetValue(messageEntry)))
            {
                if (value == null)
                    return false;

                if (typeof (Tuple<,>) == value.GetType())
                    return false;

                var item1Type = value.GetType().GetProperty("Item1", BindingFlags);
                var item1Value = item1Type?.GetValue(value);

                if (!(item1Value is bool))
                    return false;

                if (!(bool) item1Value)
                    return false;
            }

            return true;
        }
    }

    public class MessageEntry
    {
        public MessageEntry()
        {
            MessageId = new Tuple<bool, int>(true, 1);
            MessageDate = new Tuple<bool, DateTime>(false, DateTime.Now);
            Subject = new Tuple<bool, string>(true, "Hello, World!");
        }

        // Pay attention, I changed this place,
        // so as not to duplicate the reflection code.
        // For properties and field, it is similar, but still disconnects
        public Tuple<bool, int> MessageId { get; internal set; }

        public Tuple<bool, DateTime> MessageDate { get; internal set; }
        public Tuple<bool, string> Subject { get; internal set; }
        public Tuple<bool, string> EmailFrom { get; internal set; }
        public Tuple<bool, string> EmailTo { get; internal set; }
        public Tuple<bool, string> EmailCC { get; internal set; }
        public Tuple<bool, string> EmailBCC { get; internal set; }
        public Tuple<bool, string> EmailDateSent { get; internal set; }
        public Tuple<bool, string> BodyHTML { get; internal set; }
    }
}


来源: stackexchange

问:
sklearn Hierarchical Agglomerative Clustering using similarity matrix
Given a distance matrix, with similarity between various professors :

```<code>              prof1     prof2     prof3
       prof1     0        0.8     0.9
       prof2     0.8      0       0.2
       prof3     0.9      0.2     0
</code>```

I need to perform hierarchical clustering on this data, where the above data is in the form of 2-d matrix

```<code>       data_matrix=[[0,0.8,0.9],[0.8,0,0.2],[0.9,0.2,0]]
</code>```

I tried checking if I can implement it using sklearn.cluster  AgglomerativeClustering but it is considering all the 3 rows as 3 separate vectors and not as a distance matrix. Can it be done using this or scipy.cluster.hierarchy?

答:
Yes, you can do it with sklearn. You need to set:

affinity='precomputed', to use a matrix of distances

linkage='complete' or 'average', because default linkage(Ward) works only on coordinate input.

With precomputed affinity, input matrix is interpreted as a matrix of distances between observations. The following code

```<code>from sklearn.cluster import AgglomerativeClustering
data_matrix = [[0,0.8,0.9],[0.8,0,0.2],[0.9,0.2,0]]
model = AgglomerativeClustering(affinity='precomputed', n_clusters=2, linkage='complete').fit(data_matrix)
print(model.labels_)
</code>```

will return labels [1 0 0]: the 1st professor goes to one cluster, and the 2nd and 3rd - to another.

ContentLicense: CC BY-SA 3.0

Body:
Given a distance matrix, with similarity between various professors :

              prof1     prof2     prof3
       prof1     0        0.8     0.9
       prof2     0.8      0       0.2
       prof3     0.9      0.2     0

I need to perform hierarchical clustering on this data, where the above data is in the form of 2-d matrix

       data_matrix=[[0,0.8,0.9],[0.8,0,0.2],[0.9,0.2,0]]

I tried checking if I can implement it using sklearn.cluster  AgglomerativeClustering but it is considering all the 3 rows as 3 separate vectors and not as a distance matrix. Can it be done using this or scipy.cluster.hierarchy?

Body:
Yes, you can do it with sklearn. You need to set:

affinity='precomputed', to use a matrix of distances

linkage='complete' or 'average', because default linkage(Ward) works only on coordinate input.

With precomputed affinity, input matrix is interpreted as a matrix of distances between observations. The following code

from sklearn.cluster import AgglomerativeClustering
data_matrix = [[0,0.8,0.9],[0.8,0,0.2],[0.9,0.2,0]]
model = AgglomerativeClustering(affinity='precomputed', n_clusters=2, linkage='complete').fit(data_matrix)
print(model.labels_)

will return labels [1 0 0]: the 1st professor goes to one cluster, and the 2nd and 3rd - to another.


问:
How get context Confluence using atlassian-python-api?
I want to get context page confluence,
used python module atlassian-python-api

https://github.com/AstroTech/atlassian-python-api

found example how to create new page

```<code>from atlassian import Confluence

confluence = Confluence(
    url='http://localhost:8090',
    username='admin',
    password='admin')

status = confluence.create_page(
    space='DEMO',
    title='This is the title',
    body='This is the body. You can use <strong>HTML tags</strong>!')

print(status)
</code>```

How get context, example for this page
http://conf01:8080/pages/viewpage.action?pageId=111113
?

答: According to the example, you can either use get_page_by_title or get_page_by_id for getting page content.

ContentLicense: CC BY-SA 4.0

Body:
I want to get context page confluence,
used python module atlassian-python-api

https://github.com/AstroTech/atlassian-python-api

found example how to create new page

from atlassian import Confluence

confluence = Confluence(
    url='http://localhost:8090',
    username='admin',
    password='admin')

status = confluence.create_page(
    space='DEMO',
    title='This is the title',
    body='This is the body. You can use HTML tags!')

print(status)

How get context, example for this page
http://conf01:8080/pages/viewpage.action?pageId=111113
?


问:
Django Form Error: Select a valid choice. ... is not one of the available choices
I am trying to create a dynamic choice field. I have a view that creates a list of tuples. The first value of the tuple is the primary key of the object ServiceWriter while the second value is the name of the ServiceWriter. The list then gets passed into the form class. When I make the selection and submit the page the form is decided to be not valid and the following form error is printed in the shell: "Select a valid choice. (First value of tuple. ie 1,2,3..) is not one of the available choices."

```<code>forms.py

class CreateAdvancedRO(forms.Form):
service_writer = forms.ChoiceField()

def __init__(self, writer_choices, *args, **kwargs):
    super(CreateAdvancedRO, self).__init__(*args, **kwargs)
    self.fields['service_writer'].choices = writer_choices
    self.helper = FormHelper()
    self.helper.form_id = 'id-create-advanced-ro'
    self.helper.form_method = 'post'
    self.helper.add_input(Submit('submit', 'Open Repair Order'))
</code>```

Note: I am not using a ModelForm.

```<code>views.py
class CreateAdvancedRO(View):
form_class = CreateAdvancedRO
writer_form = CreateServiceWriter
add_line_form = AddJobLine

def post(self, request):
    writer_choices = []
    form = self.form_class(writer_choices, request.POST)
    print(form.errors)
    if form.is_valid():
        '''Do something'''
    else:
        writer_choices = []
        try:
            writers = ServiceWriter.objects.filter(user=request.user)
            for writer in writers:
                writer_choices.append((str(writer.id), writer.name))
        except ObjectDoesNotExist:
            pass
        form = self.form_class(writer_choices, request.POST)
        writer_form = self.writer_form()
        add_line_form = self.add_line_form()
        return render(request, 'free/advanced_create.html', {'form': form, 'writer_form': wri
                                                             'add_line_form': add_line_form})
</code>```

I have tried both of the following in the view:

```<code>writer_choices.append((str(writer.id), writer.name)) and
writer_choices.append((writer.id, writer.name))
</code>```

Here is the ServiceWriter model, just in case.

```<code>class ServiceWriter(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=20, blank=False)

def __str__(self):
    return str(self.name)
</code>```

Any thoughts?
Thanks for the help.

答: It looks like you're trying to validate the form against an empty list of choices. Have you tried populating writer_choices before instantiating or attempting to validate the form?</p>

Body:
I am trying to create a dynamic choice field. I have a view that creates a list of tuples. The first value of the tuple is the primary key of the object ServiceWriter while the second value is the name of the ServiceWriter. The list then gets passed into the form class. When I make the selection and submit the page the form is decided to be not valid and the following form error is printed in the shell: "Select a valid choice. (First value of tuple. ie 1,2,3..) is not one of the available choices."

forms.py

class CreateAdvancedRO(forms.Form):
service_writer = forms.ChoiceField()

def __init__(self, writer_choices, *args, **kwargs):
    super(CreateAdvancedRO, self).__init__(*args, **kwargs)
    self.fields['service_writer'].choices = writer_choices
    self.helper = FormHelper()
    self.helper.form_id = 'id-create-advanced-ro'
    self.helper.form_method = 'post'
    self.helper.add_input(Submit('submit', 'Open Repair Order'))

Note: I am not using a ModelForm.

views.py
class CreateAdvancedRO(View):
form_class = CreateAdvancedRO
writer_form = CreateServiceWriter
add_line_form = AddJobLine

def post(self, request):
    writer_choices = []
    form = self.form_class(writer_choices, request.POST)
    print(form.errors)
    if form.is_valid():
        '''Do something'''
    else:
        writer_choices = []
        try:
            writers = ServiceWriter.objects.filter(user=request.user)
            for writer in writers:
                writer_choices.append((str(writer.id), writer.name))
        except ObjectDoesNotExist:
            pass
        form = self.form_class(writer_choices, request.POST)
        writer_form = self.writer_form()
        add_line_form = self.add_line_form()
        return render(request, 'free/advanced_create.html', {'form': form, 'writer_form': wri
                                                             'add_line_form': add_line_form})

I have tried both of the following in the view:

writer_choices.append((str(writer.id), writer.name)) and
writer_choices.append((writer.id, writer.name))

Here is the ServiceWriter model, just in case.

class ServiceWriter(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=20, blank=False)

def __str__(self):
    return str(self.name)

Any thoughts?
Thanks for the help.


问:
Deserialize some fields in a json to a different class
I have a json of below format:

```<code>{
    "id": 0,
    "alternateId": 0,
    "familyName": "",
    "givenName": "",
    "firstName":"",
    "lastName": "",
    "middleName": "",
    "suffix": "",
    "motherName": "",
    "datOfBirth": "",
    "sex": "",
    "alias": [
        {
        "firstName": "",
        "lastName": "",
        "middleName": "",
        "suffix": "",
        }
    ]
}
</code>```

As you can observe, four fields firstName, lastName, middleName, and suffix which are present in the alias field are also present above it as fields of parent class.

Currently I have the following classes:

```<code>public class Person
{
    private int     id;
    private int     alternateId;
    private String  familyName;
    private String  givenName;
    private String  firstName;
    private String  lastName;
    private String  middleName;
    private String  suffix;
    private String  motherName;
    private Date    datOfBirth;
    private String  sex;
    private Set<Alias>  alias;
}

public class Alias
{
    private String  firstName;
    private String  lastName;
    private String  middleName;
    private String  suffix;
}
</code>```

And its working good with the jackson mapper. But my question is can the fields which are in Person class be combined to a new field primaryAlias and class be reduced to :

```<code>public class Person
{
    private int     id;
    private int     alternateId;
    private String  familyName;
    private String  givenName;
    private Alias   primaryAlias;
    private String  motherName;
    private Date    datOfBirth;
    private String  sex;
    private Set<Alias>  alias;
}
</code>```

without changing the current json. Can something be done to write a deserialiser in jackson which will map the fields firstName, lastName, middleName, and suffix of the json to be loaded into the new variable primaryAlias?

No need for complete code to do so, but a hint of what to do will be enough. I tried searching but maybe I am missing the perfect terminology to describe this problem.

Maybe I can explain better with images. This is whats currently happening:

And this is what I want:

答:
To your rescue, comes @JsonCreator which gives control to you before creation of class, so that you can populate the properties yourself :)

Here is my quick work (I have just used limited properties of your big json). Similarly my toString method is just to reflect that properties are loaded. You can have a meaningful toString if you want.

```<code>import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
import java.util.Set;

public class JacksonTest {

    final static ObjectMapper mapper = new ObjectMapper();

    public static void main(String[] args) throws Exception {

        final String jsonInString = "{\n"
                + "    \"id\": 0,\n"
                + "    \"familyName\": \"someFN\",\n"
                + "    \"givenName\": \"someGivenName\",\n"
                + "    \"firstName\":\"firstNameInperson\",\n"
                + "    \"lastName\": \"\",\n"
                + "    \"middleName\": \"\",\n"
                + "    \"suffix\": \"\",    \n"
                + "    \"motherName\": \"\",\n"
                + "    \"alias\": [\n"
                + "        {\n"
                + "        \"firstName\": \"firstNameInAlias\",\n"
                + "        \"lastName\": \"\",\n"
                + "        \"middleName\": \"\",\n"
                + "        \"suffix\": \"\"\n"
                + "        }\n"
                + "    ]\n"
                + "}";
        //System.out.println(jsonInString);

        Person person = mapper.readValue(jsonInString, Person.class);
        System.out.println(person);
        // System.out.println(newFoo.getSomething());
    }
}

class Person {

    @JsonProperty
    private int id;

    @JsonProperty
    private String familyName;

    Alias alias;

    @JsonProperty
    private String motherName;
    @JsonProperty
    private Set<Alias> aliases;

    @JsonCreator
    public Person(final Map<String, Object> properties) {
        System.out.println("printing in constructor.." + properties);
        id = (Integer) properties.get("id");
        familyName = (String) properties.get("familyName");
        Alias al = new Alias();
        al.firstName = (String) properties.get("firstName");
        al.lastName = (String) properties.get("lastName");
        al.middleName = (String) properties.get("middleName");
        al.suffix = (String) properties.get("suffix");
        this.alias = al;
        TypeReference aliasesType = new TypeReference<Set<Alias>>() {
        };
        try {
            aliases = JacksonTest.mapper.readValue(JacksonTest.mapper.writeValueAsString(properties.get("alias")), aliasesType);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public String toString() {
        return "Person: familyName:" + familyName + ", Alias: " + alias + " Aliases:" + aliases;
    }

}

class Alias {

    @JsonProperty
    String firstName;

    @JsonProperty
    String lastName;

    @JsonProperty
    String middleName;

    @JsonProperty
    String suffix;

    public String toString() {
        return "Alias : firstName::" + firstName;
    }
}
</code>```

Body:
I have a json of below format:

{
    "id": 0,
    "alternateId": 0,
    "familyName": "",
    "givenName": "",
    "firstName":"",
    "lastName": "",
    "middleName": "",
    "suffix": "",
    "motherName": "",
    "datOfBirth": "",
    "sex": "",
    "alias": [
        {
        "firstName": "",
        "lastName": "",
        "middleName": "",
        "suffix": "",
        }
    ]
}

As you can observe, four fields firstName, lastName, middleName, and suffix which are present in the alias field are also present above it as fields of parent class.

Currently I have the following classes:

public class Person
{
    private int     id;
    private int     alternateId;
    private String  familyName;
    private String  givenName;
    private String  firstName;
    private String  lastName;
    private String  middleName;
    private String  suffix;
    private String  motherName;
    private Date    datOfBirth;
    private String  sex;
    private Set<Alias>  alias;
}

public class Alias
{
    private String  firstName;
    private String  lastName;
    private String  middleName;
    private String  suffix;
}

And its working good with the jackson mapper. But my question is can the fields which are in Person class be combined to a new field primaryAlias and class be reduced to :

public class Person
{
    private int     id;
    private int     alternateId;
    private String  familyName;
    private String  givenName;
    private Alias   primaryAlias;
    private String  motherName;
    private Date    datOfBirth;
    private String  sex;
    private Set<Alias>  alias;
}

without changing the current json. Can something be done to write a deserialiser in jackson which will map the fields firstName, lastName, middleName, and suffix of the json to be loaded into the new variable primaryAlias?

No need for complete code to do so, but a hint of what to do will be enough. I tried searching but maybe I am missing the perfect terminology to describe this problem.

Maybe I can explain better with images. This is whats currently happening:

And this is what I want:

Body:
To your rescue, comes @JsonCreator which gives control to you before creation of class, so that you can populate the properties yourself :)

Here is my quick work (I have just used limited properties of your big json). Similarly my toString method is just to reflect that properties are loaded. You can have a meaningful toString if you want.

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
import java.util.Set;

public class JacksonTest {

    final static ObjectMapper mapper = new ObjectMapper();

    public static void main(String[] args) throws Exception {

        final String jsonInString = "{\n"
                + "    \"id\": 0,\n"
                + "    \"familyName\": \"someFN\",\n"
                + "    \"givenName\": \"someGivenName\",\n"
                + "    \"firstName\":\"firstNameInperson\",\n"
                + "    \"lastName\": \"\",\n"
                + "    \"middleName\": \"\",\n"
                + "    \"suffix\": \"\",    \n"
                + "    \"motherName\": \"\",\n"
                + "    \"alias\": [\n"
                + "        {\n"
                + "        \"firstName\": \"firstNameInAlias\",\n"
                + "        \"lastName\": \"\",\n"
                + "        \"middleName\": \"\",\n"
                + "        \"suffix\": \"\"\n"
                + "        }\n"
                + "    ]\n"
                + "}";
        //System.out.println(jsonInString);

        Person person = mapper.readValue(jsonInString, Person.class);
        System.out.println(person);
        // System.out.println(newFoo.getSomething());
    }
}

class Person {

    @JsonProperty
    private int id;

    @JsonProperty
    private String familyName;

    Alias alias;

    @JsonProperty
    private String motherName;
    @JsonProperty
    private Set<Alias> aliases;

    @JsonCreator
    public Person(final Map<String, Object> properties) {
        System.out.println("printing in constructor.." + properties);
        id = (Integer) properties.get("id");
        familyName = (String) properties.get("familyName");
        Alias al = new Alias();
        al.firstName = (String) properties.get("firstName");
        al.lastName = (String) properties.get("lastName");
        al.middleName = (String) properties.get("middleName");
        al.suffix = (String) properties.get("suffix");
        this.alias = al;
        TypeReference aliasesType = new TypeReference<Set<Alias>>() {
        };
        try {
            aliases = JacksonTest.mapper.readValue(JacksonTest.mapper.writeValueAsString(properties.get("alias")), aliasesType);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public String toString() {
        return "Person: familyName:" + familyName + ", Alias: " + alias + " Aliases:" + aliases;
    }

}

class Alias {

    @JsonProperty
    String firstName;

    @JsonProperty
    String lastName;

    @JsonProperty
    String middleName;

    @JsonProperty
    String suffix;

    public String toString() {
        return "Alias : firstName::" + firstName;
    }
}


问:
How can I programmatically select a listview item?
How can I programmatically select a listview item?

I have the following listview:

```<code>listview =
    select [ Html.Events.on "change" (Json.Decode.map InputContentType Html.Events.targetValue) ]
        [ option [ value "instructions" ] [ text "Content Type" ]
        , option [ value "Article" ] [ text "Article" ]
        , option [ value "Video" ] [ text "Video" ]
        , option [ value "Answer" ] [ text "Answer" ]
        , option [ value "Podcast" ] [ text "Podcast" ]
        ]
</code>```

Update:

I incorporated the posted answer below and updated the solution as follows:

```<code>( isArticle, isVideo, isAnswer, isPodcast ) =
            if hasText "youtube.com" then
                ( False, True, False, False )
            else if hasText "vimeo.com" then
                ( False, True, False, False )
            else if hasText "wordpress.com" then
                ( True, False, False, False )
            else if hasText "medium.com" then
                ( True, False, False, False )
            else if hasText "stackoverflow.com" then
                ( False, False, True, False )
            else
                ( False, False, False, False )

        listview =
            select [ Html.Events.on "change" (Json.Decode.map InputContentType Html.Events.targetValue) ]
                [ option [ value "instructions" ] [ text "Content Type" ]
                , option [ value "Article", selected isArticle ] [ text "Article" ]
                , option [ value "Video", selected isVideo ] [ text "Video" ]
                , option [ value "Answer", selected isAnswer ] [ text "Answer" ]
                , option [ value "Podcast", selected isPodcast ] [ text "Podcast" ]
                ]
</code>```

答:
You are able to use the Html.Attributes.selected function to select programmatically one of the options. It accepts a Bool, so whenever it's True, it will select that option.

```<code>listview =
    select [ Html.Events.on "change" (Json.Decode.map InputContentType Html.Events.targetValue) ]
        [ option [ value "instructions" ] [ text "Content Type" ]
        , option [ value "Article", selected True ] [ text "Article" ]
        , option [ value "Video" ] [ text "Video" ]
        , option [ value "Answer" ] [ text "Answer" ]
        , option [ value "Podcast" ] [ text "Podcast" ]
        ]
</code>```

Body:
How can I programmatically select a listview item?

I have the following listview:

listview =
    select [ Html.Events.on "change" (Json.Decode.map InputContentType Html.Events.targetValue) ]
        [ option [ value "instructions" ] [ text "Content Type" ]
        , option [ value "Article" ] [ text "Article" ]
        , option [ value "Video" ] [ text "Video" ]
        , option [ value "Answer" ] [ text "Answer" ]
        , option [ value "Podcast" ] [ text "Podcast" ]
        ]

Update:

I incorporated the posted answer below and updated the solution as follows:

( isArticle, isVideo, isAnswer, isPodcast ) =
            if hasText "youtube.com" then
                ( False, True, False, False )
            else if hasText "vimeo.com" then
                ( False, True, False, False )
            else if hasText "wordpress.com" then
                ( True, False, False, False )
            else if hasText "medium.com" then
                ( True, False, False, False )
            else if hasText "stackoverflow.com" then
                ( False, False, True, False )
            else
                ( False, False, False, False )

        listview =
            select [ Html.Events.on "change" (Json.Decode.map InputContentType Html.Events.targetValue) ]
                [ option [ value "instructions" ] [ text "Content Type" ]
                , option [ value "Article", selected isArticle ] [ text "Article" ]
                , option [ value "Video", selected isVideo ] [ text "Video" ]
                , option [ value "Answer", selected isAnswer ] [ text "Answer" ]
                , option [ value "Podcast", selected isPodcast ] [ text "Podcast" ]
                ]

Body:
You are able to use the Html.Attributes.selected function to select programmatically one of the options. It accepts a Bool, so whenever it's True, it will select that option.

listview =
    select [ Html.Events.on "change" (Json.Decode.map InputContentType Html.Events.targetValue) ]
        [ option [ value "instructions" ] [ text "Content Type" ]
        , option [ value "Article", selected True ] [ text "Article" ]
        , option [ value "Video" ] [ text "Video" ]
        , option [ value "Answer" ] [ text "Answer" ]
        , option [ value "Podcast" ] [ text "Podcast" ]
        ]


问:
Querying MongoDB embedded documents, not arrays, in a tabular format
I imported the below JSON into MongoDB (mongoimport --host localhost --db test --collection employees --type json --file Employees.json --jsonArray)

```<code>[
    {
        "Employee" : {
            "Basics" : {
                "Name" : "James Bond",
                "Age" : 42
            },
            "Addresses" : {
                "Address" : {
                    "City" : "London",
                    "Country" : "England"
                },
                "Address" : {
                    "City" : "Paris",
                    "Country" : "France"
                }
            },
            "Cars" : {
                "Car" : {
                    "Model" : "Aston Martin",
                    "Year" : 1977
                },
                "Car" : {
                    "Model" : "Audi",
                    "Year" : 2000
                }
            }
        }
    },
    {
        "Employee" : {
            "Basics" : {
                ..
            },
            "Addresses" : {
                "Address" : {
                    ..
                },
                "Address" : {
                    ..
                }
            },
            "Cars" : {
                "Car" : {
                    ..
                }
            }
        }
    }
]
</code>```

To get the results in a tabular format I used the below query but it fetches only Aston Martin and not Audi.

```<code>db.employees.aggregate(
[
{$match: {'Employee.Basics.Name':{$eq:"James Bond"}}},
{$project: {carModel:'$Employee.Cars.Car.Model',_id:0}}
]);
</code>```

Is there a way I can get both values? (In a tabular format with
specific fields - not like
db.getCollection('employees').find({'Employee.Basics.Name':{$eq:"James
Bond"}});)

Looking at other examples, it looks like the JSON should have had Array of Cars and Addresses, is there a way I can update the documents in MongoDB to change them to Arrays now?

I'm new to MongoDB, (just 2 days old :)) so any pointers will be of great help.
Thanks in advance!

答:
If anyone has ill-formed JSON like in my example, you can use the below Java code to fix it. (I got the JSON by using https://sourceforge.net/projects/xml2json-converter/). </p>

```<code>private final Deque<Integer> arrayStack = new ArrayDeque<Integer>();
private final Deque<Integer> arrayElemStack = new ArrayDeque<Integer>();

String[] arrayElemNames = {"Employee","Address","Car"};
String[] arrayNames = {"Addresses","Cars"};

public void cleanJSON() throws IOException {

    try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputJsonFileName))) {
        try (Stream<String> stream = Files.lines(Paths.get(inputJsonFileName))) {
            stream.map((str) -> formatRootElem(str)).map((str) -> formatArrayElems(str))
                    .map((str) -> formatArrays(str)).forEach((str) -> writeToOutput(writer, str));
        }
    }

}

private void writeToOutput(BufferedWriter writer, String str) {
    try {
        writer.write(str + "\n");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private String formatRootElem(String str) {
    if (str.equals("{")) {
        return "[";
    } else if (str.equals("}")) {
        return "]";
    } else if ((str.contains("Employees") && str.contains("{")) || str.equals("  }")) {
        return "";
    }
    return str;
}

private String formatArrayElems(String str) {
    if (checkInArray(str, arrayElemNames)) {
        arrayElemStack.push(1);
        return "{" + str;
    }
    if (!arrayElemStack.isEmpty()) {
        if (str.contains("{")) {
            int count = arrayElemStack.pop();
            arrayElemStack.push(++count);
        } else if (str.contains("}")) {
            int count = arrayElemStack.pop();
            --count;
            if (count == 0) {
                str = str.replace("}", "}}");
            } else {
                arrayElemStack.push(count);
            }
        }
    }
    return str;
}

private String formatArrays(String str) {
    if (checkInArray(str, arrayNames)) {
        str = str.replace('{', '[');
        arrayStack.push(1);
    } else if (!arrayStack.isEmpty()) {
        if (str.contains("{")) {
            int count = arrayStack.pop();
            arrayStack.push(++count);
        } else if (str.contains("}")) {
            int count = arrayStack.pop();
            --count;
            if (count == 0) {
                str = str.replace('}', ']');
            } else {
                arrayStack.push(count);
            }
        }
    }
    System.out.println(str);
    return str;
}

private boolean checkInArray(String str, String[] strArray) {
    for (String arrayElem : strArray) {
        if (str.contains(arrayElem) && str.contains(":")) {
            return true;
        }
    }
    return false;
}
</code>```

Body:
I imported the below JSON into MongoDB (mongoimport --host localhost --db test --collection employees --type json --file Employees.json --jsonArray)

[
    {
        "Employee" : {
            "Basics" : {
                "Name" : "James Bond",
                "Age" : 42
            },
            "Addresses" : {
                "Address" : {
                    "City" : "London",
                    "Country" : "England"
                },
                "Address" : {
                    "City" : "Paris",
                    "Country" : "France"
                }
            },
            "Cars" : {
                "Car" : {
                    "Model" : "Aston Martin",
                    "Year" : 1977
                },
                "Car" : {
                    "Model" : "Audi",
                    "Year" : 2000
                }
            }
        }
    },
    {
        "Employee" : {
            "Basics" : {
                ..
            },
            "Addresses" : {
                "Address" : {
                    ..
                },
                "Address" : {
                    ..
                }
            },
            "Cars" : {
                "Car" : {
                    ..
                }
            }
        }
    }
]

To get the results in a tabular format I used the below query but it fetches only Aston Martin and not Audi.

db.employees.aggregate(
[
{$match: {'Employee.Basics.Name':{$eq:"James Bond"}}},
{$project: {carModel:'$Employee.Cars.Car.Model',_id:0}}
]);

Is there a way I can get both values? (In a tabular format with
specific fields - not like
db.getCollection('employees').find({'Employee.Basics.Name':{$eq:"James
Bond"}});)

Looking at other examples, it looks like the JSON should have had Array of Cars and Addresses, is there a way I can update the documents in MongoDB to change them to Arrays now?

I'm new to MongoDB, (just 2 days old :)) so any pointers will be of great help.
Thanks in advance!

Body:
If anyone has ill-formed JSON like in my example, you can use the below Java code to fix it. (I got the JSON by using https://sourceforge.net/projects/xml2json-converter/).

private final Deque<Integer> arrayStack = new ArrayDeque<Integer>();
private final Deque<Integer> arrayElemStack = new ArrayDeque<Integer>();

String[] arrayElemNames = {"Employee","Address","Car"};
String[] arrayNames = {"Addresses","Cars"};

public void cleanJSON() throws IOException {

    try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputJsonFileName))) {
        try (Stream<String> stream = Files.lines(Paths.get(inputJsonFileName))) {
            stream.map((str) -> formatRootElem(str)).map((str) -> formatArrayElems(str))
                    .map((str) -> formatArrays(str)).forEach((str) -> writeToOutput(writer, str));
        }
    }

}

private void writeToOutput(BufferedWriter writer, String str) {
    try {
        writer.write(str + "\n");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private String formatRootElem(String str) {
    if (str.equals("{")) {
        return "[";
    } else if (str.equals("}")) {
        return "]";
    } else if ((str.contains("Employees") && str.contains("{")) || str.equals("  }")) {
        return "";
    }
    return str;
}

private String formatArrayElems(String str) {
    if (checkInArray(str, arrayElemNames)) {
        arrayElemStack.push(1);
        return "{" + str;
    }
    if (!arrayElemStack.isEmpty()) {
        if (str.contains("{")) {
            int count = arrayElemStack.pop();
            arrayElemStack.push(++count);
        } else if (str.contains("}")) {
            int count = arrayElemStack.pop();
            --count;
            if (count == 0) {
                str = str.replace("}", "}}");
            } else {
                arrayElemStack.push(count);
            }
        }
    }
    return str;
}

private String formatArrays(String str) {
    if (checkInArray(str, arrayNames)) {
        str = str.replace('{', '[');
        arrayStack.push(1);
    } else if (!arrayStack.isEmpty()) {
        if (str.contains("{")) {
            int count = arrayStack.pop();
            arrayStack.push(++count);
        } else if (str.contains("}")) {
            int count = arrayStack.pop();
            --count;
            if (count == 0) {
                str = str.replace('}', ']');
            } else {
                arrayStack.push(count);
            }
        }
    }
    System.out.println(str);
    return str;
}

private boolean checkInArray(String str, String[] strArray) {
    for (String arrayElem : strArray) {
        if (str.contains(arrayElem) && str.contains(":")) {
            return true;
        }
    }
    return false;
}


问:
How to create a json file using existing json file as template?
I have a json file which is mostly standard for all my work, the only difference is few parameters.

Now I want to know how can I using java use this json file as a template and provide the parameters as input and save the new json file on local directory?

```<code> {
    "key" : "HWM_NAME",
    "value" : "PINE_SLS_SVC_CUST_CNTCT"
  }, {
    "key" : "TOPIC",
    "value" : "SLS_SVC_CUST_CNTCT2"
  }, {
    "key" : "SRC_SCHEMA",
    "value" : "party_pkg"
  }, {
    "key" : "SRC_TABLE",
    "value" : "SLS_SVC_CUST_CNTCT"
  }, {
    "key" : "TGT_SCHEMA",
    "value" : "mstrdata_hub"
  }, {
    "key" : "TGT_TABLE",
    "value" : "SLS_SVC_CUST_CNTCT"
  } ]
},
</code>```

So here I wish to just change the Value: "PINE_SLS_SVC_CUST_CNTCT" to some other value that I would take as input from user and give me a new json file with those values.

PS: I am working on Java Swing to create a GUI to get the parameters from the user and provide the json file as output.enter image description here

this is how GUI looks

答:
Consider using some JSON Library, for example GSon

Read the values from json

```<code>List<LinkedTreeMap> values = gson.fromJson(json, ArrayList.class);
...
</code>```

update the values, here you can write values from UI components!!!!

```<code>for (LinkedTreeMap pair : values) {
            //Update values
            System.out.println(pair.toString());
        }
</code>```

And generate JSON from java objects

```<code>import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;

        ...

    Gson gson = new Gson();
    String json = gson.toJson(values);
</code>```

Body:
I have a json file which is mostly standard for all my work, the only difference is few parameters.

Now I want to know how can I using java use this json file as a template and provide the parameters as input and save the new json file on local directory?

 {
    "key" : "HWM_NAME",
    "value" : "PINE_SLS_SVC_CUST_CNTCT"
  }, {
    "key" : "TOPIC",
    "value" : "SLS_SVC_CUST_CNTCT2"
  }, {
    "key" : "SRC_SCHEMA",
    "value" : "party_pkg"
  }, {
    "key" : "SRC_TABLE",
    "value" : "SLS_SVC_CUST_CNTCT"
  }, {
    "key" : "TGT_SCHEMA",
    "value" : "mstrdata_hub"
  }, {
    "key" : "TGT_TABLE",
    "value" : "SLS_SVC_CUST_CNTCT"
  } ]
},

So here I wish to just change the Value: "PINE_SLS_SVC_CUST_CNTCT" to some other value that I would take as input from user and give me a new json file with those values.

PS: I am working on Java Swing to create a GUI to get the parameters from the user and provide the json file as output.enter image description here

this is how GUI looks

Body:
Consider using some JSON Library, for example GSon

Read the values from json

List<LinkedTreeMap> values = gson.fromJson(json, ArrayList.class);
...

update the values, here you can write values from UI components!!!!

for (LinkedTreeMap pair : values) {
            //Update values
            System.out.println(pair.toString());
        }

And generate JSON from java objects

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;

        ...

    Gson gson = new Gson();
    String json = gson.toJson(values);


问:
Semantic UI React Menu pointing won't change active state on Route change
I've build small SPA in React using Semantic UI React. Menu is working as it should and when I click on any of the menu items, it takes me where its supposed to.

The problem is that, if I go to a page/Route and from there change my page/Route to another one, active field in pointing Menu stays pointing at the previous page.

Everything is imported the way it should. I just want to find the way for my menu to always point at the appropriate Route that is currently shown.

Here is my code:

```<code>render() {

const { activeItem } = this.state

return (
  <div>
      <BrowserRouter>
        <div>
          <Menu pointing>
            <Menu.Item name='Home' as={Link} to='/home' active={activeItem === 'Home'} onClick={this.handleItemClick} />
            <Menu.Item name='Regions' as={Link} to='/regions' active={activeItem === 'Regions'} onClick={this.handleItemClick} />
            <Menu.Item name='Countries' as={Link} to='/countries' active={activeItem === 'Countries'} onClick={this.handleItemClick} />
            <Menu.Item name='AllCountries' as={Link} to='/allcountries' active={activeItem === 'AllCountries'} onClick={this.handleItemClick} />
            <Menu.Menu position='left'>
              <Menu.Item>
                <Form.Group onSubmit={this.submit}>
                  <Input placeholder='Search...' value={this.state.searchTerm} onChange={this.takeTerm} onKeyPress={this.showData}/>
                  <Link to="/countrydata"><Button type="submit" circular icon="search" /></Link>
                </Form.Group>
              </Menu.Item>
            </Menu.Menu>
            <Button.Group>
              <Button>English</Button>
              <Button.Or text="or"/>
              <Button>Francais</Button>
              <Button.Or text="or"/>
              <Button>Italiano</Button>
            </Button.Group>
          </Menu>
          <Segment>
          <Switch>
            <Route path="/regions" component={Regions}/>
            <Route path="/countries" component={Countries}/>
            <Route path="/allcountries" component={AllCountries}/>
            <Route path="/countrydata" component={Country} />
            <Route path="/" component={Home} />
          </Switch>
          </Segment>
          {this.state.notFound ? (<div className="showError">Searched country does not exist</div>) : <div></div>}
        </div>
      </BrowserRouter>
  </div>
)
</code>```

}
}

答:
We use a component:</p>

```<code>const MenuLink = ({ to, exact, ...rest }) => (
  <Route path={to} exact={exact} children={({ match }) => (
    <Link to={to}><Menu.Item active={!!match}{...rest} /></Link>
  )} />
);
</code>```

Body:
I've build small SPA in React using Semantic UI React. Menu is working as it should and when I click on any of the menu items, it takes me where its supposed to.

The problem is that, if I go to a page/Route and from there change my page/Route to another one, active field in pointing Menu stays pointing at the previous page.

Everything is imported the way it should. I just want to find the way for my menu to always point at the appropriate Route that is currently shown.

Here is my code:

render() {

const { activeItem } = this.state

return (

      <BrowserRouter>

          <Menu pointing>
            <Menu.Item name='Home' as={Link} to='/home' active={activeItem === 'Home'} onClick={this.handleItemClick} />
            <Menu.Item name='Regions' as={Link} to='/regions' active={activeItem === 'Regions'} onClick={this.handleItemClick} />
            <Menu.Item name='Countries' as={Link} to='/countries' active={activeItem === 'Countries'} onClick={this.handleItemClick} />
            <Menu.Item name='AllCountries' as={Link} to='/allcountries' active={activeItem === 'AllCountries'} onClick={this.handleItemClick} />
            <Menu.Menu position='left'>
              <Menu.Item>
                <Form.Group onSubmit={this.submit}>
                  <Input placeholder='Search...' value={this.state.searchTerm} onChange={this.takeTerm} onKeyPress={this.showData}/>
                  <Link to="/countrydata"><Button type="submit" circular icon="search" /></Link>
                </Form.Group>
              </Menu.Item>
            </Menu.Menu>
            <Button.Group>
              <Button>English</Button>
              <Button.Or text="or"/>
              <Button>Francais</Button>
              <Button.Or text="or"/>
              <Button>Italiano</Button>
            </Button.Group>
          </Menu>
          <Segment>
          <Switch>
            <Route path="/regions" component={Regions}/>
            <Route path="/countries" component={Countries}/>
            <Route path="/allcountries" component={AllCountries}/>
            <Route path="/countrydata" component={Country} />
            <Route path="/" component={Home} />
          </Switch>
          </Segment>
          {this.state.notFound ? (
Searched country does not exist
) :

}

      </BrowserRouter>

)

}
}

Body:
We use a component:

const MenuLink = ({ to, exact, ...rest }) => (
  <Route path={to} exact={exact} children={({ match }) => (
    <Link to={to}><Menu.Item active={!!match}{...rest} /></Link>
  )} />
);


问:
AngularJS cannot load ng-view inti index.html
I am trying to setup a one page application with AngularJS.
I am using Node with Express, and I have an apache server used as a middleware, if that matters.
My index.html page loads well but no view is loaded inside the ng-view.

Here is my code

```<code><!DOCTYPE html>
<html>
<head>
    <link rel="icon" type="image/png" href="public/img/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="public/img/favicon-16x16.png" sizes="16x16">

    <link rel="stylesheet" type="text/css" href="vendor/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="vendor/bootstrap/3.3.7/css/bootstrap-theme.min.css">
    <link rel="stylesheet" type="text/css" href="public/css/style.css">
    <link rel="stylesheet" type="text/css" href="public/css/font-awesome-4.7.0/css/font-awesome.min.css">

    <script type="text/javascript" src="vendor/angularjs/1.4.7/js/angular.min.js"></script>
    <script type="text/javascript" src="vendor/angularjs/1.4.7/js/angular-base64.min.js"></script>
    <script type="text/javascript" src="vendor/angularjs/1.4.7/js/angular-sanitize.js"></script>
    <script type="text/javascript" src="vendor/lodash.js/4.16.4/js/lodash.min.js"></script>
    <script type="text/javascript" src="vendor/jquery/1.11.3/js/jquery.min.js"></script>
    <script type="text/javascript" src="vendor/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="node_modules/angular-route/angular-route.min.js"></script>

    <script>
      var myApp = angular.module('lispCDpoc', ['ngRoute']);

      myApp.config(function($routeProvider, $locationProvider) {
        console.log('oui');
        $locationProvider.hashPrefix('');
        $routeProvider.
          when('/', {
            templateUrl: 'pages/test.html',
            controller: 'testController'
          }).
          otherwise({
            redirectTo: '/'
          });
      });

      myApp.controller('testController', function($scope) {
        $scope.message = 'Message for my test page';
      });
    </script>

    <meta charset="utf-8">
    <title>LISP Monitoring POC</title>
  </head>

  <body>
    <div>
      <nav class="navbar navbar-default navbar-custom">
        <div class="navbar-header">
          <a class="navbar-brand" href="#"><img                        src="public/img/sg_logo_small.png" class="sg-logo"></a>
        </div>
        <ul class="nav navbar-nav">
          <li class="active"><a href="#dashboard">Dashboard</a></li>
          <li><a href="#releasenote">Release Note</a></li>
        </ul>
        <div>
            <img class="logo-lisp" src="public/img/lisp2.png">
        </div>
      </nav>
      <div ng-view></div>
    </div>
  </body>
  </html>
</code>```

I can't find the reason why my index.html page loads but it does not insert the test.html code

```<code><div>
    <h1>Test Page</h1>
    <p>{{message}}</p>
</div>
</code>```

答:
Don't forget to declare your app module in your main template.

```<code>  <body ng-app="lispCDpoc">
    <div>
      <nav class="navbar navbar-default navbar-custom">
        <div class="navbar-header">
          <a class="navbar-brand" href="#"><img                        src="public/img/sg_logo_small.png" class="sg-logo"></a>
        </div>
        <ul class="nav navbar-nav">
          <li class="active"><a href="#dashboard">Dashboard</a></li>
          <li><a href="#releasenote">Release Note</a></li>
        </ul>
        <div>
            <img class="logo-lisp" src="public/img/lisp2.png">
        </div>
      </nav>
      <div ng-view></div>
    </div>
  </body>
</code>```

Here's a working Plunkr: https://plnkr.co/edit/HlYxdCsLzfCNCY1dq7vp?p=preview

Body:
I am trying to setup a one page application with AngularJS.
I am using Node with Express, and I have an apache server used as a middleware, if that matters.
My index.html page loads well but no view is loaded inside the ng-view.

Here is my code

<!DOCTYPE html>

    <link rel="icon" type="image/png" href="public/img/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="public/img/favicon-16x16.png" sizes="16x16">

    <link rel="stylesheet" type="text/css" href="vendor/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="vendor/bootstrap/3.3.7/css/bootstrap-theme.min.css">
    <link rel="stylesheet" type="text/css" href="public/css/style.css">
    <link rel="stylesheet" type="text/css" href="public/css/font-awesome-4.7.0/css/font-awesome.min.css">

    <meta charset="utf-8">
    <title>LISP Monitoring POC</title>

Dashboard

Release Note

I can't find the reason why my index.html page loads but it does not insert the test.html code

Test Page

{{message}}

Body:
Don't forget to declare your app module in your main template.

  <body ng-app="lispCDpoc">
    <div>
      <nav class="navbar navbar-default navbar-custom">
        <div class="navbar-header">
          <a class="navbar-brand" href="#"><img                        src="public/img/sg_logo_small.png" class="sg-logo"></a>
        </div>
        <ul class="nav navbar-nav">
          <li class="active"><a href="#dashboard">Dashboard</a></li>
          <li><a href="#releasenote">Release Note</a></li>
        </ul>
        <div>
            <img class="logo-lisp" src="public/img/lisp2.png">
        </div>
      </nav>
      <div ng-view></div>
    </div>
  </body>

Here's a working Plunkr: https://plnkr.co/edit/HlYxdCsLzfCNCY1dq7vp?p=preview


问:
How to get min time from datetime in sql server 2008 r2
How to write below code in in SQL server 2008 r2

```<code>DECLARE @date date
DECLARE @datetime datetime

SELECT @datetime = GETDATE()
select @date = GETDATE()

select format(cast(min(@date + @datetime) as datetime), 'hh:mm:ss tt')
</code>```

this piece of code doesn't work in SQL Server 2008 r

答:
Your code is confusing. You are trying to add two dates which doesn't make sense. Anyway, here's how to convert a datetime to output the hh:mm:ss format.

```<code>DECLARE @datetime datetime
SELECT @datetime = GETDATE()

select
   DT = convert(char(10),@datetime,120)
   ,TimeOnly = left(cast(@datetime as time),8)
</code>```

Body:
How to write below code in in SQL server 2008 r2

DECLARE @date date
DECLARE @datetime datetime

SELECT @datetime = GETDATE()
select @date = GETDATE()

select format(cast(min(@date + @datetime) as datetime), 'hh:mm:ss tt')

this piece of code doesn't work in SQL Server 2008 r

Body:
Your code is confusing. You are trying to add two dates which doesn't make sense. Anyway, here's how to convert a datetime to output the hh:mm:ss format.

DECLARE @datetime datetime
SELECT @datetime = GETDATE()

select
   DT = convert(char(10),@datetime,120)
   ,TimeOnly = left(cast(@datetime as time),8)


问:
c# What happens if I use code a .NET 3.5 function on a machine that has .Net 2 installed
Just out of interest, if I built some code using the Enumerable.Distinct function which appeared in .Net 3.5 and then ran it on a machine with .Net 2.0 on it, what would happen?</p>

答: .Net 2.0 won't understand the command because the library isn't there.</p>

ContentLicense: CC BY-SA 2.5


问:
Unsuccessful Updating table with PHP using Update table Set
I have a table buildtracker connected to a form. I am attempting to edit the data in a particular row and therefore Update the row.

The table consists of these columns:  ID key, EnteredBy, INI

```<code>$user = 'root';
$pass = '';
$db = 'cl_db';
$conn = new mysqli('localhost', $user, $pass, $db) or die("Something bad happened.");

$rowID = $conn->real_escape_string($_POST['ID']);
$enteredBy    = $conn->real_escape_string($_POST['enteredBy']);
$ini   = $conn->real_escape_string($_POST['ini']);

$query   = "UPDATE buildtracker SET
          EnteredBy = '$enteredBy', INI = '$ini'
          WHERE ID = '$rowID' ";

$success = $conn->query($query); //insertion above ^ is the column names

if (!$success) {
    die("Couldn't enter data: ".$conn->error);
    }
return $query;
</code>```

I'm receiving no new data or updates on the table. What can I do differently to improve upon this?

Thanks!

答:
I don't know in what context this code is, in your application.

But is is [highly] recommended to use prepared statements for protection against any SQL injection attacks, especially direct data from $_POST is used (can be sanitized).

Checking whether query is executed or not in prepared statements is via $stmt->execute().

```<code>$user = 'root';
$pass = '';
$db = 'cl_db';
$conn = new mysqli('localhost', $user, $pass, $db) or die("Something bad happened.");
$prepare_query = "UPDATE buildtracker SET EnteredBy=?, INI=? WHERE ID=?";
$success = $conn->query($prepare_query); //insertion above ^ is the column names
if ($stmt = $conn->prepare($query)) {

    // Possible data sanitation can be done below
    $rowID = ($_POST['ID']);
    $enteredBy = ($_POST['enteredBy']);
    $ini = ($_POST['ini']);

    // bind parameters
    $stmt->bind_param('ssi', $enteredBy, $ini, $rowID);

    // CHECKING is here: execute query (or die)
    // Can check also for ($stmt->affected_rows > 0)
    if (!$stmt->execute()){
        die("Couldn't enter data: ".$conn->error);
    }

    return $query;
}
</code>```

And using PDO instead of MySQLi would probably be better recommended.

Body:
I have a table buildtracker connected to a form. I am attempting to edit the data in a particular row and therefore Update the row.

The table consists of these columns:  ID key, EnteredBy, INI

$user = 'root';
$pass = '';
$db = 'cl_db';
$conn = new mysqli('localhost', $user, $pass, $db) or die("Something bad happened.");

$rowID = $conn->real_escape_string($_POST['ID']);
$enteredBy    = $conn->real_escape_string($_POST['enteredBy']);
$ini   = $conn->real_escape_string($_POST['ini']);

$query   = "UPDATE buildtracker SET
          EnteredBy = '$enteredBy', INI = '$ini'
          WHERE ID = '$rowID' ";

$success = $conn->query($query); //insertion above ^ is the column names

if (!$success) {
    die("Couldn't enter data: ".$conn->error);
    }
return $query;

I'm receiving no new data or updates on the table. What can I do differently to improve upon this?

Thanks!

Body:
I don't know in what context this code is, in your application.

But is is [highly] recommended to use prepared statements for protection against any SQL injection attacks, especially direct data from $_POST is used (can be sanitized).

Checking whether query is executed or not in prepared statements is via $stmt->execute().

$user = 'root';
$pass = '';
$db = 'cl_db';
$conn = new mysqli('localhost', $user, $pass, $db) or die("Something bad happened.");
$prepare_query = "UPDATE buildtracker SET EnteredBy=?, INI=? WHERE ID=?";
$success = $conn->query($prepare_query); //insertion above ^ is the column names
if ($stmt = $conn->prepare($query)) {

    // Possible data sanitation can be done below
    $rowID = ($_POST['ID']);
    $enteredBy = ($_POST['enteredBy']);
    $ini = ($_POST['ini']);

    // bind parameters
    $stmt->bind_param('ssi', $enteredBy, $ini, $rowID);

    // CHECKING is here: execute query (or die)
    // Can check also for ($stmt->affected_rows > 0)
    if (!$stmt->execute()){
        die("Couldn't enter data: ".$conn->error);
    }

    return $query;
}

And using PDO instead of MySQLi would probably be better recommended.


问:
How to set tensorflow gpu memory allocation outside of my code?
I am using tensorflow on the spark.
my tensorflow allocates almost all GPU memory ( 10GB or 12GB).
only 'import tensorflow' take all memory
I know how to configure gpu memory fraction inside the code. The way I know is to add the code mentioned below

```<code>import tensorflow as tf
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.2)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
</code>```

BUT.. On the spark, Even though I add this congifuration in the code, It cannot be applied to other GPU machines..
So, I want to know how to configure or set up the gpu fraction outside of the code, which means by tensorflow itself..

答:
At tensorflow/tensorflow/core/common_runtime/gpu/gpu_device.cc
Change from

```<code>if (config_memory_fraction == 0) {
allocated_memory = available_memory;
</code>```

to

```<code>if (config_memory_fraction == 0) {
allocated_memory = total_memory * 0.2(fraction u want to use);
</code>```

After then, BUILD it by bazel.

It is kinda hardcoding.
If u modify source code, u can do dynamic allocation of gpu memory

Body:
I am using tensorflow on the spark.
my tensorflow allocates almost all GPU memory ( 10GB or 12GB).
only 'import tensorflow' take all memory
I know how to configure gpu memory fraction inside the code. The way I know is to add the code mentioned below

import tensorflow as tf
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.2)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))

BUT.. On the spark, Even though I add this congifuration in the code, It cannot be applied to other GPU machines..
So, I want to know how to configure or set up the gpu fraction outside of the code, which means by tensorflow itself..

Body:
At tensorflow/tensorflow/core/common_runtime/gpu/gpu_device.cc
Change from

if (config_memory_fraction == 0) {
allocated_memory = available_memory;

to

if (config_memory_fraction == 0) {
allocated_memory = total_memory * 0.2(fraction u want to use);

After then, BUILD it by bazel.

It is kinda hardcoding.
If u modify source code, u can do dynamic allocation of gpu memory


问:
Using coordinatorLayout anchor's with constraintLayout
I want to design something like this :

as you can see fab is between header and the body.

it's easy to do it with coordinatorLayout with app:anchor and app:anchorGravity attributes

but i want to do it with constraintLayout.

any ideas ?

答:
I've found the answer :))</p>

```<code><FAB
   ...
   app:layout_constraintTop_toBottomOf="@+id/header"
   app:layout_constraintBottom_toTopOf="@id/body"/>
</code>```

Body:
I've found the answer :))

<FAB
   ...
   app:layout_constraintTop_toBottomOf="@+id/header"
   app:layout_constraintBottom_toTopOf="@id/body"/>


问:
Unable to use = operator in a "If" statement
Why can't I use = operator over here. Anyway to solve this problem ?

```<code> If PictureBox1.Image = My.Resources.pic001 Then
       x = 1
    Else
       x = 0
    End If
</code>```

The error message is:

Operator '=' is not defined for types
  'System.Drawing.Image' and
  'System.Drawing.Bitmap'

答:
As the error message says, the operator '=' is not defined for the types you are comparing. i.e. it is not possible to compare a System.Drawing.Image to a System.Drawing.Bitmap

You will need to compare the images bit-by-bit or create a hash value for each one and compare those.

There is a thread here which has a C# example (it shouldn't be hard to convert to VB):

http://www.codeguru.com/forum/showthread.php?t=363130

EDIT: There might be another solution, I have not tried it and I don't know if, and it probably won't, work as expeted but there is an Equals() method available on System.Drawing.Image (and Bitmap is derived from Image). You might have some luck with that.

Body:
Why can't I use = operator over here. Anyway to solve this problem ?

 If PictureBox1.Image = My.Resources.pic001 Then
       x = 1
    Else
       x = 0
    End If

The error message is:

Operator '=' is not defined for types
  'System.Drawing.Image' and
  'System.Drawing.Bitmap'


问:
Problems with pairing using maps and lists for a lending system
I'm trying to get my lending system to function correctly, the problem seems to be focused in the part of the code below.

I'm trying to make it so every time I enter an item ID and borrower ID it finds the inputted ID's (if correct), pairs and retrieves them from the accessors to initiate a transaction. Every time I input an item and ID I always get the "No user input found" error I made, I suspect its because i'm doing something wrong with the LoanTransaction part of my code as I know the item ID and borrower ID I input to test is correct.

I'm still quite new to using maps and lists together so any advice and help would be useful stuff for me. Many thanks!

Suspect code

```<code>LoanTransaction mrkr = null
for (LoanTransaction t: parent.getLoans()) {
  if (t.getBorrower() == bwr && t.getItem() == itm) {
    mrkr = t;
    break;
  }
}
</code>```

Full Method

```<code>public void loanTransaction() {
    Integer itmID = new Integer(txtItemID.getText());
    Item itm = parent.getItems().get(itmID);
    Integer borrowerID = new Integer(txtBorrowerID.getText());
    Borrower bwr = parent.getBorrowers().get(borrowerID);

    if (itm == null) {
    JOptionPane.showMessageDialog(this, "Item not found",
          "Error", JOptionPane.ERROR_MESSAGE);
      return;
    }
    Borrower bby = itm.getBorrowedBy();
    if (bby != null) {
      JOptionPane.showMessageDialog(this, "Already on loan",
          "Error", JOptionPane.ERROR_MESSAGE);
      return;
    }

   LoanTransaction mrkr = null;
    for (LoanTransaction t: parent.getLoans()) {
      if (t.getBorrower() == bwr && t.getItem() == itm) {
        mrkr = t;
        break;
      }
    }
    if (mrkr == null) {
      JOptionPane.showMessageDialog(this, "No user input found",
          "Error", JOptionPane.ERROR_MESSAGE);
      return;
    }
        parent.getLoans().add(mrkr);
        itm.clearBorrowedBy();
        itm.setBorrowedBy(bwr);
        System.out.printf("Item loaned: [%s]\n\n", itm);
}
</code>```

Accessors

```<code>public Map<Integer, Borrower>  getBorrowers() { return borrowers; }
public Map<Integer, Item>      getItems()     { return items; }
public List<LoanTransaction> getLoans()       { return loans; }
</code>```

答:
When you do a == comparison in Java between two objects, it’s an identity comparison, not an equals comparison. I don’t know how you judge if two borrowers are the same, but this code would only work if the two borrower objects were literally the same instance. What you want to do is use the equals method:

t.getBorrower().equals(bwr)

And similarly for the Item class. Also, you want to make sure you implement the equals (and hashCode) methods in your Borrower and Item classes such that each object knows how to judge itself equal to another object of the same type (such as comparing borrower IDs). If you don’t, it’ll still be an identity comparison.

Body:
I'm trying to get my lending system to function correctly, the problem seems to be focused in the part of the code below.

I'm trying to make it so every time I enter an item ID and borrower ID it finds the inputted ID's (if correct), pairs and retrieves them from the accessors to initiate a transaction. Every time I input an item and ID I always get the "No user input found" error I made, I suspect its because i'm doing something wrong with the LoanTransaction part of my code as I know the item ID and borrower ID I input to test is correct.

I'm still quite new to using maps and lists together so any advice and help would be useful stuff for me. Many thanks!

Suspect code

LoanTransaction mrkr = null
for (LoanTransaction t: parent.getLoans()) {
  if (t.getBorrower() == bwr && t.getItem() == itm) {
    mrkr = t;
    break;
  }
}

Full Method

public void loanTransaction() {
    Integer itmID = new Integer(txtItemID.getText());
    Item itm = parent.getItems().get(itmID);
    Integer borrowerID = new Integer(txtBorrowerID.getText());
    Borrower bwr = parent.getBorrowers().get(borrowerID);

    if (itm == null) {
    JOptionPane.showMessageDialog(this, "Item not found",
          "Error", JOptionPane.ERROR_MESSAGE);
      return;
    }
    Borrower bby = itm.getBorrowedBy();
    if (bby != null) {
      JOptionPane.showMessageDialog(this, "Already on loan",
          "Error", JOptionPane.ERROR_MESSAGE);
      return;
    }

   LoanTransaction mrkr = null;
    for (LoanTransaction t: parent.getLoans()) {
      if (t.getBorrower() == bwr && t.getItem() == itm) {
        mrkr = t;
        break;
      }
    }
    if (mrkr == null) {
      JOptionPane.showMessageDialog(this, "No user input found",
          "Error", JOptionPane.ERROR_MESSAGE);
      return;
    }
        parent.getLoans().add(mrkr);
        itm.clearBorrowedBy();
        itm.setBorrowedBy(bwr);
        System.out.printf("Item loaned: [%s]\n\n", itm);
}

Accessors

public Map<Integer, Borrower>  getBorrowers() { return borrowers; }
public Map<Integer, Item>      getItems()     { return items; }
public List<LoanTransaction> getLoans()       { return loans; }


问:
How to show the selected options static from db + angular js
```<code><select name="gender" ng-model="list.gender" data-select-id="bc813756-82d5-45d7-932c-ab9afd0a08da" class="initialized">
    <option value="" disabled="">Gender</option>
    <option ng-selected="list.gender == 'Male'" value="Male" >Male</option>
    <option ng-selected="list.gender == 'Female'" value="Female" >Female</option>
</select>
</code>```

Suppose I am getting the "Male" value from DB, how to show selected option?

答:
We should not use ng-model and ng-selected together. This is what the AngularJS docs says:

Note: ngSelected does not interact with the select and ngModel directives, it only sets the selected attribute on the element. If you are using ngModel on the select, you should not use ngSelected on the options, as ngModel will set the select value and selected options.

So, remove the ng-selected directive from your options, and set list.gender in the controller to the value pulled from the DB.

```<code>app.controller('someController', ['$scope', function($scope){
    // .... some code ...
    $scope.list = { gender: 'Male' }; // set this to the value from DB

    // .... some code ...
}]);
</code>```

The HTML

```<code><select name="gender" ng-model="list.gender" class="initialized">
    <option value="" disabled="">Gender</option>
    <option value="Male" >Male</option>
    <option value="Female" >Female</option>
</select>
</code>```

Hope it helps

Body:
<select name="gender" ng-model="list.gender" data-select-id="bc813756-82d5-45d7-932c-ab9afd0a08da" class="initialized">
    <option value="" disabled="">Gender</option>
    <option ng-selected="list.gender == 'Male'" value="Male" >Male</option>
    <option ng-selected="list.gender == 'Female'" value="Female" >Female</option>
</select>

Suppose I am getting the "Male" value from DB, how to show selected option?

Body:
We should not use ng-model and ng-selected together. This is what the AngularJS docs says:

Note: ngSelected does not interact with the select and ngModel directives, it only sets the selected attribute on the element. If you are using ngModel on the select, you should not use ngSelected on the options, as ngModel will set the select value and selected options.

So, remove the ng-selected directive from your options, and set list.gender in the controller to the value pulled from the DB.

app.controller('someController', ['$scope', function($scope){
    // .... some code ...
    $scope.list = { gender: 'Male' }; // set this to the value from DB

    // .... some code ...
}]);

The HTML

<select name="gender" ng-model="list.gender" class="initialized">
    <option value="" disabled="">Gender</option>
    <option value="Male" >Male</option>
    <option value="Female" >Female</option>
</select>

Hope it helps


问:
Form submit vs. Javascript POST Request
I'm making a POST request with a very simple HTML form. The request fails in the form format, but works in Javascript.

It's very simple, so here is almost the entire form:

```<code><form method="post" action="[apiUrl]" target="_blank">
  <input type="hidden" name="payload" value="[payload]">
  <!-- ... -->
</form>
</code>```

*Please note that [apiUrl] and [payload] are variables that are injected into the HTML.

The request fails with a custom message from the API (seems it can't parse the payload):

```<code>{
  "Error": {
    "Message": "Noun and Verb are Required Request Parameters",
    "ValidationError": false
  },
  "Result": "ERROR"
}
</code>```

However, the exact same request will succeed when performed by Javascript (I've tested with both Axios and jQuery, and also with Paw).

```<code>$.post(this.apiUrl, this.payload, response => {
  console.log('Success!', response);
});
</code>```

The payload is just a Javascript Object. The variables are set like this:

```<code>this.apiUrl = request.url;
this.payload = JSON.stringify(request.parameters);
</code>```

Why does it fail as a form?

答:
I met similar problem when I was building the back-end(using Node&Express.js) and front-end(Angular.js) separately using JSON apis.  And it took 12 hours to find the reason why not working with html forms.

The problem was on the back-end side, when you submit using jquery $.post, Content-type is application/json but when you submit using html form Content-type is application/form-data.

You can test the APIs using postman, if you select the content-type as form-data that api will not work.

So to solve the problem, you have to rebuild backend apis to be compatable with Content-type application/form-data.

Additionally in my case, I used body-parser node package to analyze form data.

Title: Form submit vs. Javascript POST Request

Body:
I'm making a POST request with a very simple HTML form. The request fails in the form format, but works in Javascript.

It's very simple, so here is almost the entire form:

<form method="post" action="[apiUrl]" target="_blank">
  <input type="hidden" name="payload" value="[payload]">

</form>

*Please note that [apiUrl] and [payload] are variables that are injected into the HTML.

The request fails with a custom message from the API (seems it can't parse the payload):

{
  "Error": {
    "Message": "Noun and Verb are Required Request Parameters",
    "ValidationError": false
  },
  "Result": "ERROR"
}

However, the exact same request will succeed when performed by Javascript (I've tested with both Axios and jQuery, and also with Paw).

$.post(this.apiUrl, this.payload, response => {
  console.log('Success!', response);
});

The payload is just a Javascript Object. The variables are set like this:

this.apiUrl = request.url;
this.payload = JSON.stringify(request.parameters);

Why does it fail as a form?


问:
Safest way to update game score from client to server database? Javascript
So I have this game that is completely run on the client. No server interaction what so ever apart from downloading the initial scripts to play the game. Anyway at the end of the game I would like for the client to send me back the scores which should be updated in the server database. Now I have come to accept the fact that there is no way on earth I can hide this from a hacker and send the scores unaltered. But I would like to know till what level can I modify the whole process that it virtually becomes pretty infeasible for the hacker manipulate the data which is being sent. For sure I would not like the score to be sent as plain text from client machine and I don't want my server to perform complex decryption algorithm. What is the best way hence to achieve considerable amount of security that every tom dick and harry doesn't hack the scores... I hope someone could provide a nice little way that I could work on... :) Thanks

So my ideal result should be -> have trusted result from a calculation (of score) made by an untrusted party (the player)!

-Edit-

Someone told me something about hiding the data in a picture get request. Like, I am implementing this game on canvas (html5). So he asked me at the end of the game to fetch a game over image from my server, and they request should contain the hashed score. I did not exactly understand the complete process but if you could explain it, would be really glad! :)

coda^   so you can mask the requests nicely

shouvik how do I do it!?

coda^   you can compose the checksum you want to submit. like 12312312a12313a232 is your md5 which contains the score. bring in an asset into the canvas like

coda^   server.com/images/md5_hash_of_score/congratulations.png

coda^   which you can rewrite server side via htaccess

答: Make the client send you the credentials (or some sort of session information in case you don't have logon credentials) and do that over SSL (https). This way you have both authentication and integrity control. Very easy and extremely lightweight for both server and client.</p>


问:
How to check with rspec if a method(e.g. #each) returns an Enumerator when no block is given?
I defined my_each method in the enumerable_methods.rb. It works the same as #each: when no block is given it returns an Enumerator. In my enumerable_methods_spec.rb:

```<code>describe Enumerable do
  let(:array) {[1,2,3,4]}
  let(:answer) {[]}

  describe "#my_each" do
    ...

    context "when no block is given" do
      it "returns an Enumerator" do
        expect(array.my_each).to eql(array.to_enum(:my_each))
      end
    end
  end

end
</code>```

I got this error in terminal:

```<code>Failures:

  1) Enumerable#my_each when no block is given returns an Enumerator
     Failure/Error: expect(array.my_each).to eql(array.to_enum(:my_each))

       expected: #<Enumerator: [1, 2, 3, 4]:my_each>
            got: #<Enumerator: [1, 2, 3, 4]:my_each>

       (compared using eql?)

       Diff:

     # ./enumerable_methods_spec.rb:23:in `block (4 levels) in <top (required)>'

Finished in 0.02475 seconds (files took 0.12087 seconds to load)
2 examples, 1 failure
</code>```

I couldn't figure out how to fix it.

答:
I would split the test into two:</p>

```<code>expect(array.my_each).to be_a(Enumerator)
expect(array.my_each.to_a).to eq(array)
</code>```

Body:
I defined my_each method in the enumerable_methods.rb. It works the same as #each: when no block is given it returns an Enumerator. In my enumerable_methods_spec.rb:

describe Enumerable do
  let(:array) {[1,2,3,4]}
  let(:answer) {[]}

  describe "#my_each" do
    ...

    context "when no block is given" do
      it "returns an Enumerator" do
        expect(array.my_each).to eql(array.to_enum(:my_each))
      end
    end
  end

end

I got this error in terminal:

Failures:

  1) Enumerable#my_each when no block is given returns an Enumerator
     Failure/Error: expect(array.my_each).to eql(array.to_enum(:my_each))

       expected: #<Enumerator: [1, 2, 3, 4]:my_each>
            got: #<Enumerator: [1, 2, 3, 4]:my_each>

       (compared using eql?)

       Diff:

     # ./enumerable_methods_spec.rb:23:in `block (4 levels) in <top (required)>'

Finished in 0.02475 seconds (files took 0.12087 seconds to load)
2 examples, 1 failure

I couldn't figure out how to fix it.

Body:
I would split the test into two:

expect(array.my_each).to be_a(Enumerator)
expect(array.my_each.to_a).to eq(array)


问:
javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json
I work on a project, made with Spring Framework, where i want to use JaxB, to convert an object to json, and i recieve this error:

```<code>javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json
at javax.xml.bind.helpers.AbstractMarshallerImpl.setProperty(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.setProperty(Unknown Source)
at com.fabbydesign.controller.DashboardController.main(DashboardController.java:82)
</code>```

The code that i test is:

```<code>public static void main(String[] args) throws ParseException{

    ReturnBean rb = new ReturnBean();
    rb.setStatus(1);
    rb.setMessage("Message here!");

    JAXBContext jc;
    try {
        jc = JAXBContext.newInstance(ReturnBean.class);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
        marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
        marshaller.marshal(rb, System.out);

    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
</code>```

I have added in pom.xml EclipseLink dependency:

```<code><dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
        <version>2.6.4</version>
    </dependency>
</code>```

and, i have added the file jaxb.properties with the content:

```<code>javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
</code>```

I don't know why i still recieve this error, because, as i read on this forum i think i did all.
What i want to mention, is, that the code that i test is in the directory:

```<code>src\main\java\com\fabbydesign\controller
</code>```

and the file jaxb.properties is in the directory:

```<code>src\main\resources\com\fabbydesign\controller
</code>```

What I did wrong?

答:
Simple, you can specify system variable like:

```<code>System.setProperty("javax.xml.bind.context.factory", "org.eclipse.persistence.jaxb.JAXBContextFactory");
</code>```

It worked for me.

Body:
I work on a project, made with Spring Framework, where i want to use JaxB, to convert an object to json, and i recieve this error:

javax.xml.bind.PropertyException: name: eclipselink.media-type value: application/json
at javax.xml.bind.helpers.AbstractMarshallerImpl.setProperty(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.setProperty(Unknown Source)
at com.fabbydesign.controller.DashboardController.main(DashboardController.java:82)

The code that i test is:

public static void main(String[] args) throws ParseException{

    ReturnBean rb = new ReturnBean();
    rb.setStatus(1);
    rb.setMessage("Message here!");

    JAXBContext jc;
    try {
        jc = JAXBContext.newInstance(ReturnBean.class);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
        marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
        marshaller.marshal(rb, System.out);

    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

I have added in pom.xml EclipseLink dependency:

<dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
        <version>2.6.4</version>
    </dependency>

and, i have added the file jaxb.properties with the content:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

I don't know why i still recieve this error, because, as i read on this forum i think i did all.
What i want to mention, is, that the code that i test is in the directory:

src\main\java\com\fabbydesign\controller

and the file jaxb.properties is in the directory:

src\main\resources\com\fabbydesign\controller

What I did wrong?

Body:
Simple, you can specify system variable like:

System.setProperty("javax.xml.bind.context.factory", "org.eclipse.persistence.jaxb.JAXBContextFactory");

It worked for me.


答:
As simple as this?

```<code>expect(array.my_each).to be_an Enumerator
</code>```

An actual content check would also be useful, as shown in @mudasobwa's answer.

Title: How to check with rspec if a method(e.g. #each) returns an Enumerator when no block is given?

Body:
As simple as this?

expect(array.my_each).to be_an Enumerator

An actual content check would also be useful, as shown in @mudasobwa's answer.


问:
JavaScript - How can I use the print function to output 2 values that are stored in an array when those values are the same?
```<code>var students = [
{
    name : "Dave",
    track : "Front End Development",
    achievement: 158,
    points: 14703
},
{
    name : "Jody",
    track : "iOS Development with swift",
    achievement: 133,
    points: 16303
},
{
    name : "Dave",
    track : "PHP Development",
    achievement: 55,
    points: 2023
},
{
    name : "Shawdesh",
    track : "Learn Wordpress",
    achievement: 40,
    points: 1950
},
{
    name : "Liton",
    track : "Rails Development",
    achievement: 98,
    points: 450
}
]

var student;
var message = [];
var search;

function print(message) {
document.getElementById('output').innerHTML = message;
}

function getStudentReport(student) {
var report = "<h3> Student: " + student.name + "</h3>";
report += "<p>Track: "+ student.track + "</p>";
report += "<p>achievement: "+ student.achievement + "</p>";
report += "<p>Points: "+ student.points + "</p>";
return report;
}

while(true) {
search = prompt("Search the student recoards: type a name [Jody] or (type quit to exit.)");
if (search == null || search.toLowerCase() == 'quit') {
    break;
}
for (var i = 0; i < students.length; i += 1) {
    student = students[i];
    if (student.name.toLowerCase() === search.toLowerCase()) {
        message.push(getStudentReport(student));
    }
}
for (var j = 0; j < message.length; j += 1) {
        document.write(message[j]);
    }
}
</code>```

When the prompt function runs, if I write #Dave the message array stores 2 value because in #students Array the Dave name uses two times.

But when I print this array by print function it only prints the last value. But when I print it by document.write it prints 2 value.

So, now my question is: How can I print 2 values that are stored in a message array using my #print function?

答:
Sure it will add just the last message since you're using affection = that will override the content, instea use += to append the new message to the old content, like :

```<code>function print(message) {
    document.getElementById('output').innerHTML += message;
}
</code>```

Hope this helps.

Body:
var students = [
{
    name : "Dave",
    track : "Front End Development",
    achievement: 158,
    points: 14703
},
{
    name : "Jody",
    track : "iOS Development with swift",
    achievement: 133,
    points: 16303
},
{
    name : "Dave",
    track : "PHP Development",
    achievement: 55,
    points: 2023
},
{
    name : "Shawdesh",
    track : "Learn Wordpress",
    achievement: 40,
    points: 1950
},
{
    name : "Liton",
    track : "Rails Development",
    achievement: 98,
    points: 450
}
]

var student;
var message = [];
var search;

function print(message) {
document.getElementById('output').innerHTML = message;
}

function getStudentReport(student) {
var report = "
 Student: " + student.name + "
";
report += "
Track: "+ student.track + "
";
report += "
achievement: "+ student.achievement + "
";
report += "
Points: "+ student.points + "
";
return report;
}

while(true) {
search = prompt("Search the student recoards: type a name [Jody] or (type quit to exit.)");
if (search == null || search.toLowerCase() == 'quit') {
    break;
}
for (var i = 0; i < students.length; i += 1) {
    student = students[i];
    if (student.name.toLowerCase() === search.toLowerCase()) {
        message.push(getStudentReport(student));
    }
}
for (var j = 0; j < message.length; j += 1) {
        document.write(message[j]);
    }
}

When the prompt function runs, if I write #Dave the message array stores 2 value because in #students Array the Dave name uses two times.

But when I print this array by print function it only prints the last value. But when I print it by document.write it prints 2 value.

So, now my question is: How can I print 2 values that are stored in a message array using my #print function?

Body:
Sure it will add just the last message since you're using affection = that will override the content, instea use += to append the new message to the old content, like :

function print(message) {
    document.getElementById('output').innerHTML += message;
}

Hope this helps.


问:
Performance gain of glColorMask()/glDepthMask() on modern hardware?
In my application I have some shaders which write only depth buffer to use it later for shadowing. Also I have some other shaders which render a fullscreen quad whose depth will not affect all subsequent draw calls, so it's depth values may be thrown away.

Assuming the application runs on modern hardware (produced 5 years ago till now), will I gain any additional performance if I disable color buffer writing (glColorMask(all to GL_FALSE)) for shadow map shaders, and depth buffer writing (with glDepthMask()) for fullscreen quad shaders?

In other words, do these functions really disable some memory operations or they just alter some mask bits which are used in fixed bitwise-operations logic in this part of rendering pipeline?

And the same question about testing. If I know beforehand that all fragments will pass depth test, will disabling depth test improve performance?

My FPS measurement don't show any significant difference, but the result may be different on another machine.

Finally, if rendering runs faster with depth/color test/write disabled, how much faster does it run? Wouldn't this performance gain be negated by gl functions call overhead?

答:
Your question is missing a very important thing: you have to do something.

Every fragment has color and depth values. Even if your FS doesn't generate a value, there will still be a value there. Therefore, every fragment produced that is not discarded will write these values, so long as:

The color is routed to a color buffer via glDrawBuffers.

There is an appropriate color/depth buffer attached to the FBO.

The color/depth write mask allows it to be written.

So if you're rendering and you don't want to write one of those colors or to the depth buffer, you've got to do one of these. Changing #1 or #2 is an FBO state change, which is among the most heavyweight operations you can do in OpenGL. Therefore, your choices are to make an FBO change or to change the write mask. The latter will always be the more performance-friendly operation.

Maybe in your case, your application doesn't stress the GPU or CPU enough for such a change to matter. But in general, changing write masks are a better idea than playing with the FBO.

If I know beforehand that all fragments will pass depth test, will disabling depth test improve performance?

Are you changing other state at the same time, or is that the only state you're interested in?

One good way to look at these kinds of a priori performance questions is to look at Vulkan or D3D12 and see what it would require in that API. Changing any pipeline state there is a big deal. But changing two pieces of state is no bigger of a deal than one.

So if changing the depth test correlates with changing other state (blend modes, shaders, etc), it's probably not going to hurt any more.

At the same time, if you really care enough about performance for this sort of thing to matter, you should do application testing. And that should happen after you implement this, and across all hardware of interest. And your code should be flexible enough to easily switch from one to the other as needed.


问:
PHP & WordPress - How can I have a function run after post meta updates to output to a JSON file?
I'm using save_post_{post_type} hook to generate a JSON file with all the content of a custom post type.

```<code>add_action('save_post_book', 'updateBooks');

function updateBooks(){
    $url = site_url().'/wp-json/wp/v2/books?_embed=true/';
    $params = array( 'timeout' => 30, 'sslverify' => false );
    $response = wp_remote_get( $url, $params );
    $body = wp_remote_retrieve_body( $response );
    $path = $_SERVER['DOCUMENT_ROOT'];
    file_put_contents($path.'/books.json', $body);
}
</code>```

The problem is with ACF custom fields. I believe the hook runs before post meta updates. So the new values from the ACF fields are not sent to the JSON files.

Solution

```<code>add_action('acf/save_post', 'updateJson', 20);

function updateJson($post_id){
    $post_type = get_post_type($post_id);
    $url = site_url().'/wp-json/wp/v2/'.$post_type.'?_embed=true/';
    $params = array( 'timeout' => 30, 'sslverify' => false );
    $response = wp_remote_get( $url, $params );
    $body = wp_remote_retrieve_body( $response );
    $path = $_SERVER['DOCUMENT_ROOT'];
    file_put_contents($path.'/'.$post_type.'.json', $body);
}
</code>```

答:
Use the ACF hooks:

https://www.advancedcustomfields.com/resources/

You can specify the field or run in all of them

Body:
I'm using save_post_{post_type} hook to generate a JSON file with all the content of a custom post type.

add_action('save_post_book', 'updateBooks');

function updateBooks(){
    $url = site_url().'/wp-json/wp/v2/books?_embed=true/';
    $params = array( 'timeout' => 30, 'sslverify' => false );
    $response = wp_remote_get( $url, $params );
    $body = wp_remote_retrieve_body( $response );
    $path = $_SERVER['DOCUMENT_ROOT'];
    file_put_contents($path.'/books.json', $body);
}

The problem is with ACF custom fields. I believe the hook runs before post meta updates. So the new values from the ACF fields are not sent to the JSON files.

Solution

add_action('acf/save_post', 'updateJson', 20);

function updateJson($post_id){
    $post_type = get_post_type($post_id);
    $url = site_url().'/wp-json/wp/v2/'.$post_type.'?_embed=true/';
    $params = array( 'timeout' => 30, 'sslverify' => false );
    $response = wp_remote_get( $url, $params );
    $body = wp_remote_retrieve_body( $response );
    $path = $_SERVER['DOCUMENT_ROOT'];
    file_put_contents($path.'/'.$post_type.'.json', $body);
}