问:
Get const visibility in PHP
Since PHP 7.1, they introduced const visibility, and I need to read it thorugh reflection. I went as far as creating my ReflectionClass like this:

```<code>$rc = new ReflectionClass(static::class);
</code>```

The function getConstants() returns a name/value map and getConstant($name) just its value. Both doesn't return visibility information. Shouldn't there be a ReflectionConst class similarly to functions, properties, etc.?

Is there any other way to obtain this information?

答:
Reflection changes for this are touched on in the feature's RFC, though I don't know if they've been documented elsewhere yet.

The new class is ReflectionClassConstant with relevant methods (among others):

isPublic()

isPrivate()

isProtected()

ReflectionClass has two new methods:

getReflectionConstants() - returns an array of ReflectionClassConstants

getReflectionConstant() - retrieves a ReflectionClassConstant by name

Example:

```<code>class Foo
{
    private const BAR = 42;
}

$r = new ReflectionClass(Foo::class);

var_dump(
    $r->getReflectionConstants(),
    $r->getReflectionConstant('BAR')->isPrivate()
);
</code>```

Outputs:

```<code>array(1) {
  [0]=>
  object(ReflectionClassConstant)#2 (2) {
    ["name"]=>
    string(3) "BAR"
    ["class"]=>
    string(3) "Foo"
  }
}
bool(true)
</code>```

Title: Get const visibility in PHP

Body:
Since PHP 7.1, they introduced const visibility, and I need to read it thorugh reflection. I went as far as creating my ReflectionClass like this:

$rc = new ReflectionClass(static::class);

The function getConstants() returns a name/value map and getConstant($name) just its value. Both doesn't return visibility information. Shouldn't there be a ReflectionConst class similarly to functions, properties, etc.?

Is there any other way to obtain this information?

Body:
Reflection changes for this are touched on in the feature's RFC, though I don't know if they've been documented elsewhere yet.

The new class is ReflectionClassConstant with relevant methods (among others):

isPublic()

isPrivate()

isProtected()

ReflectionClass has two new methods:

getReflectionConstants() - returns an array of ReflectionClassConstants

getReflectionConstant() - retrieves a ReflectionClassConstant by name

Example:

class Foo
{
    private const BAR = 42;
}

$r = new ReflectionClass(Foo::class);

var_dump(
    $r->getReflectionConstants(),
    $r->getReflectionConstant('BAR')->isPrivate()
);

Outputs:

array(1) {
  [0]=>
  object(ReflectionClassConstant)#2 (2) {
    ["name"]=>
    string(3) "BAR"
    ["class"]=>
    string(3) "Foo"
  }
}
bool(true)


来源: stackexchange

问:
Convert formatted lines of delimited text into an associative array
I have a string of key->value pairs in the following colon-separated format:

```<code>MIME-Version: 1.0
From: "Tim Lincecum"
Reply-To: "Tim Lincecum"
Return-path: "Tim Lincecum"
Content-Type: text/html; charset=iso-8859-1
Subject: Giants Win World Series!
</code>```

How do I get an associative array such that arr['From'] = "Tim Lincecum", etc.?

I know there's the explode() function, but the only delimiter I see (colon) is in the middle of a key and a value rather than between each pair. How can I approach this?

答:
Since I did a good guess in comments - I think i need to repeat it here as an answer:

There is a newlines between parameters, so with

```<code>$parameters_pairs = explode("\r\n", $parameters_string);
</code>```

you can split it into the name-value pairs, separated with colon.

ContentLicense: CC BY-SA 4.0

Body:
I have a string of key->value pairs in the following colon-separated format:

MIME-Version: 1.0
From: "Tim Lincecum"
Reply-To: "Tim Lincecum"
Return-path: "Tim Lincecum"
Content-Type: text/html; charset=iso-8859-1
Subject: Giants Win World Series!

How do I get an associative array such that arr['From'] = "Tim Lincecum", etc.?

I know there's the explode() function, but the only delimiter I see (colon) is in the middle of a key and a value rather than between each pair. How can I approach this?

Body:
Since I did a good guess in comments - I think i need to repeat it here as an answer:

There is a newlines between parameters, so with

$parameters_pairs = explode("\r\n", $parameters_string);

you can split it into the name-value pairs, separated with colon.

ContentLicense: CC BY-SA 2.5


问:
Swift - Custom swipe gesture to the right
I would like to create the same effect as the native function to come back to a previous view (but with a specific button).

I tried to code this:

```<code>// Swipe to go back
      let backSwipe = UISwipeGestureRecognizer(target: self, action: #selector(self.back(_:)))
      backSwipe.direction = UISwipeGestureRecognizerDirection.right
      self.view.addGestureRecognizer(backSwipe)
</code>```

In fact, this code works! But it's not as smooth as the native function. This code changes comeback to the previous view when we scroll maybe 1/3 of the current width's view.
However, in the native function we can hold the swipe gesture.

Do you have any idea about how I can do that?

答:
A swipe transition like the one you're talking about would have to be custom. Unless you're looking to specifically learn how to implement that functionality I'd say it's probably ok to use a library. </p>

<p>Check out this cocoapod here. It's a pod that helps with the building of transition animations. </p>

ContentLicense: CC BY-SA 3.0

Body:
I would like to create the same effect as the native function to come back to a previous view (but with a specific button).

I tried to code this:

// Swipe to go back
      let backSwipe = UISwipeGestureRecognizer(target: self, action: #selector(self.back(_:)))
      backSwipe.direction = UISwipeGestureRecognizerDirection.right
      self.view.addGestureRecognizer(backSwipe)

In fact, this code works! But it's not as smooth as the native function. This code changes comeback to the previous view when we scroll maybe 1/3 of the current width's view.
However, in the native function we can hold the swipe gesture.

Do you have any idea about how I can do that?

Body:
A swipe transition like the one you're talking about would have to be custom. Unless you're looking to specifically learn how to implement that functionality I'd say it's probably ok to use a library.

Check out this cocoapod here. It's a pod that helps with the building of transition animations.


问:
jsf select one menu get the selected item
I'm doing a project on jsf and i'm using a select one menu that allows the user to choose an item and them press submit. When the button is clicked the jsf call the bean and it should receive the value selected but i always get a empty result. I saw other post and i guess i'm pretty close of others answers, i guess it just a small detail that is missing

Here is my code:

```<code>        <h:selectOneMenu id="sel1" value="#{foo.bankName}">
            <f:selectItems value="#{foo.bankNameMap}" />
        </h:selectOneMenu>

<h:commandButton id="validate" value="Submit"
                            action="#{foo.submit}"/>
</code>```

And now on bean:

```<code> public String getBankName() {
            return bankName;
        }

    public void setBankName(String bankName) {
        this.bankName = bankName;
    }

    private static Map<String,Object> bankNameMap;

    public Map<String,Object> getBankNameMap() {
        return bankNameMap;
    }

    @PostConstruct
    public void init() {
            initiateDropDown();
     }

     public void  initiateDropDown() {
            bankNameMap = new LinkedHashMap<String,Object>();
             bankNameMap.put("aaaa" , "aaaa");
     }

    public void submit(){ //method called when clicked on the button
          System.out.println("item " +bankName);
    }
</code>```

output:

item

Thanks in advance

答:
You created a method initiateDropDown(); to populate map, but you never called it. I suppose that you can not select aaaa from <h:selectOneMenu/> component, because it does not exist in map. Your map is empty. Also, return type is missing on your submit() method. You need to set return type of method to pass compile time. For example public void submit();.

The simplest way to get existing code work should be:

```<code>public Map<String, Object> getBankNameMap() {
    initiateDropDown();
    return bankNameMap;
}

public void submit() { // method called when clicked on the button
    System.out.println("item " + bankName);
}
</code>```

JSF seems pretty good . Just make sure your elements are in <h:form>.

```<code><h:body>
    <h:form id="myForm">
        <h:selectOneMenu id="sel1" value="#{foo.bankName}">
            <f:selectItems value="#{foo.bankNameMap}" />
        </h:selectOneMenu>
        <h:commandButton id="validate" value="Submit" action="#{foo.submit}"/>
    </h:form>
<h:body>
</code>```

Body:
I'm doing a project on jsf and i'm using a select one menu that allows the user to choose an item and them press submit. When the button is clicked the jsf call the bean and it should receive the value selected but i always get a empty result. I saw other post and i guess i'm pretty close of others answers, i guess it just a small detail that is missing

Here is my code:

        <h:selectOneMenu id="sel1" value="#{foo.bankName}">
            <f:selectItems value="#{foo.bankNameMap}" />
        </h:selectOneMenu>

<h:commandButton id="validate" value="Submit"
                            action="#{foo.submit}"/>

And now on bean:

 public String getBankName() {
            return bankName;
        }

    public void setBankName(String bankName) {
        this.bankName = bankName;
    }

    private static Map<String,Object> bankNameMap;

    public Map<String,Object> getBankNameMap() {
        return bankNameMap;
    }

    @PostConstruct
    public void init() {
            initiateDropDown();
     }

     public void  initiateDropDown() {
            bankNameMap = new LinkedHashMap<String,Object>();
             bankNameMap.put("aaaa" , "aaaa");
     }

    public void submit(){ //method called when clicked on the button
          System.out.println("item " +bankName);
    }

output:

item

Thanks in advance

Body:
You created a method initiateDropDown(); to populate map, but you never called it. I suppose that you can not select aaaa from <h:selectOneMenu/> component, because it does not exist in map. Your map is empty. Also, return type is missing on your submit() method. You need to set return type of method to pass compile time. For example public void submit();.

The simplest way to get existing code work should be:

public Map<String, Object> getBankNameMap() {
    initiateDropDown();
    return bankNameMap;
}

public void submit() { // method called when clicked on the button
    System.out.println("item " + bankName);
}

JSF seems pretty good . Just make sure your elements are in <h:form>.

<h:body>
    <h:form id="myForm">
        <h:selectOneMenu id="sel1" value="#{foo.bankName}">
            <f:selectItems value="#{foo.bankNameMap}" />
        </h:selectOneMenu>
        <h:commandButton id="validate" value="Submit" action="#{foo.submit}"/>
    </h:form>
<h:body>


问:
When are files updated?
I have a set of code which runs in an infinite loop, cancelled through terminal with control C. In this code I use the code json.dumps(dictionary,outfile)

I have noticed that this does not actually put the data into the file until I have used control C to terminate the process. Why does the file not update until after the program has terminated?

答:
Anthony Rossi is basically right, you need to flush the data using outfile.flush(). But why is that so?

json.dump expects a "a .write()-supporting file-like object", see here. Somewhere in your code, you have used open to get your outfile. If we have a look at the documentation for open, we can read the following:

buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows:

Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device’s “block size” and falling back on io.DEFAULT_BUFFER_SIZE. On many systems, the buffer will typically be 4096 or 8192 bytes long.

“Interactive” text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files.

I guess you haven't specified the buffering parameter and your data is smaller than 4 / 8 kb. Therefore, the write is buffered and not directly written to the file.

When you kill your program using Ctrl+C, the outfile is closed and flushes the data to your file.

To fix this, simply put outfile.flush() after your json.dump() as Anthony Rossi suggested.

Title: When are files updated?


问:
Using levenshtein in MySQL search for one result
I am trying to do a search on my MySQL database to get the row that contains the most similar value to the one searched for.

Even if the closest result is very different, I'd still like to return it (Later on I do a string comparison and add the 'unknown' into the learning pool)

I would like to search my table 'responses' via the 'msg1' column and get one result, the one with the lowest levenshtein score, as in the one that is the most similar out of the whole column.

This sort of thing:

```<code>SELECT * FROM people WHERE levenshtein('$message', 'msg1') ORDER BY ??? LIMIT 1
</code>```

I don't quite grasp the concept of levenshtein here, as you can see I am searching the whole table, sorting it by ??? (the function's score?) and then limiting it to one result.

