问:
What are the minimum files needed to get jqGrid working with MVC?
I downloaded the files for jqGrid but I'm not quite sure what files I need to reference. So far I have these files:

<link href='@Url.Content("~/Content/themes/base/jquery-ui.css")' ... />
<link href='@Url.Content("~/Content/themes/redmond/jquery-ui-1.8.custom.css")' ... />
<link href='@Url.Content("~/Content/themes/redmond/ui.jqgrid.css")' ... />
<link href='@Url.Content("~/Scripts/jquery.jqGrid-4.3.1/css/ui.jqgrid.css")' ... />

```

I saw another example suggesting that these were the files needed in addition to jQuery. Can someone confirm this is all that's needed and in the correct order or advise if I need to add more. For example do I need the link to the locale file?

I am just starting out learning about jqGrid. I looked around and didn't yet find a good example of how to use this with MVC3 and Razor. Does anyone have links to references that they have found very useful. Just really need one good link but most links I found with Google were old and not using Razor.

答:
I would regard this as a canonical example - a code snippet which represents
a simple, runnable - jqGrid with minimal coding, but still powerful enough to show the most important features (according to this documentation):

// see: https://free-jqgrid.github.io/getting-started/
// CDN used: https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid
$(function() {
  $("#grid").jqGrid({
    autowidth: true, height: 45,
    colNames: ['First name', 'Last name', 'Updated?'],
    colModel: [{name: "firstName"}, {name: "lastName"}, {name: "updated"}],
    data: [
      { id: 10, firstName: "Jane", lastName: "Doe", updated: "no"},
      { id: 20, firstName: "Justin", lastName: "Time", updated: "no" }
    ],
    loadComplete: function() {

     // demo - how to access grid data
     var ids = $(this).jqGrid('getDataIDs'); // ids for each row
     var gridData = $(this).jqGrid('getGridParam', 'data'); // all rows
     var gridLen  = gridData.length; // number of rows

     // now get a list from the data
     var nameList = [];
     for(var i=0; i<gridLen; i++) {
       nameList.push(gridData[i].firstName+' [id:'+ ids[i] +']');
     }
     var strList = nameList.join(", ");
     $("#nameList").html(strList);

     var rowKey = ids[1]; // rowKey for the operations below

     // get data from the 2nd row
     var secondRow=$(this).jqGrid('getRowData', rowKey);
     $("#getRowData").html(secondRow.firstName + ', ' + secondRow.lastName
        + ', updated:' + secondRow.updated);

     // set update flag by modifying row data
     secondRow.updated = "yes";
     $(this).jqGrid('setRowData', rowKey, secondRow);

     // update single cell (read, modify, write)
     var lastName=$(this).jqGrid('getCell', rowKey, "lastName");
     lastName=lastName.toUpperCase();
     // first change the cell in the visible part of grid
     $(this).jqGrid('setCell', rowKey, "lastName", lastName);
     // now change the internal local data
     $(this).jqGrid('getLocalRow', rowKey).lastName = lastName;

     // make column label of "Updated?" column larger
     $(this).jqGrid('setLabel', 2, '
Updated?
');

     // --- now verify the changes ---
     gridData = $(this).jqGrid('getGridParam', 'data'); // get rows again
     var rowList = [];
     for(var i=0; i<gridLen; i++) {
       rowList.push(gridData[i].firstName + ', ' + gridData[i].lastName
          + ', updated:' + gridData[i].updated);
     }
     $("#showGridData").html(rowList.join("; "));

    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>Canonical jqGrid example</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.2/css/ui.jqgrid.min.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.2/jquery.jqgrid.min.js"></script>

<table id="grid"></table>
<br/><b>First names list:</b><div id="nameList"></div>
<br/><b>Get data from row#1 (before update):</b><div id="getRowData"></div>
<br/><b>Verify changes (after update):</b><div id="showGridData"></div></code>```

You can use it, together with Oleg's answer as a working starting point for your development in your own MVC application (in that case, use @Url.Content syntax as in the answer above) - and last but not least as a code snippet template for further StackOverflow questions related to jqGrid.

I have added some code to show how you can access the internal grid data. It addresses questions like "how can I access data from a specific row?"
However, if you don't need that code in your snippet, you can just remove the entire loadComplete section, the grid demo will still work.

If you require paging in your snippet, see this answer.

Note: I spent a lot of time with jqQuery keys (needed to uniquely address a row) to find out how they work in detail. Here's some info from my experiences in a nutshell:

If you don't explicitly specify a key in the colModel, then JQGrid assumes "id" as the key field. This is what this example does: The data populates the id field and this is used as a key

