问:
How to databind a dropdownlist at page load
Assuming i have two dropdownlists namely: dropdownlistA and dropdownlistB. at page load, i bind values to dropdownlistA. however, depending on the value selected or displayed in dropdownlistA, i want to bind data to dropdownlistB.

Currently, i can bind data to dropdownlistA alright and i already have the required dataset and datatable bind data to dropdownlist. However, dropdownlistB does not bind at page load since the criteria for filling the dataset to bind dropdownlistB (which is the value of dropdownlistA) is not selected. how can i make this wwork.

I am currently considered if this might work. If i were to call the databind for dropdownlistA in a different declared method besides its binding in page load, and select the value from bind in the declared method, would any value be selected?

For example:
  In during page load, i call the a method that returns dataset values which i bind to dropdownlistA(caseIDDropDownList). then i call another method (CreateexhibitDataSet()) which contains the dataset values for binding dropdownlistB(exhibitDropDownList). however, i need to define a criteria in the CreateExhibitDataset() method which i will use to generate the dataset values to bind dropdownlistB. if i were to call for the data bind of dropdownlistA(caseIDDropdownList) again in the CreateExhibitDataset() method and pick the value in the dropdown list, would i get any values?

How can i work around this to bind both dropdownlists on page load?

```<code>protected void Page_Load(object sender, EventArgs e)
    {
        //mgrID = "M510";
        //mgrID = Request.QueryString["mgrID"];
        mgrID = (string)(Session["userID"]);

        if (mgrID != null)
        {
            if (!IsPostBack)
            {
                CreateCasesDataset();
                DataView caseDataView = new DataView(caseDataSet.Tables[0]);
                caseIDDropDownList.DataSource = caseDataView;
                caseIDDropDownList.DataTextField = "CaseID";
                caseIDDropDownList.DataBind();

                CreateExhibitDataset();

                DataView exhibDataView = new DataView(exhibitDataSet.Tables[0]);
                exhibitsDropDownList.DataSource = exhibDataView;
                exhibitsDropDownList.DataTextField = "ExhibitID";
                exhibitsDropDownList.DataBind();
            }
        }
        else
        {
            string message = "The System couldnt identify you with any ID. Please Log in to access system functions";
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<script type = 'text/javascript'>");
            sb.Append("window.onload=function(){");
            sb.Append("alert('");
            sb.Append(message);
            sb.Append("')};");
            sb.Append("</script>");
            ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
        }

    }
</code>```

And this is the additional code of the CreateExhibitMethod

```<code>private void CreateExhibitDataset()
    {
        caseIDDropDownList.DataBind();
        string selectedCaseID = caseIDDropDownList.SelectedValue.ToString();

        SqlConnection exhibitConnection = new SqlConnection(strConn);
        exhibitSqlDataAdapter.SelectCommand = new SqlCommand("SELECT ExhibitID FROM Exhibits WHERE CaseID = '"+selectedCaseID+"'", exhibitConnection);
        exhibitSqlDataAdapter.Fill(exhibitDataSet);
    }
</code>```

答:
I think you don't want dropdownlistB to be bound at page load because you do not know which items to bound to.
You can use an asp.UpdatePanel to do this, but this requires you to configure Ajax.
You can also consider jQuery for this:
Bind the change event:

```<code>$(document).ready(function() {
    $('#dropdownlistA').change(getdropdownlistB);
});

 function getdropdownlistB() {
            var ID= $("#getdropdownlistA").attr("value");
 dropdownlistB= $('#dropdownlistB').attr('disabled', true).children('option').remove().end().append('<option value="0">Loading...</option>');

            PageMethod("my.aspx/getdropdownlistBbyID", ["ID", ID], getdropdownlistBResponse)
        }

function PageMethod(wsurl, paramArray, onSuccess) {
            var pagePath = window.location.pathname;
            //Create list of parameters in the form:
            //{"paramName1":"paramValue1","paramName2":"paramValue2"}
            var paramList = '';
            if (paramArray.length > 0) {
                for (var i = 0; i < paramArray.length; i += 2) {
                    if (paramList.length > 0) paramList += ',';
                    paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
                }
            }
            paramList = '{' + paramList + '}';
            //Call the page method
            $.ajax({
                type: "POST",
                url: wsurl,
                contentType: "application/json; charset=utf-8",
                data: paramList,
                dataType: "json",
                async: false,
                success: onSuccess,
                error: function(xhr, status, error) {
                    alert("error")
                }
            });
        }

 function getdropdownlistBResponse(response) {
            var listB= (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
            var dropdownlistB= $('#dropdownlistB');
            dropdownlistB.attr('disabled', false).children('option').remove();
            if (listB.length == 0) { dropdownlistB.attr('disabled', true).append('<option value="0">Select A...</option>'); }
            for (var i = 0; i < listB.length; i++) {
                var val = listB[i].bVal;
                var text = listB[i].bText;
                var def = listB[i].Default;

                dropdownlistB.append('<option value="' + val + '">' + text + '</option>');
                if (def) { dropdownlistB.val(val); } //set the default
            }

        }
</code>```

Then in the ASPX page you get the data for dropdownlistB:

```<code>[WebMethod]
        public static List<listB> getdropdownlistBbyID(string ID)
            //called from script to get the dropdownlistB, using the selection ID from dropdownlistA
        {

           .. Insert code to get your data
            List<listB> blist= new List<listB>() { };
            ...Insert code to fill blist with your data with rows of 3 values {ID, text, default yes/no}

            return blist;
        }
</code>```

Body:
Assuming i have two dropdownlists namely: dropdownlistA and dropdownlistB. at page load, i bind values to dropdownlistA. however, depending on the value selected or displayed in dropdownlistA, i want to bind data to dropdownlistB.

Currently, i can bind data to dropdownlistA alright and i already have the required dataset and datatable bind data to dropdownlist. However, dropdownlistB does not bind at page load since the criteria for filling the dataset to bind dropdownlistB (which is the value of dropdownlistA) is not selected. how can i make this wwork.

I am currently considered if this might work. If i were to call the databind for dropdownlistA in a different declared method besides its binding in page load, and select the value from bind in the declared method, would any value be selected?

For example:
  In during page load, i call the a method that returns dataset values which i bind to dropdownlistA(caseIDDropDownList). then i call another method (CreateexhibitDataSet()) which contains the dataset values for binding dropdownlistB(exhibitDropDownList). however, i need to define a criteria in the CreateExhibitDataset() method which i will use to generate the dataset values to bind dropdownlistB. if i were to call for the data bind of dropdownlistA(caseIDDropdownList) again in the CreateExhibitDataset() method and pick the value in the dropdown list, would i get any values?

How can i work around this to bind both dropdownlists on page load?

protected void Page_Load(object sender, EventArgs e)
    {
        //mgrID = "M510";
        //mgrID = Request.QueryString["mgrID"];
        mgrID = (string)(Session["userID"]);

        if (mgrID != null)
        {
            if (!IsPostBack)
            {
                CreateCasesDataset();
                DataView caseDataView = new DataView(caseDataSet.Tables[0]);
                caseIDDropDownList.DataSource = caseDataView;
                caseIDDropDownList.DataTextField = "CaseID";
                caseIDDropDownList.DataBind();

                CreateExhibitDataset();

                DataView exhibDataView = new DataView(exhibitDataSet.Tables[0]);
                exhibitsDropDownList.DataSource = exhibDataView;
                exhibitsDropDownList.DataTextField = "ExhibitID";
                exhibitsDropDownList.DataBind();
            }
        }
        else
        {
            string message = "The System couldnt identify you with any ID. Please Log in to access system functions";
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("");
            ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
        }

    }

And this is the additional code of the CreateExhibitMethod

private void CreateExhibitDataset()
    {
        caseIDDropDownList.DataBind();
        string selectedCaseID = caseIDDropDownList.SelectedValue.ToString();

        SqlConnection exhibitConnection = new SqlConnection(strConn);
        exhibitSqlDataAdapter.SelectCommand = new SqlCommand("SELECT ExhibitID FROM Exhibits WHERE CaseID = '"+selectedCaseID+"'", exhibitConnection);
        exhibitSqlDataAdapter.Fill(exhibitDataSet);
    }

Body:
I think you don't want dropdownlistB to be bound at page load because you do not know which items to bound to.
You can use an asp.UpdatePanel to do this, but this requires you to configure Ajax.
You can also consider jQuery for this:
Bind the change event:

$(document).ready(function() {
    $('#dropdownlistA').change(getdropdownlistB);
});

 function getdropdownlistB() {
            var ID= $("#getdropdownlistA").attr("value");
 dropdownlistB= $('#dropdownlistB').attr('disabled', true).children('option').remove().end().append('<option value="0">Loading...</option>');

            PageMethod("my.aspx/getdropdownlistBbyID", ["ID", ID], getdropdownlistBResponse)
        }