I'd then like to set $reply to the value in column "reply" from this singular row that I get.

Help would be greatly appreciated, I can't find many examples of what I'm looking for. I may be doing this completely wrong, I'm not sure.

Thank you!

答:
Try this</p>

```<code>SELECT * FROM people WHERE levenshtein('$message', 'msg1') <= 0
</code>```

Body:
I am trying to do a search on my MySQL database to get the row that contains the most similar value to the one searched for.

Even if the closest result is very different, I'd still like to return it (Later on I do a string comparison and add the 'unknown' into the learning pool)

I would like to search my table 'responses' via the 'msg1' column and get one result, the one with the lowest levenshtein score, as in the one that is the most similar out of the whole column.

This sort of thing:

SELECT * FROM people WHERE levenshtein('$message', 'msg1') ORDER BY ??? LIMIT 1

I don't quite grasp the concept of levenshtein here, as you can see I am searching the whole table, sorting it by ??? (the function's score?) and then limiting it to one result.

I'd then like to set $reply to the value in column "reply" from this singular row that I get.

Help would be greatly appreciated, I can't find many examples of what I'm looking for. I may be doing this completely wrong, I'm not sure.

Thank you!

Body:
Try this

SELECT * FROM people WHERE levenshtein('$message', 'msg1') <= 0


问:
Get Multiple rows from multiple values (columns) in SQL Server 2008 R2
I have this table

```<code>+-----+------+--------+--------+
| ID  | Name |  Start |   End  |
+-----+------+--------+--------+
| 20  | Mike |   1    |    3   |
| 21  | Luke |   4    |    7   |
+-----+------+--------+--------+
</code>```

And I want to generate all rows based on the range (start / end) of each person.

The outcome should be this

```<code>+-----+------+-----------------+
| ID  | Name |    Start_End    |
+-----+------+-----------------+
| 20  | Mike |        1        |
| 20  | Mike |        2        |
| 20  | Mike |        3        |
| 21  | Luke |        4        |
| 21  | Luke |        5        |
| 21  | Luke |        6        |
| 21  | Luke |        7        |
+-----+------+--------+--------+
</code>```

To get unique values based on Start and End column, I have this function

```<code>CREATE FUNCTION [dbo].[ufn_SplitRange] (@Start INT, @End INT)
RETURNS TABLE
AS
RETURN
(
    SELECT  TOP (@End - @Start+1) ROW_NUMBER() OVER (ORDER BY S.[object_id])+(@Start - 1) [Start_End]
    FROM    sys.all_objects S WITH (NOLOCK)
);
</code>```

The above function returns the output of (based on Mike range of 1-3):

```<code>1
2
3
</code>```

I have been trying several approaches and, I can't find the right solution, it seems a very common task, but a tricky one.

Any input is highly appreciated

答:
You could use recursive cte like this

```<code>DECLARE @SampleData AS TABLE
(
    Id int,
    Name varchar(10),
    Start int,
    [End] int
)

INSERT INTO @SampleData
(
    Id,
    Name,
    Start,
    [End]
)
VALUES
(1,'Mike',1,3),
(2,'Luke',4,7)

;WITH temp AS
(
    SELECT Id, sd.Name, sd.Start , sd.[End]
    FROM @SampleData sd

    UNION ALL

    SELECT t.Id, t.Name, t.Start + 1, t.[End]
    FROM temp t
    WHERE t.Start < t.[End]
)
SELECT t.Id, t.Name, t.Start AS [Start_End]
FROM temp t
ORDER BY t.Id
OPTION (MAXRECURSION 0)
</code>```

Demo link: http://rextester.com/AFNYFW81782

Body:
I have this table

+-----+------+--------+--------+
| ID  | Name |  Start |   End  |
+-----+------+--------+--------+
| 20  | Mike |   1    |    3   |
| 21  | Luke |   4    |    7   |
+-----+------+--------+--------+

And I want to generate all rows based on the range (start / end) of each person.

The outcome should be this

+-----+------+-----------------+
| ID  | Name |    Start_End    |
+-----+------+-----------------+
| 20  | Mike |        1        |
| 20  | Mike |        2        |
| 20  | Mike |        3        |
| 21  | Luke |        4        |
| 21  | Luke |        5        |
| 21  | Luke |        6        |
| 21  | Luke |        7        |
+-----+------+--------+--------+

To get unique values based on Start and End column, I have this function

CREATE FUNCTION [dbo].[ufn_SplitRange] (@Start INT, @End INT)
RETURNS TABLE
AS
RETURN
(
    SELECT  TOP (@End - @Start+1) ROW_NUMBER() OVER (ORDER BY S.[object_id])+(@Start - 1) [Start_End]
    FROM    sys.all_objects S WITH (NOLOCK)
);

The above function returns the output of (based on Mike range of 1-3):

1
2
3

I have been trying several approaches and, I can't find the right solution, it seems a very common task, but a tricky one.

Any input is highly appreciated

Body:
You could use recursive cte like this

DECLARE @SampleData AS TABLE
(
    Id int,
    Name varchar(10),
    Start int,
    [End] int
)

INSERT INTO @SampleData
(
    Id,
    Name,
    Start,
    [End]
)
VALUES
(1,'Mike',1,3),
(2,'Luke',4,7)

;WITH temp AS
(
    SELECT Id, sd.Name, sd.Start , sd.[End]
    FROM @SampleData sd

    UNION ALL

    SELECT t.Id, t.Name, t.Start + 1, t.[End]
    FROM temp t
    WHERE t.Start < t.[End]
)
SELECT t.Id, t.Name, t.Start AS [Start_End]
FROM temp t
ORDER BY t.Id
OPTION (MAXRECURSION 0)

Demo link: http://rextester.com/AFNYFW81782


问:
Validation on name TextBoxes
I have a grid where in insert/edit mode you can update the item for a person's names.

I've been asked to provide validation to ensure only alphanumerics are added.

After talking with a colleague we were thinking only validation for length should be done.

The user should be able to enter any characters they like.

Does this sound correct? I understand some names could contain special characters etc.

答: You may need to consider whether you will allow the accented characters that are common in many European names, but this aside alphas (do you really need numerics?) only are probably the way to go to provide security from XSS attacks. </p>

Title: Validation on name TextBoxes


问:
The most efficient way to calculate total number of all descendants in self reference table
I am looking for an efficient way to calculate total number of all sub categories (all levels) for a given category, without retrieving all the data from the database

Here is my Model:

```<code>public class Category
{
    public Category()
    {
        SubCategories = new HashSet<Category>();
    }

    public Guid CategoryId { get; set; }
    public string Title { get; set; }

    [ForeignKey("ParentCategory")]
    public Guid? ParentCategoryId { get; set; }

    //navigation properties
    public virtual Category ParentCategory { get; set; }
    public virtual ICollection<Category> SubCategories { get; set; }
}
</code>```

And my ViewModel:

```<code>    public class CategoryViewModel
{
    public CategoryViewModel()
    {
        SubCategories = new List<CategoryViewModel>();
    }

    public Guid CategoryId { get; set; }

    [Required]
    public string Title { get; set; }

    public Guid? ParentCategoryId { get; set; }

    public virtual CategoryViewModel ParentCategory { get; set; }

    public virtual List<CategoryViewModel> SubCategories { get; set; }

    public int TotalOfDirectSubCategories { get; set; }
    public int TotalOfAllSubCategories { get; set; }
}
</code>```

My AutoMapping:

```<code>            cfg.CreateMap<Category, CategoryViewModel>()
            .PreserveReferences()
            .ReverseMap();
</code>```

And finally my EF to retrieve data:

```<code>                data = _ctx.Categories.Where(x => x.ParentCategoryId == categoryId)
                //.Include(x => x.SubCategories)
                .ToList();
</code>```

Let's assume a category can contain thousands of sub categories. Since this will be SOA solution, and data will be passed from Web API into my client app, I don't want to pass all subCategories data with every web API call, so I will only need data for requested category, and corresponding counts.

Let assume we have
'cat 1' > 'cat 1 1' > 'cat 1 1 1'

'cat 1' contains exactly 2 sub categories. 'cat 1 1' contains one sub category. I can retrieve 'cat 1' data by calling web API method 'getCategory(null)', and to retrieve 'cat 1 1' data I would call 'getCategory(GuidOfCat11)'

For 'cat 1':

TotalOfDirectSubCategories - 1

TotalOfAllSubCategories - 2

And again, no subCategories will be included

答:
Here is the best I could implement, do you think there is a better approach:

AutoMapper:

```<code>            cfg.CreateMap<Category, CategoryViewModel>()
            .PreserveReferences()
            .ForMember(x => x.TotalOfDirectSubCategories, x => x.MapFrom(z => z.SubCategories.Count))
            .ReverseMap();
</code>```

Populating CategoryViewModel:

```<code>        public List<CategoryViewModel> GetAllCategoriesAndTasksForParentCategoryAndUser(Guid? categoryId)
    {
        var data = new List<Category>();

        if (categoryId == null) // retrieve root level categories
        {
                data = _ctx.Categories.Where(x => x.ParentCategoryId == null)
                    .Include(x => x.SubCategories)
                    .Include(x => x.Tasks)
                    .ToList();
        }
        else
        {
                data = _ctx.Categories.Where(x => x.CategoryId == categoryId)
                    .Include(x => x.SubCategories)
                    .Include(x => x.Tasks)
                    .ToList();
        }

        var dataToReturn = Mapper.Map<List<Category>, List<CategoryViewModel>>(data);
        foreach (var category in data)
        {
            var vm = dataToReturn.First(x => x.CategoryId == category.CategoryId);

            //subCategories
            int totalCount = 0;
            SubCategoriesCount(ref totalCount, category);
            vm.TotalOfAllSubCategories = totalCount;
        }

        return dataToReturn;

    }
</code>```

And finally, the method:

```<code>    private void SubCategoriesCount(ref int subCatCount, Category category)
    {
        if (category.SubCategories != null || category.SubCategories.Count() != 0)
        {
            subCatCount += category.SubCategories.Count();

            foreach (var subCat in category.SubCategories)
            {
                SubCategoriesCount(ref subCatCount, subCat);
            }
        }
    }
</code>```

Body:
I am looking for an efficient way to calculate total number of all sub categories (all levels) for a given category, without retrieving all the data from the database

Here is my Model:

public class Category
{
    public Category()
    {
        SubCategories = new HashSet<Category>();
    }

    public Guid CategoryId { get; set; }
    public string Title { get; set; }

    [ForeignKey("ParentCategory")]
    public Guid? ParentCategoryId { get; set; }

    //navigation properties
    public virtual Category ParentCategory { get; set; }
    public virtual ICollection<Category> SubCategories { get; set; }
}