Otherwise, if you need a different key, specify {name: "myKey", hidden:true, key:true} in the colModel, and "myKey" in the colNames as well (if you forget that, you'll get a count mismatch error). Then you can populate "myKey" in the data. The order of occurance is important! In this case, there is no "id" but a "myKey" field. Key fields don't need to be hidden. If you omit the hidden attribute (or set false as value), then the key is shown as column in the grid.

Note that in case of such a key remapping, jqGrid internally uses _id_ as property to store the key. You can see that if you use the function .jqGrid('getGridParam', 'data'), then each row contains such a property.

Specifying key: true multiple times is useless, because only the last field with that attribute is regarded as key (i.e. the rightmost key column). Having said that, you can't specify compound keys this way! If you need a compound key, then you have to concatenate the keys into one single key field.

If you neither specify a key on your own, nor populate the id field, then jqGrid creates its own values and assigns them to the id field of each row. They are typically named "jqg1" (for the first row), "jqg2" (for the second) and so forth.

The example also shows how to update a row. For more details, see here and there. Note that if you update data this way, it's only updated on the client (in your browser). You have to save the value (i.e. send the updated data to the server via AJAX, provide a SAVE button etc.) if you want to make the change permanent, otherwise it's discarded on re-load.

Column titles (i.e. the titles that are displayed to the user) are defined by the colNames property, don't confuse them with the name property inside the colModel. The name property inside the colModel defines the field names, which is important for the data binding. The order of appearance in both colNames and colModel is important, because they correlate with each other (for example, 'Last Name' in colNames appears at the second position, and so does the corresponding field {name: '"lastName"' ...} inside colModel appear at position 2).

If you want to change column titles later in your code (i.e. after the definition), take a look here: How to update column titles dynamically.

Useful links: jqGrid free edition - getting started, jgGrid - colmodel options

Body:
I downloaded the files for jqGrid but I'm not quite sure what files I need to reference. So far I have these files:

<link href='@Url.Content("~/Content/themes/base/jquery-ui.css")' ... />
<link href='@Url.Content("~/Content/themes/redmond/jquery-ui-1.8.custom.css")' ... />
<link href='@Url.Content("~/Content/themes/redmond/ui.jqgrid.css")' ... />
<link href='@Url.Content("~/Scripts/jquery.jqGrid-4.3.1/css/ui.jqgrid.css")' ... />

I saw another example suggesting that these were the files needed in addition to jQuery. Can someone confirm this is all that's needed and in the correct order or advise if I need to add more. For example do I need the link to the locale file?

I am just starting out learning about jqGrid. I looked around and didn't yet find a good example of how to use this with MVC3 and Razor. Does anyone have links to references that they have found very useful. Just really need one good link but most links I found with Google were old and not using Razor.

Body:
I would regard this as a canonical example - a code snippet which represents
a simple, runnable - jqGrid with minimal coding, but still powerful enough to show the most important features (according to this documentation):

// see: https://free-jqgrid.github.io/getting-started/
// CDN used: https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid
$(function() {
  $("#grid").jqGrid({
    autowidth: true, height: 45,
    colNames: ['First name', 'Last name', 'Updated?'],
    colModel: [{name: "firstName"}, {name: "lastName"}, {name: "updated"}],
    data: [
      { id: 10, firstName: "Jane", lastName: "Doe", updated: "no"},
      { id: 20, firstName: "Justin", lastName: "Time", updated: "no" }
    ],
    loadComplete: function() {

     // demo - how to access grid data
     var ids = $(this).jqGrid('getDataIDs'); // ids for each row
     var gridData = $(this).jqGrid('getGridParam', 'data'); // all rows
     var gridLen  = gridData.length; // number of rows

     // now get a list from the data
     var nameList = [];
     for(var i=0; i<gridLen; i++) {
       nameList.push(gridData[i].firstName+' [id:'+ ids[i] +']');
     }
     var strList = nameList.join(", ");
     $("#nameList").html(strList);

     var rowKey = ids[1]; // rowKey for the operations below

     // get data from the 2nd row
     var secondRow=$(this).jqGrid('getRowData', rowKey);
     $("#getRowData").html(secondRow.firstName + ', ' + secondRow.lastName
        + ', updated:' + secondRow.updated);

     // set update flag by modifying row data
     secondRow.updated = "yes";
     $(this).jqGrid('setRowData', rowKey, secondRow);

     // update single cell (read, modify, write)
     var lastName=$(this).jqGrid('getCell', rowKey, "lastName");
     lastName=lastName.toUpperCase();
     // first change the cell in the visible part of grid
     $(this).jqGrid('setCell', rowKey, "lastName", lastName);
     // now change the internal local data
     $(this).jqGrid('getLocalRow', rowKey).lastName = lastName;

     // make column label of "Updated?" column larger
     $(this).jqGrid('setLabel', 2, '<h3>Updated?</h3>');

     // --- now verify the changes ---
     gridData = $(this).jqGrid('getGridParam', 'data'); // get rows again
     var rowList = [];
     for(var i=0; i<gridLen; i++) {
       rowList.push(gridData[i].firstName + ', ' + gridData[i].lastName
          + ', updated:' + gridData[i].updated);
     }
     $("#showGridData").html(rowList.join("; "));

    }
  });
});

<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>Canonical jqGrid example</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.2/css/ui.jqgrid.min.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.2/jquery.jqgrid.min.js"></script>

<table id="grid"></table>
<br/><b>First names list:</b><div id="nameList"></div>
<br/><b>Get data from row#1 (before update):</b><div id="getRowData"></div>
<br/><b>Verify changes (after update):</b><div id="showGridData"></div>

You can use it, together with Oleg's answer as a working starting point for your development in your own MVC application (in that case, use @Url.Content syntax as in the answer above) - and last but not least as a code snippet template for further StackOverflow questions related to jqGrid.

I have added some code to show how you can access the internal grid data. It addresses questions like "how can I access data from a specific row?"
However, if you don't need that code in your snippet, you can just remove the entire loadComplete section, the grid demo will still work.

If you require paging in your snippet, see this answer.

Note: I spent a lot of time with jqQuery keys (needed to uniquely address a row) to find out how they work in detail. Here's some info from my experiences in a nutshell:

If you don't explicitly specify a key in the colModel, then JQGrid assumes "id" as the key field. This is what this example does: The data populates the id field and this is used as a key

Otherwise, if you need a different key, specify {name: "myKey", hidden:true, key:true} in the colModel, and "myKey" in the colNames as well (if you forget that, you'll get a count mismatch error). Then you can populate "myKey" in the data. The order of occurance is important! In this case, there is no "id" but a "myKey" field. Key fields don't need to be hidden. If you omit the hidden attribute (or set false as value), then the key is shown as column in the grid.

Note that in case of such a key remapping, jqGrid internally uses _id_ as property to store the key. You can see that if you use the function .jqGrid('getGridParam', 'data'), then each row contains such a property.

Specifying key: true multiple times is useless, because only the last field with that attribute is regarded as key (i.e. the rightmost key column). Having said that, you can't specify compound keys this way! If you need a compound key, then you have to concatenate the keys into one single key field.

If you neither specify a key on your own, nor populate the id field, then jqGrid creates its own values and assigns them to the id field of each row. They are typically named "jqg1" (for the first row), "jqg2" (for the second) and so forth.

The example also shows how to update a row. For more details, see here and there. Note that if you update data this way, it's only updated on the client (in your browser). You have to save the value (i.e. send the updated data to the server via AJAX, provide a SAVE button etc.) if you want to make the change permanent, otherwise it's discarded on re-load.

Column titles (i.e. the titles that are displayed to the user) are defined by the colNames property, don't confuse them with the name property inside the colModel. The name property inside the colModel defines the field names, which is important for the data binding. The order of appearance in both colNames and colModel is important, because they correlate with each other (for example, 'Last Name' in colNames appears at the second position, and so does the corresponding field {name: '"lastName"' ...} inside colModel appear at position 2).

If you want to change column titles later in your code (i.e. after the definition), take a look here: How to update column titles dynamically.

Useful links: jqGrid free edition - getting started, jgGrid - colmodel options


来源: stackexchange

问:
How to determine if the Status Bar is translucent or not in an app implementing your library?
I have created a small library to place Views beside/above/below an existing View (e.g. Help arrow or something like that), I use

```<code>MainView.getLocationOnScreen(..);
</code>```

to determine the position of the Main View where the Sibling View will be placed nearby.

Usually I'm determining the top (Y) of the Main View  by the method above minus the height of the status bar using the following method:

```<code>protected boolean isTranslucentStaturBar()
{
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        Window w = ((Activity) mainActionView.getContext()).getWindow();

   --> return // SOME EXPRESSION TO DETERMINE IF THE STATUS BAR IS TRANSLUCENT <--- ?????
        // I Need to know what expression I need to write here
        // i.e. How to ready the flag: WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
    }

    return false;
}

protected int getStatusBarHeight() {
    if (isTranslucentStaturBar()) {
        return 0;
    }

    int result = 0;
    int resourceId = mainActionView.getContext().getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        result = mainActionView.getContext().getResources().getDimensionPixelSize(resourceId);
    }
    return result;
}
</code>```

My problem is with Androids >= Kitkat, where you can actually set the status bar to translucent and window content spread to fill the place below the status bard icons..

答:
Thanks mate! Translated to Xamarin Android:

```<code>        bool trans;
        var flags = Window.Attributes.Flags;
        if ((flags & WindowManagerFlags.TranslucentStatus) == WindowManagerFlags.TranslucentStatus)
            trans = true;
        else
            trans = false;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have created a small library to place Views beside/above/below an existing View (e.g. Help arrow or something like that), I use

MainView.getLocationOnScreen(..);

to determine the position of the Main View where the Sibling View will be placed nearby.

Usually I'm determining the top (Y) of the Main View  by the method above minus the height of the status bar using the following method:

protected boolean isTranslucentStaturBar()
{
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        Window w = ((Activity) mainActionView.getContext()).getWindow();

   --> return // SOME EXPRESSION TO DETERMINE IF THE STATUS BAR IS TRANSLUCENT <--- ?????
        // I Need to know what expression I need to write here
        // i.e. How to ready the flag: WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
    }

    return false;
}

protected int getStatusBarHeight() {
    if (isTranslucentStaturBar()) {
        return 0;
    }

    int result = 0;
    int resourceId = mainActionView.getContext().getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        result = mainActionView.getContext().getResources().getDimensionPixelSize(resourceId);
    }
    return result;
}

My problem is with Androids >= Kitkat, where you can actually set the status bar to translucent and window content spread to fill the place below the status bard icons..

Body:
Thanks mate! Translated to Xamarin Android:

        bool trans;
        var flags = Window.Attributes.Flags;
        if ((flags & WindowManagerFlags.TranslucentStatus) == WindowManagerFlags.TranslucentStatus)
            trans = true;
        else
            trans = false;


问:
MS Graph API Unknown Error when trying to get folder's children
When trying to access a specific folder in my sharepoint site's drive using the Microsoft Graph API relative pathing I get an unknown error. This exact same request worked fine just over a week ago but stopped working this week when using it again.

Test Results is a folder on my site's drive. According to OneDrive dev docs this is how the request should look: /drive/root:/path/to/folder:/children

Actual Request (site-id removed):

```<code>https://graph.microsoft.com/v1.0/sites/<site-id>/drive/root:/Test%20Results:/children
</code>```

Expected Result: a list of all folders/items within the 'Test Results' folder

Actual Result:

```<code>{
    "error": {
        "code": "-1, Microsoft.SharePoint.Client.UnknownError",
        "message": "Unknown Error",
        "innerError": {
            "request-id": "79b530f9-1bb9-455d-84e0-b3144fbf9c1c",
            "date": "2017-11-06T18:58:11"
        }
    }
}
</code>```

This originally used beta instead of v1.0 but it seems that the sharepoint and drive calls are no longer beta (also get the same results using beta in place of v1.0).

I've tried several different changes to my previously working request, but keep getting the unknown error. Am I missing something here since it's no longer using beta - or is this a bug on the Microsoft side? Any help is greatly appreciated.

答: According to this post, the issue was on the MS side. They reverted and the issue is now resolved for me.</p>

Body:
When trying to access a specific folder in my sharepoint site's drive using the Microsoft Graph API relative pathing I get an unknown error. This exact same request worked fine just over a week ago but stopped working this week when using it again.

Test Results is a folder on my site's drive. According to OneDrive dev docs this is how the request should look: /drive/root:/path/to/folder:/children

Actual Request (site-id removed):

https://graph.microsoft.com/v1.0/sites/<site-id>/drive/root:/Test%20Results:/children

Expected Result: a list of all folders/items within the 'Test Results' folder

Actual Result:

{
    "error": {
        "code": "-1, Microsoft.SharePoint.Client.UnknownError",
        "message": "Unknown Error",
        "innerError": {
            "request-id": "79b530f9-1bb9-455d-84e0-b3144fbf9c1c",
            "date": "2017-11-06T18:58:11"
        }
    }
}

This originally used beta instead of v1.0 but it seems that the sharepoint and drive calls are no longer beta (also get the same results using beta in place of v1.0).

I've tried several different changes to my previously working request, but keep getting the unknown error. Am I missing something here since it's no longer using beta - or is this a bug on the Microsoft side? Any help is greatly appreciated.


问:
Unable to create a list that is able to dinstinguish between integer and float based on user input
The code is supposed to create a list of five list's, with each list created from the numbers the user input each time (of five). So e.g. if user key in

```<code>1 2 3 4 5

1 2

1.5 2

2.2

1
</code>```

The output should be : [[1, 2, 3, 4, 5], [1, 2], [1.5, 2], [2,2], [1]]
Any help is appreciated. I understand that to solve this problem, you need to convert the string into a int or float, but cannot seem to get it to work.

```<code>nlist = []
n = len(nlist)

while n < 5:
    num = input("Enter a Number: ").split()

    for x in num:

        if '.' in num[x]:
            num[x] = float(num[x])
        else:
            num[x] = int(num[x])

    nlist.append(num)
    n = n + 1
print(nlist)
</code>```

答:
Using list comprehension with str.find to see whether to convert to float or int:

```<code>>>> out = []
>>> for i in range(n):
        inp = input().split()
        out.append([ float(ele) if ele.find('.')>-1 else int(ele) for ele in inp])
</code>```

#driver values :

```<code>IN : n = 5
IN :
1 2 3 4 5
1 2
1.5 2
2.2
1

OUT : [[1, 2, 3, 4, 5], [1, 2], [1.5, 2], [2.2], [1]]
</code>```

Body:
The code is supposed to create a list of five list's, with each list created from the numbers the user input each time (of five). So e.g. if user key in

1 2 3 4 5

1 2

1.5 2

2.2

1

The output should be : [[1, 2, 3, 4, 5], [1, 2], [1.5, 2], [2,2], [1]]
Any help is appreciated. I understand that to solve this problem, you need to convert the string into a int or float, but cannot seem to get it to work.

nlist = []
n = len(nlist)

while n < 5:
    num = input("Enter a Number: ").split()

    for x in num:

        if '.' in num[x]:
            num[x] = float(num[x])
        else:
            num[x] = int(num[x])

    nlist.append(num)
    n = n + 1
print(nlist)

Body:
Using list comprehension with str.find to see whether to convert to float or int:

>>> out = []
>>> for i in range(n):
        inp = input().split()
        out.append([ float(ele) if ele.find('.')>-1 else int(ele) for ele in inp])

#driver values :

IN : n = 5
IN :
1 2 3 4 5
1 2
1.5 2
2.2
1

OUT : [[1, 2, 3, 4, 5], [1, 2], [1.5, 2], [2.2], [1]]


问:
How to get the highest key from dictionary (python)?
I'm new to Python and I am having a small problem I want to solve

```<code>a={"1" : 3, "2" : 3, "6":3}
</code>```

I have this dic and I would like to get the maximum key out of him
for example in the dictionary above I would like to get the key 6 as a value

答:
If you want the original key (as as string, not an integer), you could simply use max with int as key argument:

```<code>a = {"1" : 3, "2" : 3, "6":3}
max(a, key=int)
# '6'
</code>```

Body:
I'm new to Python and I am having a small problem I want to solve

a={"1" : 3, "2" : 3, "6":3}

I have this dic and I would like to get the maximum key out of him
for example in the dictionary above I would like to get the key 6 as a value

Body:
If you want the original key (as as string, not an integer), you could simply use max with int as key argument:

a = {"1" : 3, "2" : 3, "6":3}
max(a, key=int)
# '6'


问:
How to define a tokenized tag field in Sanity?
I've seen people sport beautiful tokenized tag-fields in their Sanity studios. I don't think they are using a plug-in, so what's the incantation that will turn my homely array of strings into a tokenized tag field?</p>

答:
You can use the layout option, like this:

{
  title: "Tags",
  name: "tags",
  type: "array",
  of: [{type: "string"}],
  options: {
    layout: "tags"
  }
}```

There was an error in the docs. This is now documented here: https://www.sanity.io/docs/schema-types/array-type#options Thank you for bringing this to our attention!

Body:
You can use the layout option, like this:

{
  title: "Tags",
  name: "tags",
  type: "array",
  of: [{type: "string"}],
  options: {
    layout: "tags"
  }
}

There was an error in the docs. This is now documented here: https://www.sanity.io/docs/schema-types/array-type#options Thank you for bringing this to our attention!


问:
How to use tomcat with spring without web.xml?
I have a JAX-RS application deployed on Tomcat 7. I am deploying the application on Tomcat without any web.xml file.

I want to use spring for injecting some of the dependencies in my project. I am not using any XML file to configure beans, instead I have created a class and annotated it with @Configuration annotation, which contains all the bean definitions. Now, I am trying to use that bean by annotating a field in a separate class with @Autowired, but the field is null.

How should I make spring work with this setup ?

EDIT:
I was able to initialize spring application context , by creating a web.xml in WEB-INF/ with the following contents.

```<code><web-app>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>
</code>```

I checked the tomcat logs , and verified that the bean is created by spring. But the problem is when I try to use that bean, the field in the class is null.

答:
What you are missing is the way to initialize the Spring Dispatcher Servlet.
You need to implement the interface WebApplicationInitializer and in this class, you pass all the Java configurations needed for your application.

You have to define AnnotationConfigWebApplicationContext where you can register your configuration class :

```<code>context.register(MyConfig.class);
</code>```

or you can define the base packages containing all your config classes :

```<code>context.setConfigLocation("com.example.app.config");
</code>```

Full example :

```<code>    public class MyWebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext container) {
        AnnotationConfigWebApplicationContext context
          = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation("com.example.app.config");

        container.addListener(new ContextLoaderListener(context));

        ServletRegistration.Dynamic dispatcher = container
          .addServlet("dispatcher", new DispatcherServlet(context));

        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }
}
</code>```

Last thing, if you use maven, don't forget to set the property failOnmissingwebxml to false in the pom.xml.

You can find more info here

Body:
I have a JAX-RS application deployed on Tomcat 7. I am deploying the application on Tomcat without any web.xml file.

I want to use spring for injecting some of the dependencies in my project. I am not using any XML file to configure beans, instead I have created a class and annotated it with @Configuration annotation, which contains all the bean definitions. Now, I am trying to use that bean by annotating a field in a separate class with @Autowired, but the field is null.

How should I make spring work with this setup ?

EDIT:
I was able to initialize spring application context , by creating a web.xml in WEB-INF/ with the following contents.

<web-app>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

I checked the tomcat logs , and verified that the bean is created by spring. But the problem is when I try to use that bean, the field in the class is null.

Body:
What you are missing is the way to initialize the Spring Dispatcher Servlet.
You need to implement the interface WebApplicationInitializer and in this class, you pass all the Java configurations needed for your application.

You have to define AnnotationConfigWebApplicationContext where you can register your configuration class :

context.register(MyConfig.class);

or you can define the base packages containing all your config classes :

context.setConfigLocation("com.example.app.config");

Full example :

    public class MyWebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext container) {
        AnnotationConfigWebApplicationContext context
          = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation("com.example.app.config");

        container.addListener(new ContextLoaderListener(context));

        ServletRegistration.Dynamic dispatcher = container
          .addServlet("dispatcher", new DispatcherServlet(context));

        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }
}