function PageMethod(wsurl, paramArray, onSuccess) {
            var pagePath = window.location.pathname;
            //Create list of parameters in the form:
            //{"paramName1":"paramValue1","paramName2":"paramValue2"}
            var paramList = '';
            if (paramArray.length > 0) {
                for (var i = 0; i < paramArray.length; i += 2) {
                    if (paramList.length > 0) paramList += ',';
                    paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
                }
            }
            paramList = '{' + paramList + '}';
            //Call the page method
            $.ajax({
                type: "POST",
                url: wsurl,
                contentType: "application/json; charset=utf-8",
                data: paramList,
                dataType: "json",
                async: false,
                success: onSuccess,
                error: function(xhr, status, error) {
                    alert("error")
                }
            });
        }

 function getdropdownlistBResponse(response) {
            var listB= (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
            var dropdownlistB= $('#dropdownlistB');
            dropdownlistB.attr('disabled', false).children('option').remove();
            if (listB.length == 0) { dropdownlistB.attr('disabled', true).append('<option value="0">Select A...</option>'); }
            for (var i = 0; i < listB.length; i++) {
                var val = listB[i].bVal;
                var text = listB[i].bText;
                var def = listB[i].Default;

                dropdownlistB.append('<option value="' + val + '">' + text + '</option>');
                if (def) { dropdownlistB.val(val); } //set the default
            }

        }

Then in the ASPX page you get the data for dropdownlistB:

[WebMethod]
        public static List<listB> getdropdownlistBbyID(string ID)
            //called from script to get the dropdownlistB, using the selection ID from dropdownlistA
        {

           .. Insert code to get your data
            List<listB> blist= new List<listB>() { };
            ...Insert code to fill blist with your data with rows of 3 values {ID, text, default yes/no}

            return blist;
        }


来源: stackexchange

问:
Angularjs : How to display float number to nearst rounded number
I have an angularjs variable bill_amount which store 500.44. How can I display it to 501 without using controller function.
I use{{bill_amount | number: 0}} but it show 500 when the amount is greater than .5 then it adds +1 on the amount but I need to add +1  on the amount if the amount is greater then .0 like if the amount is 500.1 than I want to show 501.

答:
You can create a custom filter to round numbers up:

```<code>angular.module('app').filter('numberCeil', function(){
    return function(value){
        return Math.ceil(value);
    };
});
</code>```

Then use it like a regular filter:

```<code>{{ bill_amount | numberCeil }}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can create a custom filter to round numbers up:

angular.module('app').filter('numberCeil', function(){
    return function(value){
        return Math.ceil(value);
    };
});

Then use it like a regular filter:

{{ bill_amount | numberCeil }}


问:
Reading a string with fgets into a char array from a filestream. [C]
I am trying to make a programm which decrypts a series of letters from a file.
Sadly, I am failing to read the letters into a char array (string) because I do not really know how the fgets() function works.
So my actual code looks like this:

```<code>#define stringlength 80

int main(void)
{
   FILE *source;
   char puffer[stringlength], name[20];

   printf("Which file do you want to read: ");
   scanf("%s",name);
   if( (source=fopen(name,"r")) == NULL)
   {
      fprintf(stderr, "Can not open %s\n", name);
      return EXIT_FAILURE;
   }
   while(fgets(puffer, stringlength, source))
   {
     fputs(puffer, stdout);
   }
   return EXIT_SUCCESS;
}
</code>```

So actually this kinda works. It opens the command prompt and writes the the sequence of letters in that window.
But now I have to use every single letter and compare it with the key's letters.
It just compares the right four bits with a XOR to keep the result letter in the same column of the ASCII chart.
I have already written a algorithm which works for single letters:

```<code>saveLeftFourBits = letterOfFile >> 4;
saveLeftFourBits = saveLeftFourBits << 4;
letterOfFile = letterOfFile & 0x0F;
letterOfKey = letterOfKey & 0x0F;
temp = letterOfFile ^ letterOfKey;
temp |= saveLeftFourBits;
</code>```

temp should be the resulting letter.
So now I am struggling with how to read a single letter from the fgets function into a variable (in letterOfFile) and compare it with the letterOfKey.
Or is there maybe a string-function which does that is a lot easier way?
I hope someone can help me. :)

答:
puffer is where fgets store a line of 80 chars max, including (if size permits) the trailing \n.

To deal with all characters of a line, do a loop from the start of puffer until you reach the end of line, meaning either \0 or \n

```<code>char letterOfKey = '#';     // Define it
char *s;
for(s=puffer ; *s && *s != '\n' ; s++) {
   *s = (*s & 0xF0) | ((*s ^ letterOfKey) & 0x0F);
}
fputs(puffer, stdout);
</code>```

Explanation

s points to the beginning of puffer and is incremented. The loop ends when the character pointed to by s is either 0 or \n. For each character in the line, *s, bitwise operations are done and stored back to *s. And,

(*s & 0xF0) keeps the 4 MSb

| is the bitwise OR

(*s ^ letterOfKey) does an Exclusive OR between the 2 operands

& 0x0F keeps the 4 LSb

See also Bitwise operations in C

Body:
I am trying to make a programm which decrypts a series of letters from a file.
Sadly, I am failing to read the letters into a char array (string) because I do not really know how the fgets() function works.
So my actual code looks like this:

#define stringlength 80

int main(void)
{
   FILE *source;
   char puffer[stringlength], name[20];

   printf("Which file do you want to read: ");
   scanf("%s",name);
   if( (source=fopen(name,"r")) == NULL)
   {
      fprintf(stderr, "Can not open %s\n", name);
      return EXIT_FAILURE;
   }
   while(fgets(puffer, stringlength, source))
   {
     fputs(puffer, stdout);
   }
   return EXIT_SUCCESS;
}

So actually this kinda works. It opens the command prompt and writes the the sequence of letters in that window.
But now I have to use every single letter and compare it with the key's letters.
It just compares the right four bits with a XOR to keep the result letter in the same column of the ASCII chart.
I have already written a algorithm which works for single letters:

saveLeftFourBits = letterOfFile >> 4;
saveLeftFourBits = saveLeftFourBits << 4;
letterOfFile = letterOfFile & 0x0F;
letterOfKey = letterOfKey & 0x0F;
temp = letterOfFile ^ letterOfKey;
temp |= saveLeftFourBits;

temp should be the resulting letter.
So now I am struggling with how to read a single letter from the fgets function into a variable (in letterOfFile) and compare it with the letterOfKey.
Or is there maybe a string-function which does that is a lot easier way?
I hope someone can help me. :)

Body:
puffer is where fgets store a line of 80 chars max, including (if size permits) the trailing \n.

To deal with all characters of a line, do a loop from the start of puffer until you reach the end of line, meaning either \0 or \n

char letterOfKey = '#';     // Define it
char *s;
for(s=puffer ; *s && *s != '\n' ; s++) {
   *s = (*s & 0xF0) | ((*s ^ letterOfKey) & 0x0F);
}
fputs(puffer, stdout);

Explanation

s points to the beginning of puffer and is incremented. The loop ends when the character pointed to by s is either 0 or \n. For each character in the line, *s, bitwise operations are done and stored back to *s. And,

(*s & 0xF0) keeps the 4 MSb

| is the bitwise OR

(*s ^ letterOfKey) does an Exclusive OR between the 2 operands

& 0x0F keeps the 4 LSb

See also Bitwise operations in C


问:
MatLab Quadratic Equation With ln
How to solve the function f(x)=ln(x^2)-0.7=0 with a known Matlab command?

```<code>clc;clear all;close all;

f(x)=ln(x^2)-0.7=0
B=sqrt f(x)
</code>```

答:
Put the following code into a MATLAB script, name it "main.m".

```<code>function b=main
    clc
    x=solveF()
    y=f(x)
    b=sqrt(y)
end

function y=f(x)
    y=log(x^2)-0.7
end

function x=solveF()
    g = @(x) abs(f(x)-0)
    x = fminsearch(g, 1.0)
end
</code>```

Then run it as:

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

You will get the results:

```<code>x =

     1.4190

y =

   -3.4643e-05

b =

    0.0000 + 0.0059i

ans =

    0.0000 + 0.0059i
</code>```

Title: MatLab Quadratic Equation With ln

Body:
How to solve the function f(x)=ln(x^2)-0.7=0 with a known Matlab command?

clc;clear all;close all;

f(x)=ln(x^2)-0.7=0
B=sqrt f(x)

Body:
Put the following code into a MATLAB script, name it "main.m".

function b=main
    clc
    x=solveF()
    y=f(x)
    b=sqrt(y)
end

function y=f(x)
    y=log(x^2)-0.7
end

function x=solveF()
    g = @(x) abs(f(x)-0)
    x = fminsearch(g, 1.0)
end

Then run it as:

main

You will get the results:

x =

     1.4190

y =

   -3.4643e-05

b =

    0.0000 + 0.0059i

ans =

    0.0000 + 0.0059i


问:
Custom URL structure for wordpress custom post type
I have two Custom Post type,

```<code>register_post_type( 'classes',
    array(
        .
        .
        'rewrite'   => array( 'slug' => 'classes', 'with_front' => false )
    )
);

register_post_type( 'lessons',
    array(
        .
        .
        'rewrite'   => array( 'slug' => 'chapters', 'with_front' => false )
    )
);
</code>```

I have created a custom admin UI to manage (create/update/delete) this two post type, the lesson post type is design to be a child post type for classes post type. So everytime someone create a lesson, it requires a parent post from the list of post type classes.

Now I have a problem with the url structure,

the URL of the classes will be site.dev/classes/class-post-name

and the URL of the lesson will be site.dev/chapters/lesson-post-name this is also the URL I can i see on wp_posts table under guid column

How can I acheive a URL structure like below that will also be stored as guid?
site.dev/classes/parent-post-post-name/chapters/lesson-post-name

答: Parent Post From Another Post Type and a new URL structure will help in achieving the results. The lessons post type should be hierarchical and classes should be non-hierarchical. One thing is notable in the metabox that you don't need to save the metabox manually. WordPress itself checks for field name parent_id and saves it.

Body:
I have two Custom Post type,

register_post_type( 'classes',
    array(
        .
        .
        'rewrite'   => array( 'slug' => 'classes', 'with_front' => false )
    )
);

register_post_type( 'lessons',
    array(
        .
        .
        'rewrite'   => array( 'slug' => 'chapters', 'with_front' => false )
    )
);

I have created a custom admin UI to manage (create/update/delete) this two post type, the lesson post type is design to be a child post type for classes post type. So everytime someone create a lesson, it requires a parent post from the list of post type classes.

Now I have a problem with the url structure,

the URL of the classes will be site.dev/classes/class-post-name

and the URL of the lesson will be site.dev/chapters/lesson-post-name this is also the URL I can i see on wp_posts table under guid column

How can I acheive a URL structure like below that will also be stored as guid?
site.dev/classes/parent-post-post-name/chapters/lesson-post-name


问:
wkhtmltopdf goes extremely slow on different environment
I am developing a PHP web application with CakePHP 3.4 framework, and i am using wkhtmltopdf 0.12.4 to output dynamic content in a .pdf file. Currently i'm using three different environments where i develop and test my application:

In my local environment (XAMPP 32-bit for Windows), wkhtmltopdf works great. It takes ~1 second in rendering .pdf files

In a remote testing environment (CentOS 7 64-bit using apache2, 4GB memory), works great too.

In my third remote testing environment (Another CentOS 7 64-bit distro with similar CPU specs as the second one and 4GB memory), wkhtmltopdf takes up to 20 seconds in rendering the same .pdf file

What could be causing this behavior in the third environment? How can i monitor or debug wkhtmltopdf process to help me identify why .pdf rendering is so slow?

答:
Remove rgba and set border-radius to 1px in your CSS files (or completely remove them if they are not needed). That should speed up the PDF generation process.

Similar issue


问:
Tree View in R Shiny using shinyTree package
I am creating Tree View in R Shiny using shinyTree package, able to do the same. The code which has been used for server part has list creation. Now, additional requirement is to convert the dataframe into list and import the same to achieve the tree structure using renderTree.

Here is the code which I have written:

```<code>#ui part
library(shiny)
library(shinyTree) # Using shinyTree Package

# UI for application that demonstrates a Tree View

shinyUI(
  pageWithSidebar(
    # Application title
    headerPanel("Tree View in Shiny"),

    sidebarPanel(
      helpText(HTML("A simple Shiny Tree example.
                  <hr>Created using shinyTree Package."))
    ),
    mainPanel(
      # Show a simple table.
      shinyTree("tree")
    )
  ))
#--------------------------------------------------------------------

#server part

library(shiny)
library(shinyTree)

# server logic required to generate a tree structure

shinyServer(function(input, output, session) {
  output$tree <- renderTree({
    **list(
      Folder1 = list(File1.1 = structure("",sticon="file"), File1.2 = structure("",sticon="file")),
      Folder2 = list(
        Subfolder2.1 = list(File2.1.1 = structure("",sticon="file"), File2.1.2 = structure("",sticon="file")
                            , File2.1.3=structure("",sticon="file")),
        Subfolder2.2 = list(File2.2.1 = structure("",sticon="file"), File2.2.2 = structure("",sticon="file")),
        File2.3 = structure("",sticon="file")
      )**
    )
  })
})
</code>```

The star part of the code needs to be replaced with list (that has been converted using dataframe). How I can achieve the same.

答:
Here Recursion method cab be used to get tree structure from a dataframe.

Solution:

Code to convert dataframe to tree (list)

```<code>a<-read.csv("Tree.csv") # Importing the dataframe

# Recursion function to get tree structure
gettree<-function(a)
{

# defining tree as list
tree<-list()

# Condition to identifly if selected column is not last column
if(class(a)!="factor"&&length(a)>1)
{

# getting uniques list of names from the columns to create folder
b<-unique(a[,1])

# runnig file name in loop
for(i in b)
{
# check if the flie name i not blank
if(i!="")
{
# subset data for content of folder
subdata<-a[which(a[,1]==i),]

# if there is only one element for that item change icon as file
if(length(subdata[,-1])==1)
{tree[[i]]=structure("",sticon="file")}
else{
# call the function recursively
tree[[i]]<-gettree(subdata[,-1])
  }}

}}

# Change icon of last columns as file
if(class(a)=="factor"||length(a)==1)
{
for(i in a)
{
  tree[[i]]=structure("",sticon="file")
}

}
return(tree)
}
</code>```

ui.R

```<code>library(shiny)
library(shinyTree) # Using shinyTree Package

# UI for application that demonstrates a Tree View

shinyUI(
pageWithSidebar(
# Application title
headerPanel("Tree View in Shiny"),

sidebarPanel(
  helpText(HTML("A simple Shiny Tree example.
              <hr>Created using shinyTree Package."))
),
mainPanel(

  shinyTree("tree")
)
))
</code>```

Server.R

```<code># server logic required to generate a tree structure

shinyServer(function(input, output, session) {
a<-read.csv("Tree.csv")

# call the function get tree and pass the data frame
tree<-gettree(a)

# render the list in tree
output$tree <- renderTree({
tree
  })
})
</code>```

Body:
I am creating Tree View in R Shiny using shinyTree package, able to do the same. The code which has been used for server part has list creation. Now, additional requirement is to convert the dataframe into list and import the same to achieve the tree structure using renderTree.

Here is the code which I have written:

#ui part
library(shiny)
library(shinyTree) # Using shinyTree Package

# UI for application that demonstrates a Tree View

shinyUI(
  pageWithSidebar(
    # Application title
    headerPanel("Tree View in Shiny"),

    sidebarPanel(
      helpText(HTML("A simple Shiny Tree example.

Created using shinyTree Package."))
    ),
    mainPanel(
      # Show a simple table.
      shinyTree("tree")
    )
  ))
#--------------------------------------------------------------------

#server part

library(shiny)
library(shinyTree)

# server logic required to generate a tree structure

shinyServer(function(input, output, session) {
  output$tree <- renderTree({
    **list(
      Folder1 = list(File1.1 = structure("",sticon="file"), File1.2 = structure("",sticon="file")),
      Folder2 = list(
        Subfolder2.1 = list(File2.1.1 = structure("",sticon="file"), File2.1.2 = structure("",sticon="file")
                            , File2.1.3=structure("",sticon="file")),
        Subfolder2.2 = list(File2.2.1 = structure("",sticon="file"), File2.2.2 = structure("",sticon="file")),
        File2.3 = structure("",sticon="file")
      )**
    )
  })
})

The star part of the code needs to be replaced with list (that has been converted using dataframe). How I can achieve the same.

Body:
Here Recursion method cab be used to get tree structure from a dataframe.

Solution:

Code to convert dataframe to tree (list)

a<-read.csv("Tree.csv") # Importing the dataframe

# Recursion function to get tree structure
gettree<-function(a)
{

# defining tree as list
tree<-list()

# Condition to identifly if selected column is not last column
if(class(a)!="factor"&&length(a)>1)
{

# getting uniques list of names from the columns to create folder
b<-unique(a[,1])

# runnig file name in loop
for(i in b)
{
# check if the flie name i not blank
if(i!="")
{
# subset data for content of folder
subdata<-a[which(a[,1]==i),]

# if there is only one element for that item change icon as file
if(length(subdata[,-1])==1)
{tree[[i]]=structure("",sticon="file")}
else{
# call the function recursively
tree[[i]]<-gettree(subdata[,-1])
  }}

}}

# Change icon of last columns as file
if(class(a)=="factor"||length(a)==1)
{
for(i in a)
{
  tree[[i]]=structure("",sticon="file")
}

}
return(tree)
}

ui.R

library(shiny)
library(shinyTree) # Using shinyTree Package

# UI for application that demonstrates a Tree View

shinyUI(
pageWithSidebar(
# Application title
headerPanel("Tree View in Shiny"),

sidebarPanel(
  helpText(HTML("A simple Shiny Tree example.
              <hr>Created using shinyTree Package."))
),
mainPanel(

  shinyTree("tree")
)
))

Server.R

# server logic required to generate a tree structure

shinyServer(function(input, output, session) {
a<-read.csv("Tree.csv")

# call the function get tree and pass the data frame
tree<-gettree(a)

# render the list in tree
output$tree <- renderTree({
tree
  })
})


问:
config-map kubernetes multiple environments
I am trying to deploy a Spring Boot application using configuration data from Kubernetes cluster. I have a simple RestController that prints a message by reading from a Kubernetes cluster.

```<code>    private String message = "Message not coming from Kubernetes config map";

@RequestMapping(value="/echo", method=GET)
public String printKubeConfig() {
    return message;
}
</code>```

Specified the name of the config map in my application.yml

```<code>spring:
  application:
    name: echo-configmap
</code>```

echo-configmap

```<code>apiVersion: v1
kind: ConfigMap
metadata:
  name: echo-configmap
data:
  application.properties: |-
    message=Hello from dev Kubernetes Configmap
  application_qa.properties: |-
    message=Hello from qa Kubernetes Configmap
</code>```

I have several environments like qa, int, test etc

What's the best way to specify environment specific properties in the config map? And how to access them in Spring boot application?

Ex: if the application is deployed in qa, my service should return the message "Hello from qa Kubernetes Configmap"

We also have plans to read these configuration files from GIT in future. How to handle that usecase?

答:
Your use case sounds very much like you should take look at spring-cloud-config - https://cloud.spring.io/spring-cloud-config/

The config-server is an infrastructure component that serves configuration that could be located in a git repository.

A config-client application would connect to config-server at startup and loads the configuration applicable to the current profiles.

You could have different branches for different environments - or use profiles per environment. In your kubernetes deployment manifest you could set the profile by setting SPRING_PROFILES_ACTIVE environment variable.

Body:
I am trying to deploy a Spring Boot application using configuration data from Kubernetes cluster. I have a simple RestController that prints a message by reading from a Kubernetes cluster.

    private String message = "Message not coming from Kubernetes config map";

@RequestMapping(value="/echo", method=GET)
public String printKubeConfig() {
    return message;
}

Specified the name of the config map in my application.yml

spring:
  application:
    name: echo-configmap

echo-configmap

apiVersion: v1
kind: ConfigMap
metadata:
  name: echo-configmap
data:
  application.properties: |-
    message=Hello from dev Kubernetes Configmap
  application_qa.properties: |-
    message=Hello from qa Kubernetes Configmap

I have several environments like qa, int, test etc

What's the best way to specify environment specific properties in the config map? And how to access them in Spring boot application?

Ex: if the application is deployed in qa, my service should return the message "Hello from qa Kubernetes Configmap"

We also have plans to read these configuration files from GIT in future. How to handle that usecase?


问:
Windows Console and Qt Unicode Text
I spent a whole day trying to figure this out with no luck.  I looked Everywhere but no luck with working code.

OS: Win XP Sp2
IDE & FRAMEWORK: C++, Qt Creator 2.0.

I am trying to output some unicode (UTF-8) text to the windows console but all I see is gibberish in place of the unicode chars.  I know the win console does support unicode (since win 2000)... at least according to Wikipedia and many on the net but I don't see how to make it work with Qt.  Most "solutions" I've seen (haven't seen many) use C++ and WInAPI tech... which I can't use because that is not the Qt way.  I am using QStrings and Qt!

Code is bellow.  I took out all the different things I tried to keep the code simple for the post.  Hope someone can get the code to work.

```<code>#include <QtCore/QCoreApplication>
#include <QString>
#include <QTextStream>
#include <QDate>
#include <QFile>
using namespace std;

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QTextStream qin(stdin);
    QTextStream qout(stdout);

    //The last 2 chars in QString each need a double slash for an accent.
    QString szqLine = QString::fromUtf8("abc áéüóöú őű");

    //I want this text console output to be in red text color.
    qout << "Bellow are some unicode characters: " << endl;

    //The Win XP console does not display the unicode chars correctly!!
    //The cosole does not display unicode chars even though it is capable
    //according to wikipedia.  I just don't know how with Qt.
    //I want this text output in white(or default font color, not red.)
    qout << szqLine << endl;

    //Would be nice to get some unicode input from console too.
    qout << "Write some unicode chars like above: " << endl;
    QString szqInput;
    szqInput = QString::fromUtf8(qin.readLine());
    qout << "You wrote: " << endl;
    qout << szqInput << endl;

    return app.exec();
}
</code>```

答:
Okay, I did some testing with this code. No special setup for the console is required.

```<code>#include <QTextStream>

#ifdef Q_OS_WIN32
#include <windows.h>
#include <iostream>
#else
#include <locale.h>
#endif

class ConsoleTextStream: public QTextStream {
  public:
    ConsoleTextStream();
    ConsoleTextStream& operator<<(const QString &string);
};

ConsoleTextStream::ConsoleTextStream():
  QTextStream(stdout, QIODevice::WriteOnly)
{
}

ConsoleTextStream& ConsoleTextStream::operator<<(const QString &string)
{
#ifdef Q_OS_WIN32
  WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE),
      string.utf16(), string.size(), NULL, NULL);
#else
  QTextStream::operator<<(string);
#endif
  return *this;
}

class ConsoleInput: public QTextStream {
public:
  ConsoleInput();
  QString readLine();
};

ConsoleInput::ConsoleInput():
  QTextStream(stdin, QIODevice::ReadOnly)
{
}

QString ConsoleInput::readLine()
{
#ifdef Q_OS_WIN32
  const int bufsize = 512;
  wchar_t buf[bufsize];
  DWORD read;
  QString res;
  do {
    ReadConsoleW(GetStdHandle(STD_INPUT_HANDLE),
        buf, bufsize, &read, NULL);
    res += QString::fromWCharArray(buf, read);
  } while (read > 0 && res[res.length() - 1] != '\n');
  // could just do res.truncate(res.length() - 2), but better be safe
  while (res.length() > 0
         && (res[res.length() - 1] == '\r' || res[res.length() - 1] == '\n'))
    res.truncate(res.length() - 1);
  return res;
#else
  return QTextStream::readLine();
#endif
}

int main()
{
#ifndef Q_OS_WIN32
  setlocale(LC_ALL, "");
#endif
  ConsoleTextStream qout;
  qout << QString::fromUtf8("Текст на иврите: לחם גרוזיני מסורתי הנאפה בתנור לבנים\n");
  qout << QString::fromUtf8("Текст на японском: ※当サイト内コンテンツ・画像・写真データの、転載・転用・加工・無断複製は禁止いたします。\n");
  qout << QString::fromUtf8("Текст на европейском: áéüóöú őű\n");
  qout << flush; // needed on Linux
  ConsoleInput qin;
  QString s = qin.readLine();
  qout << s << endl;
  s = qin.readLine(); // one more time, to ensure we read everything ok
  qout << s << endl;
  return 0;
}
</code>```

On Windows it prints square boxes for all text except Russian and European. It looks like Lucida Console doesn't have support for Hebrew and Japanese. The funny thing is, when I copy the text from the console to the clipboard and then paste somewhere with Unicode support (e. g. in a browser), it does show up correctly. This proves that Windows actually outputs Unicode, just doesn't display it. Some console font with full Unicode support is needed.

Note that in the example above I have overridden only one operator<<(), but I would need to override them all if I wanted to use them, because they return QTextStream& but aren't virtual, so it is necessary to make them all return ConsoleTextStream&, otherwise something like qout << 1 << someUnicodeString won't work correctly.

I also tested this example on Linux with UTF-8 locale, works perfectly.

Console input with ReadConsoleW() works because the console is configured in so-called line input mode by default, so it waits until the user hits Enter but doesn't wait until enough characters available to fill the buffer, so it does exactly what we want: reads a line provided that the buffer size is enough.

ContentLicense: CC BY-SA 2.5

Title: Windows Console and Qt Unicode Text

Body:
I spent a whole day trying to figure this out with no luck.  I looked Everywhere but no luck with working code.

OS: Win XP Sp2
IDE & FRAMEWORK: C++, Qt Creator 2.0.

I am trying to output some unicode (UTF-8) text to the windows console but all I see is gibberish in place of the unicode chars.  I know the win console does support unicode (since win 2000)... at least according to Wikipedia and many on the net but I don't see how to make it work with Qt.  Most "solutions" I've seen (haven't seen many) use C++ and WInAPI tech... which I can't use because that is not the Qt way.  I am using QStrings and Qt!

Code is bellow.  I took out all the different things I tried to keep the code simple for the post.  Hope someone can get the code to work.

#include <QtCore/QCoreApplication>
#include <QString>
#include <QTextStream>
#include <QDate>
#include <QFile>
using namespace std;

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QTextStream qin(stdin);
    QTextStream qout(stdout);

    //The last 2 chars in QString each need a double slash for an accent.
    QString szqLine = QString::fromUtf8("abc áéüóöú őű");

    //I want this text console output to be in red text color.
    qout << "Bellow are some unicode characters: " << endl;

    //The Win XP console does not display the unicode chars correctly!!
    //The cosole does not display unicode chars even though it is capable
    //according to wikipedia.  I just don't know how with Qt.
    //I want this text output in white(or default font color, not red.)
    qout << szqLine << endl;

    //Would be nice to get some unicode input from console too.
    qout << "Write some unicode chars like above: " << endl;
    QString szqInput;
    szqInput = QString::fromUtf8(qin.readLine());
    qout << "You wrote: " << endl;
    qout << szqInput << endl;

    return app.exec();
}

Body:
Okay, I did some testing with this code. No special setup for the console is required.

#include <QTextStream>

#ifdef Q_OS_WIN32
#include <windows.h>
#include <iostream>
#else
#include <locale.h>
#endif

class ConsoleTextStream: public QTextStream {
  public:
    ConsoleTextStream();
    ConsoleTextStream& operator<<(const QString &string);
};

ConsoleTextStream::ConsoleTextStream():
  QTextStream(stdout, QIODevice::WriteOnly)
{
}

ConsoleTextStream& ConsoleTextStream::operator<<(const QString &string)
{
#ifdef Q_OS_WIN32
  WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE),
      string.utf16(), string.size(), NULL, NULL);
#else
  QTextStream::operator<<(string);
#endif
  return *this;
}

class ConsoleInput: public QTextStream {
public:
  ConsoleInput();
  QString readLine();
};

ConsoleInput::ConsoleInput():
  QTextStream(stdin, QIODevice::ReadOnly)
{
}

QString ConsoleInput::readLine()
{
#ifdef Q_OS_WIN32
  const int bufsize = 512;
  wchar_t buf[bufsize];
  DWORD read;
  QString res;
  do {
    ReadConsoleW(GetStdHandle(STD_INPUT_HANDLE),
        buf, bufsize, &read, NULL);
    res += QString::fromWCharArray(buf, read);
  } while (read > 0 && res[res.length() - 1] != '\n');
  // could just do res.truncate(res.length() - 2), but better be safe
  while (res.length() > 0
         && (res[res.length() - 1] == '\r' || res[res.length() - 1] == '\n'))
    res.truncate(res.length() - 1);
  return res;
#else
  return QTextStream::readLine();
#endif
}

int main()
{
#ifndef Q_OS_WIN32
  setlocale(LC_ALL, "");
#endif
  ConsoleTextStream qout;
  qout << QString::fromUtf8("Текст на иврите: לחם גרוזיני מסורתי הנאפה בתנור לבנים\n");
  qout << QString::fromUtf8("Текст на японском: ※当サイト内コンテンツ・画像・写真データの、転載・転用・加工・無断複製は禁止いたします。\n");
  qout << QString::fromUtf8("Текст на европейском: áéüóöú őű\n");
  qout << flush; // needed on Linux
  ConsoleInput qin;
  QString s = qin.readLine();
  qout << s << endl;
  s = qin.readLine(); // one more time, to ensure we read everything ok
  qout << s << endl;
  return 0;
}

On Windows it prints square boxes for all text except Russian and European. It looks like Lucida Console doesn't have support for Hebrew and Japanese. The funny thing is, when I copy the text from the console to the clipboard and then paste somewhere with Unicode support (e. g. in a browser), it does show up correctly. This proves that Windows actually outputs Unicode, just doesn't display it. Some console font with full Unicode support is needed.

Note that in the example above I have overridden only one operator<<(), but I would need to override them all if I wanted to use them, because they return QTextStream& but aren't virtual, so it is necessary to make them all return ConsoleTextStream&, otherwise something like qout << 1 << someUnicodeString won't work correctly.

I also tested this example on Linux with UTF-8 locale, works perfectly.

Console input with ReadConsoleW() works because the console is configured in so-called line input mode by default, so it waits until the user hits Enter but doesn't wait until enough characters available to fill the buffer, so it does exactly what we want: reads a line provided that the buffer size is enough.


问:
How to resize a QLabel displayed by a QWidgetAction after changing it's text
I use a QWidgetAction to add a header to a context menu (that will also show up on Windows, no matter what style is used, in contrast to addSection(), which does not always actually display the title).

The action's widget is a QLabel. It's text is changed by each invocation of the context menu. The menu is setup in the constructor of my class, and the QWidgetAction is added like so (all m_ variables are member variables declared in the header):

```<code>m_contextMenu = new QMenu(this);
m_menuTitle = new QLabel;
m_menuTitle->setAlignment(Qt::AlignCenter);
m_menuTitle->setMargin(4);
QWidgetAction *titleAction = new QWidgetAction(m_contextMenu);
titleAction->setDefaultWidget(m_menuTitle);
m_contextMenu->addAction(titleAction);
m_contextMenu->addSeparator();
</code>```

When the menu is requested, the text of the label is changed and the menu is displayed like so:

```<code>m_menuTitle->setText(tr("%1 „%2“").arg(some_variable, some_other_variable));
...
m_contextMenu->exec(place_to_display);
</code>```

When the label's text is set for the first time (with a short text the label's text is set to), everything is fine:

but when it's set to some longer text, the size remains the same and the text is cropped:

I tried to fix this, but the only working solution I found was to define the QActions displayed in the menu in the constructor, owned by this, setting the label's text, clearing the menu and adding the actions again, like so:

```<code>m_contextMenu->clear();

m_menuTitle->setText(tr("%1 „%2“").arg(some_variable, some_other_variable));

m_contextMenu->addAction(m_menuTitleAction);
m_contextMenu->addSeparator();
m_contextMenu->addAction(m_editAction);
m_contextMenu->addAction(m_deleteAction);

m_contextMenu->exec(place_to_display);
</code>```

Is there a way to resize the title without rebuilding the menu each time?

答:
The solution is to send a resize event instead:

```<code>m_menuTitle->setText(tr("%1 „%2“").arg(some_variable, some_other_variable));
...
QResizeEvent re(new_size, m_contextMenu->size());
qApp->sendEvent(m_contextMenu, &re);
</code>```

This will set the QMenu's internal itemsDirty flag and will force geometry recalculation when the menu is shown. Note that the new size in the event does not matter, as the menu will aways resize based on its sizeHint()!

Body:
I use a QWidgetAction to add a header to a context menu (that will also show up on Windows, no matter what style is used, in contrast to addSection(), which does not always actually display the title).

The action's widget is a QLabel. It's text is changed by each invocation of the context menu. The menu is setup in the constructor of my class, and the QWidgetAction is added like so (all m_ variables are member variables declared in the header):

m_contextMenu = new QMenu(this);
m_menuTitle = new QLabel;
m_menuTitle->setAlignment(Qt::AlignCenter);
m_menuTitle->setMargin(4);
QWidgetAction *titleAction = new QWidgetAction(m_contextMenu);
titleAction->setDefaultWidget(m_menuTitle);
m_contextMenu->addAction(titleAction);
m_contextMenu->addSeparator();

When the menu is requested, the text of the label is changed and the menu is displayed like so:

m_menuTitle->setText(tr("%1 „%2“").arg(some_variable, some_other_variable));
...
m_contextMenu->exec(place_to_display);

When the label's text is set for the first time (with a short text the label's text is set to), everything is fine:

but when it's set to some longer text, the size remains the same and the text is cropped:

I tried to fix this, but the only working solution I found was to define the QActions displayed in the menu in the constructor, owned by this, setting the label's text, clearing the menu and adding the actions again, like so:

m_contextMenu->clear();

m_menuTitle->setText(tr("%1 „%2“").arg(some_variable, some_other_variable));

m_contextMenu->addAction(m_menuTitleAction);
m_contextMenu->addSeparator();
m_contextMenu->addAction(m_editAction);
m_contextMenu->addAction(m_deleteAction);

m_contextMenu->exec(place_to_display);

Is there a way to resize the title without rebuilding the menu each time?

Body:
The solution is to send a resize event instead:

m_menuTitle->setText(tr("%1 „%2“").arg(some_variable, some_other_variable));
...
QResizeEvent re(new_size, m_contextMenu->size());
qApp->sendEvent(m_contextMenu, &re);

This will set the QMenu's internal itemsDirty flag and will force geometry recalculation when the menu is shown. Note that the new size in the event does not matter, as the menu will aways resize based on its sizeHint()!


问:
maximum numbers in js
How to make my input maximum 10 digits length.How to make possible to enter only 10 numbers.</p>

```<code><input type="text" maxlength="10" onkeyup="return isAllowedSymbol(this); checkNumbers(this);" "placeholder="Enter data" name="answer" ><br>

  function checkNumbers(input)
    {
     if (input.value.length > 10)
        {
         input.value = input.value.replace(input.value, '');
        }
    }
</code>```

答:
You are already doing it with maxlength="10", you have quotes messed up though. JS is redundant.

<input type="text" maxlength="10" placeholder="Enter data" name="answer" >
```

Title: maximum numbers in js

Body:
How to make my input maximum 10 digits length.How to make possible to enter only 10 numbers.

<input type="text" maxlength="10" onkeyup="return isAllowedSymbol(this); checkNumbers(this);" "placeholder="Enter data" name="answer" >

  function checkNumbers(input)
    {
     if (input.value.length > 10)
        {
         input.value = input.value.replace(input.value, '');
        }
    }

Body:
You are already doing it with maxlength="10", you have quotes messed up though. JS is redundant.

<input type="text" maxlength="10" placeholder="Enter data" name="answer" ><br>


问:
error_get_last() returns NULL in PHP 7 when a custom exception handler is set
Ok, this took some time to break it down. Here it is:

There is an included faulty script which is the following for the remainder of this post:

faulty.php

```<code><?php
$a = 4 // missing semicolon
$b = 2;
</code>```

Then consider the following script for handling the error. Note, that the custom exception handler is initially not registered.

script.php

```<code><?php

// disable default display of errors
ini_set('display_errors', 0);

// register functions
#set_exception_handler('catchException'); // initially not set
register_shutdown_function('catchError');

// define error function
function catchError(){

  echo "PHP version: ".phpversion();

  if(is_null(error_get_last())) echo "<h1>No errors fetched!</h1>";
  else                          echo "<h1>Error fetched:</h1>";

  var_dump(error_get_last());

}

// define exception function (not used in all examples)
function catchException(){}

// include faulty script
include("D:/temp/faulty.php");
</code>```

Result with no custom exception handler

The results for PHP 5 and 7 are identical. The error_get_last() function returns the last ocurred error (Screenshot).

Result with custom error handler

Now we set a custom function uncommenting the line

```<code>set_exception_handler('catchException');
</code>```

This will work fine in PHP 5, however in PHP 7 the error_get_last() function returns NULL (Screenshot).

Question

Why is this? Especially confusing as the custom exception handler is empty, e.g. not "successfully handling" the error.

How to prevent this?

All the best and thanks for hints!

Update: problem and solution

The thing (not really a problem) is that PHP 7 throws an exception of type ParseError rather then producing an error. Thus, it is best handled with an exception handler. Make a nice exception handler to handle the exception well:

```<code>function catchException($e){

  echo "<h1>".get_class($e)."</h1>";
  echo $e->getMessage()."<br>";

}
</code>```

答:
PHP 7 throws a ParseError exception instead of triggering an error of type E_PARSE. The default exception handler seems to trigger an error if an uncaught exception is encountered. However if you replace it with set_exception_handler() it no longer happens unless you do it yourself.

See PHP docs:

PHP 7 changes how most errors are reported by PHP. Instead of reporting errors through the traditional error reporting mechanism used by PHP 5, most errors are now reported by throwing Error exceptions.

Body:
Ok, this took some time to break it down. Here it is:

There is an included faulty script which is the following for the remainder of this post:

faulty.php

<?php
$a = 4 // missing semicolon
$b = 2;

Then consider the following script for handling the error. Note, that the custom exception handler is initially not registered.

script.php

<?php

// disable default display of errors
ini_set('display_errors', 0);

// register functions
#set_exception_handler('catchException'); // initially not set
register_shutdown_function('catchError');

// define error function
function catchError(){

  echo "PHP version: ".phpversion();

  if(is_null(error_get_last())) echo "
No errors fetched!
";
  else                          echo "
Error fetched:
";

  var_dump(error_get_last());

}

// define exception function (not used in all examples)
function catchException(){}

// include faulty script
include("D:/temp/faulty.php");

Result with no custom exception handler

The results for PHP 5 and 7 are identical. The error_get_last() function returns the last ocurred error (Screenshot).

Result with custom error handler

Now we set a custom function uncommenting the line

set_exception_handler('catchException');

This will work fine in PHP 5, however in PHP 7 the error_get_last() function returns NULL (Screenshot).

Question

Why is this? Especially confusing as the custom exception handler is empty, e.g. not "successfully handling" the error.

How to prevent this?

All the best and thanks for hints!

Update: problem and solution

The thing (not really a problem) is that PHP 7 throws an exception of type ParseError rather then producing an error. Thus, it is best handled with an exception handler. Make a nice exception handler to handle the exception well:

function catchException($e){

  echo "
".get_class($e)."
";
  echo $e->getMessage()."
";

}


答:
Your code fscanf(f,"%d%d%d",ItemI[i],ItemQ[i],Price[i]) passes the values of ItemI[i], ItemQ[i], and Price[i] to fscanf. However, fscanf needs to know the addressess of the objects so that it can store new values in them. Change that code to fscanf(f, "%d%d%d", &ItemI[i], &ItemQ[i], &Price[i]).

Additionally, do not rely on fscanf to return EOF when it fails. It may fail not because it reaches the end of the file but because it finds fewer than three numerals in the input that can be interpreted as integers, in which case it returns the number of items it converted before failing. So it could return 0, 1, or 2. Instead, you should check whether the return value of fscanf is equal to the number of items you want, 3.

Title: about Search in Arrays

Body:
...........................................................................................................................................................
Hi everyone i got a little problem when i search for element in arrays
when i enter the number like 1007 he give me Error: Invalid item ID all the time

this is Myfile

1007 5 30

1004 4 10

1003 3 20

And this is my function

void DisplayItemInfoForAParticularItem(){
    FILE* f = fopen("items.txt", "r");
    int ItemID,ItemQuantity,PricePerUnit, i = 0,flag = 0;
    int ItemI[10], ItemQ[10],Price[10];

    while(fscanf(f,"%d%d%d",ItemI[i],ItemQ[i],Price[i]) != EOF){
        ++i;
    }
    printf("Enter itemID: ");
    scanf("%d",&ItemID);
    for(i=0; i<10; i++)
    {

        if(ItemI[i]==ItemID)
        {
            flag = 1;
            printf("ItemID  Quantity    Price Per Unit (SAR)");
            printf("%d  %d  %d",ItemI[i],ItemQ[i],Price[i]);
            break;
        }
    }
    if(flag==0)
    {
         printf("Error: Invalid item ID");
    }

    fclose(f);
   return ;
}

thank you for your help ............................................................................................................................................................................................................................................................................................................


问:
Matlab vectorization of 3 nested for-loops
I would like to vectorize the 3 nested for-loops in the following code:

```<code>    StepX=sqrt(3/2);
    StepY=sqrt(1/2);
    StepZ=sqrt(3);
    AuxX=StepX/6;
    AuxY=StepY/2;
    AuxZ=StepZ/3;

    n=1
    for i=0:L_x-1;
     for j=0:L_y-1;
      for k=0:L_z-1;
             A1(n,:)=[0+i*StepX 0+j*StepY 0+k*StepZ];  % Layer A1
             A2(n,:)=[3*AuxX+i*StepX AuxY+j*StepY 0+k*StepZ]; %  Layer A2
             B1(n,:)=[2*AuxX+i*StepX 0+j*StepY AuxZ+k*StepZ]; % Layer B1
             B2(n,:)=[5*AuxX+i*StepX AuxY+j*StepY AuxZ+k*StepZ]; % Layer B2
             C1(n,:)=[4*AuxX+i*StepX 0+j*StepY 2*AuxZ+k*StepZ]; % Layer C1
             C2(n,:)=[1*AuxX+i*StepX 1*AuxY+j*StepY 2*AuxZ+k*StepZ]; % Layer C2
             n=n+1;
       end
     end
    end
</code>```

I tried to do it as follows:

```<code> [A1_X,A1_Y,A1_Z] = ndgrid(0*AuxX:StepX:L_x-1,0*AuxY:StepY:L_y-1,0*AuxZ:StepZ:L_z-1);
A1 = [A1_X(:),A1_Y(:),A1_Z(:)]; % Layer A1

 [A2_X,A2_Y,A2_Z] = ndgrid(3*AuxX:StepX:L_x-1,1*AuxY:StepY:L_y-1,0*AuxZ:StepZ:L_z-1);
A2 = [A2_X(:),A2_Y(:),A2_Z(:)]; % Layer A2

[B1_X,B1_Y,B1_Z] = ndgrid(2*AuxX:StepX:L_x-1,0*AuxY:StepY:L_y-1,1*AuxZ:StepZ:L_z-1);
B1 = [B1_X(:),B1_Y(:),B1_Z(:)]; % Layer B1

 [B2_X,B2_Y,B2_Z] = ndgrid(5*AuxX:StepX:L_x-1,1*AuxY:StepY:L_y-1,1*AuxZ:StepZ:L_z-1);
B2 = [B2_X(:),B2_Y(:),B2_Z(:)]; % Layer B2

[C1_X,C1_Y,C1_Z] = ndgrid(4*AuxX:StepX:L_x-1,0*AuxY:StepY:L_y-1,2*AuxZ:StepZ:L_z-1);
C1 = [C1_X(:),C1_Y(:),C1_Z(:)]; % Layer C1

[C2_X,C2_Y,C2_Z] = ndgrid(1*AuxX:StepX:L_x-1,1*AuxY:StepY:L_y-
1,2*AuxZ:StepZ:L_z-1);
C2 = [C2_X(:),C2_Y(:),C2_Z(:)]; % Layer C1
</code>```

It seems that I wasn't careful enough with the endpoints of each layer, so the grids were messed up. Could you please help me to fix it?

Thanks in advance!

答:
After days of thinking, I came up with a simple solution:

```<code>StepX=sqrt(3/2);
StepY=sqrt(1/2);
StepZ=sqrt(3);
AuxX=StepX/6;
AuxY=StepY/2;
AuxZ=StepZ/3;

i = 0:L_x-1;
j = 0:L_y-1;
k = 0:L_z-1;

[I,J,K] = ndgrid(i,j,k);
A1 = [I(:)*StepX,J(:)*StepY,K(:)*StepZ];
A2 = [3*AuxX+I(:)*StepX,AuxY+J(:)*StepY,0+K(:)*StepZ];
B1 = [2*AuxX+I(:)*StepX,0+J(:)*StepY,AuxZ+K(:)*StepZ];
B2 = [5*AuxX+I(:)*StepX,AuxY+J(:)*StepY,AuxZ+K(:)*StepZ];
C1 = [4*AuxX+I(:)*StepX,0+J(:)*StepY,2*AuxZ+K(:)*StepZ];
C2 = [1*AuxX+I(:)*StepX,1*AuxY+J(:)*StepY,2*AuxZ+K(:)*StepZ];
</code>```

For the vectorized version it takes about 0.008 seconds for L_x=80,L_y=20 and L_z=20.
However, using the nested-loops version it takes about 1.9 seconds for the same values.

Body:
I would like to vectorize the 3 nested for-loops in the following code:

    StepX=sqrt(3/2);
    StepY=sqrt(1/2);
    StepZ=sqrt(3);
    AuxX=StepX/6;
    AuxY=StepY/2;
    AuxZ=StepZ/3;

    n=1
    for i=0:L_x-1;
     for j=0:L_y-1;
      for k=0:L_z-1;
             A1(n,:)=[0+i*StepX 0+j*StepY 0+k*StepZ];  % Layer A1
             A2(n,:)=[3*AuxX+i*StepX AuxY+j*StepY 0+k*StepZ]; %  Layer A2
             B1(n,:)=[2*AuxX+i*StepX 0+j*StepY AuxZ+k*StepZ]; % Layer B1
             B2(n,:)=[5*AuxX+i*StepX AuxY+j*StepY AuxZ+k*StepZ]; % Layer B2
             C1(n,:)=[4*AuxX+i*StepX 0+j*StepY 2*AuxZ+k*StepZ]; % Layer C1
             C2(n,:)=[1*AuxX+i*StepX 1*AuxY+j*StepY 2*AuxZ+k*StepZ]; % Layer C2
             n=n+1;
       end
     end
    end

I tried to do it as follows:

 [A1_X,A1_Y,A1_Z] = ndgrid(0*AuxX:StepX:L_x-1,0*AuxY:StepY:L_y-1,0*AuxZ:StepZ:L_z-1);
A1 = [A1_X(:),A1_Y(:),A1_Z(:)]; % Layer A1

 [A2_X,A2_Y,A2_Z] = ndgrid(3*AuxX:StepX:L_x-1,1*AuxY:StepY:L_y-1,0*AuxZ:StepZ:L_z-1);
A2 = [A2_X(:),A2_Y(:),A2_Z(:)]; % Layer A2

[B1_X,B1_Y,B1_Z] = ndgrid(2*AuxX:StepX:L_x-1,0*AuxY:StepY:L_y-1,1*AuxZ:StepZ:L_z-1);
B1 = [B1_X(:),B1_Y(:),B1_Z(:)]; % Layer B1

 [B2_X,B2_Y,B2_Z] = ndgrid(5*AuxX:StepX:L_x-1,1*AuxY:StepY:L_y-1,1*AuxZ:StepZ:L_z-1);
B2 = [B2_X(:),B2_Y(:),B2_Z(:)]; % Layer B2

[C1_X,C1_Y,C1_Z] = ndgrid(4*AuxX:StepX:L_x-1,0*AuxY:StepY:L_y-1,2*AuxZ:StepZ:L_z-1);
C1 = [C1_X(:),C1_Y(:),C1_Z(:)]; % Layer C1

[C2_X,C2_Y,C2_Z] = ndgrid(1*AuxX:StepX:L_x-1,1*AuxY:StepY:L_y-
1,2*AuxZ:StepZ:L_z-1);
C2 = [C2_X(:),C2_Y(:),C2_Z(:)]; % Layer C1

It seems that I wasn't careful enough with the endpoints of each layer, so the grids were messed up. Could you please help me to fix it?

Thanks in advance!

Body:
After days of thinking, I came up with a simple solution:

StepX=sqrt(3/2);
StepY=sqrt(1/2);
StepZ=sqrt(3);
AuxX=StepX/6;
AuxY=StepY/2;
AuxZ=StepZ/3;

i = 0:L_x-1;
j = 0:L_y-1;
k = 0:L_z-1;

[I,J,K] = ndgrid(i,j,k);
A1 = [I(:)*StepX,J(:)*StepY,K(:)*StepZ];
A2 = [3*AuxX+I(:)*StepX,AuxY+J(:)*StepY,0+K(:)*StepZ];
B1 = [2*AuxX+I(:)*StepX,0+J(:)*StepY,AuxZ+K(:)*StepZ];
B2 = [5*AuxX+I(:)*StepX,AuxY+J(:)*StepY,AuxZ+K(:)*StepZ];
C1 = [4*AuxX+I(:)*StepX,0+J(:)*StepY,2*AuxZ+K(:)*StepZ];
C2 = [1*AuxX+I(:)*StepX,1*AuxY+J(:)*StepY,2*AuxZ+K(:)*StepZ];

For the vectorized version it takes about 0.008 seconds for L_x=80,L_y=20 and L_z=20.
However, using the nested-loops version it takes about 1.9 seconds for the same values.


问:
How to provide model dependency information for use by Django's dumpdata?
Attempting to run the dumpdata command in Django release 1.2.1:

```<code>./manage.py dumpdata myapp
</code>```

I get the error "Can't resolve dependencies for myapp.model1 myapp.model2 myapp.model3".

Dumpdata is fine if I specify the list of models - e.g.,

```<code>./manage dumpdata myapp.model1 myapp.model2 myapp.model3 etc.
</code>```

Is there a way to encode the dependency information in my models.py ?

答:
Perhaps you're using natural_keys & MySQL? There's a bug reported on this.

Try commenting out all you natural_keys' code. Then dumpdata and voila.

Body:
Attempting to run the dumpdata command in Django release 1.2.1:

./manage.py dumpdata myapp

I get the error "Can't resolve dependencies for myapp.model1 myapp.model2 myapp.model3".

Dumpdata is fine if I specify the list of models - e.g.,

./manage dumpdata myapp.model1 myapp.model2 myapp.model3 etc.

Is there a way to encode the dependency information in my models.py ?


问:
UIBarButtonItem position different when placed via storyboard vs. programmatically
In my app, I have a toolbar with UIBarButtonItems.

In most circumstances, the UIBarButtonItems are set via storyboard, and look as follows:

In a special case, I have to replace one UIBarButtonItem programmatically. This is done with the following code:

```<code>let rotatingButton = UIButton(type: .custom)
rotatingButton.setImage(UIImage(named: "LocalizationInUseNoFix"), for: .normal)
rotatingButton.addTarget(self, action: #selector(localizationButtonTapped), for: .touchUpInside)
rotatingButton.rotateStart()
let barButtonItem = UIBarButtonItem(customView: rotatingButton)
leftBarButtonItems![2] = barButtonItem
</code>```

When the rotatingButton is displayed in the toolbar, it placed at a different position. It is shifted to the right, as you can see here:

How can I achieve to place both UIBarButtonItems at the same position?

EDIT:

By now I realized that the horizontal shift of the programmatically created UIBarButtonItem is not always the same, without any changes to the code: Sometimes it is shifted left, and not right:

EDIT 2:

I found a workaround:

If I set a width constrain to my button like

```<code>rotatingButton.widthAnchor.constraint(equalToConstant: 40).isActive = true
</code>```

then the button is apparently always correctly placed. But I hate to hard-code constraints like this.

Is there a more elegant way to do it?

答:
Try the below steps to perform your task:

Store left bar button items into an NSMutableArray

Replace desired UIBarbuttonItem

Set leftbarbuttonitems to this new array

Hope this steps will work

Body:
In my app, I have a toolbar with UIBarButtonItems.

In most circumstances, the UIBarButtonItems are set via storyboard, and look as follows:

In a special case, I have to replace one UIBarButtonItem programmatically. This is done with the following code:

let rotatingButton = UIButton(type: .custom)
rotatingButton.setImage(UIImage(named: "LocalizationInUseNoFix"), for: .normal)
rotatingButton.addTarget(self, action: #selector(localizationButtonTapped), for: .touchUpInside)
rotatingButton.rotateStart()
let barButtonItem = UIBarButtonItem(customView: rotatingButton)
leftBarButtonItems![2] = barButtonItem

When the rotatingButton is displayed in the toolbar, it placed at a different position. It is shifted to the right, as you can see here:

How can I achieve to place both UIBarButtonItems at the same position?

EDIT:

By now I realized that the horizontal shift of the programmatically created UIBarButtonItem is not always the same, without any changes to the code: Sometimes it is shifted left, and not right:

EDIT 2:

I found a workaround:

If I set a width constrain to my button like

rotatingButton.widthAnchor.constraint(equalToConstant: 40).isActive = true

then the button is apparently always correctly placed. But I hate to hard-code constraints like this.

Is there a more elegant way to do it?


答:
add filter in your app

```<code> app.filter("numberExchange", [
      function () {
          return function(item) {
              return Math.ceil(item);
          }
      }

    ]);
</code>```

and then use it on your view :
{{bill_amount | numberExchange}}

Title: Angularjs : How to display float number to nearst rounded number

Body:
I have an angularjs variable bill_amount which store 500.44. How can I display it to 501 without using controller function.
I use{{bill_amount | number: 0}} but it show 500 when the amount is greater than .5 then it adds +1 on the amount but I need to add +1  on the amount if the amount is greater then .0 like if the amount is 500.1 than I want to show 501.

Body:
add filter in your app

 app.filter("numberExchange", [
      function () {
          return function(item) {
              return Math.ceil(item);
          }
      }

    ]);

and then use it on your view :
{{bill_amount | numberExchange}}


问:
Paint polygon already drawn
I'm trying make a volume user control (only the UI). I have everything working, except when the bar goes below 50% of picturebox.Width (which is 100) I want the triangle colour to change, for example from red to green. The three lines commented in mouseMove event is what I want to accomplish, but that won't work. Thank you in advance.

This is an example of my control:

My code so far:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows;

namespace ControlAudio
{
    public partial class volumen: UserControl
    {
        Bitmap im_soundOn = Properties.Resources.sound_on;
        Bitmap im_soundOff = Properties.Resources.sound_off;
        int coordenadaX;
        bool barClicked = false;
        bool muted = false;

        public volumen()
        {
            InitializeComponent();

        }
        //Dibujar triangulo
        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            var g = e.Graphics;
            var points = new PointF[] { new PointF(0, 0), new PointF(1, 0), new PointF(0, 1) };

            var mx = g.Transform.Clone();

            g.TranslateTransform(100f, 100f);
            g.ScaleTransform(-135f, -70f);
            g.FillPolygon(Brushes.Olive, points);
            g.Transform = mx;
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            barClicked = true;
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            barClicked = false;
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            MouseEventArgs me = (MouseEventArgs)e;
            Point coordenadasNuevas = me.Location;
            coordenadaX = coordenadasNuevas.X;

            if(barClicked && pictureBox1.Width <= 100)
            {
                if (coordenadaX > 100)
                {
                    coordenadaX = 100;
                }
                pictureBox1.Width = coordenadaX;
            }

            //When it reaches 0
            if (pictureBox1.Width == 0) {
                pictureBox1.Width = 0;
                muted = true;
                pb_imagen.Image = im_soundOff;
            }
            else //When it goes over 0
            {
                muted = false;
                pb_imagen.Image = im_soundOn;
            }

            //if(pictureBox1.Width <= 50) g.FillPolygon(Brushes.Olive, points);
            //if(pictureBox1.Width >50 && pictureBox1.Width <= 90) g.FillPolygon(Brushes.Yellow, points);
            //if (pictureBox1.Width > 90) g.FillPolygon(Brushes.Red, points);

        }
    }
}
</code>```

答:
In order to solve this, and thanks to @LarsTech, I did the following:

Created a brush with the default colour: Brush brush = Brushes.Red;

In the pictureBox1_Paint event I changed the previous g.FillPolygon(Brushes.Olive, points); to g.FillPolygon(brush, points);

In the MouseMove event, I added the following:

```<code>if (pictureBox1.Width <= 50)
{
    brush = Brushes.LightGreen;
    pictureBox1.Invalidate();
}
else if (pictureBox1.Width > 50 && pictureBox1.Width <= 90)
{
    brush = Brushes.Yellow;
    pictureBox1.Invalidate();
}
else
{
    brush = Brushes.Red;
    pictureBox1.Invalidate();
}
</code>```

Title: Paint polygon already drawn

Body:
I'm trying make a volume user control (only the UI). I have everything working, except when the bar goes below 50% of picturebox.Width (which is 100) I want the triangle colour to change, for example from red to green. The three lines commented in mouseMove event is what I want to accomplish, but that won't work. Thank you in advance.

This is an example of my control:

My code so far:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows;

namespace ControlAudio
{
    public partial class volumen: UserControl
    {
        Bitmap im_soundOn = Properties.Resources.sound_on;
        Bitmap im_soundOff = Properties.Resources.sound_off;
        int coordenadaX;
        bool barClicked = false;
        bool muted = false;

        public volumen()
        {
            InitializeComponent();

        }
        //Dibujar triangulo
        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            var g = e.Graphics;
            var points = new PointF[] { new PointF(0, 0), new PointF(1, 0), new PointF(0, 1) };

            var mx = g.Transform.Clone();

            g.TranslateTransform(100f, 100f);
            g.ScaleTransform(-135f, -70f);
            g.FillPolygon(Brushes.Olive, points);
            g.Transform = mx;
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            barClicked = true;
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            barClicked = false;
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            MouseEventArgs me = (MouseEventArgs)e;
            Point coordenadasNuevas = me.Location;
            coordenadaX = coordenadasNuevas.X;

            if(barClicked && pictureBox1.Width <= 100)
            {
                if (coordenadaX > 100)
                {
                    coordenadaX = 100;
                }
                pictureBox1.Width = coordenadaX;
            }

            //When it reaches 0
            if (pictureBox1.Width == 0) {
                pictureBox1.Width = 0;
                muted = true;
                pb_imagen.Image = im_soundOff;
            }
            else //When it goes over 0
            {
                muted = false;
                pb_imagen.Image = im_soundOn;
            }

            //if(pictureBox1.Width <= 50) g.FillPolygon(Brushes.Olive, points);
            //if(pictureBox1.Width >50 && pictureBox1.Width <= 90) g.FillPolygon(Brushes.Yellow, points);
            //if (pictureBox1.Width > 90) g.FillPolygon(Brushes.Red, points);

        }
    }
}

Body:
In order to solve this, and thanks to @LarsTech, I did the following:

Created a brush with the default colour: Brush brush = Brushes.Red;

In the pictureBox1_Paint event I changed the previous g.FillPolygon(Brushes.Olive, points); to g.FillPolygon(brush, points);

In the MouseMove event, I added the following:

if (pictureBox1.Width <= 50)
{
    brush = Brushes.LightGreen;
    pictureBox1.Invalidate();
}
else if (pictureBox1.Width > 50 && pictureBox1.Width <= 90)
{
    brush = Brushes.Yellow;
    pictureBox1.Invalidate();
}
else
{
    brush = Brushes.Red;
    pictureBox1.Invalidate();
}


问:
Using regex cut full name to surname and initials
I have a dataset of full names like:

```<code>Ivanov Ivan Ivanovich,
Petrov Petr Petrovich,
Ahmed Hasan,
Omar Singh,
Trump Donald John,
Mohmadi Hussein Ahmad Husseini
</code>```

i need, using Java method

```<code>replaceAll(String regex, String text)
</code>```

make a dataset like:

```<code>Ivanov I. I.,
Petrov P. P.,
Ahmed H.,
Omar S.,
Trump D. J.,
Mohmadi H. A. H.
</code>```

I try to use - replaceAll("(?:^[A-Za-z']*)|[^\\sА-ЯІЇЄ]", ".")) but it does not works.

What regex I need to use?

答:
If you're looking for a single method call regex solution then use this regex using \G:

```<code>name = name.replaceAll("(\\p{L}+|\\G)(\\h+\\p{L})\\p{L}*", "$1$2.");
</code>```

RegEx Demo

\G asserts position at the end of the previous match or the start of the string for the first match

RegEx Breakup:

(\\p{L}+|\\G): Capture first name or end of previous match in group #1

(\\h+\\p{L}): Capture white-space and start letter of next name component in group #2

\\p{L}*:  Followed by 0 or more unicode letters

Body:
I have a dataset of full names like:

Ivanov Ivan Ivanovich,
Petrov Petr Petrovich,
Ahmed Hasan,
Omar Singh,
Trump Donald John,
Mohmadi Hussein Ahmad Husseini

i need, using Java method

replaceAll(String regex, String text)

make a dataset like:

Ivanov I. I.,
Petrov P. P.,
Ahmed H.,
Omar S.,
Trump D. J.,
Mohmadi H. A. H.

I try to use - replaceAll("(?:^[A-Za-z']*)|[^\\sА-ЯІЇЄ]", ".")) but it does not works.

What regex I need to use?

Body:
If you're looking for a single method call regex solution then use this regex using \G:

name = name.replaceAll("(\\p{L}+|\\G)(\\h+\\p{L})\\p{L}*", "$1$2.");

RegEx Demo

\G asserts position at the end of the previous match or the start of the string for the first match

RegEx Breakup:

(\\p{L}+|\\G): Capture first name or end of previous match in group #1

(\\h+\\p{L}): Capture white-space and start letter of next name component in group #2

\\p{L}*:  Followed by 0 or more unicode letters


问:
Where does Asp.Net UserAuthentication store users?
I was checking up to create a login system, now I found this standard login from Visual Studio. this link Authentication Methods I chose Individual User Accounts.

Now I'm curious to know where the data is saved.

I made a registration to the program afterwards I closed the app, hosted it again on my localhost and I still could log in with the same account.

I debugged the code, but it refers to the dll: Microsoft.AspNet.Identity.Core
I checked my local database but there are no users.
Removed the local database, still able to log in or register

答: Check your app data folder. You might have a DB automatically there. If not, Click View->Server Explorer. You might see something useful there.</p>


问:
Laravel web route variable is not returning as supposed
I have the following route :

```<code>    Route::get('/web/{cat_id?}/{post_type}','WebPostsController@index')
->where('post_type', '(pictures|videos|links|companies)')
->name('post_index');
</code>```

Controller file :

```<code> public function index($post_type,$post_id = null,$cat_id = null)
    {

        dd($post_type);
}
</code>```

When access the URL /public/web/15/videos
It return '15' which is supposed to return {post_type} value (videos) while it returning the {cat_id?} value.

答:
The variables passed in to the action have to follow the definition in the route.

That is, in your case, you expect the cat_id first, then the post_type which means that you will have to define the method as:

```<code>public function index($cat_id, $post_type) { }
</code>```

Furthermore, I expect that you will have some issues with it still, cause you can not have an optional parameter and then a forced parameter. So either move the $cat_id param as a optional to the end of the route and use $post_type before (/public/web/videos/15) or make both forced.

Body:
I have the following route :

    Route::get('/web/{cat_id?}/{post_type}','WebPostsController@index')
->where('post_type', '(pictures|videos|links|companies)')
->name('post_index');

Controller file :

 public function index($post_type,$post_id = null,$cat_id = null)
    {

        dd($post_type);
}

When access the URL /public/web/15/videos
It return '15' which is supposed to return {post_type} value (videos) while it returning the {cat_id?} value.

Body:
The variables passed in to the action have to follow the definition in the route.

That is, in your case, you expect the cat_id first, then the post_type which means that you will have to define the method as:

public function index($cat_id, $post_type) { }

Furthermore, I expect that you will have some issues with it still, cause you can not have an optional parameter and then a forced parameter. So either move the $cat_id param as a optional to the end of the route and use $post_type before (/public/web/videos/15) or make both forced.


问:
Loading of json files from S3 to sparkR dataframe
I have jason files saved in S3 bucket.  I am trying to load them as dataframe in spark R and I am getting error logs.  Following is my code.  Where am I going wrong?

```<code>devtools::install_github('apache/spark@v2.2.0',subdir='R/pkg',force=TRUE)

library(SparkR)

sc=sparkR.session(master='local')

Sys.setenv("AWS_ACCESS_KEY_ID"="xxxx",
       "AWS_SECRET_ACCESS_KEY"= "yyyy",
       "AWS_DEFAULT_REGION"="us-west-2")

movie_reviews <-SparkR::read.df(path="s3a://bucketname/reviews_Movies_and_TV_5.json",sep = "",source="json")
</code>```

I have tried all combinations of s3a , s3n, s3 and none seems to work.

I get following error log in my sparkR console

17/12/09 06:56:06 WARN FileStreamSink: Error while looking for metadata directory.
17/12/09 06:56:06 ERROR RBackendHandler: loadDF on org.apache.spark.sql.api.r.SQLUtils failed
java.lang.reflect.InvocationTargetException

答:
For me it works</p>

```<code>read.df("s3://bucket/file.json", "json", header = "true", inferSchema = "true", na.strings = "NA")
</code>```

Body:
I have jason files saved in S3 bucket.  I am trying to load them as dataframe in spark R and I am getting error logs.  Following is my code.  Where am I going wrong?

devtools::install_github('apache/spark@v2.2.0',subdir='R/pkg',force=TRUE)

library(SparkR)

sc=sparkR.session(master='local')

Sys.setenv("AWS_ACCESS_KEY_ID"="xxxx",
       "AWS_SECRET_ACCESS_KEY"= "yyyy",
       "AWS_DEFAULT_REGION"="us-west-2")

movie_reviews <-SparkR::read.df(path="s3a://bucketname/reviews_Movies_and_TV_5.json",sep = "",source="json")

I have tried all combinations of s3a , s3n, s3 and none seems to work.

I get following error log in my sparkR console

17/12/09 06:56:06 WARN FileStreamSink: Error while looking for metadata directory.
17/12/09 06:56:06 ERROR RBackendHandler: loadDF on org.apache.spark.sql.api.r.SQLUtils failed
java.lang.reflect.InvocationTargetException

Body:
For me it works

read.df("s3://bucket/file.json", "json", header = "true", inferSchema = "true", na.strings = "NA")


问:
Get the value of a combo box with text block
I have a combo box of patterns for a snake's color and I want to know which pattern the user chose,I added pictures to show the available patterns,but when I do
pattern=combobox2.Text; It doesn't show me the text i'm looking for.

```<code><ComboBox Name="ComboBox2" FontWeight="Bold" FontSize="15" Canvas.Left="320" Canvas.Top="222" Width="135" Height="24">
        <ComboBoxItem
         Name="Pattern1" FontFamily="Verdana" FontSize="12" FontWeight="Bold">
            <StackPanel Orientation="Horizontal">
                <Image Source="Pics/snakepattern.jpg" Height="12" Width="19"></Image>
                <TextBlock Text=" Pattern1"></TextBlock>
            </StackPanel>
        </ComboBoxItem>
        <ComboBoxItem
        Name="Pattern2" FontFamily="Verdana" FontSize="12" FontWeight="Bold">
            <StackPanel Orientation="Horizontal">
                <Image Source="Pics/snakepattern2.jpg" Height="14" Width="20"></Image>
                <TextBlock Text=" Pattern2"></TextBlock>
            </StackPanel>
        </ComboBoxItem>
        <ComboBoxItem
        Name="Pattern3" FontFamily="Verdana" FontSize="12" FontWeight="Bold">
            <StackPanel Orientation="Horizontal" Height="15">
                <Image Source="Pics/snakepattern3.jpg" Height="20"></Image>
                <TextBlock Text=" Pattern3"></TextBlock>
            </StackPanel>
        </ComboBoxItem>
        <ComboBoxItem
        Name="Pattern4" FontFamily="Verdana" FontSize="12" FontWeight="Bold">
            <StackPanel Orientation="Horizontal">
                <Image Source="Pics/snakepattern4.jpg" Height="13" Width="20"></Image>
                <TextBlock Text=" Pattern4"></TextBlock>
            </StackPanel>
        </ComboBoxItem>
        <ComboBoxItem
        Name="Pattern5" FontFamily="Verdana" FontSize="12" FontWeight="Bold">
            <StackPanel Orientation="Horizontal">
                <Image Source="Pics/snakepattern5.png" Height="17" Width="23"></Image>
                <TextBlock Text=" Pattern5"></TextBlock>
            </StackPanel>
        </ComboBoxItem>
    </ComboBox>
</code>```

I want it to show me the texts "Pattern1","Pattern2" (according to what the user chose)
how do I do that in the c# code?

答:
You should have a view model like this:

```<code>public class SnakePattern
{
    public string Name { get; set; }
    public ImageSource Image { get; set; }
}

public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public ObservableCollection<SnakePattern> Patterns { get; }
        = new ObservableCollection<SnakePattern>();

    private SnakePattern selectedPattern;
    public SnakePattern SelectedPattern
    {
        get { return selectedPattern; }
        set
        {
            selectedPattern = value;
            PropertyChanged?.Invoke(this,
                new PropertyChangedEventArgs(nameof(SelectedPattern)));
        }
    }
}
</code>```

and bind the ComboBox to it like this:

```<code><ComboBox ItemsSource="{Binding Patterns}"
          SelectedItem="{Binding SelectedPattern}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding Image}" Height="12" Width="19"/>
                <TextBlock Text="{Binding Name}"/>
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
</code>```

Initialize it in the constructor of your MainWindow, and assign it to the MainWindow DataContext property like this:

```<code>public MainWindow()
{
    InitializeComponent();

    var vm = new ViewModel();
    vm.Patterns.Add(new SnakePattern
    {
        Name = "Pattern 1",
        Image = new BitmapImage(new Uri("pack://application:,,,/Pics/snakepattern1.jpg"))
    });
    ...
    vm.SelectedPattern = vm.Patterns[0];

    DataContext = vm;
}
</code>```

To get the selected pattern, just access the DataContext (or keep the view model in a member variable):

```<code>var vm = (ViewModel)DataContext;
var selectedPattern = vm.SelectedPattern;
</code>```

Body:
I have a combo box of patterns for a snake's color and I want to know which pattern the user chose,I added pictures to show the available patterns,but when I do
pattern=combobox2.Text; It doesn't show me the text i'm looking for.

<ComboBox Name="ComboBox2" FontWeight="Bold" FontSize="15" Canvas.Left="320" Canvas.Top="222" Width="135" Height="24">
        <ComboBoxItem
         Name="Pattern1" FontFamily="Verdana" FontSize="12" FontWeight="Bold">
            <StackPanel Orientation="Horizontal">
                <Image Source="Pics/snakepattern.jpg" Height="12" Width="19"></Image>
                <TextBlock Text=" Pattern1"></TextBlock>
            </StackPanel>
        </ComboBoxItem>
        <ComboBoxItem
        Name="Pattern2" FontFamily="Verdana" FontSize="12" FontWeight="Bold">
            <StackPanel Orientation="Horizontal">
                <Image Source="Pics/snakepattern2.jpg" Height="14" Width="20"></Image>
                <TextBlock Text=" Pattern2"></TextBlock>
            </StackPanel>
        </ComboBoxItem>
        <ComboBoxItem
        Name="Pattern3" FontFamily="Verdana" FontSize="12" FontWeight="Bold">
            <StackPanel Orientation="Horizontal" Height="15">
                <Image Source="Pics/snakepattern3.jpg" Height="20"></Image>
                <TextBlock Text=" Pattern3"></TextBlock>
            </StackPanel>
        </ComboBoxItem>
        <ComboBoxItem
        Name="Pattern4" FontFamily="Verdana" FontSize="12" FontWeight="Bold">
            <StackPanel Orientation="Horizontal">
                <Image Source="Pics/snakepattern4.jpg" Height="13" Width="20"></Image>
                <TextBlock Text=" Pattern4"></TextBlock>
            </StackPanel>
        </ComboBoxItem>
        <ComboBoxItem
        Name="Pattern5" FontFamily="Verdana" FontSize="12" FontWeight="Bold">
            <StackPanel Orientation="Horizontal">
                <Image Source="Pics/snakepattern5.png" Height="17" Width="23"></Image>
                <TextBlock Text=" Pattern5"></TextBlock>
            </StackPanel>
        </ComboBoxItem>
    </ComboBox>

I want it to show me the texts "Pattern1","Pattern2" (according to what the user chose)
how do I do that in the c# code?

Body:
You should have a view model like this:

public class SnakePattern
{
    public string Name { get; set; }
    public ImageSource Image { get; set; }
}

public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public ObservableCollection<SnakePattern> Patterns { get; }
        = new ObservableCollection<SnakePattern>();

    private SnakePattern selectedPattern;
    public SnakePattern SelectedPattern
    {
        get { return selectedPattern; }
        set
        {
            selectedPattern = value;
            PropertyChanged?.Invoke(this,
                new PropertyChangedEventArgs(nameof(SelectedPattern)));
        }
    }
}

and bind the ComboBox to it like this:

<ComboBox ItemsSource="{Binding Patterns}"
          SelectedItem="{Binding SelectedPattern}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding Image}" Height="12" Width="19"/>
                <TextBlock Text="{Binding Name}"/>
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

Initialize it in the constructor of your MainWindow, and assign it to the MainWindow DataContext property like this:

public MainWindow()
{
    InitializeComponent();

    var vm = new ViewModel();
    vm.Patterns.Add(new SnakePattern
    {
        Name = "Pattern 1",
        Image = new BitmapImage(new Uri("pack://application:,,,/Pics/snakepattern1.jpg"))
    });
    ...
    vm.SelectedPattern = vm.Patterns[0];

    DataContext = vm;
}

To get the selected pattern, just access the DataContext (or keep the view model in a member variable):

var vm = (ViewModel)DataContext;
var selectedPattern = vm.SelectedPattern;


问:
Working with Box2D/Cocos2D in an external iOS project
I have followed the instructions as per this article and have been working with Cocos2D without much issues. Recently, I tried including the Box2D headers to try some physics like so:

```<code>#import "Box2D.h"
</code>```

This resulted in a lot of errors where the Box2D.h file could not include the rest of the header files:

```<code>../cocos2d-iphone-0.99.5/external/Box2d/Box2D/Box2D.h:34:0 ../cocos2d-iphone-0.99.5/external/Box2d/Box2D/Box2D.h:34:37: error: Box2D/Common/b2Settings.h: No such file or directory
</code>```

That's the first error and the rest of the 23 are like that, but for the different headers in Box2D.h.

I have already added the projects/targets to the current project as per the instructions in the article, so my project currently looks like this:

Also, I have attempted to remedy this by selecting all .m files in my project and setting the file type to sourcecode.cpp.objcpp but do not think that this is the issue. I am certain that under the User Header Search Paths build setting, the folders where these headers are stored are added. If it weren't, Cocos2D wouldn't be able to compile either.

What am I doing wrong?

答: I don't know if this is immediately obvious to other programmers, but I fixed this by checking the Always Search User Paths setting in the target settings. Hope it helps someone else.

Body:
I have followed the instructions as per this article and have been working with Cocos2D without much issues. Recently, I tried including the Box2D headers to try some physics like so:

#import "Box2D.h"

This resulted in a lot of errors where the Box2D.h file could not include the rest of the header files:

../cocos2d-iphone-0.99.5/external/Box2d/Box2D/Box2D.h:34:0 ../cocos2d-iphone-0.99.5/external/Box2d/Box2D/Box2D.h:34:37: error: Box2D/Common/b2Settings.h: No such file or directory

That's the first error and the rest of the 23 are like that, but for the different headers in Box2D.h.

I have already added the projects/targets to the current project as per the instructions in the article, so my project currently looks like this:

Also, I have attempted to remedy this by selecting all .m files in my project and setting the file type to sourcecode.cpp.objcpp but do not think that this is the issue. I am certain that under the User Header Search Paths build setting, the folders where these headers are stored are added. If it weren't, Cocos2D wouldn't be able to compile either.

What am I doing wrong?


问:
Categorize objects in different lists depending on a property
I'm having a problem in categorizing objects in different lists using the interest property.

I have a list of users objects as List, my user class looks like the following:

```<code>class User {
    private int id;
    private String name;
    private String interest;
    //constructors, getters & setters etc...
}
</code>```

I'm trying to display users depending on a certain interest, but I feel like there's an easier way to do this other than what I've tried.

And I need the interest list to be dynamic other than using a fixed set of elements in a switch, And also I don't know if there is a better and more efficient way without having to use 3 lists a list for each interest.

Here's what I've done so far:

```<code>List<User> javaInterestList;
List<User> javascriptInterestList;
List<User> cInterestList;

public void category(List<User> unfilteredList) {
    for (User u : unfilteredList) {
        String interest = u.getInterest().toLowerCase();
        switch (interest) {
        case "java":
            javaInterestList.add(u);
            break;
        case "c":
            cInterestList.add(u);
            break;
        case "javascript":
            javascriptInterestList.add(u);
            break;
        }
    }
}
</code>```

The problem in the above that I'm restricted to only 3 interests, Is there any way to solve this problem and a better, cleaner way to do it?

答:
The thing to think about here is not the mechanism of filtering, rather the used data-structure.

In such a situation, you are allocating different type of users with a certain interest (key). Which is a perfect use case for maps.

I think you just need to use a map for the following situation.

The problem in the above that I'm restricted to only 3 interests, Is there any way to solve this problem

Of course you can categorize as many interests as you desire, take a look at the following method:

```<code>public static Map<String,List<User>> category(List<User> unfilteredList){
        Map<String,List<User>> result = new HashMap<>();
        for(User u :unfilteredList){
            String inerest = u.getInterest();
            if(result.containsKey(u.getInterest())){
                List<User> users = new ArrayList<>(result.get(inerest));
                users.add(u);
                result.put(inerest, users);
            }else{
                List<User> users = new ArrayList<>();
                users.add(u);
                result.put(inerest, users);
            }
        }
        return result;
    }
</code>```

Is there a better, cleaner way to do it?

Yes, using Java 8 Streams you can easily rewrite the above in only one line of code:

```<code>public static  Map<String,List<User>> category(List<User> unfilteredList){
        return unfilteredList.stream().collect(Collectors.groupingBy(u -> u.getInterest()));
    }
</code>```

Body:
I'm having a problem in categorizing objects in different lists using the interest property.

I have a list of users objects as List, my user class looks like the following:

class User {
    private int id;
    private String name;
    private String interest;
    //constructors, getters & setters etc...
}

I'm trying to display users depending on a certain interest, but I feel like there's an easier way to do this other than what I've tried.

And I need the interest list to be dynamic other than using a fixed set of elements in a switch, And also I don't know if there is a better and more efficient way without having to use 3 lists a list for each interest.

Here's what I've done so far:

List<User> javaInterestList;
List<User> javascriptInterestList;
List<User> cInterestList;

public void category(List<User> unfilteredList) {
    for (User u : unfilteredList) {
        String interest = u.getInterest().toLowerCase();
        switch (interest) {
        case "java":
            javaInterestList.add(u);
            break;
        case "c":
            cInterestList.add(u);
            break;
        case "javascript":
            javascriptInterestList.add(u);
            break;
        }
    }
}

The problem in the above that I'm restricted to only 3 interests, Is there any way to solve this problem and a better, cleaner way to do it?

Body:
The thing to think about here is not the mechanism of filtering, rather the used data-structure.

In such a situation, you are allocating different type of users with a certain interest (key). Which is a perfect use case for maps.

I think you just need to use a map for the following situation.

The problem in the above that I'm restricted to only 3 interests, Is there any way to solve this problem

Of course you can categorize as many interests as you desire, take a look at the following method:

public static Map<String,List<User>> category(List<User> unfilteredList){
        Map<String,List<User>> result = new HashMap<>();
        for(User u :unfilteredList){
            String inerest = u.getInterest();
            if(result.containsKey(u.getInterest())){
                List<User> users = new ArrayList<>(result.get(inerest));
                users.add(u);
                result.put(inerest, users);
            }else{
                List<User> users = new ArrayList<>();
                users.add(u);
                result.put(inerest, users);
            }
        }
        return result;
    }

Is there a better, cleaner way to do it?

Yes, using Java 8 Streams you can easily rewrite the above in only one line of code:

public static  Map<String,List<User>> category(List<User> unfilteredList){
        return unfilteredList.stream().collect(Collectors.groupingBy(u -> u.getInterest()));
    }


问:
How to solve this error: Failed to resolve: com.android.support:appcompat-v7:26.1.0
I have just installed Android Studio 3.0.1 and I have attempted numerous solutions from the previous time this question was asked but none of them seem to be working. I still receive this error: Failed to resolve: com.android.support:appcompat-v7:26.1.0

My top level build file is as follows:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {

    allprojects{
        repositories{
            jcenter()
        }
    }
    repositories {
        // Gradle 4.1 and higher include support for Google's Maven repo using
        // the google() method. And you need to include this repo to download
        // Android plugin 3.0.0 or higher.
        maven { url "https://maven.google.com" }
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}
</code>```

My app build.gradle file includes:

```<code>apply plugin: 'com.android.application'

repositories {
    maven { url "https://maven.google.com" }
    jcenter { url "http://jcenter.bintray.com/" }
}

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

    defaultConfig {
        applicationId "com.example.application"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
    }
    buildTypes {

        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:26.0.1'
    compile 'com.android.support:design:23.1.1'
}
</code>```

答:
The man cause of the issue is the below code.

```<code>allprojects{ repositories{ jcenter() } }
</code>```

Replace it with this one

allprojects { repositories { google() jcenter() } }

Please let me know if it solves your problem.

Body:
I have just installed Android Studio 3.0.1 and I have attempted numerous solutions from the previous time this question was asked but none of them seem to be working. I still receive this error: Failed to resolve: com.android.support:appcompat-v7:26.1.0

My top level build file is as follows:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {

    allprojects{
        repositories{
            jcenter()
        }
    }
    repositories {
        // Gradle 4.1 and higher include support for Google's Maven repo using
        // the google() method. And you need to include this repo to download
        // Android plugin 3.0.0 or higher.
        maven { url "https://maven.google.com" }
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

My app build.gradle file includes:

apply plugin: 'com.android.application'

repositories {
    maven { url "https://maven.google.com" }
    jcenter { url "http://jcenter.bintray.com/" }
}

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

    defaultConfig {
        applicationId "com.example.application"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
    }
    buildTypes {

        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:26.0.1'
    compile 'com.android.support:design:23.1.1'
}

Body:
The man cause of the issue is the below code.

allprojects{ repositories{ jcenter() } }

Replace it with this one

allprojects { repositories { google() jcenter() } }

Please let me know if it solves your problem.