And my ViewModel:

    public class CategoryViewModel
{
    public CategoryViewModel()
    {
        SubCategories = new List<CategoryViewModel>();
    }

    public Guid CategoryId { get; set; }

    [Required]
    public string Title { get; set; }

    public Guid? ParentCategoryId { get; set; }

    public virtual CategoryViewModel ParentCategory { get; set; }

    public virtual List<CategoryViewModel> SubCategories { get; set; }

    public int TotalOfDirectSubCategories { get; set; }
    public int TotalOfAllSubCategories { get; set; }
}

My AutoMapping:

            cfg.CreateMap<Category, CategoryViewModel>()
            .PreserveReferences()
            .ReverseMap();

And finally my EF to retrieve data:

                data = _ctx.Categories.Where(x => x.ParentCategoryId == categoryId)
                //.Include(x => x.SubCategories)
                .ToList();

Let's assume a category can contain thousands of sub categories. Since this will be SOA solution, and data will be passed from Web API into my client app, I don't want to pass all subCategories data with every web API call, so I will only need data for requested category, and corresponding counts.

Let assume we have
'cat 1' > 'cat 1 1' > 'cat 1 1 1'

'cat 1' contains exactly 2 sub categories. 'cat 1 1' contains one sub category. I can retrieve 'cat 1' data by calling web API method 'getCategory(null)', and to retrieve 'cat 1 1' data I would call 'getCategory(GuidOfCat11)'

For 'cat 1':

TotalOfDirectSubCategories - 1

TotalOfAllSubCategories - 2

And again, no subCategories will be included

Body:
Here is the best I could implement, do you think there is a better approach:

AutoMapper:

            cfg.CreateMap<Category, CategoryViewModel>()
            .PreserveReferences()
            .ForMember(x => x.TotalOfDirectSubCategories, x => x.MapFrom(z => z.SubCategories.Count))
            .ReverseMap();

Populating CategoryViewModel:

        public List<CategoryViewModel> GetAllCategoriesAndTasksForParentCategoryAndUser(Guid? categoryId)
    {
        var data = new List<Category>();

        if (categoryId == null) // retrieve root level categories
        {
                data = _ctx.Categories.Where(x => x.ParentCategoryId == null)
                    .Include(x => x.SubCategories)
                    .Include(x => x.Tasks)
                    .ToList();
        }
        else
        {
                data = _ctx.Categories.Where(x => x.CategoryId == categoryId)
                    .Include(x => x.SubCategories)
                    .Include(x => x.Tasks)
                    .ToList();
        }

        var dataToReturn = Mapper.Map<List<Category>, List<CategoryViewModel>>(data);
        foreach (var category in data)
        {
            var vm = dataToReturn.First(x => x.CategoryId == category.CategoryId);

            //subCategories
            int totalCount = 0;
            SubCategoriesCount(ref totalCount, category);
            vm.TotalOfAllSubCategories = totalCount;
        }

        return dataToReturn;

    }

And finally, the method:

    private void SubCategoriesCount(ref int subCatCount, Category category)
    {
        if (category.SubCategories != null || category.SubCategories.Count() != 0)
        {
            subCatCount += category.SubCategories.Count();

            foreach (var subCat in category.SubCategories)
            {
                SubCategoriesCount(ref subCatCount, subCat);
            }
        }
    }


问:
Validating raw_input inside a for loop
I'm attempting to create a validation loop to check a user input against a defined list, but for some reason the code gets stuck in a loop perpetually asking the user to re-enter the value. I tested by adding a print command into the loop and the input data is being stored to the attributes dictionary, but it never seem to meet the == criteria to trigger the break from the for loop.

Here's my code so far, would really appreciate any suggestions on where I'm going amiss:

```<code>attributes = {'Name': 'None', 'Class': 'None', 'Strength': 3, 'Agility': 3, 'Wounds': 3, 'Intelligence': 3}

attributes['Name'] = raw_input('What is your character\'s name?')
attributes['Class'] = raw_input('Choose your character\'s class, enter Warrior, Mage, Ranger or Thief.')

#this is the section I am struggling with!
for values in attributes:
    if attributes['Class'] != "Warrior" or "Mage" or "Ranger" or "Thief":
        attributes['Class'] = raw_input('Please choose either Warrior, Mage, Ranger or Thief.')
        continue
    elif attributes['Class'] == "Warrior" or "Mage" or "Ranger" or "Thief":
        break

if attributes["Class"] == "Warrior":
    attributes["Strength"] += 1
    attributes["Wounds"] += 1
elif attributes["Class"] == "Mage":
    attributes["Intelligence"] += 2
elif attributes["Class"] == "Ranger":
    attributes["Strength"] += 1
    attributes["Agility"] += 1
elif attributes["Class"] == "Thief":
    attributes["Agility"] += 1
    attributes["Intelligence"] += 1

print
print 'Name: ' + attributes['Name']
print 'Class: ' + attributes['Class']
print 'STR: ' + str(attributes['Strength']), 'AGI: ' + str(attributes['Agility']), 'WOU: ' + str(attributes['Wounds']) ,'INT: ' + str(attributes['Intelligence'])
</code>```

答:
The or works different than you think.
It gives you the first value that is true. In Python non-empty strings are always true. Therefore:

```<code>>>> "Warrior" or "Mage" or "Ranger" or "Thief"
'Warrior'
</code>```

Change your code to:

```<code>if attributes['Class'] not in ("Warrior", "Mage", "Ranger", "Thief"):
    attributes['Class'] = raw_input('Please choose either Warrior, Mage, Ranger or Thief.')
    continue
else:
    break
</code>```

This checks if the entered input is in the names in your tuple. If not, it asks for new input, otherwise it stops asking for input.

Title: Validating raw_input inside a for loop

Body:
I'm attempting to create a validation loop to check a user input against a defined list, but for some reason the code gets stuck in a loop perpetually asking the user to re-enter the value. I tested by adding a print command into the loop and the input data is being stored to the attributes dictionary, but it never seem to meet the == criteria to trigger the break from the for loop.

Here's my code so far, would really appreciate any suggestions on where I'm going amiss:

attributes = {'Name': 'None', 'Class': 'None', 'Strength': 3, 'Agility': 3, 'Wounds': 3, 'Intelligence': 3}

attributes['Name'] = raw_input('What is your character\'s name?')
attributes['Class'] = raw_input('Choose your character\'s class, enter Warrior, Mage, Ranger or Thief.')

#this is the section I am struggling with!
for values in attributes:
    if attributes['Class'] != "Warrior" or "Mage" or "Ranger" or "Thief":
        attributes['Class'] = raw_input('Please choose either Warrior, Mage, Ranger or Thief.')
        continue
    elif attributes['Class'] == "Warrior" or "Mage" or "Ranger" or "Thief":
        break

if attributes["Class"] == "Warrior":
    attributes["Strength"] += 1
    attributes["Wounds"] += 1
elif attributes["Class"] == "Mage":
    attributes["Intelligence"] += 2
elif attributes["Class"] == "Ranger":
    attributes["Strength"] += 1
    attributes["Agility"] += 1
elif attributes["Class"] == "Thief":
    attributes["Agility"] += 1
    attributes["Intelligence"] += 1

print
print 'Name: ' + attributes['Name']
print 'Class: ' + attributes['Class']
print 'STR: ' + str(attributes['Strength']), 'AGI: ' + str(attributes['Agility']), 'WOU: ' + str(attributes['Wounds']) ,'INT: ' + str(attributes['Intelligence'])

Body:
The or works different than you think.
It gives you the first value that is true. In Python non-empty strings are always true. Therefore:

>>> "Warrior" or "Mage" or "Ranger" or "Thief"
'Warrior'

Change your code to:

if attributes['Class'] not in ("Warrior", "Mage", "Ranger", "Thief"):
    attributes['Class'] = raw_input('Please choose either Warrior, Mage, Ranger or Thief.')
    continue
else:
    break

This checks if the entered input is in the names in your tuple. If not, it asks for new input, otherwise it stops asking for input.


答:
The line

```<code>if attributes['Class'] != "Warrior" or "Mage" or "Ranger" or "Thief":
</code>```

will always resolve to True because bool("Mare") == True so your loop never breaks.

What I think you are looking for is something closer to:

```<code>if attributes['Class'] not in ("Warrior", "Mage", "Ranger", "Thief"):
</code>```

If you are just trying to check the value of attributes['Class'], the following loop might be more appropriate:

```<code>while attributes['Class'] not in ("Warrior", "Mage", "Ranger", "Thief"):
    attributes['Class'] = raw_input('Please choose either Warrior, Mage, Ranger or Thief.')
</code>```

Title: Validating raw_input inside a for loop

Body:
The line

if attributes['Class'] != "Warrior" or "Mage" or "Ranger" or "Thief":

will always resolve to True because bool("Mare") == True so your loop never breaks.

What I think you are looking for is something closer to:

if attributes['Class'] not in ("Warrior", "Mage", "Ranger", "Thief"):

If you are just trying to check the value of attributes['Class'], the following loop might be more appropriate:

while attributes['Class'] not in ("Warrior", "Mage", "Ranger", "Thief"):
    attributes['Class'] = raw_input('Please choose either Warrior, Mage, Ranger or Thief.')


问:
Program Flow C#
I am learning C# at the moment. In the example below, I believe I have the correct code but there must be an error or two (maybe more) somewhere. Please see the code below:

```<code>    public static string ReturnAgeGroup(int age)
    {
        if (age >= 65)
        {
            return "senior citizen";
        }
        if (age < 21)
        {
            return "minor";
        }
        if (age >= 21 & age < 65)
        {
            return "adult";
        }
    }
</code>```

There is a red squiggly line underneath RetrunAgeGroup, which says not all code paths return a value when I hover over it. Why is this? Every possibility, regarding age, is covered by the conditions.

Is/are there any other error(s) that I have failed to identify?

Regards

答:
IntellySence cannot be sure, that you variable realy 100% passes into one of IFs.
Replace last if to else.

```<code>public static string ReturnAgeGroup(int age)
{
    if (age >= 65)
        return "senior citizen";
    if (age < 21)
        return "minor";
    else
        return "adult";
}
</code>```

Title: Program Flow C#

Body:
I am learning C# at the moment. In the example below, I believe I have the correct code but there must be an error or two (maybe more) somewhere. Please see the code below:

    public static string ReturnAgeGroup(int age)
    {
        if (age >= 65)
        {
            return "senior citizen";
        }
        if (age < 21)
        {
            return "minor";
        }
        if (age >= 21 & age < 65)
        {
            return "adult";
        }
    }

There is a red squiggly line underneath RetrunAgeGroup, which says not all code paths return a value when I hover over it. Why is this? Every possibility, regarding age, is covered by the conditions.

Is/are there any other error(s) that I have failed to identify?

Regards

Body:
IntellySence cannot be sure, that you variable realy 100% passes into one of IFs.
Replace last if to else.

public static string ReturnAgeGroup(int age)
{
    if (age >= 65)
        return "senior citizen";
    if (age < 21)
        return "minor";
    else
        return "adult";
}


问:
Get ID value from Angular scope and use in statment
I have a array of objects that are displayed in my scope once selected via two drop down selection boxes, first box to select name second to select format.

example of a object

```<code> {
    "name": "tim",
            "format": [
                {"Fname": "a", "id": "1"},
                {"Fname": "b", "id": "2"},
                {"Fname": "c", "id": "3"}
            ]
        },
</code>```