Last thing, if you use maven, don't forget to set the property failOnmissingwebxml to false in the pom.xml.

You can find more info here


问:
Sound working incorrectly on HTML webpage
I noticed a problem with the sounds of my clickable links, in that the sound doesn't always play.

I have the following bit of code at the top of my  section which contains the src to the sound i'm wanting played

```<code><audio id="sound1" src="sounds/mouseClick.wav" preload="auto"></audio>
</code>```

This is where i reference the function to play the sound

```<code> <a href="questionnaire1.html" onclick="play()";> <img src="images/nextnewImage.jpg" alt="Take the Questionnaire" style="width:50%; height:auto"></a>
</code>```

And this is the bit of jQuery i've tried implementing to play the sound, which is outwith my body tag, before the closing html tag.

```<code>      <script>

         play(){

    $('.sound').live('click', function () {
    var sound = $("#sound1")[0];

    sound.load();
    sound.play();

    return false;
});
});
         }

    </script>
</code>```

答:
Try creating a new Audio object and pass in the url to the sound file as a parameter.

var audio = new Audio("sounds/mouseClick.wav");

$('#start').on("click", function() {
  audio.play();
});

$('#pause').on("click", function() {
  audio.pause();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container{
  border: 1px solid black;
  padding: 5px;
  margin: 5px;
}</code>```

    <button id="start">play</button>
    <button id="pause">pause</button>

```

Body:
I noticed a problem with the sounds of my clickable links, in that the sound doesn't always play.

I have the following bit of code at the top of my  section which contains the src to the sound i'm wanting played

<audio id="sound1" src="sounds/mouseClick.wav" preload="auto"></audio>

This is where i reference the function to play the sound

And this is the bit of jQuery i've tried implementing to play the sound, which is outwith my body tag, before the closing html tag.

Body:
Try creating a new Audio object and pass in the url to the sound file as a parameter.

var audio = new Audio("sounds/mouseClick.wav");

$('#start').on("click", function() {
  audio.play();
});

$('#pause').on("click", function() {
  audio.pause();
});

.container{
  border: 1px solid black;
  padding: 5px;
  margin: 5px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
  <!-- add a button and handle this in jQuery !-->
  <div>
    <button id="start">play</button>
    <button id="pause">pause</button>
  </div>
</div>


问:
Trying to escape a single quote from the lines in a csv file before copying the record to Excel using C# script
In an SSIS package, I’m trying to write out the contents of a .CSV file to a .XLS file because the Excel Connection Manager does not work well but having issues when trying to accomplish this via the C# script below.

Just a point of clarification, I am NOT INSERTING RECORDS into a DB but into an EXCEL file.

Any help/direction would be appreciated.  Thanks.

If I do a REPLACE function within the SQL code that creates the .CSV file to remove the single quote and run the C# code again then the issue is resolved but the manager for this excel file wants it there and I'd like to remedy the code in order to provide that.

I am getting this error when I execute the code:

```<code>System.Data.OleDb.OleDbException (0x80040E14): Syntax error (missing
operator) in query expression ''SAM'S/COSTCO - RETAIL/CONSUMAB')'.
   at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
   at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
   at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
   at ST_3c46305a87ab4837b1d2cd33ee47f34c.ScriptMain.Main()
</code>```

In the code below I tried to insert the following before the FIRST line within the WHILE loop below:

line = line.REPLACE(“’”, “\’”);

Here is the C# script code I'm working with:

```<code>try
{
    //Declare Variables
    string SourceFolderPath = Dts.Variables["User::SourceFolderPath"].Value.ToString();
    string DestinationFolderPath = Dts.Variables["User::DestinationFolderPath"].Value.ToString();
    string FileExtension = Dts.Variables["User::FileExtension"].Value.ToString();
    string FileDelimiter = Dts.Variables["User::FileDelimiter"].Value.ToString();
    string CreateTableStatement = "";
    string ColumnList = "";
    //Reading file names one by one
    string SourceDirectory = SourceFolderPath;
    string[] fileEntries = Directory.GetFiles(SourceDirectory, "*" + FileExtension);
    foreach (string fileName in fileEntries)
    {
        // do something with fileName
        //MessageBox.Show(fileName);
        //Read first line(Header) and prepare Create Statement for Excel Sheet
        System.IO.StreamReader file = new System.IO.StreamReader(fileName);
        string filenameonly = (((fileName.Replace(SourceDirectory, "")).Replace(FileExtension, "")).Replace("\\", ""));
        CreateTableStatement = (" Create Table [" + filenameonly + "] ([" + file.ReadLine().Replace(FileDelimiter, "] Text,[")) + "] Text)";
        file.Close();
        //MessageBox.Show(CreateTableStatement.ToString());
        //Construct ConnectionString for Excel
        //string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + DestinationFolderPath + "\\" + filenameonly
        //    + ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
        string connstring = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + DestinationFolderPath + "\\" + filenameonly + ";" + "Extended Properties=\"Excel 8.0;HDR=YES;IMEX=0\"";
        OleDbConnection Excel_OLE_Con = new OleDbConnection();
        OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
        //drop Excel file if exists
        File.Delete(DestinationFolderPath + "\\" + filenameonly + ".xls");
        Excel_OLE_Con.ConnectionString = connstring;
        Excel_OLE_Con.Open();
        Excel_OLE_Cmd.Connection = Excel_OLE_Con;
        //Use OLE DB Connection and Create Excel Sheet
        Excel_OLE_Cmd.CommandText = CreateTableStatement;
        Excel_OLE_Cmd.ExecuteNonQuery();
        //Writing Data of File to Excel Sheet in Excel File
        int counter = 0;
        string line;
        System.IO.StreamReader SourceFile = new System.IO.StreamReader(fileName);
        while ((line = SourceFile.ReadLine()) != null)
        {
            if (counter == 0)
            {
                ColumnList = "[" + line.Replace(FileDelimiter, "],[") + "]";
            }
            else
            {
                string query = "Insert into [" + filenameonly + "] (" + ColumnList + ") VALUES('" + line.Replace(FileDelimiter, "','") + "')";
                // MessageBox.Show(query.ToString());
                var command = query;
                Excel_OLE_Cmd.CommandText = command;
                Excel_OLE_Cmd.ExecuteNonQuery();
            }

            counter++;
        }

        Excel_OLE_Con.Close();
        SourceFile.Close();
        Dts.TaskResult = (int)ScriptResults.Success;
    }
}
catch (Exception exception)
{
    // Create Log File for Errors
    using (StreamWriter sw = File.CreateText(Dts.Variables["User::DestinationFolderPath"].Value.ToString() + "\\" + "ErrorLog_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".log"))
    {
        sw.WriteLine(exception.ToString());
        Dts.TaskResult = (int)ScriptResults.Failure;
    }
}

Dts.TaskResult = (int)ScriptResults.Success;
</code>```

答:
```<code>line = line.REPLACE("'", "''");
</code>```

That should work for you, unless I'm completely mistaken.

Body:
In an SSIS package, I’m trying to write out the contents of a .CSV file to a .XLS file because the Excel Connection Manager does not work well but having issues when trying to accomplish this via the C# script below.

Just a point of clarification, I am NOT INSERTING RECORDS into a DB but into an EXCEL file.

Any help/direction would be appreciated.  Thanks.

If I do a REPLACE function within the SQL code that creates the .CSV file to remove the single quote and run the C# code again then the issue is resolved but the manager for this excel file wants it there and I'd like to remedy the code in order to provide that.

I am getting this error when I execute the code:

System.Data.OleDb.OleDbException (0x80040E14): Syntax error (missing
operator) in query expression ''SAM'S/COSTCO - RETAIL/CONSUMAB')'.
   at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
   at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
   at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
   at ST_3c46305a87ab4837b1d2cd33ee47f34c.ScriptMain.Main()

In the code below I tried to insert the following before the FIRST line within the WHILE loop below:

line = line.REPLACE(“’”, “\’”);

Here is the C# script code I'm working with:

try
{
    //Declare Variables
    string SourceFolderPath = Dts.Variables["User::SourceFolderPath"].Value.ToString();
    string DestinationFolderPath = Dts.Variables["User::DestinationFolderPath"].Value.ToString();
    string FileExtension = Dts.Variables["User::FileExtension"].Value.ToString();
    string FileDelimiter = Dts.Variables["User::FileDelimiter"].Value.ToString();
    string CreateTableStatement = "";
    string ColumnList = "";
    //Reading file names one by one
    string SourceDirectory = SourceFolderPath;
    string[] fileEntries = Directory.GetFiles(SourceDirectory, "*" + FileExtension);
    foreach (string fileName in fileEntries)
    {
        // do something with fileName
        //MessageBox.Show(fileName);
        //Read first line(Header) and prepare Create Statement for Excel Sheet
        System.IO.StreamReader file = new System.IO.StreamReader(fileName);
        string filenameonly = (((fileName.Replace(SourceDirectory, "")).Replace(FileExtension, "")).Replace("\\", ""));
        CreateTableStatement = (" Create Table [" + filenameonly + "] ([" + file.ReadLine().Replace(FileDelimiter, "] Text,[")) + "] Text)";
        file.Close();
        //MessageBox.Show(CreateTableStatement.ToString());
        //Construct ConnectionString for Excel
        //string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + DestinationFolderPath + "\\" + filenameonly
        //    + ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
        string connstring = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + DestinationFolderPath + "\\" + filenameonly + ";" + "Extended Properties=\"Excel 8.0;HDR=YES;IMEX=0\"";
        OleDbConnection Excel_OLE_Con = new OleDbConnection();
        OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
        //drop Excel file if exists
        File.Delete(DestinationFolderPath + "\\" + filenameonly + ".xls");
        Excel_OLE_Con.ConnectionString = connstring;
        Excel_OLE_Con.Open();
        Excel_OLE_Cmd.Connection = Excel_OLE_Con;
        //Use OLE DB Connection and Create Excel Sheet
        Excel_OLE_Cmd.CommandText = CreateTableStatement;
        Excel_OLE_Cmd.ExecuteNonQuery();
        //Writing Data of File to Excel Sheet in Excel File
        int counter = 0;
        string line;
        System.IO.StreamReader SourceFile = new System.IO.StreamReader(fileName);
        while ((line = SourceFile.ReadLine()) != null)
        {
            if (counter == 0)
            {
                ColumnList = "[" + line.Replace(FileDelimiter, "],[") + "]";
            }
            else
            {
                string query = "Insert into [" + filenameonly + "] (" + ColumnList + ") VALUES('" + line.Replace(FileDelimiter, "','") + "')";
                // MessageBox.Show(query.ToString());
                var command = query;
                Excel_OLE_Cmd.CommandText = command;
                Excel_OLE_Cmd.ExecuteNonQuery();
            }

            counter++;
        }

        Excel_OLE_Con.Close();
        SourceFile.Close();
        Dts.TaskResult = (int)ScriptResults.Success;
    }
}
catch (Exception exception)
{
    // Create Log File for Errors
    using (StreamWriter sw = File.CreateText(Dts.Variables["User::DestinationFolderPath"].Value.ToString() + "\\" + "ErrorLog_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".log"))
    {
        sw.WriteLine(exception.ToString());
        Dts.TaskResult = (int)ScriptResults.Failure;
    }
}

Dts.TaskResult = (int)ScriptResults.Success;

Body:
line = line.REPLACE("'", "''");

That should work for you, unless I'm completely mistaken.


问:
Getting error when importing Tkinter and making a window
Here is my code guys:

```<code>from tkinter import *

root = Tk()
theLabel = Label(root, 'Hello World')
theLabel.pack()
root.mainloop()
</code>```

Here is the error:

Traceback (most recent call last):   File
  "C:/Users/argel/PycharmProjects/day2/rockpaper.py", line 4, in

      theLabel = Label(root, 'Hello World')   File "C:\Users\argel\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py",
  line 2760, in init
      Widget.init(self, master, 'label', cnf, kw)   File "C:\Users\argel\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py",
  line 2289, in init
      classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)] AttributeError: 'str' object has no attribute 'items'

Thank you for your help

答:
Just change theLabel = Label(root, 'Hello World') to theLabel = Label(root, text='Hello World') and it will work.

I have a suggestion to improve your code:

Rather than from tkinter import * use import tkinter as tk.

from tkinter import * is actually discouraged so I strongly recommend you do not use this method.

Remember you would also need to change your script slightly if you do.  It would look like this:

```<code>import tkinter as tk

root = tk.Tk()
theLabel = tk.Label(root, text='Hello World')
theLabel.pack()
root.mainloop()
</code>```

For more information the differences between imports please see this post.

I hope it solved your problem.

Body:
Here is my code guys:

from tkinter import *

root = Tk()
theLabel = Label(root, 'Hello World')
theLabel.pack()
root.mainloop()

Here is the error:

Traceback (most recent call last):   File
  "C:/Users/argel/PycharmProjects/day2/rockpaper.py", line 4, in

      theLabel = Label(root, 'Hello World')   File "C:\Users\argel\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py",
  line 2760, in init
      Widget.init(self, master, 'label', cnf, kw)   File "C:\Users\argel\AppData\Local\Programs\Python\Python36-32\lib\tkinter__init__.py",
  line 2289, in init
      classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)] AttributeError: 'str' object has no attribute 'items'