and I send it to the scope using

```<code> $scope.productTypeChange = function () {
        $scope.formats = $scope.productsandformats.find(ps => ps.name == $scope.formData.ProductType.name)
}
</code>```

I get a pint out on my scope like

```<code> {"ProductType":{"name":"tim"},"formatType":{"Fname":"a","id":"1"}}
</code>```

I then want have a if statement based on the ID value printed in the scope, I have tried so far to get the ID value, however it dose not seem to work, Is this the correct way to get the ID >

```<code>$scope.setCanvasSize = function() {
    divHeight = $('.image-builder').height();
    if ($scope.formData.ProductType.name.id = 1) {
        // Aratio = 0.67;
        Aratio = 2;
    } else if ($scope.formData.ProductType.name.id = 2) {
        Aratio = 0.56;
    } else if ($scope.formData.ProductType.name.id = 3) {
        divHeight = divHeight / 1.5;
        Aratio = 2;
    } else if ($scope.formData.ProductType.name.id = 4) {
        Aratio = 0.67;
    } else {
        Aratio = 1
    }
    canvas.setHeight(divHeight - 15);
    canvas.setWidth((divHeight - 15) * Aratio);
    canvas.renderAll();
    $scope.position();
};
</code>```

答:
You are using the object wrongly. If

```<code>$scope.formats={"ProductType":{"name":"tim"},"formatType":{"Fname":"a","id":"1"}};
</code>```

Then to get id you have to access the object like this

```<code>$scope.formats.formatType.id
</code>```

You also have to check correctly in if statements. In your question you are assigning values instead of comparison. So, it should be like this:

```<code>if($scope.formats.formatType.id=="1"){
//do calculations
}
</code>```

Body:
I have a array of objects that are displayed in my scope once selected via two drop down selection boxes, first box to select name second to select format.

example of a object

 {
    "name": "tim",
            "format": [
                {"Fname": "a", "id": "1"},
                {"Fname": "b", "id": "2"},
                {"Fname": "c", "id": "3"}
            ]
        },

and I send it to the scope using

 $scope.productTypeChange = function () {
        $scope.formats = $scope.productsandformats.find(ps => ps.name == $scope.formData.ProductType.name)
}

I get a pint out on my scope like

 {"ProductType":{"name":"tim"},"formatType":{"Fname":"a","id":"1"}}

I then want have a if statement based on the ID value printed in the scope, I have tried so far to get the ID value, however it dose not seem to work, Is this the correct way to get the ID >

$scope.setCanvasSize = function() {
    divHeight = $('.image-builder').height();
    if ($scope.formData.ProductType.name.id = 1) {
        // Aratio = 0.67;
        Aratio = 2;
    } else if ($scope.formData.ProductType.name.id = 2) {
        Aratio = 0.56;
    } else if ($scope.formData.ProductType.name.id = 3) {
        divHeight = divHeight / 1.5;
        Aratio = 2;
    } else if ($scope.formData.ProductType.name.id = 4) {
        Aratio = 0.67;
    } else {
        Aratio = 1
    }
    canvas.setHeight(divHeight - 15);
    canvas.setWidth((divHeight - 15) * Aratio);
    canvas.renderAll();
    $scope.position();
};

Body:
You are using the object wrongly. If

$scope.formats={"ProductType":{"name":"tim"},"formatType":{"Fname":"a","id":"1"}};

Then to get id you have to access the object like this

$scope.formats.formatType.id

You also have to check correctly in if statements. In your question you are assigning values instead of comparison. So, it should be like this:

if($scope.formats.formatType.id=="1"){
//do calculations
}


答:
you can do like this.</p>

```<code>public static string ReturnAgeGroup(int age)
{
    if (age >= 65)
    {
        return "senior citizen";
    }
    if (age < 21)
    {
        return "minor";
    }

    return "adult";
}
</code>```

Title: Program Flow C#

Body:
you can do like this.

public static string ReturnAgeGroup(int age)
{
    if (age >= 65)
    {
        return "senior citizen";
    }
    if (age < 21)
    {
        return "minor";
    }

    return "adult";
}


问:
How to access a resource from a java library packed into its own .jar
I have a library project with some resources that I would like to load and use.
I would be using this library in another project so I have to pack the resources into the .jar. This is how that's achieved:

```<code><resources>
    <resource>
        <directory>src/main/resources</directory>
    </resource>
</resources>
</code>```

The problem comes when trying to retrieve the file, I do:

```<code>String resourceName = "myTemplateResource.json";
URL url = MyClass.class.getClassLoader().getResource(resourceName);
</code>```

url is assigned a null value. It happens in the library's tests and in the dependant project. Any hint of what is missing?

Also tested using

```<code>MyClass.class.getResource("/myTemplateResourceName.json");
</code>```

and

```<code>MyClass.class.getClassLoader().getResource("src/main/resources/myTemplateResource.json");
</code>```

with the same result.

答:
Use getResourceAsStream() method to load the resource from the .jar file as follows:

```<code>ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(locaiton);
</code>```

e.g.: If the file 'myTemplateResourceName.json' is located directly in the resources folder, use only the file name. It is wrong if you add a slash (/) in front of the path.

```<code>InputStream inputStream = classLoader.getResourceAsStream("myTemplateResourceName.json");
</code>```

Note: You have to place the resource file in the main/resources (don't keep it in the test/resources section since that is not packed in the jar file) folder in the project which is being used to create the jar file.

Body:
I have a library project with some resources that I would like to load and use.
I would be using this library in another project so I have to pack the resources into the .jar. This is how that's achieved:

<resources>
    <resource>
        <directory>src/main/resources</directory>
    </resource>
</resources>

The problem comes when trying to retrieve the file, I do:

String resourceName = "myTemplateResource.json";
URL url = MyClass.class.getClassLoader().getResource(resourceName);

url is assigned a null value. It happens in the library's tests and in the dependant project. Any hint of what is missing?

Also tested using

MyClass.class.getResource("/myTemplateResourceName.json");

and

MyClass.class.getClassLoader().getResource("src/main/resources/myTemplateResource.json");

with the same result.

Body:
Use getResourceAsStream() method to load the resource from the .jar file as follows:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(locaiton);

e.g.: If the file 'myTemplateResourceName.json' is located directly in the resources folder, use only the file name. It is wrong if you add a slash (/) in front of the path.

InputStream inputStream = classLoader.getResourceAsStream("myTemplateResourceName.json");

Note: You have to place the resource file in the main/resources (don't keep it in the test/resources section since that is not packed in the jar file) folder in the project which is being used to create the jar file.


问:
Cast List<int> to List<string> in .NET 2.0
Can you cast a List<int> to List<string> somehow?

I know I could loop through and .ToString() the thing, but a cast would be awesome.

I'm in C# 2.0 (so no LINQ).

答:
.NET 2.0 has the ConvertAll method where you can pass in a converter function:

```<code>List<int>    l1 = new List<int>(new int[] { 1, 2, 3 } );
List<string> l2 = l1.ConvertAll<string>(delegate(int i) { return i.ToString(); });
</code>```

OwnerDisplayName: lomaxx

Body:
.NET 2.0 has the ConvertAll method where you can pass in a converter function:

List<int>    l1 = new List<int>(new int[] { 1, 2, 3 } );
List<string> l2 = l1.ConvertAll<string>(delegate(int i) { return i.ToString(); });

OwnerDisplayName: Glenn Slaven


问:
git pull on server using hook after I push locally
I'm working with html & css files locally. After I git push the files to my server (into a bare directory which I created with mkdir bare_repos/mysite && cd bare_repos/mysite && git init --bare), I don't want to have to ssh into the server, go into my ~/public_html/mysite directory and type git pull. I think a hook should do this but I'm not sure how?

The files in my bare_repos/mysite/hooks/ directory are: applypatch-msg.sample, post-update.sample, pre-commit.sample, pre-rebase.sample, prepare-commit-msg.sample, commit-msg.sample, pre-applypatch.sample, pre-push.sample, pre-receive.sample, update.sample

Which file should I edit and what should be added to it? I want to be able to push from my local machine and then simply see the changes on website from my browser (no ssh'ing needed)

答:
I followed instructions here. I created a post-receive file and added:

```<code>#!/bin/sh
GIT_WORK_TREE=/home/username/public_html/mysite git checkout -f
</code>```

Then I made it executable (chmod +x post-receive)

Now when I git push, changes are automatically seen on my website.

Body:
I followed instructions here. I created a post-receive file and added:

#!/bin/sh
GIT_WORK_TREE=/home/username/public_html/mysite git checkout -f

Then I made it executable (chmod +x post-receive)

Now when I git push, changes are automatically seen on my website.


问:
How to remove unused strange element from site?
i have one little issue that cant resolve myself. I want to remove second box (at bottom) in this page but when inspect CSS found that both elements are defined as :

```<code>``````
</code>```

so dont know how to handle that box, and remove it. Form in that page are generated by "User registration & user profile – Profile Builder plugin".

答:
in your css:

```<code>:css selector {
  display:none;
}
</code>```

you also can declare in html:

```<code><pre style="display:none;"> ```
```

Body:
i have one little issue that cant resolve myself. I want to remove second box (at bottom) in this page but when inspect CSS found that both elements are defined as :

so dont know how to handle that box, and remove it. Form in that page are generated by "User registration & user profile – Profile Builder plugin".

Body:
in your css:

:css selector {
  display:none;
}

you also can declare in html:

<pre style="display:none;"> </pre>


问:
JQuery how to click div inside li to update another div
I have a ul i am appending li's with two div's through JavaScript to it, shown as below

```<code>c_list = $('.encounter_creatures_list > ul')
db.transaction(
    function(transaction) {
        transaction.executeSql(
          'SELECT * FROM creatures;',
          [],
            function (transaction, result) {
               var creature_array = new Array();
               for (i=0; i < result.rows.length; i++){
                 var row = result.rows.item(i)
               li = $("li[key='" + row.id + "']")
                     if(li.length > 0) {
                       // $('#name', li).html(encounter.name)
                     } else {
                      creature_array.push(row)
                       var counter = 0
                           li = $("<li key='"+ row.id + "' class='list_"+ row.id + "'>"+ row.name +  "<div class='plus_"+ row.id + "'>+</div> <div class='counter_"+ row.id + "'>"+ counter  +"</div></li>")
                       li.css({'border': '1px solid #999999', 'color': '#222222', 'display': 'block', 'font-size': '17px', 'font-weight': 'bold', 'margin-bottom': '-0.5px', 'padding': '12px 10px', 'text-decoration': 'none'})
                       c_list.append(li)
 //                           alert($(".counter_"+ row.id + "", li).text())
//                           $(".plus_"+ row.id + "", li).click(function(event) {
//                              $(".counter_"+ row.id + "", li).text(counter + 1)
//                             event.preventDefault();
//                           })

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

I want to do the part which i have commented, i.e. clicking one div to update another inside li.

答:
Add another class to the div that is static. Than add this to your onload event. All elements with the class .classname will have the onclick functionality.

```<code>$(".classname").live("click", function() {
  var rowid = $(this).attr("key");
  alert($(".counter_"+ rowid, li).text());
  $(".counter_"+ rowid, li).text(counter + 1);
});
</code>```

One side note. Your code is a bit messy. You should try to refactor it a bit.

Body:
I have a ul i am appending li's with two div's through JavaScript to it, shown as below

c_list = $('.encounter_creatures_list > ul')
db.transaction(
    function(transaction) {
        transaction.executeSql(
          'SELECT * FROM creatures;',
          [],
            function (transaction, result) {
               var creature_array = new Array();
               for (i=0; i < result.rows.length; i++){
                 var row = result.rows.item(i)
               li = $("li[key='" + row.id + "']")
                     if(li.length > 0) {
                       // $('#name', li).html(encounter.name)
                     } else {
                      creature_array.push(row)
                       var counter = 0
                           li = $("
"+ row.name +  "
+

"+ counter  +"

")
                       li.css({'border': '1px solid #999999', 'color': '#222222', 'display': 'block', 'font-size': '17px', 'font-weight': 'bold', 'margin-bottom': '-0.5px', 'padding': '12px 10px', 'text-decoration': 'none'})
                       c_list.append(li)
 //                           alert($(".counter_"+ row.id + "", li).text())
//                           $(".plus_"+ row.id + "", li).click(function(event) {
//                              $(".counter_"+ row.id + "", li).text(counter + 1)
//                             event.preventDefault();
//                           })

                    }
               }
            })
       })

I want to do the part which i have commented, i.e. clicking one div to update another inside li.

Body:
Add another class to the div that is static. Than add this to your onload event. All elements with the class .classname will have the onclick functionality.

$(".classname").live("click", function() {
  var rowid = $(this).attr("key");
  alert($(".counter_"+ rowid, li).text());
  $(".counter_"+ rowid, li).text(counter + 1);
});

One side note. Your code is a bit messy. You should try to refactor it a bit.


问:
Invalid argument supplied for foreach() MySQLi
I am stuck with a Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\risman\admin\edit.php on line 53 in a system I am building and don't have the slightest clue. It must have something to do with the fact that I newbie at coding.

It reads as follows on line 5 :

```<code>if($_POST['rowid']) {
    $id = $_POST['rowid'];
    $sql = "SELECT * FROM user WHERE id = $id";
    $result = $koneksi->query($sql);
    foreach ($result as $baris) { ?>
</code>```

Thanks to all the wise guys around here

答:
The problem is because: probably $result is not an array.
Please try this:

```<code>if($_POST['rowid']) {
$id = $_POST['rowid'];
$sql = "SELECT * FROM user WHERE id = $id";
$result = $koneksi->query($sql);
var_dump($result);
//foreach ($result as $baris) { ?>
</code>```

The result should be an array something like that:

```<code> array(2) { [0]=>
                  array(3) { ["ID"]=> int(1) ["NAME"]=> string(5)   "BLARZ" ["PASS"]=> string(3) "123" } [1]=>
                 array(3) { ["ID"]=> int(2) ["NAME"]=> string(5) "OTHER" ["PASS"]=> string(3) "789" } }
</code>```

Body:
I am stuck with a Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\risman\admin\edit.php on line 53 in a system I am building and don't have the slightest clue. It must have something to do with the fact that I newbie at coding.

It reads as follows on line 5 :

if($_POST['rowid']) {
    $id = $_POST['rowid'];
    $sql = "SELECT * FROM user WHERE id = $id";
    $result = $koneksi->query($sql);
    foreach ($result as $baris) { ?>

Thanks to all the wise guys around here

Body:
The problem is because: probably $result is not an array.
Please try this:

if($_POST['rowid']) {
$id = $_POST['rowid'];
$sql = "SELECT * FROM user WHERE id = $id";
$result = $koneksi->query($sql);
var_dump($result);
//foreach ($result as $baris) { ?>

The result should be an array something like that:

 array(2) { [0]=>
                  array(3) { ["ID"]=> int(1) ["NAME"]=> string(5)   "BLARZ" ["PASS"]=> string(3) "123" } [1]=>
                 array(3) { ["ID"]=> int(2) ["NAME"]=> string(5) "OTHER" ["PASS"]=> string(3) "789" } }


答:
Why are you accessing the "value" using the array (Assuming, since you're using find) as in "$scope.formData.ProductType.name.id" instead of accessing the value withing "$scope.formats.formatType.id" (That you already filtered).

Also, in the filtered variable you don't have a format that match the kind of "$scope.formData.ProductType.name.id", instead you have to access the variable like this -> "$scope.formats.formatType.id"

Title: Get ID value from Angular scope and use in statment


问:
MySQL UNION not working
I'm attempting a mysql union but nothing is returned?  Below is an example.  In total there is 16 select queries

```<code>$url_array = array(
   "euro-gbp","euro-aud","euro-usd",
   "euro-jpy","gbp-jpy","euro-cad",
   "usd-cad","usd-jpy","cad-jpy",
   "gbp-usd","aud-usd","gbp-cad",
   "aud-cad","aud-jpy","aud-nzd",
   "euro-nzd","gbp-aud","gbp-nzd",
   "nzd-usd","nzd-cad","nzd-jpy");

foreach($url_array as $urls) {
   $sql[]= "SELECT *
     FROM `data_analysis_child`
     WHERE type='".$urls."'
     ORDER BY id DESC
     LIMIT 2";

}

$sql = implode(" UNION ",$sql);
</code>```

The sql result

```<code>SELECT * FROM `data_analysis_child` WHERE type='euro-gbp' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-aud' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='usd-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='usd-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='cad-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-nzd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-nzd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-aud' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-nzd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='nzd-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='nzd-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='nzd-jpy' ORDER BY id DESC LIMIT 2
</code>```

How do i solve?  Is there a better way to restructure this query?

答:
The documentation of UNION clearly explains:

To apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the SELECT:

```<code>(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);
</code>```

It also says:

Note

Previous versions of MySQL may permit such statements without parentheses. In MySQL 5.7, the requirement for parentheses is enforced.

If you are using MySQL 5.7 or newer, the code doesn't return anything because the query doesn't run. You should check the type of the returned value (the query functions return FALSE when the query is invalid) and the error message.

Title: MySQL UNION not working

Body:
I'm attempting a mysql union but nothing is returned?  Below is an example.  In total there is 16 select queries

$url_array = array(
   "euro-gbp","euro-aud","euro-usd",
   "euro-jpy","gbp-jpy","euro-cad",
   "usd-cad","usd-jpy","cad-jpy",
   "gbp-usd","aud-usd","gbp-cad",
   "aud-cad","aud-jpy","aud-nzd",
   "euro-nzd","gbp-aud","gbp-nzd",
   "nzd-usd","nzd-cad","nzd-jpy");

foreach($url_array as $urls) {
   $sql[]= "SELECT *
     FROM `data_analysis_child`
     WHERE type='".$urls."'
     ORDER BY id DESC
     LIMIT 2";

}

$sql = implode(" UNION ",$sql);

The sql result

SELECT * FROM `data_analysis_child` WHERE type='euro-gbp' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-aud' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='usd-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='usd-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='cad-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-nzd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-nzd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-aud' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-nzd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='nzd-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='nzd-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='nzd-jpy' ORDER BY id DESC LIMIT 2

How do i solve?  Is there a better way to restructure this query?

Body:
The documentation of UNION clearly explains:

To apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the SELECT:

(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);

It also says:

Note

Previous versions of MySQL may permit such statements without parentheses. In MySQL 5.7, the requirement for parentheses is enforced.

If you are using MySQL 5.7 or newer, the code doesn't return anything because the query doesn't run. You should check the type of the returned value (the query functions return FALSE when the query is invalid) and the error message.


问:
Is my website more vulnerable if API website gets hacked?
Say I have a website that is pulling data from Constant Contact or Mailchimp through their API. Then for some unfortunate reason, one of these websites get hacked. Is my site now more vulnerable to an attack since I am connected through an API?</p>

答:
Well on the surface it doesn't make your site less secure, as you are just requesting data from an external compromised data source.

However, if the API data source has been comprised the hackers could send data via the API which you might save to your database or display on your site, so hackers could potentially insert malicious scripts into your database or cause some reputational damage by sending all sorts of crap data (swear words, advertise porn sites etc) which you will display on your site.

In general the more complexity you add to any system (real life or virtual), the more ways it can be exploited, so it is always good to do some homework before you introduce any library or dependencies to your codebase.

EDIT
To add the above, OWASP do a great job by laying out all the risks with using a compromised API.
https://www.owasp.org/index.php/Top_10_2017-A9-Using_Components_with_Known_Vulnerabilities


问:
When i Choose from The main Menu I Get: game.sh: 423: Syntax error: end of file unexpected (expecting "fi")
```<code>!# /bin/sh
# game.sh:
#  Chooses games based on genre and title
#  Also Shows descriptions of games

# Genre Menu
clear
printf "%s\n" "Game genre Menu"
printf "%s\n"
printf "%s\n" "1. First Person Shooter"
printf "%s\n" "2. Arcade"
printf "%s\n" "3. RPG"
printf "%s\n" "4. RPG (Infocom A-Jo)" #1-12
printf "%s\n" "5. RPG (Infocom Le-St)" #13-24
printf "%s\n" "6. RPG (Infocom Su-Zo)" #25-36
printf "%s\n" "7. RPG (Infocom ZZinvisiclues)" #37-45
read -p "Enter Number: " GENRE
 if [ $GENRE = 1 ]
 then
 # Menu for First Person Shooters
 clear
 printf "%s\n" "First Person Shooter Menu"
 printf "%s\n"
 printf "%s\n" "1. DOOM"
 printf "%s\n" "2. DOOM II"
 printf "%s\n" "3. Final DOOM (TNT)"
 printf "%s\n" "4. Final DOOM (Plutonia)"
 printf "%s\n" "5. Quake"
 printf "%s\n" "6. Duke Nukem 3D Atomic Edition"
 printf "%s\n" "7. Heretic"
 printf "%s\n" "8. Hexen"
 printf "%s\n" "9. Shadow Warrior"
 read -p "Enter Number: " FPSGAME
  # FPSGAME Choices
  if [ $FPSGAME = 1 ]
  then
    cd /mnt/mmcblk0p1/BKUP/Games/doom/prboom/
    ./prboom
  elif [ $FPSGAME = 2 ]
  then
    cd /mnt/mmcblk0p1/BKUP/Games/doom2/prboom/
    ./prboom
  elif [ $FPSGAME = 3 ]
  then
    cd /mnt/mmcblk0p1/BKUP/Games/tnt/prboom/
    ./prboom
  elif [ $FPSGAME = 4 ]
  then
    cd /mnt/mmcblk0p1/BKUP/Games/plutonia/prboom/
    ./prboom
  elif [ $FPSGAME = 5 ]
  then
    cd /mnt/mmcblk0p1/BKUP/Games/sdlquake/
    ./sdlquake
  elif [ $FPSGAME = 6 ]
  then
    cd /mnt/mmcblk0p1/BKUP/Games/eduke32/
    ./eduke32
  elif [ $FPSGAME = 7 ]
  then
    cd /mnt/mmcblk0p1/BKUP/Games/hheritic-0.2.0-src/
    ./hheretic-sdl
  elif [ $FPSGAME = 8 ]
  then
  cd /mnt/mmcblk0p1/BKUP/Games/hhexen-1.6.0/
  ./hhexen-sdl
  elif [ $FPSGAME = 9 ]
  then
  cd /mnt/mmcblk0p1/BKUP/Games/Shadow_Warrior/
  ./sw
  else
    printf "%s\n" "Oops! Unknown Selection."
  fi

 elif [ $GENRE = 2 ]
 then
 # Menu for Arcade
 clear
 printf "%s\n" "Arcade Menu"
 printf "%s\n"
 printf "%s\n" "1. ASCII Portal"
 printf "%s\n" "2. Dave Gnukem"
 printf "%s\n" "3. Open Liero"
 printf "%s\n" "4. Open Tyrian"
 printf "%s\n" "5. PowerManga"
 printf "%s\n" "6. Asteroids"
 printf "%s\n" "7. Spout"
 printf "%s\n" "8. TCGS Car"
 read -p "Enter Number: " ARCGAME
  # ARCGAME Choices
  if [ $ARCGAME = 1 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/asciiportal/
   ./asciiportal
  elif [ $ARCGAME = 2 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/DaveGnukem/
   ./davegnukem.dge
  elif [ $ARCGAME = 3 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/openliero/
   ./liero1.34
  elif [ $ARCGAME = 4 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/opentyrian
   ./opentyrian.dge
  elif [ $ARCGAME = 5 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/powermanga
   ./powermanga
  elif [ $ARCGAME = 6 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/sdlroids
   ./sdlroids
  elif [ $ARCGAME = 7 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/spout/
   ./spout
  elif [ $ARCGAME = 8 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/tcgs_car/
   ./tcgs_Car
  else
   printf "%s\n" "Oops! Unknown Selection."
  fi

 elif [ $GENRE = 3 ]
 then
 # Menu for RPG
 clear
 printf "%s\n" "RPG Menu"
 printf "%s\n"
 printf "%s\n" "1. Meritous"
 printf "%s\n" "2. Nethack"
 printf "%s\n" "3. Powder"
 read -p "Enter Number: " RPGGAME
  # RPGGAME Choices
  if [ $RPGGAME = 1 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/meritous/
   ./meritous.dge
  elif [ $RPGGAME = 2 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/nethack-3.4.3-nanonote-bin/
   ./nethack
  elif [ $RPGGAME = 3 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/powder
   ./powder
  else
   printf "%s\n" "Oops! Unknown Selection."
  fi

 elif [ $GENRE = 4 ]
 then
 # Menu for RPG (Infocom A-Jo)
 clear
 printf "%s\n" "RPG {Infocom A-Jo) Menu"
 printf "%s\n"
 printf "%s\n" "1. A Mind Forever Voyaging (1985)"
 printf "%s\n" "2. Arthur (1989)"
 printf "%s\n" "3. Ballyhoo (1986)"
 printf "%s\n" "4. Beyond Zork: The Coconut of Quendor (1987)"
 printf "%s\n" "5. Border Zone (1987)"
 printf "%s\n" "6. Bureaucracy (1987)"
 printf "%s\n" "7. Cutthroats (1984)"
 printf "%s\n" "8. Deadline (1982)"
 printf "%s\n" "9. Enchanter (1983)"
 printf "%s\n" "10. Hollywood Hijinx (1986)"
 printf "%s\n" "11. Infidel (1983)"
 printf "%s\n" "12. Journey (1989)"
 read -p "Enter Number: " INFOAJGAME
  # INFOAJGAME Choices
  if [ $INFOAJGAME = 1 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   ./frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/A_Mind_Forever_Voyaging/Amfv.z4
  elif [ $INFOAJGAME = 2 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   ./frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Arthur/ARTHUR.Z6
  elif [ $INFOAJGAME = 3 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   ./frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Ballyhoo/Ballyhoo.z3
  elif [ $INFOAJGAME = 4 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   ./frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Beyond_Zork_The_Coconut_of_Quendor/BeyondZo.z5
  elif [ $INFOAJGAME = 5 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   ./frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Border_Zone/Borderzo.z5
  elif [ $INFOAJGAME = 6 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   ./frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Bureaucracy/BureaucrPATCHED.z4
  elif [ $INFOAJGAME = 7 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   ./frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Cutthroats/Cutthroa.z3
  elif [ $INFOAJGAME = 8 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   ./frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Deadline/Deadline.z3
  elif [ $INFOAJGAME = 9 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   ./frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Enchanter/Enchante.z3
  elif [ $INFOAJGAME = 10 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   ./frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Hollywood_Hijinx/Hollywoo.z3
  elif [ $INFOAJGAME = 11 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   ./frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Infidel/Infidel.z3
  elif [ $INFOAJGAME = 12 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   ./frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Journey/Journey.z6
  else
   printf "%s\n" "Oops! Unknown Selection."
  fi

 elif [ $GENRE = 5 ]
 then
 # Menu for RPG (Infocom Le-St)
 clear
 printf "%s\n" "RPG {Infocom Le-St) Menu"
 printf "%s\n"
 printf "%s\n" "1. Leather Goddesses of Phobos (1986)"
 printf "%s\n" "2. Moonmist (1986)"
 printf "%s\n" "3. Nord and Bert Couldn't Make Head or Tail of It (1987)"
 printf "%s\n" "4. Planetfall (1983)"
 printf "%s\n" "5. Plundered Hearts (1987)"
 printf "%s\n" "6. Seastalker (1984)"
 printf "%s\n" "7. Sherlock: The Riddle of the Crown Jewels (1987)"
 printf "%s\n" "8. Shogun (1988)"
 printf "%s\n" "9. Sorcerer (1984)"
 printf "%s\n" "10. Spellbreaker (1985)"
 printf "%s\n" "11. Starcross (1982)"
 printf "%s\n" "12. Stationfall (1987)"
 read -p "Enter Number: " INFOLSGAME
  # INFOLSGAME Choices
  if [ $INFOLSGAME = 1 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Leather_Goddesses_of_Phobos/Leather.z3
  if [ $INFOLSGAME = 2 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Moonmist/Moonmist.z3
  if [ $INFOLSGAME = 3 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Nord_and_Bert_Couldnt_Make_Head_or_Tail_of_It/Nordandb.z4
  if [ $INFOLSGAME = 4 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Planetfall/Planetfa.z3
  if [ $INFOLSGAME = 5 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Plundered_Hearts/Plundere.z3
  if [ $INFOLSGAME = 6 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Seastalker/Seastalk.z3
  if [ $INFOLSGAME = 7 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Sherlock_The_Riddle_of_the_Crown_Jewels/Sherlock.z5
  if [ $INFOLSGAME = 8 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Shogun/Shogun.z6
  if [ $INFOLSGAME = 9 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Sorcerer/Sorcerer.z3
  if [ $INFOLSGAME = 10 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Spellbreaker/Spellbre.z3
  if [ $INFOLSGAME = 11 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Starcross/Starcros.z3
  if [ $INFOLSGAME = 12 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Stationfall/Stationf.z3
  else
   printf "%s\n" "Oops! Unknown Selection."
  fi

 elif [ $GENRE = 6 ]
 then
 # Menu for RPG (Infocom Su-Zo)
 clear
 printf "%s\n" "RPG (Infocom Su-Zo) Menu"
 printf "%s\n"
 printf "%s\n" "1. Suspect (1984)"
 printf "%s\n" "2. Suspended (1983)"
 printf "%s\n" "3. The Hitchhikers Guide To The Galaxy (1987)"
 printf "%s\n" "4. The Lurking Horror (1984)"
 printf "%s\n" "5. The Witness (1982)"
 printf "%s\n" "6. Trinity (1986)"
 printf "%s\n" "7. Wishbringer (1985)"
 printf "%s\n" "8. Zork 1: The Great Underground Empire (1981)"
 printf "%s\n" "9. Zork 2: The Wizard of Frobozz (1981)"
 printf "%s\n" "10. Zork 3: The Dungeon Master (1982)"
 printf "%s\n" "11. Zork: The Undiscovered Underground (1997)"
 printf "%s\n" "12. Zork Zero: The Revenge of Megaboz (1988)"
 read -p "Enter Number: " INFOSZGAME
  # INFOSZGAME Choices
  if [ $INFOSZGAME = 1 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Suspect/Suspect.z3
  if [ $INFOSZGAME = 2 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Suspended/Suspend.z3
  if [ $INFOSZGAME = 3 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/The_Hitchhikers_Guide_To_The_Galaxy/Hitchhik.z5
  if [ $INFOSZGAME = 4 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/The_Lurking_Horror/Lurking.z3
  if [ $INFOSZGAME = 5 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/The_Witness/Witness.z3
  if [ $INFOSZGAME = 6 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Trinity/Trinity.z4
  if [ $INFOSZGAME = 7 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Wishbringer/Wishbrin.z3
  if [ $INFOSZGAME = 8 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Zork_1_The_Great_Underground_Empire/Zork1.z3
  if [ $INFOSZGAME = 9 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Zork_2_The_Wizard_of_Frobozz/Zork2.z3
  if [ $INFOSZGAME = 10 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Zork_3_The_Dungeon_Master/Zork3.z3
  if [ $INFOSZGAME = 11 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Zork_The_Undiscovered_Underground/ZTUU.Z5
  if [ $INFOSZGAME = 12 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Zork_Zero_The_Revenge_of_Megaboz/Zork0.z6
  else
   printf "%s\n" "Oops! Unknown Selection."
  fi

 elif [ $GENRE = 7 ]
 then
 # Menu for RPG (Infocom ZZinvisiclues)
 clear
 printf "%s\n" "RPG (Infocom ZZinvisiclues) Menu"
 printf "%s\n"
 printf "%s\n" "1. advntizm"
 printf "%s\n" "2. comdyizm"
 printf "%s\n" "3. diversizm"
 printf "%s\n" "4. fant1izm"
 printf "%s\n" "5. fant2izm"
 printf "%s\n" "6. hitchhik"
 printf "%s\n" "7. mystizm"
 printf "%s\n" "8. scifizm"
 read -p "Enter Number: " INFOZZGAME
  # INFOZZGAME Choices
  if [ $INFOZZGAME = 1 ]
   then
  cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/zzInvisiclues/advntizm.z5
  if [ $INFOZZGAME = 2 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/zzInvisiclues/comdyizm.z5
  if [ $INFOZZGAME = 3 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/zzInvisiclues/diversizm.z5
  if [ $INFOZZGAME = 4 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/zzInvisiclues/fant1izm.z5
  if [ $INFOZZGAME = 5 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/zzInvisiclues/fant2izm.z5
  if [ $INFOZZGAME = 6 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/zzInvisiclues/hitchhik.z5
  if [ $INFOZZGAME = 7 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/zzInvisiclues/mystizm.z5
  if [ $INFOZZGAME = 8 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/zzInvisiclues/scifizm.z5
  else
   printf "%s\n" "Oops! Unknown Selection."
  fi

fi
</code>```

答:
You must end all if statements with a fi. Seems to me that you might want an elif instead of if there where it says if [ $INFOLSGAME = 2 ], and also for subsequent alternatives. A switch statement might be better suited for this type of situation.

```<code>  # INFOLSGAME Choices
  if [ $INFOLSGAME = 1 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Leather_Goddesses_of_Phobos/Leather.z3
  if [ $INFOLSGAME = 2 ]
  then
    ...
</code>```

Body:
You must end all if statements with a fi. Seems to me that you might want an elif instead of if there where it says if [ $INFOLSGAME = 2 ], and also for subsequent alternatives. A switch statement might be better suited for this type of situation.

  # INFOLSGAME Choices
  if [ $INFOLSGAME = 1 ]
  then
   cd /mnt/mmcblk0p1/BKUP/Games/frotz/
   .frotz /mnt/mmcblk0p1/BKUP/Games/frotz/infocom/Leather_Goddesses_of_Phobos/Leather.z3
  if [ $INFOLSGAME = 2 ]
  then
    ...


问:
MustacheJS - access value by property as index
Scope :

```<code>let bases = [{id: "51667c34ed4dd", name: "CAYENNE", sort: 1}, {id: "516682b6a160e", name: "FORT DE FRANCE", sort: 2}, {id: "516682c230fbb", name: "POINT A PITRE", sort: 3}];
let filters = {bases: {51667c34ed4dd: true, 516682b6a160e: false, 516682c230fbb: true}, aircrafts: {}};
let set = {bases, filters};
</code>```

Template :

```<code>{{#bases}}
    <input type="checkbox" class="base_checkbox" value="1" id="{{id}}" name="{{name}}" {{(if checked)}}checked="checked"{{/(if checked)}}>
{{/bases}}
</code>```

Usage :

```<code>Mustache.render(template, set);
</code>```

In {{#bases}} loop, how can i access another external object value with current scope property as key ?

like : {{filters.bases {{id}} }} where {{id}} is the property of current object in loop.

答:
Resolved with :

```<code>bases.forEach(b => {
    b.checked = () => {
        return filters["bases"][b.id];
    }
});
</code>```

Mustache use the function returned value as variable.

Body:
Scope :

let bases = [{id: "51667c34ed4dd", name: "CAYENNE", sort: 1}, {id: "516682b6a160e", name: "FORT DE FRANCE", sort: 2}, {id: "516682c230fbb", name: "POINT A PITRE", sort: 3}];
let filters = {bases: {51667c34ed4dd: true, 516682b6a160e: false, 516682c230fbb: true}, aircrafts: {}};
let set = {bases, filters};

Template :

{{#bases}}
    <input type="checkbox" class="base_checkbox" value="1" id="{{id}}" name="{{name}}" {{(if checked)}}checked="checked"{{/(if checked)}}>
{{/bases}}

Usage :

Mustache.render(template, set);

In {{#bases}} loop, how can i access another external object value with current scope property as key ?

like : {{filters.bases {{id}} }} where {{id}} is the property of current object in loop.

Body:
Resolved with :

bases.forEach(b => {
    b.checked = () => {
        return filters["bases"][b.id];
    }
});

Mustache use the function returned value as variable.


答:
You need a return outside of the if statements, or to remove one of your cases and use it as default. For example, if we were to us adult as default we would do something like this: </p>

```<code> public static string ReturnAgeGroup(int age)
 {
     if (age >= 65)
     {
         return "senior citizen";
     }
     if (age < 21)
     {
         return "minor";
     }
     return "adult";
  }
</code>```

Title: Program Flow C#

Body:
I am learning C# at the moment. In the example below, I believe I have the correct code but there must be an error or two (maybe more) somewhere. Please see the code below:

    public static string ReturnAgeGroup(int age)
    {
        if (age >= 65)
        {
            return "senior citizen";
        }
        if (age < 21)
        {
            return "minor";
        }
        if (age >= 21 & age < 65)
        {
            return "adult";
        }
    }

There is a red squiggly line underneath RetrunAgeGroup, which says not all code paths return a value when I hover over it. Why is this? Every possibility, regarding age, is covered by the conditions.

Is/are there any other error(s) that I have failed to identify?

Regards

Body:
You need a return outside of the if statements, or to remove one of your cases and use it as default. For example, if we were to us adult as default we would do something like this:

 public static string ReturnAgeGroup(int age)
 {
     if (age >= 65)
     {
         return "senior citizen";
     }
     if (age < 21)
     {
         return "minor";
     }
     return "adult";
  }


问:
Using Cassandra for Message Archive Management (mod_mam) database in Ejabberd 16.09
I'm trying to use Cassandra for mod_mam in Ejabberd 16.09. Does that version of Ejabberd support Cassandra? If it does, how to configure Ejabberd to use Cassandra?

Also, I found some Erlang-Cassandra driver such as Cqerl, Erlcass, and Erlang-cassandra-cql. Can I use them to connect Ejabberd and Cassandra?

答:
ejabberd doesn't support Cassandra as a database backend. The only available backends at the moment are: internal (i.e. Mnesia), Riak, MySQL, PostgreSQL, MS SQL, sqlite and other ODBC compatible databases.
Of course you can use mentioned Erlang drivers, but this will not be very easy to write a new database backend using them: some experience in Erlang and ejabberd is required.</p>


问:
What happens if the amount of characters that are entered into your character array is less than the amount of spaces you specified
```<code>char ch_arry[20] = { S, A, L, L, Y};
printf( "%s", ch_arry[] );
</code>```

Will it fill the end of the array with null characters?

答:
From the C Standard (6.7.9 Initialization)

19 The initialization shall occur in initializer list order, each
  initializer provided for a particular subobject overriding any
  previously listed initializer for the same subobject;151) all
  subobjects that are not initialized explicitly shall be initialized
  implicitly the same as objects that have static storage duration.

And

10 If an object that has automatic storage duration is not initialized
  explicitly, its value is indeterminate. If an object that has static
  or thread storage duration is not initialized explicitly, then:

— if it has pointer type, it is initialized to a null pointer;

— if it has arithmetic type, it is initialized to (positive or
  unsigned) zero;

— if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero
  bits;

So if you have a declaration like this

```<code>char ch_arry[20] = { 'S', 'A', 'L', 'L', 'Y'};
</code>```

then all elements of the array that are not initialized explicitly will be initialized implicitly with zeroes.

Body:
char ch_arry[20] = { S, A, L, L, Y};
printf( "%s", ch_arry[] );

Will it fill the end of the array with null characters?

Body:
From the C Standard (6.7.9 Initialization)

19 The initialization shall occur in initializer list order, each
  initializer provided for a particular subobject overriding any
  previously listed initializer for the same subobject;151) all
  subobjects that are not initialized explicitly shall be initialized
  implicitly the same as objects that have static storage duration.

And

10 If an object that has automatic storage duration is not initialized
  explicitly, its value is indeterminate. If an object that has static
  or thread storage duration is not initialized explicitly, then:

— if it has pointer type, it is initialized to a null pointer;

— if it has arithmetic type, it is initialized to (positive or
  unsigned) zero;

— if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero
  bits;

So if you have a declaration like this

char ch_arry[20] = { 'S', 'A', 'L', 'L', 'Y'};

then all elements of the array that are not initialized explicitly will be initialized implicitly with zeroes.


问:
Generating pdf using phpexcel
I am creating pdf file by using phpExcel and I have 24 columns in the data from the database and only 17 columns are in the pdf and remaining is cut off.Is there any way to have all 24 columns in the pdf file?How can I achieve it?</p>

答: I set page orientation to landscape. Unfortunately, it was the only solution I could found.</p>

Title: Generating pdf using phpexcel


问:
Return Maximum Value along with day + time value grouped by month
Using MS-SQL 2012. Having a real puzzle trying to retrieve specific datafields from a large climatology dataset.

I have stripped this large raw data file down to a temp table called #max_temp which correctly pulls back the max value for each day along with the time it occurred and day/month value for reference:

```<code>monthid month   day time    current_temp
1       12     24   12:45   9.1
1       12     25   12:25   8.3
1       12     26   23:55   8.6
1       12     27   00:00   8.6
1       12     28   13:15   5.9
1       12     29   12:50   5
1       12     30   13:32   6.3
1       12     31   12:49   6.9
2        1      1   23:59   12
2        1      2   01:12   12.7
2        1      3   03:55   6.2
</code>```

What I want to retrieve is an output grouped by monthID, so returning:

```<code>monthid     month   day time    current_temp
    1       12      24  12:45   9.1
    2       1       9   20:04   15.1  <<*not shown in above sample*>>
</code>```

From looking at other similar questions I have tried the following the code but not getting to the end solution or the query fails.

```<code>select *
from (select t.*, ROW_NUMBER () over (partition by t.monthid, t.time order by t.current_temp desc) as rn
from #max_temp t) x
where rn=1
order by monthid asc
</code>```

or

```<code>select monthid, day, time, current_temp
from #max_temp
where current_temp= (select max(current_temp) from #max_temp group by MonthID, day, time)
</code>```

Thanks in advance for your help,
Elliot.

答:
Remove t.time from the partition by like so:

```<code>select *
from (
  select t.*, ROW_NUMBER () over (partition by t.monthid order by t.current_temp desc) as rn
  from #max_temp t
  ) x
where rn=1
order by monthid asc
</code>```

Having time in the partition would give you the greatest value for current_temp for each monthid and time, but since you just want the greatest current_temp for each monthid, remove time from that expression.

Body:
Using MS-SQL 2012. Having a real puzzle trying to retrieve specific datafields from a large climatology dataset.

I have stripped this large raw data file down to a temp table called #max_temp which correctly pulls back the max value for each day along with the time it occurred and day/month value for reference:

monthid month   day time    current_temp
1       12     24   12:45   9.1
1       12     25   12:25   8.3
1       12     26   23:55   8.6
1       12     27   00:00   8.6
1       12     28   13:15   5.9
1       12     29   12:50   5
1       12     30   13:32   6.3
1       12     31   12:49   6.9
2        1      1   23:59   12
2        1      2   01:12   12.7
2        1      3   03:55   6.2

What I want to retrieve is an output grouped by monthID, so returning:

monthid     month   day time    current_temp
    1       12      24  12:45   9.1
    2       1       9   20:04   15.1  <<*not shown in above sample*>>

From looking at other similar questions I have tried the following the code but not getting to the end solution or the query fails.

select *
from (select t.*, ROW_NUMBER () over (partition by t.monthid, t.time order by t.current_temp desc) as rn
from #max_temp t) x
where rn=1
order by monthid asc

or

select monthid, day, time, current_temp
from #max_temp
where current_temp= (select max(current_temp) from #max_temp group by MonthID, day, time)

Thanks in advance for your help,
Elliot.

Body:
Remove t.time from the partition by like so:

select *
from (
  select t.*, ROW_NUMBER () over (partition by t.monthid order by t.current_temp desc) as rn
  from #max_temp t
  ) x
where rn=1
order by monthid asc

Having time in the partition would give you the greatest value for current_temp for each monthid and time, but since you just want the greatest current_temp for each monthid, remove time from that expression.


问:
webpack babel jsnext:main and dependencies transpiling
I opened the following issues last week but nobody seem to know the answer:

github.com/babel/babel-loader/issues/488

github.com/webpack/webpack/issues/2902

I really do not understand what's the current status in webpack / babel-loader in transpiling dependencies in node_modules, can anyone please clarify? I tried to stick to every issue opened everywhere.

Is webpack / babel-loader transpiling jsnext:main file?

If yes, is webpack / babel-loader transpiling jsnext:main file in node_modules even if node_modules is in exclude key?

My situation:

```<code>rules: [{
    test: /\.(js|mjs)$/i,
    exclude: [/node_modules/],
    use: [{
        loader: 'babel-loader', //settings specified in package.json
    },{
        loader: 'eslint-loader', //settings specified in package.json
    }
}]
</code>```

In my dependency package.json I tried:

```<code>"main": "index.js", <= not working (not transpiled)
"jsnext:main": "index.js", <= not working (not transpiled)
"module": "index.js", <= not working (not transpiled)
</code>```

Neither is working without removing exclude: [/node_modules/], but this can't be used in any medium-to-big sized project because of infinite compilation times.

But then: why is https://github.com/lodash/lodash/blob/es/package.json any different from my https://github.com/damianobarbati/react-create-app/blob/master/package.json?
lodash-es is getting transpiled even being in node_modules (and excluded) but my react-create-app is not: HELP!

答:
The babel-loader is not transpiling anything in node_modules when you exclude node_modules from the rule. The fields like jsnext:main or module have nothing to do with loaders/rules. When a package is imported, webpack decides what file it should use based on resolve.mainFields and then it will check which rules it should apply to that file. Usually these files are already transpiled, except that they contain ES modules (see Rollup - pkg.module).

If you want to transpile any module that has a module or jsnext:main field, you could use the rule from Jason Miller developit/transpile-esnext-modules.js which determines whether the module should be included or not (include and exclude also accept a function).

Body:
I opened the following issues last week but nobody seem to know the answer:

github.com/babel/babel-loader/issues/488

github.com/webpack/webpack/issues/2902

I really do not understand what's the current status in webpack / babel-loader in transpiling dependencies in node_modules, can anyone please clarify? I tried to stick to every issue opened everywhere.

Is webpack / babel-loader transpiling jsnext:main file?

If yes, is webpack / babel-loader transpiling jsnext:main file in node_modules even if node_modules is in exclude key?

My situation:

rules: [{
    test: /\.(js|mjs)$/i,
    exclude: [/node_modules/],
    use: [{
        loader: 'babel-loader', //settings specified in package.json
    },{
        loader: 'eslint-loader', //settings specified in package.json
    }
}]

In my dependency package.json I tried:

"main": "index.js", <= not working (not transpiled)
"jsnext:main": "index.js", <= not working (not transpiled)
"module": "index.js", <= not working (not transpiled)

Neither is working without removing exclude: [/node_modules/], but this can't be used in any medium-to-big sized project because of infinite compilation times.

But then: why is https://github.com/lodash/lodash/blob/es/package.json any different from my https://github.com/damianobarbati/react-create-app/blob/master/package.json?
lodash-es is getting transpiled even being in node_modules (and excluded) but my react-create-app is not: HELP!


问:
regex capture lines before certain keywords that may or may not be present
```<code>Changeset: 8675309
User: DOMAIN\JohnG
Date: 01/21/2004 21:03:45
Comment:  This check-in fixes issues in several features.  I also refactored some items in buf.c into a new file named bif.c because buf.c was too hard to parse.
Items:
   $/baz/proj/bif.c           Added
   $/baz/proj/buf.c          Modified, Renamed
Work Items:
   34527     The "Access Denied" message is not descriptive enough.
   35628     The UI flickers when I press the '8', 'y', 'Ctrl', and 'End' buttons at the same time.
Check-in Notes:
   Code Reviewer:  ShellM
   Performance Reviewer: ShellM
   Security Reviewer: ShellM
</code>```

I want to capture the two lines under Items. However Work Items may sometimes be missing, so Check-in Notes: would be where i stopped, and then sometimes BOTH would be missing so I would need to stop at the end of the string.

```<code>(?s)(?<=Items:).*(?(?=Work Items:)|(?=Check-in Notes:))
</code>```

this is what I have and it captures everything UP TO check-in notes which is wrong.

答:
```<code>([\s\S]*\nItems:\n)([\s\S]*?)(\nWork Items:\n[\s\S]*)?\z
</code>```

This seems to work. Your items should be placed in group 2.

([\s\S]*\nItems:\n) this tells the regex to start with "Items:"

([\s\S]*?) this means take characters, but a less as possible (non greedy)

(\nWork Items:\n[\s\S]*)?\z This tells the regex to fill the third group with "Work Items", if possible.

This leaves your second group with either

everything from "Items:" to EOF, or

everything from "Items:" to "Work Items:" (exclusive)

The keypoints are that the second group (your items) is not greedy and the third group is optional.  Meaning it will always try to match the third group, but fall back to take everything that remains.

EDIT:

After trying this in .Net the regex above did not work. But with small adjustments (like allowing for Win and *nix style line endings) it worked.

```<code>var pattern = @"((\n|\r|\r\n)Items:(\n|\r|\r\n))(?<Items>[\s\S]*?)((\n |\r |\r\n)Work Items:(\n |\r |\r\n)[\s\S]*)?\z";
var regex = new Regex(pattern);

var match = regex.Match(YOUR_FILE_HERE);
var items = match.Groups["Items"].Value;
</code>```

Body:
Changeset: 8675309
User: DOMAIN\JohnG
Date: 01/21/2004 21:03:45
Comment:  This check-in fixes issues in several features.  I also refactored some items in buf.c into a new file named bif.c because buf.c was too hard to parse.
Items:
   $/baz/proj/bif.c           Added
   $/baz/proj/buf.c          Modified, Renamed
Work Items:
   34527     The "Access Denied" message is not descriptive enough.
   35628     The UI flickers when I press the '8', 'y', 'Ctrl', and 'End' buttons at the same time.
Check-in Notes:
   Code Reviewer:  ShellM
   Performance Reviewer: ShellM
   Security Reviewer: ShellM

I want to capture the two lines under Items. However Work Items may sometimes be missing, so Check-in Notes: would be where i stopped, and then sometimes BOTH would be missing so I would need to stop at the end of the string.

(?s)(?<=Items:).*(?(?=Work Items:)|(?=Check-in Notes:))

this is what I have and it captures everything UP TO check-in notes which is wrong.

Body:
([\s\S]*\nItems:\n)([\s\S]*?)(\nWork Items:\n[\s\S]*)?\z

This seems to work. Your items should be placed in group 2.

([\s\S]*\nItems:\n) this tells the regex to start with "Items:"

([\s\S]*?) this means take characters, but a less as possible (non greedy)

(\nWork Items:\n[\s\S]*)?\z This tells the regex to fill the third group with "Work Items", if possible.

This leaves your second group with either

everything from "Items:" to EOF, or

everything from "Items:" to "Work Items:" (exclusive)

The keypoints are that the second group (your items) is not greedy and the third group is optional.  Meaning it will always try to match the third group, but fall back to take everything that remains.

EDIT:

After trying this in .Net the regex above did not work. But with small adjustments (like allowing for Win and *nix style line endings) it worked.

var pattern = @"((\n|\r|\r\n)Items:(\n|\r|\r\n))(?<Items>[\s\S]*?)((\n |\r |\r\n)Work Items:(\n |\r |\r\n)[\s\S]*)?\z";
var regex = new Regex(pattern);

var match = regex.Match(YOUR_FILE_HERE);
var items = match.Groups["Items"].Value;


问:
How to covert Immutable js Data Structure to an use case array without using .toJS() in Redux?
In am new to Redux+Immutable js I found Some performance issue with toJS method But In my use case I could not find any alternatives. So How to convert a List to Array of Objects.

My initialState

```<code>const initialState = fromJS({
   postArr:[]
});
</code>```

And I am also using SSR so my window.State will coverted to Immutable data structure

```<code>const initialState = window.__STATE__;

// Transform into Immutable.js collections,
// but leave top level keys untouched for Redux
Object
    .keys(initialState)
    .forEach(key => {
        initialState[key] = fromJS(initialState[key]);
    });
</code>```

Configure Store

```<code>import {combineReducers} from 'redux';
import {routerReducer} from 'react-router-redux';

import allPosts from './allPosts'

export default combineReducers({
    allPosts,

    //ForServerSide
    routing: routerReducer
})
</code>```

This is my Component Based Use Case

```<code>const mapStateToProps = (state) => {
    return{
        posts:state.allPosts.get('postArr')
    }
};

const mapDispatchToProps = (dispatch) => {
    return {
        getAllPosts:() => dispatch(allPosts.getAllPosts())
    }
};

@connect(mapStateToProps,mapDispatchToProps)
</code>```

But this.props.post Still Looking Like Immutable Structure But How to use it sorry for Poor console.log presentation But I wanna to show

```<code>List {size: 100, _origin: 0, _capacity: 100, _level: 5, _root: VNode…}
size
:
100
__altered
:
true
__hash
:
undefined
__ownerID
:
undefined
_capacity
:
100
_level
:
5
_origin
:
0
_root
:
VNode
_tail
:
VNode
__proto__
:
IndexedIterable
</code>```

答:
It doesn't directly answer your question, but it sounds like you're asking this question because you're unaware of how to make Redux and ImmutableJs play nicely together:

```<code>// Transform into Immutable.js collections,
// but leave top level keys untouched for Redux
</code>```

There is a library called redux-immutable which I use on my projects which allows you to manage your entire state as an ImmutableJS object:

redux-immutable is used to create an equivalent function of Redux
  combineReducers that works with Immutable.js state.

When Redux createStore reducer is created using redux-immutable then
  initialState must be an instance of Immutable.Collection.

https://www.npmjs.com/package/redux-immutable

Body:
In am new to Redux+Immutable js I found Some performance issue with toJS method But In my use case I could not find any alternatives. So How to convert a List to Array of Objects.

My initialState

const initialState = fromJS({
   postArr:[]
});

And I am also using SSR so my window.State will coverted to Immutable data structure

const initialState = window.__STATE__;

// Transform into Immutable.js collections,
// but leave top level keys untouched for Redux
Object
    .keys(initialState)
    .forEach(key => {
        initialState[key] = fromJS(initialState[key]);
    });

Configure Store

import {combineReducers} from 'redux';
import {routerReducer} from 'react-router-redux';

import allPosts from './allPosts'

export default combineReducers({
    allPosts,

    //ForServerSide
    routing: routerReducer
})

This is my Component Based Use Case

const mapStateToProps = (state) => {
    return{
        posts:state.allPosts.get('postArr')
    }
};

const mapDispatchToProps = (dispatch) => {
    return {
        getAllPosts:() => dispatch(allPosts.getAllPosts())
    }
};

@connect(mapStateToProps,mapDispatchToProps)

But this.props.post Still Looking Like Immutable Structure But How to use it sorry for Poor console.log presentation But I wanna to show

List {size: 100, _origin: 0, _capacity: 100, _level: 5, _root: VNode…}
size
:
100
__altered
:
true
__hash
:
undefined
__ownerID
:
undefined
_capacity
:
100
_level
:
5
_origin
:
0
_root
:
VNode
_tail
:
VNode
__proto__
:
IndexedIterable

Body:
It doesn't directly answer your question, but it sounds like you're asking this question because you're unaware of how to make Redux and ImmutableJs play nicely together:

// Transform into Immutable.js collections,
// but leave top level keys untouched for Redux

There is a library called redux-immutable which I use on my projects which allows you to manage your entire state as an ImmutableJS object:

redux-immutable is used to create an equivalent function of Redux
  combineReducers that works with Immutable.js state.

When Redux createStore reducer is created using redux-immutable then
  initialState must be an instance of Immutable.Collection.

https://www.npmjs.com/package/redux-immutable