Thank you for your help

Body:
Just change theLabel = Label(root, 'Hello World') to theLabel = Label(root, text='Hello World') and it will work.

I have a suggestion to improve your code:

Rather than from tkinter import * use import tkinter as tk.

from tkinter import * is actually discouraged so I strongly recommend you do not use this method.

Remember you would also need to change your script slightly if you do.  It would look like this:

import tkinter as tk

root = tk.Tk()
theLabel = tk.Label(root, text='Hello World')
theLabel.pack()
root.mainloop()

For more information the differences between imports please see this post.

I hope it solved your problem.


问:
Use BeautifulSoup to fetch rows by header
I have an html structure like this one:

```<code><table class="info" id="stats">
 <tbody>
  <tr>
   <th> Brand </th>
   <td> 2 Guys Smoke Shop </td>
  </tr>
  <tr>
   <th> Blend Type </th>
   <td> Aromatic </td>
  </tr>
  <tr>
   <th> Contents </th>
   <td> Black Cavendish, Virginia </td>
  </tr>
  <tr>
   <th> Flavoring </th>
   <td> Other / Misc </td>
  </tr>
 </tbody>
</table>
</code>```

Those attributes are not always present, sometimes I can have only Brand, other cases Brand and Flavoring.

To scrap this I did a code like this:

```<code>BlendInfo = namedtuple('BlendInfo', ['brand', 'type', 'contents', 'flavoring'])
stats_rows =  soup.find('table', id='stats').find_all('tr')
bi = BlendInfo(brand      = stats_rows[1].td.get_text(),
               type       = stats_rows[2].td.get_text(),
               contents   = stats_rows[3].td.get_text(),
               flavoring  = stats_rows[4].td.get_text())
</code>```

But as expected it fails with index out bounds (or get really messed up) when the table ordering is different (type before brand) or some of the rows are missing (no contents).

Is there any better approach to something like:

Give me the data from row with header with string 'brand'

答:
This would build a dict for you:</p>

```<code>from BeautifulSoup import BeautifulSoup

valid_headers = ['brand', 'type', 'contents', 'flavoring']

t = """<table class="info" id="stats">
 <tbody>
  <tr>
   <th> Brand </th>
   <td> 2 Guys Smoke Shop </td>
  </tr>
  <tr>
   <th> Blend Type </th>
   <td> Aromatic </td>
  </tr>
  <tr>
   <th> Contents </th>
   <td> Black Cavendish, Virginia </td>
  </tr>
  <tr>
   <th> Flavoring </th>
   <td> Other / Misc </td>
  </tr>
 </tbody>
</table>"""

bs = BeautifulSoup(t)

results = {}
for row in bs.findAll('tr'):
    hea = row.findAll('th')
    if hea.strip().lstrip().lower() in valid_headers:
        val = row.findAll('td')
        results[hea[0].string] = val[0].string

print results
</code>```

Body:
I have an html structure like this one:

    Brand
    2 Guys Smoke Shop

    Blend Type
    Aromatic

    Contents
    Black Cavendish, Virginia

    Flavoring
    Other / Misc

Those attributes are not always present, sometimes I can have only Brand, other cases Brand and Flavoring.

To scrap this I did a code like this:

BlendInfo = namedtuple('BlendInfo', ['brand', 'type', 'contents', 'flavoring'])
stats_rows =  soup.find('table', id='stats').find_all('tr')
bi = BlendInfo(brand      = stats_rows[1].td.get_text(),
               type       = stats_rows[2].td.get_text(),
               contents   = stats_rows[3].td.get_text(),
               flavoring  = stats_rows[4].td.get_text())

But as expected it fails with index out bounds (or get really messed up) when the table ordering is different (type before brand) or some of the rows are missing (no contents).

Is there any better approach to something like:

Give me the data from row with header with string 'brand'

Body:
This would build a dict for you:

from BeautifulSoup import BeautifulSoup

valid_headers = ['brand', 'type', 'contents', 'flavoring']

t = """<table class="info" id="stats">
 <tbody>
  <tr>
   <th> Brand </th>
   <td> 2 Guys Smoke Shop </td>
  </tr>
  <tr>
   <th> Blend Type </th>
   <td> Aromatic </td>
  </tr>
  <tr>
   <th> Contents </th>
   <td> Black Cavendish, Virginia </td>
  </tr>
  <tr>
   <th> Flavoring </th>
   <td> Other / Misc </td>
  </tr>
 </tbody>
</table>"""

bs = BeautifulSoup(t)

results = {}
for row in bs.findAll('tr'):
    hea = row.findAll('th')
    if hea.strip().lstrip().lower() in valid_headers:
        val = row.findAll('td')
        results[hea[0].string] = val[0].string

print results


问:
Top tips for secure web applications
I am looking for easy steps that are simple and effective in making a web application more secure.

What are your top tips for secure web applications, and what kind of attack will they stop?

答:
Do not trust user input.

Validation of expected data types and formatting is essential to avaoiding SQL injection and  Cross-Site Scripting (XSS) attacks.

OwnerDisplayName: Oded

ContentLicense: CC BY-SA 2.5

Title: Top tips for secure web applications

OwnerDisplayName: Andy Rose


问:
Is it better to use the column name or column index on .Net DataSets?
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

```<code>int price = (int)dr["Price"];
</code>```

While column index is just faster (I think):

```<code>int price = (int)dr[3];
</code>```

Would using column names break if you decide to obfuscate the database?

答:
My opinion is that you should only switch to indices if you profiled your code and it showed as the bottleneck. I don't think this will happen.

Naming stuff is good, it makes our limited brain understand problems and build links easier. That's why we are given names such as Fred, Martin, Jamie, rather than Human[189333847], Human[138924342] and Human[239333546].

OwnerDisplayName: tpower

Body:
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

int price = (int)dr["Price"];

While column index is just faster (I think):

int price = (int)dr[3];

Would using column names break if you decide to obfuscate the database?

LastEditorDisplayName: tpower

OwnerDisplayName: Coincoin


问:
Is there any way to get facebook user email with django-facebookconnect?
I already integrate django-facebookconnect on my project, but when user login email field stay empty, i mean this app does not save user email ??

It seems like it does:

```<code>user = User(username=request.facebook.uid,
                    password=sha.new(str(random.random())).hexdigest()[:8],
                    email=profile.email)
</code>```

But when i check it does not saves email, is this an error or a facebook restriction?

答:
You need to get the extended permission from facebook.</p>

```<code><?php
$app_id = "YOUR_APP_ID";
    $app_sec = "APP_SEC";
$canvas_page = "APP_CANVAS_PAGE_URL";
$scope = "&scope=user_photos,email,publish_stream";           $auth_url"http://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" .       urlencode($canvas_page).$scope;
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode(".", $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, "-_", "+/")), true);
 if (empty($data["user_id"])) {
 echo(""); }
 $access_token = $data["oauth_token"];
$user_id = $data["user_id"];
    $user = json_decode(file_get_contents( "https://graph.facebook.com/me?    access_token=" .         $access_token));
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($COOKIE["fbs" . $app_id], "\""), $args);
    ksort($args);
$payload = "";
foreach ($args as $key => $value) {
if ($key != "sig") {
$payload .= $key . "=" . $value;
}
}
if (md5($payload . $application_secret) != $args["sig"]) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie($app_id, $app_sec);
?>
</code>```

Body:
I already integrate django-facebookconnect on my project, but when user login email field stay empty, i mean this app does not save user email ??

It seems like it does:

user = User(username=request.facebook.uid,
                    password=sha.new(str(random.random())).hexdigest()[:8],
                    email=profile.email)

But when i check it does not saves email, is this an error or a facebook restriction?

Body:
You need to get the extended permission from facebook.

<?php
$app_id = "YOUR_APP_ID";
    $app_sec = "APP_SEC";
$canvas_page = "APP_CANVAS_PAGE_URL";
$scope = "&scope=user_photos,email,publish_stream";           $auth_url"http://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" .       urlencode($canvas_page).$scope;
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode(".", $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, "-_", "+/")), true);
 if (empty($data["user_id"])) {
 echo(""); }
 $access_token = $data["oauth_token"];
$user_id = $data["user_id"];
    $user = json_decode(file_get_contents( "https://graph.facebook.com/me?    access_token=" .         $access_token));
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($COOKIE["fbs" . $app_id], "\""), $args);
    ksort($args);
$payload = "";
foreach ($args as $key => $value) {
if ($key != "sig") {
$payload .= $key . "=" . $value;
}
}
if (md5($payload . $application_secret) != $args["sig"]) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie($app_id, $app_sec);
?>


答:
It is definitely possible. Check this out:

```<code>from bs4 import BeautifulSoup

html_content='''
<table class="info" id="stats">
 <tbody>
  <tr>
   <th> Brand </th>
   <td> 2 Guys Smoke Shop </td>
  </tr>
  <tr>
   <th> Blend Type </th>
   <td> Aromatic </td>
  </tr>
  <tr>
   <th> Contents </th>
   <td> Black Cavendish, Virginia </td>
  </tr>
  <tr>
   <th> Flavoring </th>
   <td> Other / Misc </td>
  </tr>
 </tbody>
</table>
'''
soup = BeautifulSoup(html_content,"lxml")
for item in soup.find_all(class_='info')[0].find_all("th"):
    header = item.text
    rows = item.find_next_sibling().text
    print(header,rows)
</code>```

Output:

```<code> Brand   2 Guys Smoke Shop
 Blend Type   Aromatic
 Contents   Black Cavendish, Virginia
 Flavoring   Other / Misc
</code>```

Title: Use BeautifulSoup to fetch rows by header

Body:
It is definitely possible. Check this out:

from bs4 import BeautifulSoup

html_content='''
<table class="info" id="stats">
 <tbody>
  <tr>
   <th> Brand </th>
   <td> 2 Guys Smoke Shop </td>
  </tr>
  <tr>
   <th> Blend Type </th>
   <td> Aromatic </td>
  </tr>
  <tr>
   <th> Contents </th>
   <td> Black Cavendish, Virginia </td>
  </tr>
  <tr>
   <th> Flavoring </th>
   <td> Other / Misc </td>
  </tr>
 </tbody>
</table>
'''
soup = BeautifulSoup(html_content,"lxml")
for item in soup.find_all(class_='info')[0].find_all("th"):
    header = item.text
    rows = item.find_next_sibling().text
    print(header,rows)

Output:

 Brand   2 Guys Smoke Shop
 Blend Type   Aromatic
 Contents   Black Cavendish, Virginia
 Flavoring   Other / Misc


问:
QGraphicsSceneMouseEvent is not called
When I click on my scene - nothing happens. I tried many various methods with QMouseEvent and QGraphicsSceneMouseEvent, tried to set focus on my object and then try to click on it - with no result. I was also looking for solution on the Internet on posts from other people, but didn't found anything that would work for me. Where I make mistakes?

Here is some code below:

This is one of my windows, where I create scene, view and object - that I want make respond on my mouse events:

```<code>TrackWindow::TrackWindow(Timers *timer)
{
timeLineBar = new QGraphicsScene(this);
timeLineBarView = new QGraphicsView(timeLineBar);
timeLineBarView->setFixedHeight(20);
timeLineBarView->setAlignment(Qt::AlignTop|Qt::AlignLeft);
timeLineBarView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
timeLineBarView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
timeLineBarView->setStyleSheet("background-color: #333333; border:none;");

QVBoxLayout *timeLineLayout = new QVBoxLayout;
timeLineLayout->addWidget(timeLineBarView);
timeLineLayout->addWidget(tracksTimelineView);
timeline = new TimeLine(timer);
timeLineBar->addItem(timeline);
//timeline->setFlag(QGraphicsItem::ItemIsFocusable);
//timeline->setFocus();
}
</code>```

Here is my Timeline class implementation:

```<code>TimeLine::TimeLine(Timers *t)
{
    timer = new Timers;
    timer = t;
    timeLineWidth = 200000;
    timeLineScale = 0.1;
}

QRectF TimeLine::boundingRect() const
{
    return QRectF(0,0,timeLineWidth,18);
}

void TimeLine::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    QRectF rect = boundingRect();

    QPen pen(Qt::NoPen);
    painter->setPen(pen);
    painter->setBrush(QColor(200,200,200));
    painter->drawRect(rect);

    for(int i=0;i<200;i++)
    {
        painter->drawText(i*30,9,QString::number(i+1));
    }

}

void TimeLine::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        timer->start();
    }
}
</code>```

And header of my class:

```<code>#ifndef TIMELINE_H
#define TIMELINE_H

#include <QObject>
#include <QColor>
#include <QRect>
#include <QGraphicsRectItem>
#include <QPainter>
#include <QGraphicsSceneMouseEvent>
#include "timers.h"

class TimeLine: public QGraphicsRectItem
{
public:
    TimeLine(Timers *t);
    QRectF boundingRect() const;

    void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget);

    float timeLineScale;
    int timeLineWidth;
    void mousePressEvent(QGraphicsSceneMouseEvent * event);

private:
    Timers *timer;

protected:

    void mouseReleaseEvent(QGraphicsSceneMouseEvent * event);

};

#endif // TRACK_H
</code>```

答:
The problem is caused by overwriting the boundingRect() method, how are you inheriting from QGraphicsRectItem it is correct to use setRect()

timeline.h

```<code>#ifndef TIMELINE_H
#define TIMELINE_H

#include "timers.h"
#include <QGraphicsRectItem>

class TimeLine : public QGraphicsRectItem
{
public:
    TimeLine(Timers *t, QGraphicsItem *parent = 0);
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
protected:
    void mousePressEvent(QGraphicsSceneMouseEvent *event);
private:
    int timeLineWidth;
    float timeLineScale;
    Timers *timer;
};

#endif // TIMELINE_H
</code>```

timeline.cpp

```<code>#include "timeline.h"

#include <QGraphicsSceneMouseEvent>
#include <QPainter>
#include <QTimer>

TimeLine::TimeLine(Timers *t, QGraphicsItem *parent):QGraphicsRectItem(parent)
{
    timer = t;
    timeLineWidth=200000;
    setRect(QRectF(0,0,timeLineWidth,18));
    timeLineScale = 0.1;

}

void TimeLine::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(option)
    Q_UNUSED(widget)
    QRectF rect = boundingRect().toRect();

    QPen pen(Qt::NoPen);
    painter->setPen(pen);
    painter->setBrush(QColor(200,200,200));
    painter->drawRect(rect);

    painter->setPen(Qt::red);
    for(int i=0;i<200;i++)
    {
        painter->drawText(i*30,9,QString::number(i+1));
    }
}

void TimeLine::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
        timer->start();
}
</code>```

Note: it is not necessary to create a Timers inside TimeLine: timer = new Timers; since afterwards you are changing the direction of the pointer and therefore that space is unusable besides that it is unnecessary.

In the following link you will find the project that you use to test the functionality.

ContentLicense: CC BY-SA 4.0

Title: QGraphicsSceneMouseEvent is not called

Body:
When I click on my scene - nothing happens. I tried many various methods with QMouseEvent and QGraphicsSceneMouseEvent, tried to set focus on my object and then try to click on it - with no result. I was also looking for solution on the Internet on posts from other people, but didn't found anything that would work for me. Where I make mistakes?

Here is some code below:

This is one of my windows, where I create scene, view and object - that I want make respond on my mouse events:

TrackWindow::TrackWindow(Timers *timer)
{
timeLineBar = new QGraphicsScene(this);
timeLineBarView = new QGraphicsView(timeLineBar);
timeLineBarView->setFixedHeight(20);
timeLineBarView->setAlignment(Qt::AlignTop|Qt::AlignLeft);
timeLineBarView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
timeLineBarView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
timeLineBarView->setStyleSheet("background-color: #333333; border:none;");

QVBoxLayout *timeLineLayout = new QVBoxLayout;
timeLineLayout->addWidget(timeLineBarView);
timeLineLayout->addWidget(tracksTimelineView);
timeline = new TimeLine(timer);
timeLineBar->addItem(timeline);
//timeline->setFlag(QGraphicsItem::ItemIsFocusable);
//timeline->setFocus();
}

Here is my Timeline class implementation:

TimeLine::TimeLine(Timers *t)
{
    timer = new Timers;
    timer = t;
    timeLineWidth = 200000;
    timeLineScale = 0.1;
}

QRectF TimeLine::boundingRect() const
{
    return QRectF(0,0,timeLineWidth,18);
}

void TimeLine::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    QRectF rect = boundingRect();

    QPen pen(Qt::NoPen);
    painter->setPen(pen);
    painter->setBrush(QColor(200,200,200));
    painter->drawRect(rect);

    for(int i=0;i<200;i++)
    {
        painter->drawText(i*30,9,QString::number(i+1));
    }

}

void TimeLine::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        timer->start();
    }
}

And header of my class:

#ifndef TIMELINE_H
#define TIMELINE_H

#include <QObject>
#include <QColor>
#include <QRect>
#include <QGraphicsRectItem>
#include <QPainter>
#include <QGraphicsSceneMouseEvent>
#include "timers.h"

class TimeLine: public QGraphicsRectItem
{
public:
    TimeLine(Timers *t);
    QRectF boundingRect() const;

    void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget);

    float timeLineScale;
    int timeLineWidth;
    void mousePressEvent(QGraphicsSceneMouseEvent * event);

private:
    Timers *timer;

protected:

    void mouseReleaseEvent(QGraphicsSceneMouseEvent * event);

};

#endif // TRACK_H

Body:
The problem is caused by overwriting the boundingRect() method, how are you inheriting from QGraphicsRectItem it is correct to use setRect()

timeline.h

#ifndef TIMELINE_H
#define TIMELINE_H

#include "timers.h"
#include <QGraphicsRectItem>

class TimeLine : public QGraphicsRectItem
{
public:
    TimeLine(Timers *t, QGraphicsItem *parent = 0);
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
protected:
    void mousePressEvent(QGraphicsSceneMouseEvent *event);
private:
    int timeLineWidth;
    float timeLineScale;
    Timers *timer;
};

#endif // TIMELINE_H

timeline.cpp

#include "timeline.h"

#include <QGraphicsSceneMouseEvent>
#include <QPainter>
#include <QTimer>

TimeLine::TimeLine(Timers *t, QGraphicsItem *parent):QGraphicsRectItem(parent)
{
    timer = t;
    timeLineWidth=200000;
    setRect(QRectF(0,0,timeLineWidth,18));
    timeLineScale = 0.1;

}

void TimeLine::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(option)
    Q_UNUSED(widget)
    QRectF rect = boundingRect().toRect();

    QPen pen(Qt::NoPen);
    painter->setPen(pen);
    painter->setBrush(QColor(200,200,200));
    painter->drawRect(rect);

    painter->setPen(Qt::red);
    for(int i=0;i<200;i++)
    {
        painter->drawText(i*30,9,QString::number(i+1));
    }
}

void TimeLine::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
        timer->start();
}

Note: it is not necessary to create a Timers inside TimeLine: timer = new Timers; since afterwards you are changing the direction of the pointer and therefore that space is unusable besides that it is unnecessary.

In the following link you will find the project that you use to test the functionality.


问:
React native: Android project not found. Maybe run react-native android first?
I had an issue in my React-Native project which was working fine earlier but suddenly it stopped working. Whenever I used the command:

```<code>react-native run-android
</code>```

I was getting an error:

Android project not found. Maybe run react-native android first?

I tried running:

```<code>react-native android
</code>```

But it said:

Unrecognized command 'android' Run react-native --help to see list of
  all available commands

After trying:

```<code>D:\ProjectRoot\ReactNativeProjects\AwesomeProject>react-native eject
</code>```

The error returned was:

Scanning folders for symlinks in
  D:\ProjectRoot\ReactNativeProjects\AwesomeProject\node_modules (48ms)
  App name must be defined in the app.json config file to define the
  project name. It must not contain any spaces or dashes.

This is the app.json file:

```<code>{
  "expo": {
    "name": "AwesomeProject",
    "description": "A very interesting project.",
    "slug": "AwesomeProject",
    "privacy": "public",
    "sdkVersion": "30.0.0",
    "platforms": ["ios", "android"],
    "ios": {
      "supportsTablet": true
    },
    "android": {
      "package": "com.project.first"
    },
    "version": "1.0.0",
    "orientation": "portrait",
    "icon": "./assets/images/icon.png",
    "splash": {
      "image": "./assets/images/splash.png",
      "resizeMode": "contain",
      "backgroundColor": "#ffffff"
    },
    "updates": {
      "fallbackToCacheTimeout": 0
    },
    "assetBundlePatterns": [
      "**/*"
    ]
  }
}
</code>```

答:
We had this issue because files from android folder gradlew and gradlew.bat (Gradle startup script for the UN*X, Windows respectively) somehow got into the global .gitignore file, and so were not presented on local environments.

Actually running react-native upgrade command restore those files, thus fixing the problem.

Body:
I had an issue in my React-Native project which was working fine earlier but suddenly it stopped working. Whenever I used the command:

react-native run-android

I was getting an error:

Android project not found. Maybe run react-native android first?

I tried running:

react-native android

But it said:

Unrecognized command 'android' Run react-native --help to see list of
  all available commands

After trying:

D:\ProjectRoot\ReactNativeProjects\AwesomeProject>react-native eject

The error returned was:

Scanning folders for symlinks in
  D:\ProjectRoot\ReactNativeProjects\AwesomeProject\node_modules (48ms)
  App name must be defined in the app.json config file to define the
  project name. It must not contain any spaces or dashes.

This is the app.json file:

{
  "expo": {
    "name": "AwesomeProject",
    "description": "A very interesting project.",
    "slug": "AwesomeProject",
    "privacy": "public",
    "sdkVersion": "30.0.0",
    "platforms": ["ios", "android"],
    "ios": {
      "supportsTablet": true
    },
    "android": {
      "package": "com.project.first"
    },
    "version": "1.0.0",
    "orientation": "portrait",
    "icon": "./assets/images/icon.png",
    "splash": {
      "image": "./assets/images/splash.png",
      "resizeMode": "contain",
      "backgroundColor": "#ffffff"
    },
    "updates": {
      "fallbackToCacheTimeout": 0
    },
    "assetBundlePatterns": [
      "**/*"
    ]
  }
}


问:
How to set custom targeting in Native ad GADRequest in iOS?
I am able to set custom targets for DFPRequest in case of banner ads.we can send like this in DFP request.

```<code>let request = DFPRequest()
request.customTargeting = [string:string]
</code>```

When it comes to Native/Sponsored ads, how to set custom targets?

```<code>let request = GADRequest()
</code>```

In GADRequest, i am not able to find any customTargeting property.Only DFPRequest detailing is given on google developer site.

https://developers.google.com/mobile-ads-sdk/docs/dfp/ios/targeting#publisher_provided_identifiers

答:
I think you can load DFPRequest from native ads. Below is the code,

```<code>adLoader.load(DFPRequest())
</code>```

So that you can target. I'm not sure of it. So please check the documentation. Here below is the link I'm providing you to check out the use case.

The loadRequest method in GADAdLoader accepts the same DFPRequest objects as banners and interstitials. You can use request objects to add targeting information, just as you would with other ad types.

Link for above: https://developers.google.com/mobile-ads-sdk/docs/dfp/ios/native

Body:
I am able to set custom targets for DFPRequest in case of banner ads.we can send like this in DFP request.

let request = DFPRequest()
request.customTargeting = [string:string]

When it comes to Native/Sponsored ads, how to set custom targets?

let request = GADRequest()

In GADRequest, i am not able to find any customTargeting property.Only DFPRequest detailing is given on google developer site.

https://developers.google.com/mobile-ads-sdk/docs/dfp/ios/targeting#publisher_provided_identifiers

Body:
I think you can load DFPRequest from native ads. Below is the code,

adLoader.load(DFPRequest())

So that you can target. I'm not sure of it. So please check the documentation. Here below is the link I'm providing you to check out the use case.

The loadRequest method in GADAdLoader accepts the same DFPRequest objects as banners and interstitials. You can use request objects to add targeting information, just as you would with other ad types.

Link for above: https://developers.google.com/mobile-ads-sdk/docs/dfp/ios/native


问:
Java 8 Streams API HAVING clause equivalent in a GroupingBy?
I have run into a hard to solve problem in Streams API. Well, it is solvable but not elegantly within a single call from what I can tell. Below, taking a stream of FeatureContentWeight objects, I want to group by feature and content and obtain maximum weights per Feature and Content. I get the values from the Map at the very end since I have no need for maintaining a Map. The problem is, I only want groups that have more than 3 items in them. So I want the maximum weights per feature and content for Feature,Content pairs that have exceeded a given count. In SQL this would just be a simple HAVING clause. In Streams API it doesn't look trivial but I have only been at Streams API for a few days now.

Any ideas appreciated. Below is my approach,

```<code>List<FeatureContentWeight> nearestNeighbors = neighborPostings
    .stream()
    .collect(
    groupingBy(
        p -> FeatureContent.Create(p.getFeatureId(), p.getContentId()),
        collectingAndThen(maxBy(comparingDouble(FeatureContentWeight::getWeight)),Optional::get))).values();
</code>```

答:
```<code>resultMap.values().removeIf(lst -> lst.size() < 3)
</code>```

just remove everything you do not need from the result

Body:
I have run into a hard to solve problem in Streams API. Well, it is solvable but not elegantly within a single call from what I can tell. Below, taking a stream of FeatureContentWeight objects, I want to group by feature and content and obtain maximum weights per Feature and Content. I get the values from the Map at the very end since I have no need for maintaining a Map. The problem is, I only want groups that have more than 3 items in them. So I want the maximum weights per feature and content for Feature,Content pairs that have exceeded a given count. In SQL this would just be a simple HAVING clause. In Streams API it doesn't look trivial but I have only been at Streams API for a few days now.

Any ideas appreciated. Below is my approach,

List<FeatureContentWeight> nearestNeighbors = neighborPostings
    .stream()
    .collect(
    groupingBy(
        p -> FeatureContent.Create(p.getFeatureId(), p.getContentId()),
        collectingAndThen(maxBy(comparingDouble(FeatureContentWeight::getWeight)),Optional::get))).values();

Body:
resultMap.values().removeIf(lst -> lst.size() < 3)

just remove everything you do not need from the result


问:
How to determine the correct end of a range function in Python?
I noticed that I get the exact same results when I am trying to do this, for example:

```<code>   range(1,13,2)
=> [1, 3, 5, 7, 9, 11]
</code>```

And

```<code>   range(1,12,2)
=> [1, 3, 5, 7, 9, 11]
</code>```

The result is the exact same, but which one would be correct in this case and why?

Does the end of a range have to do something with the steps you take?

Like, the idea that a list should give me 11 as the last number, so I
  should take 13 because we have a step of 2, or is this a bad thought?

答: Both are correct. A range is a sequence of number starting at start spaced by step and strictly lesser than stop. Because of that definition, you will find always step possible values for stop giving exact same sequence (special case: when step has the default value 1, only one single value exists for stop)</p>

Body:
I noticed that I get the exact same results when I am trying to do this, for example:

   range(1,13,2)
=> [1, 3, 5, 7, 9, 11]

And

   range(1,12,2)
=> [1, 3, 5, 7, 9, 11]

The result is the exact same, but which one would be correct in this case and why?

Does the end of a range have to do something with the steps you take?

Like, the idea that a list should give me 11 as the last number, so I
  should take 13 because we have a step of 2, or is this a bad thought?


问:
jQuery validation, how to auto clear error messages of hidden fields?
The jquery validate plugin auto removes error messages of visible fields when a value is entered, i have one hidden field populated by custom events whose error messages do not auto clear when the value is set. What would be a clean way to achieve this?

Thanks in advance for your help,

答:
OK, should anyone be interested in how to do this here is a simple way:</p>

```<code>$('.error:contains("here goes the text of the error message you want to remove")').remove();
</code>```

Body:
OK, should anyone be interested in how to do this here is a simple way:

$('.error:contains("here goes the text of the error message you want to remove")').remove();


问:
Google Translate API language code for Brazilian Portuguese
I am interesting in translating to Brazilian Portuguese. Based on the google translate API document, we only have "pt", which looks like Portugal Portuguese. Any suggestions on how to get Brazilian Portuguese via API ?</p>

答:
From what this document says, I think that the google API only has 1 type of Portugese.

They both appear on the same line as:

```<code>Portuguese (Portugal, Brazil)   pt
</code>```

Body:
From what this document says, I think that the google API only has 1 type of Portugese.

They both appear on the same line as:

Portuguese (Portugal, Brazil)   pt


问:
Why is res.render in Angular Universal taking so long?
I am building a Angular Universal App and all i have now is the Structure of the site. I did everything like in the tutorial concerning transforming my app for Angular Universal.

console.log("got Request " + new Date());
res.render(join(DIST_FOLDER, 'browser', 'index.html'), { req , time: true},
   function(err, html) {
      console.log("finished Rendering " + new Date());
      res.send(html);
   }
);
```

<p>The Rendering takes up 3 and a half seconds.. This seems like a huge amount of time to me. Also in the DeveloperTools in Chrome TTFB is 3,5 seconds.
And the app doesnt do anything yet except routing. I dont want  my future app to be so slow.</p>

<p>Anyone has a clue if this is normal or there is something to improve ?
Github repo with Problem  https://github.com/Joniras/slow-universal-rendering-example</p>

<p><strong>Setting up Workspace and running angular-universal:</strong>   </p>

```npm install
npm run build:universal
npm run serve:universal
```

Versions:

  Angular CLI: 1.5.0

  Node: 6.11.5
  OS: win32 x64
  Angular: 5.0.1
  ... animations, common, compiler, compiler-cli, core, forms
  ... http, language-service, platform-browser
  ... platform-browser-dynamic, platform-server, router
  @angular/cdk: 5.0.0-rc0
  @angular/cli: 1.5.0
  @angular/flex-layout: 2.0.0-beta.10-4905443
  @angular/material: 5.0.0-rc0
  @angular-devkit/build-optimizer: 0.0.33
  @angular-devkit/core: 0.0.20
  @angular-devkit/schematics: 0.0.35
  @ngtools/json-schema: 1.1.0
  @ngtools/webpack: 1.8.0
  @schematics/angular: 0.1.3
  typescript: 2.4.2
  webpack: 3.8.1
  express 4.16.2

  i had to style as code because otherwise i couldnt post

答:
There is a 3000 ms timeout in your code (UserService)</p>

```<code>setTimeout(() => {
          resolve(this.loggedInUser);
        }, 3000);
</code>```

Body:
I am building a Angular Universal App and all i have now is the Structure of the site. I did everything like in the tutorial concerning transforming my app for Angular Universal.

console.log("got Request " + new Date());
res.render(join(DIST_FOLDER, 'browser', 'index.html'), { req , time: true},
   function(err, html) {
      console.log("finished Rendering " + new Date());
      res.send(html);
   }
);

The Rendering takes up 3 and a half seconds.. This seems like a huge amount of time to me. Also in the DeveloperTools in Chrome TTFB is 3,5 seconds.
And the app doesnt do anything yet except routing. I dont want  my future app to be so slow.

Anyone has a clue if this is normal or there is something to improve ?
Github repo with Problem  https://github.com/Joniras/slow-universal-rendering-example

Setting up Workspace and running angular-universal:

npm install
npm run build:universal
npm run serve:universal

Versions:

  Angular CLI: 1.5.0

  Node: 6.11.5
  OS: win32 x64
  Angular: 5.0.1
  ... animations, common, compiler, compiler-cli, core, forms
  ... http, language-service, platform-browser
  ... platform-browser-dynamic, platform-server, router
  @angular/cdk: 5.0.0-rc0
  @angular/cli: 1.5.0
  @angular/flex-layout: 2.0.0-beta.10-4905443
  @angular/material: 5.0.0-rc0
  @angular-devkit/build-optimizer: 0.0.33
  @angular-devkit/core: 0.0.20
  @angular-devkit/schematics: 0.0.35
  @ngtools/json-schema: 1.1.0
  @ngtools/webpack: 1.8.0
  @schematics/angular: 0.1.3
  typescript: 2.4.2
  webpack: 3.8.1
  express 4.16.2

  i had to style as code because otherwise i couldnt post

Body:
There is a 3000 ms timeout in your code (UserService)

setTimeout(() => {
          resolve(this.loggedInUser);
        }, 3000);


问:
How to switch to f3 in the figure (Selenium + Python)
How to switch to f3?

How to know the current frame?

None of the commands below works:

```<code>driver.switch_to.frame('f3')
driver.switch_to.frame(driver.find_element_by_xpath("//frameset[@name='viewfrm']"))
driver.switch_to.frame(driver.find_element_by_xpath("//frameset[@name='f3']"))
</code>```

答:
Try the following code:</p>

```<code>driver.switch_to.frame(driver.find_element_by_name("f3"))
</code>```

Body:
How to switch to f3?

How to know the current frame?

None of the commands below works:

driver.switch_to.frame('f3')
driver.switch_to.frame(driver.find_element_by_xpath("//frameset[@name='viewfrm']"))
driver.switch_to.frame(driver.find_element_by_xpath("//frameset[@name='f3']"))

Body:
Try the following code:

driver.switch_to.frame(driver.find_element_by_name("f3"))


问:
Run chef cookook locally by keeping the cookbooks in remote server
We can run the chef cookbook locally (chef-solo or chef-zero) as follows

```<code>chef-client -z --runlist 'recipe[cookbookname::recipename]'
</code>```

Or

```<code>chef-client --local-mode C:\chefrepo\cookbooks\example\recipes\default.rb
</code>```

However, how to run CHEF client in local mode by keeping the cookbooks in remote server? Something like this?

```<code>chef-client --local-mode \\10.10.1.1\cookbooks\example\recipe
</code>```

Please clarify.

答: You can use --config-option chef_repo_path=whatever to control where the repo is located (by default it is /var/chef for chef-solo and . for local mode). That said, probably don't? Down the path of network filesystems for production file deployment lies much pain and suffering and unexplained outages. If you want a centralized storage system, that is literally what Chef Server is for.

Body:
We can run the chef cookbook locally (chef-solo or chef-zero) as follows

chef-client -z --runlist 'recipe[cookbookname::recipename]'

Or

chef-client --local-mode C:\chefrepo\cookbooks\example\recipes\default.rb

However, how to run CHEF client in local mode by keeping the cookbooks in remote server? Something like this?

chef-client --local-mode \\10.10.1.1\cookbooks\example\recipe

Please clarify.


问:
SVGZ file format
I'm working in SVG and just read about the compressed file 'SVGZ' format. As it makes our file sizes a lot smaller, I'm quite keen on using it in our web application, however the browsers do not appear to support the format. Can anyone point to any documentation on how to use SVGZ files instead of SVG in online documents/ apps.</p>

答:
SVGZ is just a gzipped SVG, see this.

Note: Not all browser support SVGZ. Your HTTP server may probably compresses its response with deflate, which have the same performance.

Title: SVGZ file format


问:
JPA Hibernate Dynamic entity mapping & persistence at runtime
Basically we have a spring boot application that requires that the user can define his/her own set of fields and that these fields should be persisted in their own class/table through JPA/Hibernate at runtime. These classes will be generated dynamically through bytebuddy.

All that should be done dynamically without having to restart the application.
The Hibernate Dynamic mapping is not an option, since we will be creating new classes entirely and re-map them.

I have also considered an EAV model but that will not work since we will need separate tables for each set of data so the JSON cannot be mixed in the same table.

The first solution that I'm considering is to proxy the EntityManagetFactory and when we have a new entity to map , I'll re-create the EntityManagetFactory  and add the new mapped entity to it, I'll also have the hbm2ddl.auto set to "update" in order to ensure that the new tables scheme will get created.

Problem is that I don't know what other classes that might need proxying, I believe I'll have to proxy the Hibernate SessionFactory but I'm not sure how many other classes that will need to be re-created and proxied and I believe that this is a complex path to go.

The other solution is to mix between the SQL and NoSQL solution by using Hibernate OGM, but in that case I'll loose any relationship that I can have with the existing SQL entities and I'm not in favor of running a second NoSQL DB.

is there are any other solutions I can explore ?

Edit:

I would use bytebuddy in order to generate the new classes dynamically and they would have the @Entity annotation, the generated classes are written into a temporary jar file ( e.g. /tmp/myjar.jar )

Using a BeanPostProcessor.postProcessAfterInitialization I would replace the LocalContainerEntityManagerFactoryBean with a proxy class.

Also I used the LocalContainerEntityManagerFactoryBean .setPersistenceUnitPostProcessors to add an extra processor that would process the classes from the newly created jar

So now after creating the new class with bytebuddy I would manually call the LocalContainerEntityManagerFactoryBeanProxy.afterProperties that does all the job of bootstrapping the JPA and hibernate layer , I do also set the "hibernate.hbm2ddl.auto" property to "update" so that the schema would be created ( I know that this is risky to be done in a production environment )

答:
Hibernate maps entities to tables, and the metadata is built during bootstrap. So, you can't modify it on the fly while the application is running.

However, as long as you keep on adding new tables without modifying the existing structure, you can address this issue at the architecture level:

You make the class changes you need.

You build the project artifacts.

You deploy the new project artifacts to a new server.

You switch traffic from the old server instance to the new one from the load balancer without any downtime.

Or, just use a NoSQL database like MongoDB with Hibernate OGM since your requirements do not fit very well into a relational database anyway.

But, if you already use a RDBMS, then it's simpler to just use JSON instead of switching to a NoSQL database just for that reason.


问:
Can we use AND and OR in a single findyBy method of Spring Data to access MonogDB?
I have added a custom query method in the Mongo Repository Interface:

```<code>Employee findByFirstNameAndLastName(Stirng firstName, String lastName);
</code>```

Which is returning Employees fulfilling the following criteria:

// FirstName AND Last Name

Above method works really good, All thanks to Spring Data.

But, I want something like this:

```<code>Employee findByFirstNameAndLastNameOrDesignation(Stirng firstName, String lastName, String designation);
</code>```

Above method should return Employee details as per following criteria:

// FirstName AND (Last Name OR Designation)

Is it possible to use AND and OR in a single method?

答:
Although SpringData is powerful it is not so powerful. There is no way that SpringData know what you want:

1) A and (B or C)

or

2) (A and B) or C
etc...

You can use @NamedQuery or @Query.

Another option is to utilize Bool algebra. For example

A and (B or C) == (A and B)or (A and C)

so you can have method with following name: findByAandB_AandC.

Body:
I have added a custom query method in the Mongo Repository Interface:

Employee findByFirstNameAndLastName(Stirng firstName, String lastName);

Which is returning Employees fulfilling the following criteria:

// FirstName AND Last Name

Above method works really good, All thanks to Spring Data.

But, I want something like this:

Employee findByFirstNameAndLastNameOrDesignation(Stirng firstName, String lastName, String designation);

Above method should return Employee details as per following criteria:

// FirstName AND (Last Name OR Designation)

Is it possible to use AND and OR in a single method?


Title: aggregate/merge over date range using data.table

Body:
Suppose I have two data.tables:

summary <- data.table(period = c("A","B","C","D"),
                 from_date = ymd(c("2017-01-01", "2017-01-03", "2017-02-08", "2017-03-07")),
                 to_date = ymd(c("2017-01-31", "2017-04-01", "2017-03-08", "2017-05-01"))
)

log <- data.table(date = ymd(c("2017-01-03","2017-01-20","2017-02-01","2017-03-03",
                               "2017-03-15","2017-03-28","2017-04-03","2017-04-23")),
                  event1 = c(4,8,8,4,3,4,7,3), event2 = c(1,8,7,3,8,4,6,3))

which look like this:

> summary
   period  from_date    to_date
1:      A 2017-01-01 2017-01-31
2:      B 2017-01-03 2017-04-01
3:      C 2017-02-08 2017-03-08
4:      D 2017-03-07 2017-05-01
> log
         date event1 event2
1: 2017-01-03      4      1
2: 2017-01-20      8      8
3: 2017-02-01      8      7
4: 2017-03-03      4      3
5: 2017-03-15      3      8
6: 2017-03-28      4      4
7: 2017-04-03      7      6
8: 2017-04-23      3      3

I would like to get the sum of event1 and event2 for each time period in the table summary.

I know I can do this:

summary[, c("event1","event2") := .(sum(log[date>=from_date & date<=to_date, event1]),
                               sum(log[date>=from_date & date<=to_date, event2]))
   , by=period][]

to get the desired result:

   period  from_date    to_date event1 event2
1:      A 2017-01-01 2017-01-31     12      9
2:      B 2017-01-03 2017-04-01     31     31
3:      C 2017-02-08 2017-03-08      4      3
4:      D 2017-03-07 2017-05-01     17     21

Now, in my real-life problem, I have about 30 columns to be summed, which I may want to change later, and summary has ~35,000 rows, log has ~40,000,000 rows. Is there an efficient way to achieve this?

Note: This is my first post here. I hope my question is clear and specific enough, please do make suggestions if there is anything I should do to improve the question. Thanks!

Body:
With data.table, it is possible to aggregate during a non-equi join using by = .EACHI.

log[summary, on = .(date >= from_date, date <= to_date), nomatch=0L,
    lapply(.SD, sum), by = .EACHI]

         date       date event1 event2
1: 2017-01-01 2017-01-31     12      9
2: 2017-01-03 2017-04-01     31     31
3: 2017-02-08 2017-03-08      4      3
4: 2017-03-07 2017-05-01     17     21

With some additional clean-up:

log[summary, on = .(date >= from_date, date <= to_date), nomatch=0L,
    c(period = period, lapply(.SD, sum)), by = .EACHI][
      , setnames(.SD, 1:2, c("from_date", "to_date"))]

    from_date    to_date period event1 event2
1: 2017-01-01 2017-01-31      A     12      9
2: 2017-01-03 2017-04-01      B     31     31
3: 2017-02-08 2017-03-08      C      4      3
4: 2017-03-07 2017-05-01      D     17     21


问:
how can i use ionViewDidLoad() in a component?
Hello I'm working on ionic 3 and I have data stored in local storage. I would like to use these data in a component , but ionViewDidLoad (which is work perfectly in a normal page) doesn't work on a component and I have got the below error:

So please is there any other suggestions ?

component code (offre.ts):

```<code>    import { Component, Input , Output } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from "angularfire2/database";
import { IonicPage, NavController, NavParams} from 'ionic-angular';
import { NativeStorage } from '@ionic-native/native-storage';

@Component({
  selector: 'offre',
  templateUrl: 'offre.html',

})
export class OffreComponent {

    @Input('var') var;
    text: string;
    datas: FirebaseListObservable<any>;
    user : any ;

  constructor(public navCtrl: NavController, public db: AngularFireDatabase, public nativeStorage: NativeStorage) {
    this.datas=db.list('/posts');

  }

  ngAfterViewInit(){
    console.log(this.var);
  }
}
</code>```

答: use ionViewCanEnter() which will be called before the ionViewDidLoad()</p>

Body:
Hello I'm working on ionic 3 and I have data stored in local storage. I would like to use these data in a component , but ionViewDidLoad (which is work perfectly in a normal page) doesn't work on a component and I have got the below error:

So please is there any other suggestions ?

component code (offre.ts):

    import { Component, Input , Output } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from "angularfire2/database";
import { IonicPage, NavController, NavParams} from 'ionic-angular';
import { NativeStorage } from '@ionic-native/native-storage';

@Component({
  selector: 'offre',
  templateUrl: 'offre.html',

})
export class OffreComponent {

    @Input('var') var;
    text: string;
    datas: FirebaseListObservable<any>;
    user : any ;

  constructor(public navCtrl: NavController, public db: AngularFireDatabase, public nativeStorage: NativeStorage) {
    this.datas=db.list('/posts');

  }

  ngAfterViewInit(){
    console.log(this.var);
  }
}


问:
What is MASM ? which we generally use it for learning assembly language code?
In 8086 processor,what ic's we use are different...i think they are of 16 bit...but we practice the code in 64 bit computers..how is it possible?please expalin>>>>What is MaSm actually?? and can you explain me where I can get the software....</p>

答:
MASM is microsoft's macro assembler. The Microsoft Assembler has been in production since 1981 and is upgraded by Microsoft to keep abreast with operating system needs and processor developments. for compatibilities issues check this

can be downloaded from here