答:
Do not use  echo for print arrays or objects.

```<code>$testing = json_encode(
    array(
        'Assignments' => array(
            0 => array(
                'ass_name'      => 'Test123',
                'class_id'      => 2,
                'date_assigned' => '2017-08-23',
                'done'          => false,
                'due'           => '2017-08-23 13:34:54',
                'id'            => 10,
                'weight'        => 65,
            ),
        ),
    )
);

$json = json_decode($testing, true);
echo $json; // prints "Array"
print_r($json); // prints all items in array
</code>```

Title: Parse this string of a JSONObject that contains a JSONArray of JSONObjects

Body:
Do not use  echo for print arrays or objects.

$testing = json_encode(
    array(
        'Assignments' => array(
            0 => array(
                'ass_name'      => 'Test123',
                'class_id'      => 2,
                'date_assigned' => '2017-08-23',
                'done'          => false,
                'due'           => '2017-08-23 13:34:54',
                'id'            => 10,
                'weight'        => 65,
            ),
        ),
    )
);

$json = json_decode($testing, true);
echo $json; // prints "Array"
print_r($json); // prints all items in array


来源: stackexchange

问:
Python shell showing error but cmd is running that program
I am new in python.I am doing addition of two numbers in cmd using input parameter .I am getting output on cmd but  getting Error on python shell.I am using windows 7 and python shell 3.3.2 . so anyone can tell me why my code is not running on python shell ?

code:

```<code>import sys
n=int(sys.argv[1])
m=int(sys.argv[2])
print(n+m)
</code>```

Error:

Traceback (most recent call last):

File "C:/pythonprogram/add.py",  line 4, in

```<code>n=int(sys.argv[1])
</code>```

IndexError: list index out of range

答:
sys.argv contains the command line parameters. When you run your script in the Python shell you're most likely not sending any parameters. I would suggest adding a check if there are command line arguments present like this:

```<code>import sys

if len(sys.argv) > 2:
    n=int(sys.argv[1])
    m=int(sys.argv[2])
    print(n+m)
</code>```

Check this out to find out more about Python and sys.argv

ContentLicense: CC BY-SA 3.0

Body:
I am new in python.I am doing addition of two numbers in cmd using input parameter .I am getting output on cmd but  getting Error on python shell.I am using windows 7 and python shell 3.3.2 . so anyone can tell me why my code is not running on python shell ?

code:

import sys
n=int(sys.argv[1])
m=int(sys.argv[2])
print(n+m)

Error:

Traceback (most recent call last):

File "C:/pythonprogram/add.py",  line 4, in

n=int(sys.argv[1])

IndexError: list index out of range

Body:
sys.argv contains the command line parameters. When you run your script in the Python shell you're most likely not sending any parameters. I would suggest adding a check if there are command line arguments present like this:

import sys

if len(sys.argv) > 2:
    n=int(sys.argv[1])
    m=int(sys.argv[2])
    print(n+m)

Check this out to find out more about Python and sys.argv


问:
How does containers scale in an AWS elasticbeanstalk multi-container
If I have a 3 containers; One for nginx(proxy and frontend), another container for user system/api and finally last for Blog post.

So when the elasticbean tries to scale does it scale all of these containers at once or it only scales the specific type of container/s which is getting high traffic?

答: As far as I can tell, it scales all at once - which makes no sense. Please, I would love to be proved wrong here.</p>


问:
How to search through every single table in database and remove specific rows
I want to know how to search through multiple tables and remove specific rows.

For example:

table_a has column issue_id

table_b has column issue_id

table_c has column issue_id

Consider the following LINQ / Entity Framework query:

```<code>Context db = new Context();

var row = from i in db.table_a
          where i.IssueID == 1
          select i;

db.Issues.RemoveRange(row);
</code>```

This only deletes rows from table_a.  Is there any method that I can use to remove the similar rows from all three tables at the same time?

答:
You can try this approach, in assumption that all interesting to us tables implement Iissue_id interface:

```<code>public interface Iissue_id
{
    int issue_id { get; set; }
}

public class table_a : Iissue_id
{
    public int issue_id { get; set; }
    //other properties
}

public void DeleteAllRowsWithIssue_id(int issue_id)
{
    using (var context = new MyContext())
    {
        foreach (var table in typeof(MyContext).Assembly.GetTypes().Where(x => x.GetInterface(nameof(Iissue_id)) != null).ToList())
            context.Database.ExecuteSqlCommand($"delete from {table.Name} where id = @p0", issue_id);
    }
}
</code>```

Body:
I want to know how to search through multiple tables and remove specific rows.

For example:

table_a has column issue_id

table_b has column issue_id

table_c has column issue_id

Consider the following LINQ / Entity Framework query:

Context db = new Context();

var row = from i in db.table_a
          where i.IssueID == 1
          select i;

db.Issues.RemoveRange(row);

This only deletes rows from table_a.  Is there any method that I can use to remove the similar rows from all three tables at the same time?

Body:
You can try this approach, in assumption that all interesting to us tables implement Iissue_id interface:

public interface Iissue_id
{
    int issue_id { get; set; }
}

public class table_a : Iissue_id
{
    public int issue_id { get; set; }
    //other properties
}

public void DeleteAllRowsWithIssue_id(int issue_id)
{
    using (var context = new MyContext())
    {
        foreach (var table in typeof(MyContext).Assembly.GetTypes().Where(x => x.GetInterface(nameof(Iissue_id)) != null).ToList())
            context.Database.ExecuteSqlCommand($"delete from {table.Name} where id = @p0", issue_id);
    }
}


问:
Has anyone tracked down whether IronPython or IronRuby will support Attributes?
I have scanned 'the Google' and have not found the definitive answer on whether the Iron* languages (any or all) will end up with Attribute support..

Anyone?

Thanks - Jon

答: As of last August IronRuby did not have Attribute support yet, and I haven't seen any recent announcements about it since then, but it is definitely a planned feature.</p>

OwnerDisplayName: jdharley

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: ALassek


问:
spring security - logout when session expires and also allowing anonymous user to access the functionality
I have a requirement to redirect to login page when session expires for a logged in user.
However the functionality is accessible as anonymous user (i.e the user not logged in) as well.

A feature "Search Address" is accessible by everyone, meaning logged in users and anonymous users (user not logged in)....

So the requirement is such, that when the user logs in and performs search, it should redirect if session has already expired, however just making it clear the same search should work if we don't login in (i.e anonymous).

An anonymous user is technically logged in, therefore they have a session created as well, however they wouldn't manually type user name/password in to login as opposed to the logged in user

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                            http://www.springframework.org/schema/security
                            http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <security:http security="none"
        pattern="^/(login\.jsp|customSkin|openlayers|images|js)[/\?].*$"
        request-matcher="regex"/>

    <security:http entry-point-ref="http403ForbiddenEntryPoint">

        <security:anonymous enabled="true" granted-authority="ROLE_GENERIC" />

        <security:custom-filter position="FORM_LOGIN_FILTER" ref="formLoginFilter"/>
        <security:custom-filter position="PRE_AUTH_FILTER" ref="PreAuthenticationFilter"/>

        <!-- <security:logout logout-success-url="/loginUI.jsp" /> -->
        <security:logout logout-url="/logout" success-handler-ref="LogoutSuccessHandler" />
        <security:session-management session-authentication-strategy-ref="sessionAuthenticationStrategy"/>

        <!-- SMES Interceptors -->
        <security:intercept-url pattern="/Mark**" access="ROLE_ABC_OSGV" />
        <security:intercept-url pattern="/abc/admin/**" access="ROLE_ABC_OSGV" />
        <security:intercept-url pattern="/abc/edit/**" access="ROLE_ABC_OSGV,ROLE_ABC_REGISTERED_USER" />
        <security:intercept-url pattern="/abclookup/**" access="ROLE_ABC_OSGV,ROLE_ABC_REGISTERED_USER,ROLE_GENERIC,ROLE_ADMIN,ROLE_EDIT,ROLE_ABC_ADMIN,ROLE_ABC_HCA" />

        <security:intercept-url pattern="/general/**" access=
                    "ROLE_ABC,
                    ROLE_GENERIC,
                    ROLE_ADMIN,
                    ROLE_ABC_EXPORT,
                    ROLE_EDIT,
                    ROLE_ABC,
                    ROLE_ABC_TPC,
                    ROLE_ABC_VMT,
                    ROLE_ABC_S,
                    ROLE_ABC_DATA_GENERIC,
                    ROLE_ABC_DATA_ADMIN,
                    ROLE_ABC_OSGV,
                    ROLE_ABC_REGISTERED_USER,
                    ROLE_ABC_ADMIN,
                    ROLE_ABC_HCA,
                    ROLE_ABC_NAMES" />

        <!-- SMES Interceptors -->
        <security:intercept-url pattern="/vicnames/edit/**" access="ROLE_ABC_ADMIN,ROLE_ABC_HCA" />
        <security:intercept-url pattern="/vicnames/admin/**" access="ROLE_ABC_ADMIN" />

        <!-- LASSI Interceptors -->
        <security:intercept-url pattern="/edit/**" access="ROLE_ADMIN,ROLE_EDIT" />
        <security:intercept-url pattern="/broadcast/save**" access="ROLE_EDIT" />
        <security:intercept-url pattern="/edmbooking/admin/**" access="ROLE_ABC_BOOKING_ADMIN" />
        <security:intercept-url pattern="/adminUdateLogicaLabels**" access="ROLE_ADMIN,ROLE_EDIT" />

        <security:intercept-url pattern="/**" access=
                    "ROLE_DQA,
                    ROLE_GENERIC,
                    ROLE_ADMIN,
                    ROLE_DQA_EXPORT,
                    ROLE_EDIT,
                    ROLE_APS,
                    ROLE_ABC_TPC,
                    ROLE_ABC_VMT,
                    ROLE_ABC_TEST,
                    ROLE_ABC_DATA_GENERIC,
                    ROLE_ABC_DATA_ADMIN,
                    ROLE_ABC_OSGV,
                    ROLE_ABC_REGISTERED_USER,
                    ROLE_ABC_ADMIN,
                    ROLE_ABC_HCA,
                    ROLE_ABC_NAMES" />
        <security:access-denied-handler ref="accessDeniedHandler"/>

    </security:http>

    <bean id="LogoutSuccessHandler"
        class="LogoutHandlerImpl">
    </bean>

    <bean id="http403ForbiddenEntryPoint"
        class="CustomHttp403ForbiddenEntryPoint">
    </bean>

    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider ref="preAuthenticationProvider" />
        <security:authentication-provider ref="myProfileAuthenticationProvider" />
    </security:authentication-manager>

    <bean id="preAuthenticationFilter" class="PreAuthenticatedProcessingFilter">
        <property name="authenticationManager" ref="authenticationManager" />
    </bean>

    <bean id="formLoginFilter" class="UsernamePasswordAuthenticationFilter">
        <property name="authenticationManager" ref="authenticationManager" />
        <property name="authenticationSuccessHandler" ref = "authenticationSuccessHandler"/>
        <property name="authenticationFailureHandler" ref = "authenticationFailureHandler" />
    </bean>

    <bean id="authenticationSuccessHandler"
        class="AuthenticationSuccessHandlerImpl">
         <!--<property name="defaultTargetUrl" value="/login.jsp"/>-->
         <property name="alwaysUseDefaultTargetUrl" value="true" />
    </bean>

    <bean id="authenticationFailureHandler"
        class="AuthenticationFailureHandler">
        <!-- <property name="defaultFailureUrl" value="/sessionTimeout.jsp?login_error=true"/> -->
        <property name="defaultFailureUrl" value="/login.jsp?login_error=true"/>
    </bean>

    <bean id="preAuthenticationProvider"
        class="PreAuthenticatedAuthenticationProvider">
        <property name="preAuthenticatedUserDetailsService" ref="lpreAuthenticatedUserDetailsService"/>
    </bean>

    <bean id="lpreAuthenticatedUserDetailsService" class="somepreauthenticateduserdetailsservice"/>

    <bean id="myProfileAuthenticationProvider"
        class="com.test.AuthenticationProvider">
        <property name="serviceInvoker" ref="authenticationServiceInvoker" />
        <property name="roleMapping">
            <map>
                <entry key="ABC_DQA" value="ROLE_DQA" />
                <entry key="ABC_APS" value="ROLE_APS" />
                <entry key="ABC_EDIT" value="ROLE_EDIT" />
                <entry key="ABC_ADMINISTRATOR" value="ROLE_ADMIN" />
                <entry key="ABC_GENERIC" value="ROLE_GENERIC" />
                <entry key="ABC_DQA_EXPORT" value="ROLE_DQA_EXPORT" />
                <entry key="ABC_FOH" value="ROLE_ABC_FOH" />
                <entry key="ABC_TPC" value="ROLE_ABC_TPC" />
                <entry key="ABC_VMT" value="ROLE_ABC_VMT" />
                <entry key="ABC_SPEAR" value="ROLE_ABC_TEST" />
                <entry key="ABC_LANDATA_GENERIC" value="ROLE_ABC_DATA_GENERIC" />
                <entry key="ABC_LANDATA_ADMIN" value="ROLE_ABC_DATA_ADMIN" />
                <entry key="ABC_OSGV"           value="ROLE_ABC_OSGV" />
                <entry key="ABC_Registered_Users" value="ROLE_ABC_REGISTERED_USER" />
                <entry key="ABC_ADMINISTRATOR_ROLE" value="ROLE_ABC_ADMIN" />
                <entry key="ABC_HISTORIAN_ROLE" value="ROLE_ABC_HCA" />
                <entry key="ABC_PUBLIC_ROLE" value="ROLE_ABC_NAMES" />
                <entry key="ABC_BOOKING_ADMIN" value="ROLE_EDM_BOOKING_ADMIN" />
            </map>
        </property>
    </bean>

     <bean id="accessDeniedHandler"
          class="someaccessdeniedhandler">
        <property name="errorPage" value="/login.jsp?access_denied=true"/>
    </bean>

    <bean id="authenticationServiceInvoker"
        class="com.test.AuthenticationServiceInvoker" />

    <bean id="sessionAuthenticationStrategy" class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy">
        <constructor-arg name="sessionRegistry" ref="sessionRegistry"/>
        <property name="maximumSessions" value="1"/>
    </bean>

    <bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"/>

</beans>

public class CustomHttp403ForbiddenEntryPoint implements AuthenticationEntryPoint {
    private static final Log logger = LogFactory.getLog(Http403ForbiddenEntryPoint.class);

    /**
     * Always returns a 403 error code to the client.
     */
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) throws IOException,
            ServletException {
        if (logger.isDebugEnabled()) {
            logger.debug("Pre-authenticated entry point called. Rejecting access");
        }
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        if (request.getUserPrincipal() == null && request.getContentType() != null && request.getContentType().toLowerCase().indexOf("multipart/form-data") > -1 ) {
            returnJSSCript(request, response, "{\"sessionTimeout\":\"true\"}");
        }
        else {
            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
        }
    }

    private void returnJSSCript(HttpServletRequest req, HttpServletResponse response, String msg){
        response.setContentType("text/html");
        try {
            String eventName = "sessionTimeout";
            PrintWriter out = response.getWriter();
            out.println("<script type=\"text/javascript\">");
            out.println("parent.fireEvent('" + eventName + "','" + msg + "');");
            out.println("</script>");
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

}
</code>```

Could you please let me know how we can redirect to a login page when the user's session has been expired without breaking the search functionality of allowing the anonymous user to still perform the search in Spring Security.

Cheers,
Tech XX

答:
Just make the search url anon, and take it out to another http configuration, So it will not be filtered in your /** chain(<security:http entry-point-ref="http403ForbiddenEntryPoint">).

```<code><security:http pattern="/general/search.json" security="none"/>
</code>```

Body:
I have a requirement to redirect to login page when session expires for a logged in user.
However the functionality is accessible as anonymous user (i.e the user not logged in) as well.

A feature "Search Address" is accessible by everyone, meaning logged in users and anonymous users (user not logged in)....

So the requirement is such, that when the user logs in and performs search, it should redirect if session has already expired, however just making it clear the same search should work if we don't login in (i.e anonymous).

An anonymous user is technically logged in, therefore they have a session created as well, however they wouldn't manually type user name/password in to login as opposed to the logged in user

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                            http://www.springframework.org/schema/security
                            http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <security:http security="none"
        pattern="^/(login\.jsp|customSkin|openlayers|images|js)[/\?].*$"
        request-matcher="regex"/>

    <security:http entry-point-ref="http403ForbiddenEntryPoint">

        <security:anonymous enabled="true" granted-authority="ROLE_GENERIC" />

        <security:custom-filter position="FORM_LOGIN_FILTER" ref="formLoginFilter"/>
        <security:custom-filter position="PRE_AUTH_FILTER" ref="PreAuthenticationFilter"/>

        <security:logout logout-url="/logout" success-handler-ref="LogoutSuccessHandler" />
        <security:session-management session-authentication-strategy-ref="sessionAuthenticationStrategy"/>

        <security:intercept-url pattern="/Mark**" access="ROLE_ABC_OSGV" />
        <security:intercept-url pattern="/abc/admin/**" access="ROLE_ABC_OSGV" />
        <security:intercept-url pattern="/abc/edit/**" access="ROLE_ABC_OSGV,ROLE_ABC_REGISTERED_USER" />
        <security:intercept-url pattern="/abclookup/**" access="ROLE_ABC_OSGV,ROLE_ABC_REGISTERED_USER,ROLE_GENERIC,ROLE_ADMIN,ROLE_EDIT,ROLE_ABC_ADMIN,ROLE_ABC_HCA" />

        <security:intercept-url pattern="/general/**" access=
                    "ROLE_ABC,
                    ROLE_GENERIC,
                    ROLE_ADMIN,
                    ROLE_ABC_EXPORT,
                    ROLE_EDIT,
                    ROLE_ABC,
                    ROLE_ABC_TPC,
                    ROLE_ABC_VMT,
                    ROLE_ABC_S,
                    ROLE_ABC_DATA_GENERIC,
                    ROLE_ABC_DATA_ADMIN,
                    ROLE_ABC_OSGV,
                    ROLE_ABC_REGISTERED_USER,
                    ROLE_ABC_ADMIN,
                    ROLE_ABC_HCA,
                    ROLE_ABC_NAMES" />

        <security:intercept-url pattern="/vicnames/edit/**" access="ROLE_ABC_ADMIN,ROLE_ABC_HCA" />
        <security:intercept-url pattern="/vicnames/admin/**" access="ROLE_ABC_ADMIN" />

        <security:intercept-url pattern="/edit/**" access="ROLE_ADMIN,ROLE_EDIT" />
        <security:intercept-url pattern="/broadcast/save**" access="ROLE_EDIT" />
        <security:intercept-url pattern="/edmbooking/admin/**" access="ROLE_ABC_BOOKING_ADMIN" />
        <security:intercept-url pattern="/adminUdateLogicaLabels**" access="ROLE_ADMIN,ROLE_EDIT" />

        <security:intercept-url pattern="/**" access=
                    "ROLE_DQA,
                    ROLE_GENERIC,
                    ROLE_ADMIN,
                    ROLE_DQA_EXPORT,
                    ROLE_EDIT,
                    ROLE_APS,
                    ROLE_ABC_TPC,
                    ROLE_ABC_VMT,
                    ROLE_ABC_TEST,
                    ROLE_ABC_DATA_GENERIC,
                    ROLE_ABC_DATA_ADMIN,
                    ROLE_ABC_OSGV,
                    ROLE_ABC_REGISTERED_USER,
                    ROLE_ABC_ADMIN,
                    ROLE_ABC_HCA,
                    ROLE_ABC_NAMES" />
        <security:access-denied-handler ref="accessDeniedHandler"/>

    </security:http>

    <bean id="LogoutSuccessHandler"
        class="LogoutHandlerImpl">
    </bean>

    <bean id="http403ForbiddenEntryPoint"
        class="CustomHttp403ForbiddenEntryPoint">
    </bean>

    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider ref="preAuthenticationProvider" />
        <security:authentication-provider ref="myProfileAuthenticationProvider" />
    </security:authentication-manager>

    <bean id="preAuthenticationFilter" class="PreAuthenticatedProcessingFilter">
        <property name="authenticationManager" ref="authenticationManager" />
    </bean>

    <bean id="formLoginFilter" class="UsernamePasswordAuthenticationFilter">
        <property name="authenticationManager" ref="authenticationManager" />
        <property name="authenticationSuccessHandler" ref = "authenticationSuccessHandler"/>
        <property name="authenticationFailureHandler" ref = "authenticationFailureHandler" />
    </bean>

    <bean id="authenticationSuccessHandler"
        class="AuthenticationSuccessHandlerImpl">

         <property name="alwaysUseDefaultTargetUrl" value="true" />
    </bean>

    <bean id="authenticationFailureHandler"
        class="AuthenticationFailureHandler">

        <property name="defaultFailureUrl" value="/login.jsp?login_error=true"/>
    </bean>

    <bean id="preAuthenticationProvider"
        class="PreAuthenticatedAuthenticationProvider">
        <property name="preAuthenticatedUserDetailsService" ref="lpreAuthenticatedUserDetailsService"/>
    </bean>

    <bean id="lpreAuthenticatedUserDetailsService" class="somepreauthenticateduserdetailsservice"/>

    <bean id="myProfileAuthenticationProvider"
        class="com.test.AuthenticationProvider">
        <property name="serviceInvoker" ref="authenticationServiceInvoker" />
        <property name="roleMapping">
            <map>
                <entry key="ABC_DQA" value="ROLE_DQA" />
                <entry key="ABC_APS" value="ROLE_APS" />
                <entry key="ABC_EDIT" value="ROLE_EDIT" />
                <entry key="ABC_ADMINISTRATOR" value="ROLE_ADMIN" />
                <entry key="ABC_GENERIC" value="ROLE_GENERIC" />
                <entry key="ABC_DQA_EXPORT" value="ROLE_DQA_EXPORT" />
                <entry key="ABC_FOH" value="ROLE_ABC_FOH" />
                <entry key="ABC_TPC" value="ROLE_ABC_TPC" />
                <entry key="ABC_VMT" value="ROLE_ABC_VMT" />
                <entry key="ABC_SPEAR" value="ROLE_ABC_TEST" />
                <entry key="ABC_LANDATA_GENERIC" value="ROLE_ABC_DATA_GENERIC" />
                <entry key="ABC_LANDATA_ADMIN" value="ROLE_ABC_DATA_ADMIN" />
                <entry key="ABC_OSGV"           value="ROLE_ABC_OSGV" />
                <entry key="ABC_Registered_Users" value="ROLE_ABC_REGISTERED_USER" />
                <entry key="ABC_ADMINISTRATOR_ROLE" value="ROLE_ABC_ADMIN" />
                <entry key="ABC_HISTORIAN_ROLE" value="ROLE_ABC_HCA" />
                <entry key="ABC_PUBLIC_ROLE" value="ROLE_ABC_NAMES" />
                <entry key="ABC_BOOKING_ADMIN" value="ROLE_EDM_BOOKING_ADMIN" />
            </map>
        </property>
    </bean>

     <bean id="accessDeniedHandler"
          class="someaccessdeniedhandler">
        <property name="errorPage" value="/login.jsp?access_denied=true"/>
    </bean>

    <bean id="authenticationServiceInvoker"
        class="com.test.AuthenticationServiceInvoker" />

    <bean id="sessionAuthenticationStrategy" class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy">
        <constructor-arg name="sessionRegistry" ref="sessionRegistry"/>
        <property name="maximumSessions" value="1"/>
    </bean>

    <bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"/>

</beans>

public class CustomHttp403ForbiddenEntryPoint implements AuthenticationEntryPoint {
    private static final Log logger = LogFactory.getLog(Http403ForbiddenEntryPoint.class);

    /**
     * Always returns a 403 error code to the client.
     */
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) throws IOException,
            ServletException {
        if (logger.isDebugEnabled()) {
            logger.debug("Pre-authenticated entry point called. Rejecting access");
        }
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        if (request.getUserPrincipal() == null && request.getContentType() != null && request.getContentType().toLowerCase().indexOf("multipart/form-data") > -1 ) {
            returnJSSCript(request, response, "{\"sessionTimeout\":\"true\"}");
        }
        else {
            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
        }
    }

    private void returnJSSCript(HttpServletRequest req, HttpServletResponse response, String msg){
        response.setContentType("text/html");
        try {
            String eventName = "sessionTimeout";
            PrintWriter out = response.getWriter();
            out.println("");
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Could you please let me know how we can redirect to a login page when the user's session has been expired without breaking the search functionality of allowing the anonymous user to still perform the search in Spring Security.

Cheers,
Tech XX

Body:
Just make the search url anon, and take it out to another http configuration, So it will not be filtered in your /** chain(<security:http entry-point-ref="http403ForbiddenEntryPoint">).

<security:http pattern="/general/search.json" security="none"/>


问:
JSON Parsing Error: Unexpected character (s) at position 226025
I saw similar question on Stackoverflow but none of them helped me to solve my issue. So, I am asking for help as I have tried to find out what is the reason behind the error I am getting but failed. Please don't mark it as a duplicate question.

I am parsing a Json file and getting the following error.

```<code>Jun 06, 2017 2:06:24 PM edu.virginia.cs.services.FileManager ParseJson
SEVERE: null
Unexpected character (s) at position 226025.
    at org.json.simple.parser.Yylex.yylex(Yylex.java:610)
    at org.json.simple.parser.JSONParser.nextToken(JSONParser.java:269)
    at org.json.simple.parser.JSONParser.parse(JSONParser.java:118)
    at org.json.simple.parser.JSONParser.parse(JSONParser.java:92)
    at edu.virginia.cs.services.FileManager.ParseJson(FileManager.java:68)
    at edu.virginia.cs.main.Processer.main(Processer.java:20)

Exception in thread "main" java.lang.NullPointerException
    at edu.virginia.cs.services.FileManager.ParseJson(FileManager.java:76)
    at edu.virginia.cs.main.Processer.main(Processer.java:20)
</code>```

Code of interest:

```<code>try {
    arr = (JSONArray) parser.parse(new FileReader(sourceFile));
} catch (IOException | ParseException ex) {
    Logger.getLogger(FileManager.class.getName()).log(Level.SEVERE, null, ex);
}
</code>```

File content looks like as follows:

```<code>[
    {
        "url": "http://www.save-on-crafts.com/",
        "title": "Events & Wedding Sale | Save 20-60% | SaveOnCrafts",
        "content": {
            "p": ["Wedding decorations, party supplies, home d cor & craft supplies at 20-70% off. Save On Crafts brings you classic and trending fashions.", "Save On Crafts has continually evolved to meet the needs of our customers   DIY brides, home decorators, party planners, florists, and caterers. Our goal is simple: provide an exciting selection of quality , , and items at the lowest price possible for the customer with discerning taste."],
            "div": ["indicates required", "(831) 768-8428", "Take a Peek at our Specials: Save up to 70%!", "Candle Holders", "Flowers & Branches", "Crystal D cor, Chandeliers", "Set the Mood with Candles", "Champagne & Ice Buckets", "Chalkboards", "Eco Confetti", "Wedding Signs", "Sola Flowers", "Natural Wood Slices", "Classic & trending styles without the traditional retail markup.", "(831) 768-8428"],
            "a": ["X", "What's New", "SPECIALS", "Wedding Decorations", "Lights | Event Lighting", "Wood Slabs & Tree Slices", "Vases", "Apothecary Jars", "Banners", "Baskets", "Bell Jars, Cloches", "Beverage Bar Supplies", "Bird Cages & Birds", "Botanicals, Lavender, Sola Flowers", "Bottles & Jars", "Branches - Natural", "Buckets & Tubs", "Burlap Fabric, Jute, and Linen", "Cake Stands", "Candles", "Candle Holders", "Candy Buffet", "Chair Sashes, Banners, Signs", "Chalkboards", "Chandeliers", "Charger & Base Plates", "Confetti", "Corsage & Bouquet Supplies", "Craft Supplies", "Crates, Boxes, & Trays", "Crystal Decorations", "Easels & Frames", "Event Decor", "Favors", "Feathers", "Floral Supplies", "Flowers", "Greenery", "Home & Garden Decor", "Lanterns", "Mirrors & Mirror Stands", "Moss Natural & Artificial", "Nautical Decor & Decorations", "Packaging, Gift Wrapping", "Paper Lanterns & Parasols", "Paper Party Decorations", "Party Supplies", "Pots & Planters", "Placecard Holders,Table Numbers, Displays", "Preserved Flowers & Leaves", "Props, Pedestals, Risers", "Ribbon", "Silk Flowers", "Signage", "Shells - Sand", "Shepherds Hooks & Stanchions", "Sola Flowers", "Succulents & Cactus", "Table Runners & Toppers", "Terrariums", "Tote Bags, Welcome Bags", "Trees, Potted Plants", "Vases & Vase Fillers", "Wedding Cake Decorations and Toppers", "Wedding Decorations", "Wedding Signs", "Wedding Themes", "Wedding Trees & Wishing Trees", "Wood Crafts", "Wood Slabs & Tree Slices", "Wreath Making Supplies, Frames, Forms", "Gifts - Holiday Decorations", "Gifts Under $25", "Ideas & Inspiration", "Shopping Cart", "About", "Shipping", "Return Policy", "Contact", "FAQ", "Privacy Policy", "Terms and Conditions", "Read More", "Shipping", "Cart"],
            "strong": ["Need Help?", "SUBSCRIBE", "wedding supplies", "party decorations", "home d cor", "Affordable Wedding & Event Decor", "Save 20-70%", "Need Help?"],
            "span": ["*", "*", "Live Chat", "Shop Categories", "Customer Service: 7am - 5pm PST (M-F) | (831)768-8428", "Copyright   2017 Save-On-Crafts. All Rights Reserved. Designated trademarks and brands are the property of their respective owners. Use of this website constitutes acceptance of the Save-On-Craftsand Privacy Policy.", "Live Chat"]
        }
    },
    {
        "url": "http://www.carsurvey.org/",
        "title": "Carsurvey.org - Car Reviews",
        "content": {
            "p": ["I feel as if this vehicle was custom built for me, love it", "Neat cruiser, comfort first, performance second", "Beast maaaaaaate!", "Best value for the money", "There are reviews on the site", "new reviews and new comments are in the Members section, awaiting approval"],
            "td": ["2 days ago", "2 days ago", "3 days ago", "3 days ago", "18 hours ago", "19 hours ago", "19 hours ago", "19 hours ago"],
            "a": ["Write a Review", "About", "Members", "Reviews by Region", "Write a Review", "About", "Members", "Reviews by Region", "BMW", "Buick", "Chevrolet", "Chrysler", "Citroen", "Dodge", "Fiat", "Ford", "Honda", "Hyundai", "Jeep", "Kia", "Mazda", "Mercedes-Benz", "Mercury", "Mitsubishi", "Nissan", "Oldsmobile", "Peugeot", "Pontiac", "Renault", "Saturn", "Subaru", "Toyota", "Vauxhall", "Volkswagen", "Volvo", "AC", "Acura", "Alfa Romeo", "Alvis", "AMC", "ARO", "Asia Motors", "Aston Martin", "Asuna", "Audi", "Austin", "Austin Healey", "Autobianchi", "Autocars", "Avanti", "Bajaj", "Bedford", "Bentley", "Birkin", "BMW", "Bombardier", "Bond", "Brennan-Mays", "Bricklin", "Bugatti", "Buick", "Cadillac", "Caterham", "Checker", "Chery", "Chevrolet", "Chrysler", "Citroen", "Commer", "Cord", "Dacia", "Daewoo", "DAF", "Daihatsu", "Datsun", "DeLorean", "DeSoto", "DeTomaso", "Dodge", "Eagle", "Edsel", "Ferrari", "Fiat", "Ford", "Franklin", "Freightliner", "FSO", "Geely", "Geo", "GMC", "Great Wall", "Grinnall", "Hillman", "Holden", "Honda", "HSV", "Humber", "Hummer", "Hyundai", "IHC", "IKA", "Infiniti", "Innocenti", "Inokom", "Iran Khodro", "Iso Rivolta", "Isuzu", "Iveco", "Jaguar", "Jeep", "Jensen", "JiangNan", "Kaiser", "Kia", "Kish Khodro", "Lada", "Laforza", "Lamborghini", "Lancia", "Land Rover", "Lexus", "Leyland", "Leyland DAF", "Lincoln", "Lotus", "Mahindra", "Maple", "Marcos", "Maruti", "Maserati", "Matra", "Maybach", "Mazda", "McLaren", "Mercedes-Benz", "Mercury", "Merkur", "Meson", "Meyers Manx", "MG", "Microcar", "Mitsubishi", "Morgan", "Morris", "Moskvitch", "Nash", "NAZA", "Nissan", "Noble", "Nova", "NSU", "Oldsmobile", "Oltcit", "Opel", "Packard", "Panther", "Perodua", "Peugeot", "Plymouth", "Pontiac", "Porsche", "Premier", "Proton", "Puma", "Pyonghwa Motors", "Quantum", "Qvale", "Ram Trucks", "Rayton Fissore", "Reliant", "Renault", "Riley", "Robert Jankel Design", "Rolls Royce", "Rover - Austin", "SAAB", "Saleen", "Samsung", "Santana", "Sao", "Saturn", "Scion", "Seat", "Sebring", "Sebring Vanguard", "Shelby", "Simca", "Singer", "Skoda", "smart", "Spartan", "SsangYong", "Standard", "Sterling", "Studebaker", "Subaru", "Sunbeam", "Suzuki", "Talbot", "Tata", "Tatra", "Tesla", "Tickford", "Toyota", "Trabant", "Triumph", "Troller", "TVR", "Vanden Plas", "Vauxhall", "Venturi", "Volga", "Volkswagen", "Volvo", "Wartburg", "Westfield", "Willys", "Wolseley", "Yugo", "Zagato", "ZAZ", "Zhengzhou Nissan", "Zhonghua", "ZXAUTO", "1997 Lexus LS", "2012 Audi A7", "1985 Dodge D100", "2007 Citroen C5", "More New Car Reviews", "1987 Chrysler New Yorker", "1995 Chevrolet Monte Carlo", "1995 Chevrolet Monte Carlo", "1995 Chevrolet Monte Carlo", "More New Comments", "Advertise on this site", "Privacy Policy"],
            "strong": ["110091", "0", "3"],
            "h1": ["Car Reviews by Manufacturer"],
            "h2": ["Most Popular", "All Manufacturers"],
            "h3": ["Newest Car Reviews", "Newest Comments", "Current Status"],
            "span": ["Copyright 1997 - 2017 CSDO Media Limited", "|"]
        }
    },
    {
        "url": "http://www.hollywood.com/",
        "title": "Hollywood.com - Best of Movies, TV, and Celebrities",
        "content": {
            "div": ["TRENDING NOW", "Hollywood.com Photo Archive", "Hollywood.com Esports", "Hollywood.com Discovery", "MovieTickets.com Discovery", "Wenn Penelope Cruz will always put her all into every role she wins, even if it means transforming herself physically. The Spanish actress has varied...", "Wenn Sean Penn reportedly resolved a dispute with fellow passengers during a recent flight to New York. The Mystic River actor had just boarded the...", "Wenn Rita Ora has hinted in a new interview that she and Cara Delevingne were more than just good friends. The 26-year-old singer and the...", "Wenn Charlie Sheen has stepped out in public with a new girlfriend. The 51-year-old actor showed off his blonde partner, known only as Jools, as...", "Wenn Tom Cruise's insistence on perfecting a zero-gravity stunt for The Mummy caused members of the film's crew to vomit. Tom stars as military operative...", "Wenn The Big Chill star Meg Tilly has made a return to Hollywood after 18 years to play Brad Pitt's wife. The actress stepped away...", "Wenn Rob Kardashian has slammed rumors he's dating reality TV star Mehgan James. A report published by Us Weekly magazine on Thursday (01Jun17) suggested that...", "Wenn Taylor Swift has been pictured with her actor boyfriend Joe Alwyn for the first time. News of the Bad Blood hitmaker's relationship with 26-year-old...", "NBC Ariana Grande has touched down in the U.K. ahead of her benefit concert for victims of the terrorist attack on her gig in...", "Wenn Alec Baldwin helped raise $5.1 million for New Jersey Democrats at an event in Collingswood, New Jersey, on Thursday night (01Jun17). The 30 Rock...", "Wenn Johnny Depp has claimed he was completely unaware his former managers were using his name to take out $40 million in loans. The fight...", "Wenn Carey Mulligan is reportedly expecting her second child. The Great Gatsby actress was pictured outside Sexy Fish restaurant in London with her husband Marcus...", "When it was first announced that Scarlett Johansson would play The Major in the wildly popular 'Ghost in the Shell' fans weren't happy, to...", "Billy Bob Thornton and the cast of Bad Santa 2 looked super naughty at AMC Loews Lincoln Square in New York City. Check out...", "Hulu's much anticipated drama The Handmaid's Tale premiered last night. This 10-part series is an adaptation from Margaret Atwood's 1985 novel of the same name, set...", "Julianne Moore and Michelle Williams premiered their new movie Wonderstruck at the 70th Cannes Film Festival. For a complete gallery of pictures, click here.", "Selena Gomez hosted WE Day celebrations at The Forum in California for her fifth year. WE Day is one of the largest Facebook non-profits in...", "Check out the super whimsical cast of NBC's Hairspray Live! before the musical premieres Wednesday, December 7th!", "Wenn / Paramount Pictures Thandie Newton wore a wig she was given on Mission: Impossible 2 to the BAFTAs on Sunday night (12Feb17). The Westworld...", "The Light Between Oceans premiered at the Venice Film Festival and co-stars and real-life lovers Michael Fassbender and Alicia Vikander were all smiles on...", "With the Margot Robbie stepping into the role of Maid Marian, and the currently-filming of Robin Hood: Origins, there's been a resurgence of interest...", "Tom Hanks is Forrest Gump, just like like Richard Gere is Edward Lewis in Pretty Woman; some actors have had such iconic movie roles,...", "Disney These days, Disney is known for pushing the envelope and hiding adult themes and jokes in their films. However, there was a time...", "ABC Television Network Abby, The Deadliest Catch Darby Stanchfield plays Abby Whelan, and she's come a long way to get to D.C. She actually grew up...", "There are many different kinds of family businesses, but one we hardly think about is acting. However, there are families that have actors going...", "It's no secret that Hollywood loves its cliches from action heroes who magically avoid every bullet fired at them to fat sitcom husbands who...", "HBO HBO's Silicon Valley just finished its first season. The show features a great cast of comedians, and it's managed to satirize the nerdy masculinity of...", "32.2x", "|", "19.2x", "|", "6.84x", "|", "6.16x", "|", "4.77x", "|", "4.22x", "|", "Powered by Crowdtangle", "1999-2017 HOLLYWOOD.COM, LLC. ALL RIGHTS RESERVED", "|   |  |   |", "MOVIE, TV, AND CELEBRITY DATA PROVIDED BY AND IS THE COPYRIGHT OF"],
            "a": ["CLOSE", "Click here - to use the wp menu builder", "Click here - to use the wp menu builder", "SIGN UP FOR OUR NEWSLETTER", "Meg Tilly Returns to Movies after Two Decade Hiatus to Play Brad Pitt's Wife", "Kathy Griffin in Tears at Press Conference", "Rob Kardashian Denies Reports He's Dating Reality Star Mehgan James", "Rita Ora talks 'ambiguous' relationship with Cara Delevingne", "Sean Penn Involved in Dispute During Flight to JFK", "Khloe Kardashian won't identify friend she claims is stealing from her", "Underwear On The Outside At The 'Captain Underpants' Premiere", "Penelope Cruz: 'I don't mind getting ugly for movie roles'", "Charlie Sheen goes public with new girlfriend", "Tom Cruise made The Mummy crew vomit with zero-gravity stunt", "Kathy Griffin in Tears at Press Conference", "Underwear On The Outside At The 'Captain Underpants' Premiere", "Khloe Kardashian won't identify friend she claims is stealing from her", "Underwear On The Outside At The 'Captain Underpants' Premiere", "'Baby Driver' Looks Like The Most Fun Movie In 2nd Trailer", "Go Behind the Voices of 'Captain Underpants: The First Movie'", "Something Is Wrong In the 'Murder on the Orient Express' Trailer", "Nicole Kidman lends her Balenciaga wedding dress to exhibition", "Penelope Cruz:  I don t mind getting ugly for movie roles", "Sean Penn Involved in Dispute During Flight to JFK", "Rita Ora talks  ambiguous  relationship with Cara Delevingne", "Charlie Sheen goes public with new girlfriend", "Tom Cruise made The Mummy crew vomit with zero-gravity stunt", "Meg Tilly Returns to Movies after Two Decade Hiatus to Play Brad Pitt s Wife", "Rob Kardashian Denies Reports He s Dating Reality Star Mehgan James", "Taylor Swift Spotted with New Boyfriend Joe Alwyn for First Time", "Ariana Grande returns to U.K. as thousands make false ticket claims for Manchester benefit show", "Alec Baldwin Raises $5 million for Democrats", "Johnny Depp was  unaware ex managers were using his name to get loans", "Carey Mulligan is Pregnant", "see more", "RED CARPET", "Travel To Tokyo For The  Ghost in the Shell  World Premiere", "The Cast Of  Bad Santa 2  Spiced Up The Red Carpet At The NYC Premiere", "Hulu s  The Handmaid s Tale  Premieres", "Julianne Moore and Michelle Williams Premiere  Wonderstruck  at Cannes", "Selena Gomez, Demi Lovato, and Alicia Keys Celebrate WE Day", "The Cast Of NBC s  Hairspray Live!  Were Super Whimsical On The Red Carpet", "Thandie Newton wore Mission: Impossible II wig to the BAFTAs", "Michael Fassbender & Alicia Vikander Are Perfection At  The Light Between Oceans  Premiere", "see more", "DID YOU KNOW?", "All the Actresses Who Have Played Maid Marian", "12 Iconic Movie Roles That Famous Actors Turned Down", "The Original Drawing For  Snow White  Was Banned By Disney Because It Was Too Sexy!", "Facts You Never Knew About The Cast of  Scandal", "11 Actors You Didn t Know Have Famous Grandparents", "15 Celebrity Dads You Didn t Know Have Hot Sons", "The 10 Most Overused Sound Effects in Hollywood", "21 Facts You Don t Know About  Silicon Valley", "see more", "Teen Mom: OG Star Ryan Edwards Has Checked into Rehab", "E! News", "How To Train Your Dragon 3: Eveything We Know So Far", "moviepilot.com", "Alec Baldwin's Advice to Kathy Griffin on Trump Brouhaha: 'F--- Them All'", "The Wrap", "Alec Baldwin Defends Kathy Griffin in Wake of Trump Decapitated Photo Controversy: 'Ignore Him'", "People", "The Wonder Woman Scene That Pays Tribute To Superman", "CinemaBlend", "14 Of The Most Utterly Bizarre Things On Display At The M tter Museum", "Ranker", "Movies", "TV", "Celebrities", "Best Of/Worst Of", "Where Are They Now?", "Did You Know", "Buzzing", "Quizzes", "Pop Lists", "News", "SSNInsider", "MovieTickets.com", "EsportsHW", "Photo Archive", "About Us", "Contact Us", "Media Kit", "PRIVACY POLICY", "TERMS OF SERVICE", "COPYRIGHT ISSUES", "DISCLOSURE", "REPORT ABUSE", "BASELINE"],
            "em": ["Want More?"],
            "h1": ["WANT MORE?"],
            "i": ["Facebook", "Google+", "Twitter", "YouTube", "Instagram"],
            "h2": ["Sign Up For Our Newsletter!", "Sign Up For Our Newsletter!"],
            "h3": ["FOLLOW US!", "LIKE US!", "TOPIC", "Category", "partners", "COMPANY", "Be friends with us"],
            "time": ["Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Mar 17, 2017", "Nov 16, 2016", "Apr 26, 2017", "May 18, 2017", "Apr 28, 2017", "Nov 18, 2016", "Feb 14, 2017", "Sep 1, 2016", "Mar 7, 2017", "Aug 15, 2013", "Oct 5, 2016", "Apr 4, 2014", "Apr 22, 2016", "Aug 22, 2014", "Sep 21, 2015", "Jun 11, 2014"],
            "span": ["Celebrities", "Movies", "Television", "Showtimes", "Search", "Esports", "Photo Archive", "The Latest", "Video", "Buzzing", "Pop Lists", "Did You Know?", "Where Are They Now?", "Featured", "Take A Sneak Peak At The Movies Coming Out This Week (8/12)", "Kathy Griffin in Tears at Press Conference", "Underwear On The Outside At The  Captain Underpants  Premiere", "Khloe Kardashian won t identify friend she claims is stealing from her", "Penelope Cruz:  I don t mind getting ugly for movie roles", "Partners", "MovieTickets.com", "SSN Insider", "Privacy Policy", "Copyright Notice", "Terms of Use", "Report Abuse", "Videos", "Buzzing", "Red Carpet", "Esports", "Photo Archive", "Newsletter Signup", "Meg Tilly Returns to Movies after Two Decade Hiatus to Play Brad Pitt's Wife", "WENN", "Kathy Griffin in Tears at Press Conference", "WENN", "Rob Kardashian Denies Reports He's Dating Reality Star Mehgan James", "WENN", "Rita Ora talks 'ambiguous' relationship with Cara Delevingne", "WENN", "Sean Penn Involved in Dispute During Flight to JFK", "WENN", "Khloe Kardashian won't identify friend she claims is stealing from her", "WENN", "Underwear On The Outside At The 'Captain Underpants' Premiere", "Michael Chaney", "Penelope Cruz: 'I don't mind getting ugly for movie roles'", "WENN", "Charlie Sheen goes public with new girlfriend", "WENN", "Sign Up for Our Newsletter!", "Follow @hollywood", "THE LATEST", "Hot on Facebook"]
        }
    }
]
</code>```

I have crawled 500K webpages and stored them in a Json file. Now, I am trying to read it. The whole file is 2GB, so I am unable to share the whole file.

I understand Json parser is getting some unexpected character (s) in the file but I am unable to find which line in the json file is erroneous. Is there any way I can find out the faulty line in the json file?

Edit

Main code in processing webpage contents is as follows.

```<code>for (Element element : elements) {
    String tagName = element.tagName();
    if (Util.isValidTag(tagName)) {
        String textValue = Util.removeNonPrintableChars(element.ownText()).trim().replace("\"", "\'");
        if (!textValue.isEmpty()) {
            if (tagTextMap.containsKey(tagName)) {
                tagTextMap.get(tagName).add(textValue);
            } else {
                ArrayList<String> arr = new ArrayList<>();
                arr.add(textValue);
                tagTextMap.put(tagName, arr);
            }
        }
    }
}
</code>```

I just removed non-printable characters and also replace double quotes by single quote, that's it.

Update

I found the problematic section in the json file.

```<code>{
    "url": "http://www.kudzu.com/",
    "title": "Atlanta roofers, hvac, plumbers, electricians and other businesses - reviews, coupons and cost estimates from your neighbors.",
    "content": {
        "h2": ["From Our Experts", "Recent Projects", "Recent Articles", "What It Costs", "Review a Business", "What It Costs", "Other Markets"],
        "body": ["\"],
        "span": ["Area", "Area", "Cost"]
    }
}
</code>```

This part - "body": ["\"], is the source of problem. I can understand now why its causing the problem.

答:
It seems you are having trouble with escaping special characters. See this list of special characters used in JSON :

\b  Backspace (ascii code 08)

\f  Form feed (ascii code 0C)

\n  New line

\r  Carriage return

\t  Tab

\"  Double quote

\  Backslash character

So, while dumping json you need to escape this special characters. Fortunately every json library's has way to do this job. As it seems you have used JSON.simple toolkit, you can use JSONObject.escape() method to escape the special characters.

Body:
I saw similar question on Stackoverflow but none of them helped me to solve my issue. So, I am asking for help as I have tried to find out what is the reason behind the error I am getting but failed. Please don't mark it as a duplicate question.

I am parsing a Json file and getting the following error.

Jun 06, 2017 2:06:24 PM edu.virginia.cs.services.FileManager ParseJson
SEVERE: null
Unexpected character (s) at position 226025.
    at org.json.simple.parser.Yylex.yylex(Yylex.java:610)
    at org.json.simple.parser.JSONParser.nextToken(JSONParser.java:269)
    at org.json.simple.parser.JSONParser.parse(JSONParser.java:118)
    at org.json.simple.parser.JSONParser.parse(JSONParser.java:92)
    at edu.virginia.cs.services.FileManager.ParseJson(FileManager.java:68)
    at edu.virginia.cs.main.Processer.main(Processer.java:20)

Exception in thread "main" java.lang.NullPointerException
    at edu.virginia.cs.services.FileManager.ParseJson(FileManager.java:76)
    at edu.virginia.cs.main.Processer.main(Processer.java:20)

Code of interest:

try {
    arr = (JSONArray) parser.parse(new FileReader(sourceFile));
} catch (IOException | ParseException ex) {
    Logger.getLogger(FileManager.class.getName()).log(Level.SEVERE, null, ex);
}

File content looks like as follows:

[
    {
        "url": "http://www.save-on-crafts.com/",
        "title": "Events & Wedding Sale | Save 20-60% | SaveOnCrafts",
        "content": {
            "p": ["Wedding decorations, party supplies, home d cor & craft supplies at 20-70% off. Save On Crafts brings you classic and trending fashions.", "Save On Crafts has continually evolved to meet the needs of our customers   DIY brides, home decorators, party planners, florists, and caterers. Our goal is simple: provide an exciting selection of quality , , and items at the lowest price possible for the customer with discerning taste."],
            "div": ["indicates required", "(831) 768-8428", "Take a Peek at our Specials: Save up to 70%!", "Candle Holders", "Flowers & Branches", "Crystal D cor, Chandeliers", "Set the Mood with Candles", "Champagne & Ice Buckets", "Chalkboards", "Eco Confetti", "Wedding Signs", "Sola Flowers", "Natural Wood Slices", "Classic & trending styles without the traditional retail markup.", "(831) 768-8428"],
            "a": ["X", "What's New", "SPECIALS", "Wedding Decorations", "Lights | Event Lighting", "Wood Slabs & Tree Slices", "Vases", "Apothecary Jars", "Banners", "Baskets", "Bell Jars, Cloches", "Beverage Bar Supplies", "Bird Cages & Birds", "Botanicals, Lavender, Sola Flowers", "Bottles & Jars", "Branches - Natural", "Buckets & Tubs", "Burlap Fabric, Jute, and Linen", "Cake Stands", "Candles", "Candle Holders", "Candy Buffet", "Chair Sashes, Banners, Signs", "Chalkboards", "Chandeliers", "Charger & Base Plates", "Confetti", "Corsage & Bouquet Supplies", "Craft Supplies", "Crates, Boxes, & Trays", "Crystal Decorations", "Easels & Frames", "Event Decor", "Favors", "Feathers", "Floral Supplies", "Flowers", "Greenery", "Home & Garden Decor", "Lanterns", "Mirrors & Mirror Stands", "Moss Natural & Artificial", "Nautical Decor & Decorations", "Packaging, Gift Wrapping", "Paper Lanterns & Parasols", "Paper Party Decorations", "Party Supplies", "Pots & Planters", "Placecard Holders,Table Numbers, Displays", "Preserved Flowers & Leaves", "Props, Pedestals, Risers", "Ribbon", "Silk Flowers", "Signage", "Shells - Sand", "Shepherds Hooks & Stanchions", "Sola Flowers", "Succulents & Cactus", "Table Runners & Toppers", "Terrariums", "Tote Bags, Welcome Bags", "Trees, Potted Plants", "Vases & Vase Fillers", "Wedding Cake Decorations and Toppers", "Wedding Decorations", "Wedding Signs", "Wedding Themes", "Wedding Trees & Wishing Trees", "Wood Crafts", "Wood Slabs & Tree Slices", "Wreath Making Supplies, Frames, Forms", "Gifts - Holiday Decorations", "Gifts Under $25", "Ideas & Inspiration", "Shopping Cart", "About", "Shipping", "Return Policy", "Contact", "FAQ", "Privacy Policy", "Terms and Conditions", "Read More", "Shipping", "Cart"],
            "strong": ["Need Help?", "SUBSCRIBE", "wedding supplies", "party decorations", "home d cor", "Affordable Wedding & Event Decor", "Save 20-70%", "Need Help?"],
            "span": ["*", "*", "Live Chat", "Shop Categories", "Customer Service: 7am - 5pm PST (M-F) | (831)768-8428", "Copyright   2017 Save-On-Crafts. All Rights Reserved. Designated trademarks and brands are the property of their respective owners. Use of this website constitutes acceptance of the Save-On-Craftsand Privacy Policy.", "Live Chat"]
        }
    },
    {
        "url": "http://www.carsurvey.org/",
        "title": "Carsurvey.org - Car Reviews",
        "content": {
            "p": ["I feel as if this vehicle was custom built for me, love it", "Neat cruiser, comfort first, performance second", "Beast maaaaaaate!", "Best value for the money", "There are reviews on the site", "new reviews and new comments are in the Members section, awaiting approval"],
            "td": ["2 days ago", "2 days ago", "3 days ago", "3 days ago", "18 hours ago", "19 hours ago", "19 hours ago", "19 hours ago"],
            "a": ["Write a Review", "About", "Members", "Reviews by Region", "Write a Review", "About", "Members", "Reviews by Region", "BMW", "Buick", "Chevrolet", "Chrysler", "Citroen", "Dodge", "Fiat", "Ford", "Honda", "Hyundai", "Jeep", "Kia", "Mazda", "Mercedes-Benz", "Mercury", "Mitsubishi", "Nissan", "Oldsmobile", "Peugeot", "Pontiac", "Renault", "Saturn", "Subaru", "Toyota", "Vauxhall", "Volkswagen", "Volvo", "AC", "Acura", "Alfa Romeo", "Alvis", "AMC", "ARO", "Asia Motors", "Aston Martin", "Asuna", "Audi", "Austin", "Austin Healey", "Autobianchi", "Autocars", "Avanti", "Bajaj", "Bedford", "Bentley", "Birkin", "BMW", "Bombardier", "Bond", "Brennan-Mays", "Bricklin", "Bugatti", "Buick", "Cadillac", "Caterham", "Checker", "Chery", "Chevrolet", "Chrysler", "Citroen", "Commer", "Cord", "Dacia", "Daewoo", "DAF", "Daihatsu", "Datsun", "DeLorean", "DeSoto", "DeTomaso", "Dodge", "Eagle", "Edsel", "Ferrari", "Fiat", "Ford", "Franklin", "Freightliner", "FSO", "Geely", "Geo", "GMC", "Great Wall", "Grinnall", "Hillman", "Holden", "Honda", "HSV", "Humber", "Hummer", "Hyundai", "IHC", "IKA", "Infiniti", "Innocenti", "Inokom", "Iran Khodro", "Iso Rivolta", "Isuzu", "Iveco", "Jaguar", "Jeep", "Jensen", "JiangNan", "Kaiser", "Kia", "Kish Khodro", "Lada", "Laforza", "Lamborghini", "Lancia", "Land Rover", "Lexus", "Leyland", "Leyland DAF", "Lincoln", "Lotus", "Mahindra", "Maple", "Marcos", "Maruti", "Maserati", "Matra", "Maybach", "Mazda", "McLaren", "Mercedes-Benz", "Mercury", "Merkur", "Meson", "Meyers Manx", "MG", "Microcar", "Mitsubishi", "Morgan", "Morris", "Moskvitch", "Nash", "NAZA", "Nissan", "Noble", "Nova", "NSU", "Oldsmobile", "Oltcit", "Opel", "Packard", "Panther", "Perodua", "Peugeot", "Plymouth", "Pontiac", "Porsche", "Premier", "Proton", "Puma", "Pyonghwa Motors", "Quantum", "Qvale", "Ram Trucks", "Rayton Fissore", "Reliant", "Renault", "Riley", "Robert Jankel Design", "Rolls Royce", "Rover - Austin", "SAAB", "Saleen", "Samsung", "Santana", "Sao", "Saturn", "Scion", "Seat", "Sebring", "Sebring Vanguard", "Shelby", "Simca", "Singer", "Skoda", "smart", "Spartan", "SsangYong", "Standard", "Sterling", "Studebaker", "Subaru", "Sunbeam", "Suzuki", "Talbot", "Tata", "Tatra", "Tesla", "Tickford", "Toyota", "Trabant", "Triumph", "Troller", "TVR", "Vanden Plas", "Vauxhall", "Venturi", "Volga", "Volkswagen", "Volvo", "Wartburg", "Westfield", "Willys", "Wolseley", "Yugo", "Zagato", "ZAZ", "Zhengzhou Nissan", "Zhonghua", "ZXAUTO", "1997 Lexus LS", "2012 Audi A7", "1985 Dodge D100", "2007 Citroen C5", "More New Car Reviews", "1987 Chrysler New Yorker", "1995 Chevrolet Monte Carlo", "1995 Chevrolet Monte Carlo", "1995 Chevrolet Monte Carlo", "More New Comments", "Advertise on this site", "Privacy Policy"],
            "strong": ["110091", "0", "3"],
            "h1": ["Car Reviews by Manufacturer"],
            "h2": ["Most Popular", "All Manufacturers"],
            "h3": ["Newest Car Reviews", "Newest Comments", "Current Status"],
            "span": ["Copyright 1997 - 2017 CSDO Media Limited", "|"]
        }
    },
    {
        "url": "http://www.hollywood.com/",
        "title": "Hollywood.com - Best of Movies, TV, and Celebrities",
        "content": {
            "div": ["TRENDING NOW", "Hollywood.com Photo Archive", "Hollywood.com Esports", "Hollywood.com Discovery", "MovieTickets.com Discovery", "Wenn Penelope Cruz will always put her all into every role she wins, even if it means transforming herself physically. The Spanish actress has varied...", "Wenn Sean Penn reportedly resolved a dispute with fellow passengers during a recent flight to New York. The Mystic River actor had just boarded the...", "Wenn Rita Ora has hinted in a new interview that she and Cara Delevingne were more than just good friends. The 26-year-old singer and the...", "Wenn Charlie Sheen has stepped out in public with a new girlfriend. The 51-year-old actor showed off his blonde partner, known only as Jools, as...", "Wenn Tom Cruise's insistence on perfecting a zero-gravity stunt for The Mummy caused members of the film's crew to vomit. Tom stars as military operative...", "Wenn The Big Chill star Meg Tilly has made a return to Hollywood after 18 years to play Brad Pitt's wife. The actress stepped away...", "Wenn Rob Kardashian has slammed rumors he's dating reality TV star Mehgan James. A report published by Us Weekly magazine on Thursday (01Jun17) suggested that...", "Wenn Taylor Swift has been pictured with her actor boyfriend Joe Alwyn for the first time. News of the Bad Blood hitmaker's relationship with 26-year-old...", "NBC Ariana Grande has touched down in the U.K. ahead of her benefit concert for victims of the terrorist attack on her gig in...", "Wenn Alec Baldwin helped raise $5.1 million for New Jersey Democrats at an event in Collingswood, New Jersey, on Thursday night (01Jun17). The 30 Rock...", "Wenn Johnny Depp has claimed he was completely unaware his former managers were using his name to take out $40 million in loans. The fight...", "Wenn Carey Mulligan is reportedly expecting her second child. The Great Gatsby actress was pictured outside Sexy Fish restaurant in London with her husband Marcus...", "When it was first announced that Scarlett Johansson would play The Major in the wildly popular 'Ghost in the Shell' fans weren't happy, to...", "Billy Bob Thornton and the cast of Bad Santa 2 looked super naughty at AMC Loews Lincoln Square in New York City. Check out...", "Hulu's much anticipated drama The Handmaid's Tale premiered last night. This 10-part series is an adaptation from Margaret Atwood's 1985 novel of the same name, set...", "Julianne Moore and Michelle Williams premiered their new movie Wonderstruck at the 70th Cannes Film Festival. For a complete gallery of pictures, click here.", "Selena Gomez hosted WE Day celebrations at The Forum in California for her fifth year. WE Day is one of the largest Facebook non-profits in...", "Check out the super whimsical cast of NBC's Hairspray Live! before the musical premieres Wednesday, December 7th!", "Wenn / Paramount Pictures Thandie Newton wore a wig she was given on Mission: Impossible 2 to the BAFTAs on Sunday night (12Feb17). The Westworld...", "The Light Between Oceans premiered at the Venice Film Festival and co-stars and real-life lovers Michael Fassbender and Alicia Vikander were all smiles on...", "With the Margot Robbie stepping into the role of Maid Marian, and the currently-filming of Robin Hood: Origins, there's been a resurgence of interest...", "Tom Hanks is Forrest Gump, just like like Richard Gere is Edward Lewis in Pretty Woman; some actors have had such iconic movie roles,...", "Disney These days, Disney is known for pushing the envelope and hiding adult themes and jokes in their films. However, there was a time...", "ABC Television Network Abby, The Deadliest Catch Darby Stanchfield plays Abby Whelan, and she's come a long way to get to D.C. She actually grew up...", "There are many different kinds of family businesses, but one we hardly think about is acting. However, there are families that have actors going...", "It's no secret that Hollywood loves its cliches from action heroes who magically avoid every bullet fired at them to fat sitcom husbands who...", "HBO HBO's Silicon Valley just finished its first season. The show features a great cast of comedians, and it's managed to satirize the nerdy masculinity of...", "32.2x", "|", "19.2x", "|", "6.84x", "|", "6.16x", "|", "4.77x", "|", "4.22x", "|", "Powered by Crowdtangle", "1999-2017 HOLLYWOOD.COM, LLC. ALL RIGHTS RESERVED", "|   |  |   |", "MOVIE, TV, AND CELEBRITY DATA PROVIDED BY AND IS THE COPYRIGHT OF"],
            "a": ["CLOSE", "Click here - to use the wp menu builder", "Click here - to use the wp menu builder", "SIGN UP FOR OUR NEWSLETTER", "Meg Tilly Returns to Movies after Two Decade Hiatus to Play Brad Pitt's Wife", "Kathy Griffin in Tears at Press Conference", "Rob Kardashian Denies Reports He's Dating Reality Star Mehgan James", "Rita Ora talks 'ambiguous' relationship with Cara Delevingne", "Sean Penn Involved in Dispute During Flight to JFK", "Khloe Kardashian won't identify friend she claims is stealing from her", "Underwear On The Outside At The 'Captain Underpants' Premiere", "Penelope Cruz: 'I don't mind getting ugly for movie roles'", "Charlie Sheen goes public with new girlfriend", "Tom Cruise made The Mummy crew vomit with zero-gravity stunt", "Kathy Griffin in Tears at Press Conference", "Underwear On The Outside At The 'Captain Underpants' Premiere", "Khloe Kardashian won't identify friend she claims is stealing from her", "Underwear On The Outside At The 'Captain Underpants' Premiere", "'Baby Driver' Looks Like The Most Fun Movie In 2nd Trailer", "Go Behind the Voices of 'Captain Underpants: The First Movie'", "Something Is Wrong In the 'Murder on the Orient Express' Trailer", "Nicole Kidman lends her Balenciaga wedding dress to exhibition", "Penelope Cruz:  I don t mind getting ugly for movie roles", "Sean Penn Involved in Dispute During Flight to JFK", "Rita Ora talks  ambiguous  relationship with Cara Delevingne", "Charlie Sheen goes public with new girlfriend", "Tom Cruise made The Mummy crew vomit with zero-gravity stunt", "Meg Tilly Returns to Movies after Two Decade Hiatus to Play Brad Pitt s Wife", "Rob Kardashian Denies Reports He s Dating Reality Star Mehgan James", "Taylor Swift Spotted with New Boyfriend Joe Alwyn for First Time", "Ariana Grande returns to U.K. as thousands make false ticket claims for Manchester benefit show", "Alec Baldwin Raises $5 million for Democrats", "Johnny Depp was  unaware ex managers were using his name to get loans", "Carey Mulligan is Pregnant", "see more", "RED CARPET", "Travel To Tokyo For The  Ghost in the Shell  World Premiere", "The Cast Of  Bad Santa 2  Spiced Up The Red Carpet At The NYC Premiere", "Hulu s  The Handmaid s Tale  Premieres", "Julianne Moore and Michelle Williams Premiere  Wonderstruck  at Cannes", "Selena Gomez, Demi Lovato, and Alicia Keys Celebrate WE Day", "The Cast Of NBC s  Hairspray Live!  Were Super Whimsical On The Red Carpet", "Thandie Newton wore Mission: Impossible II wig to the BAFTAs", "Michael Fassbender & Alicia Vikander Are Perfection At  The Light Between Oceans  Premiere", "see more", "DID YOU KNOW?", "All the Actresses Who Have Played Maid Marian", "12 Iconic Movie Roles That Famous Actors Turned Down", "The Original Drawing For  Snow White  Was Banned By Disney Because It Was Too Sexy!", "Facts You Never Knew About The Cast of  Scandal", "11 Actors You Didn t Know Have Famous Grandparents", "15 Celebrity Dads You Didn t Know Have Hot Sons", "The 10 Most Overused Sound Effects in Hollywood", "21 Facts You Don t Know About  Silicon Valley", "see more", "Teen Mom: OG Star Ryan Edwards Has Checked into Rehab", "E! News", "How To Train Your Dragon 3: Eveything We Know So Far", "moviepilot.com", "Alec Baldwin's Advice to Kathy Griffin on Trump Brouhaha: 'F--- Them All'", "The Wrap", "Alec Baldwin Defends Kathy Griffin in Wake of Trump Decapitated Photo Controversy: 'Ignore Him'", "People", "The Wonder Woman Scene That Pays Tribute To Superman", "CinemaBlend", "14 Of The Most Utterly Bizarre Things On Display At The M tter Museum", "Ranker", "Movies", "TV", "Celebrities", "Best Of/Worst Of", "Where Are They Now?", "Did You Know", "Buzzing", "Quizzes", "Pop Lists", "News", "SSNInsider", "MovieTickets.com", "EsportsHW", "Photo Archive", "About Us", "Contact Us", "Media Kit", "PRIVACY POLICY", "TERMS OF SERVICE", "COPYRIGHT ISSUES", "DISCLOSURE", "REPORT ABUSE", "BASELINE"],
            "em": ["Want More?"],
            "h1": ["WANT MORE?"],
            "i": ["Facebook", "Google+", "Twitter", "YouTube", "Instagram"],
            "h2": ["Sign Up For Our Newsletter!", "Sign Up For Our Newsletter!"],
            "h3": ["FOLLOW US!", "LIKE US!", "TOPIC", "Category", "partners", "COMPANY", "Be friends with us"],
            "time": ["Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Jun 2, 2017", "Mar 17, 2017", "Nov 16, 2016", "Apr 26, 2017", "May 18, 2017", "Apr 28, 2017", "Nov 18, 2016", "Feb 14, 2017", "Sep 1, 2016", "Mar 7, 2017", "Aug 15, 2013", "Oct 5, 2016", "Apr 4, 2014", "Apr 22, 2016", "Aug 22, 2014", "Sep 21, 2015", "Jun 11, 2014"],
            "span": ["Celebrities", "Movies", "Television", "Showtimes", "Search", "Esports", "Photo Archive", "The Latest", "Video", "Buzzing", "Pop Lists", "Did You Know?", "Where Are They Now?", "Featured", "Take A Sneak Peak At The Movies Coming Out This Week (8/12)", "Kathy Griffin in Tears at Press Conference", "Underwear On The Outside At The  Captain Underpants  Premiere", "Khloe Kardashian won t identify friend she claims is stealing from her", "Penelope Cruz:  I don t mind getting ugly for movie roles", "Partners", "MovieTickets.com", "SSN Insider", "Privacy Policy", "Copyright Notice", "Terms of Use", "Report Abuse", "Videos", "Buzzing", "Red Carpet", "Esports", "Photo Archive", "Newsletter Signup", "Meg Tilly Returns to Movies after Two Decade Hiatus to Play Brad Pitt's Wife", "WENN", "Kathy Griffin in Tears at Press Conference", "WENN", "Rob Kardashian Denies Reports He's Dating Reality Star Mehgan James", "WENN", "Rita Ora talks 'ambiguous' relationship with Cara Delevingne", "WENN", "Sean Penn Involved in Dispute During Flight to JFK", "WENN", "Khloe Kardashian won't identify friend she claims is stealing from her", "WENN", "Underwear On The Outside At The 'Captain Underpants' Premiere", "Michael Chaney", "Penelope Cruz: 'I don't mind getting ugly for movie roles'", "WENN", "Charlie Sheen goes public with new girlfriend", "WENN", "Sign Up for Our Newsletter!", "Follow @hollywood", "THE LATEST", "Hot on Facebook"]
        }
    }
]

I have crawled 500K webpages and stored them in a Json file. Now, I am trying to read it. The whole file is 2GB, so I am unable to share the whole file.

I understand Json parser is getting some unexpected character (s) in the file but I am unable to find which line in the json file is erroneous. Is there any way I can find out the faulty line in the json file?

Edit

Main code in processing webpage contents is as follows.

for (Element element : elements) {
    String tagName = element.tagName();
    if (Util.isValidTag(tagName)) {
        String textValue = Util.removeNonPrintableChars(element.ownText()).trim().replace("\"", "\'");
        if (!textValue.isEmpty()) {
            if (tagTextMap.containsKey(tagName)) {
                tagTextMap.get(tagName).add(textValue);
            } else {
                ArrayList<String> arr = new ArrayList<>();
                arr.add(textValue);
                tagTextMap.put(tagName, arr);
            }
        }
    }
}

I just removed non-printable characters and also replace double quotes by single quote, that's it.

Update

I found the problematic section in the json file.

{
    "url": "http://www.kudzu.com/",
    "title": "Atlanta roofers, hvac, plumbers, electricians and other businesses - reviews, coupons and cost estimates from your neighbors.",
    "content": {
        "h2": ["From Our Experts", "Recent Projects", "Recent Articles", "What It Costs", "Review a Business", "What It Costs", "Other Markets"],
        "body": ["\"],
        "span": ["Area", "Area", "Cost"]
    }
}

This part - "body": ["\"], is the source of problem. I can understand now why its causing the problem.


问:
Undefined index in session
I have 2 pages:

index.php

```<code><?php session_start(); ?>
<!DOCTYPE html>

<html>
<head>
    <title></title>

    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="style.css">

</head>
<body>
    <div class="container">
        <div class="wrapper">
            <h1>Welcome to the Great Number Game!</h1>
                <h3>I am thinking of a number between 1 and 100</h3>
                <h3>Take a guess!</h3>

<?php

    echo $_SESSION['message'];

?>
                <form method="post" action="process.php">
                    <input type="hidden" name="action" value="guess">
                    <input type="text" name="number">
                    <br>
                    <input type="submit" value="Submit">
                </form>
        </div>
    </div>
</form>
</body>
</html>
</code>```

and process.php

```<code><?php session_start(); ?>

<?php header('Location: index.php'); ?>

<?php

if (!isset($_SESSION["message"])) {
    $_SESSION["message"] = "";
}

if(!isset($_SESSION['num'])) {
    $_SESSION['num'] = rand(1, 100);
}

    $new_game = "<a href='logout.php'><button class='btn'>Play again</button></a>";

if ($_POST['number']) {

    $number = $_POST['number'];

    if (is_numeric($_POST['number'])) {

        if ($number > $_SESSION['num']) {
            $_SESSION['message'] = "<div class='bad-guess'>Too high!</div>";

        }elseif ($number < $_SESSION['num']) {
            $_SESSION['message'] = "<div class='bad-guess'>Too low!</div>";

        }else{
            $_SESSION['message'] = "<div class='lucky-guess'>Congratulations! ".$_POST['number']." was the number!</div><br>".$new_game;

        }

    }else{
        $_SESSION['message'] = "<div> <b>'$number'</b> is not a number. Please insert a number!</div>";
    }

}

?>
</code>```

Problem is that then I am starting session, I got the error that my $_SESSION['message'] index is undefined. Then I start guessing number, I got correct messages. So how can I define $_SESSION['message'] for sessions beggining?

答:
Check if it is set first in index.php

```<code>if(isset($_SESSION['message']))
{
    echo $_SESSION['message'];
}
</code>```

Title: Undefined index in session

Body:
I have 2 pages:

index.php

<?php session_start(); ?>
<!DOCTYPE html>

    <title></title>

    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="style.css">

Welcome to the Great Number Game!

I am thinking of a number between 1 and 100

Take a guess!

<?php

    echo $_SESSION['message'];

?>
                <form method="post" action="process.php">
                    <input type="hidden" name="action" value="guess">
                    <input type="text" name="number">

                    <input type="submit" value="Submit">
                </form>

</form>

and process.php

<?php session_start(); ?>

<?php header('Location: index.php'); ?>

<?php

if (!isset($_SESSION["message"])) {
    $_SESSION["message"] = "";
}

if(!isset($_SESSION['num'])) {
    $_SESSION['num'] = rand(1, 100);
}

    $new_game = "<button class='btn'>Play again</button>";

if ($_POST['number']) {

    $number = $_POST['number'];

    if (is_numeric($_POST['number'])) {

        if ($number > $_SESSION['num']) {
            $_SESSION['message'] = "
Too high!
";

        }elseif ($number < $_SESSION['num']) {
            $_SESSION['message'] = "
Too low!
";

        }else{
            $_SESSION['message'] = "
Congratulations! ".$_POST['number']." was the number!

".$new_game;

        }

    }else{
        $_SESSION['message'] = "
 '$number' is not a number. Please insert a number!
";
    }

}

?>

Problem is that then I am starting session, I got the error that my $_SESSION['message'] index is undefined. Then I start guessing number, I got correct messages. So how can I define $_SESSION['message'] for sessions beggining?

Body:
Check if it is set first in index.php

if(isset($_SESSION['message']))
{
    echo $_SESSION['message'];
}


问:
How to handle dependent class and avoid type checking when using common base class as function parameter?
We have a tree of objects of different types derive from a common tree node and We want to write a method to render complete tree. We are using different renderer based on UI selected Eg.. text Renderer, 2d renderer, 3d renderer. Our tree is our model and we don't want to put in rendering code inside it. so, we decided to create separate rendering code.
Our renderer have a method RenderNode(TreeNode node) that takes reference of base class TreeNode. Since, we need to work with various different kind of node, we are type checking for each tree node type and rendering it.

```<code>void RenderNode(TreeNode node) {
    if(node is NoEditNode){
        // call Derive class RenderEditNode
        RenderEditNode(node);
    }
    else if (node is PersonNode){
        // call Derive class RenderPersonNode
        RenderPersonNode(node);
    }
    else if (node is AssetNode){
        // call Derive class RenderAssetNode
        RenderAssetNode(node);
    }
    .
    .
    .
}
</code>```

Even though this is done in base class and derived Renderer will just implement specific rendering code, this is not a good OO design. In case I add a new Tree node I'll need to change all renderer and to avoid this situation we need to add render code to tree node itself which will again need to be sync when a new renderer is introduced.
So we have multiple kind of tree node and multiple kind of renderer. How can we design this to avoid type checking and avoid change one class if a new kind of another class.

答:
You can solve this if you're willing to create multiple rendering methods with the same name but different type parameters:

```<code>public void RenderNode(TreeNode node) {
    RenderNodeInternal(node as dynamic);
}

private void RenderNodeInternal(AssetNode node) {
    .
    .
    .
}

private void RenderNodeInternal(NoEditNode node) {
    .
    .
    .
}

private void RenderNodeInternal(PersonNode node) {
    .
    .
    .
}
</code>```

This leverages the dynamic mechanism to pick the correct overload based on the runtime type of node in RenderNode.

(Overall, this is doing something very similar to the original code - except you don't have to write all of the type checking code yourself)

Body:
We have a tree of objects of different types derive from a common tree node and We want to write a method to render complete tree. We are using different renderer based on UI selected Eg.. text Renderer, 2d renderer, 3d renderer. Our tree is our model and we don't want to put in rendering code inside it. so, we decided to create separate rendering code.
Our renderer have a method RenderNode(TreeNode node) that takes reference of base class TreeNode. Since, we need to work with various different kind of node, we are type checking for each tree node type and rendering it.

void RenderNode(TreeNode node) {
    if(node is NoEditNode){
        // call Derive class RenderEditNode
        RenderEditNode(node);
    }
    else if (node is PersonNode){
        // call Derive class RenderPersonNode
        RenderPersonNode(node);
    }
    else if (node is AssetNode){
        // call Derive class RenderAssetNode
        RenderAssetNode(node);
    }
    .
    .
    .
}

Even though this is done in base class and derived Renderer will just implement specific rendering code, this is not a good OO design. In case I add a new Tree node I'll need to change all renderer and to avoid this situation we need to add render code to tree node itself which will again need to be sync when a new renderer is introduced.
So we have multiple kind of tree node and multiple kind of renderer. How can we design this to avoid type checking and avoid change one class if a new kind of another class.

Body:
You can solve this if you're willing to create multiple rendering methods with the same name but different type parameters:

public void RenderNode(TreeNode node) {
    RenderNodeInternal(node as dynamic);
}

private void RenderNodeInternal(AssetNode node) {
    .
    .
    .
}

private void RenderNodeInternal(NoEditNode node) {
    .
    .
    .
}

private void RenderNodeInternal(PersonNode node) {
    .
    .
    .
}

This leverages the dynamic mechanism to pick the correct overload based on the runtime type of node in RenderNode.

(Overall, this is doing something very similar to the original code - except you don't have to write all of the type checking code yourself)


问:
PHP Simple HTML DOM Parser - Extract inner attributes
I'm trying to extract the lat/long coordinates from the following $html text:

```<code><div class="marker" data-lat="60.29805979999999" data-lng="19.07932260000007"></div>
</code>```

By doing $html->find(div[class="marker"]) just gives me an empty array? So how would I extract the inner attributes within the same div to get the coordinates?

答:
If you are using jquery you could do:

```<code>$('.marker').attr('data-lat').val();
$('.marker').attr('data-lng').val();
</code>```

In JS you could do

```<code>document.getElementsByClass("marker").getAttribute("data-lat");
document.getElementsByClass("marker").getAttribute("data-lng");
</code>```

Body:
I'm trying to extract the lat/long coordinates from the following $html text:

By doing $html->find(div[class="marker"]) just gives me an empty array? So how would I extract the inner attributes within the same div to get the coordinates?

Body:
If you are using jquery you could do:

$('.marker').attr('data-lat').val();
$('.marker').attr('data-lng').val();

In JS you could do

document.getElementsByClass("marker").getAttribute("data-lat");
document.getElementsByClass("marker").getAttribute("data-lng");


问:
how to start a next activity after clicking on viewpager?
my HomeActivity.java :

```<code>    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    FragmentManager fm = getSupportFragmentManager();
    SlidingImage_Adapter pagerAdapter = new SlidingImage_Adapter(fm);
    pager.setAdapter(pagerAdapter);
}

private Boolean exit=false;
@Override
public void onBackPressed() {
    if (exit) {
        finish();
    } else {
        Toast.makeText(this, "Tekan lagi untuk keluar.",
                Toast.LENGTH_SHORT).show();
        exit = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                exit = false;
            }
        }, 3 * 1000);
    }
    ;
}
</code>```

this is for connecting between Homeact and image_model

my SlidingImage_adapter.java :

```<code>@Override
public Fragment getItem(int arg0) {
    ImageModel myFragment = new ImageModel();
    Bundle data = new Bundle();
    data.putInt("current_page", arg0+1);
    myFragment.setArguments(data);
    return myFragment;
}
@Override
public int getCount() {
    return Page_Count;
}
</code>```

this is to take the pict from .xml that i make (layout1.xml, layout2.xml, etc)

my Image_Model.java

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle data = getArguments();
    mCurrentPage = data.getInt("current_page", 0);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = null;
    if (mCurrentPage == 1) {
        v = inflater.inflate(R.layout.layout1, container, false);
    } else if (mCurrentPage == 2) {
        v = inflater.inflate(R.layout.layout2, container, false);
    } else if (mCurrentPage == 3) {
        v = inflater.inflate(R.layout.layout3, container, false);
    }
    return v;
}
</code>```

答:
Try this</p>

```<code>    pager.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        Intent i=new Intent(getContext(), YouActivity.class);
        getContext.startActivity(i);

        }
    });
</code>```

Body:
my HomeActivity.java :

    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    FragmentManager fm = getSupportFragmentManager();
    SlidingImage_Adapter pagerAdapter = new SlidingImage_Adapter(fm);
    pager.setAdapter(pagerAdapter);
}

private Boolean exit=false;
@Override
public void onBackPressed() {
    if (exit) {
        finish();
    } else {
        Toast.makeText(this, "Tekan lagi untuk keluar.",
                Toast.LENGTH_SHORT).show();
        exit = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                exit = false;
            }
        }, 3 * 1000);
    }
    ;
}

this is for connecting between Homeact and image_model

my SlidingImage_adapter.java :

@Override
public Fragment getItem(int arg0) {
    ImageModel myFragment = new ImageModel();
    Bundle data = new Bundle();
    data.putInt("current_page", arg0+1);
    myFragment.setArguments(data);
    return myFragment;
}
@Override
public int getCount() {
    return Page_Count;
}

this is to take the pict from .xml that i make (layout1.xml, layout2.xml, etc)

my Image_Model.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle data = getArguments();
    mCurrentPage = data.getInt("current_page", 0);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = null;
    if (mCurrentPage == 1) {
        v = inflater.inflate(R.layout.layout1, container, false);
    } else if (mCurrentPage == 2) {
        v = inflater.inflate(R.layout.layout2, container, false);
    } else if (mCurrentPage == 3) {
        v = inflater.inflate(R.layout.layout3, container, false);
    }
    return v;
}

Body:
Try this

    pager.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        Intent i=new Intent(getContext(), YouActivity.class);
        getContext.startActivity(i);

        }
    });


问:
Magento - Incorrect Category title
On the Magento admin Panel my category title for example is: Outdoor Furniture. Then on the website the category title is correct, but when you click on that category the title at the top of the page is incorrect. i.e. Outdoor Furniture blah blah blah. How do I get rid of the blah blah blah?

Thanks

答: You need to update category name under "Page Title" also :

Title: Magento - Incorrect Category title


问:
Application_BeginRequest not being fired in stressed environment
We are obesrving strange problems when performing sress test of our applciation. We use Application_BeginRequest and Application_EndRequest to log the beginning and end of the web request, together, with the thread id.

However, from our logs, we see that Application_Begin_REquest is not being fired:

We use the following code to do the logging in global.asax.cs:

```<code>protected void Application_BeginRequest(object sender, EventArgs e)
{
  string url = "";
  if (HttpContext.Current != null)  // this should alway be true
    url = HttpContext.Current.Request.Url.ToString();

  Dbg.WriteLine(String.Format("Request: {0} {1}", HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"], url));

  // integration calls measurement
  HttpContext.Current.Items.Add("wcfElapsed", new TimeSpan());

}

protected void Application_EndRequest(Object sender, EventArgs e)
{
  string url = "";
  if (HttpContext.Current != null)  // this should alway be true
    url = HttpContext.Current.Request.Url.ToString();

  Dbg.WriteLine(String.Format("End request: {0} {1}", HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"], url));
}
</code>```

This is our log file. Urls are omitted The 00013 column is thread id.

```<code>  14.12.10 21:41:25.042 00013 00000            Request: 172.23.26.41
  14.12.10 21:41:25.068 00013 00000            End request: 172.23.26.41
  14.12.10 21:41:25.212 00013 00000            Request: 172.23.26.41
  14.12.10 21:41:25.223 00013 00000            End request: 172.23.26.41
  14.12.10 21:41:30.974 00013 00000            End request: 172.23.26.88
</code>```

You can see that there are two "End request" in the last two lines, but there is no (Begin) Request for the last log line.

Our Dbg.WriteLine uses System.Diagnostics trace listeners to ouput data to the file.

Environment: Windows Server 2008 R2, ASP.NET 3.5

This only happens when performin stress test. CPU utilization is around 60%, there are max 10 concurent requests executing.

Any ideas, what could be wrong?

UPDATE: I have found out that some other also did have similar problems (althoug in different configuration: http://forums.iis.net/t/1154954.aspx)
Matej

UPDATE#2: This night be related to fact, that Thread.GetHashCode() which is used to print out the thread identifier in our log fies could change. See ASP.NET - Thread.GetHashCode() changes

答:
I think it could be down to debugging to file, not being able to handle all these events. Writing to file has its limitations.

I suggest using default debug trace which you can see in DebugView.

Body:
We are obesrving strange problems when performing sress test of our applciation. We use Application_BeginRequest and Application_EndRequest to log the beginning and end of the web request, together, with the thread id.

However, from our logs, we see that Application_Begin_REquest is not being fired:

We use the following code to do the logging in global.asax.cs:

protected void Application_BeginRequest(object sender, EventArgs e)
{
  string url = "";
  if (HttpContext.Current != null)  // this should alway be true
    url = HttpContext.Current.Request.Url.ToString();

  Dbg.WriteLine(String.Format("Request: {0} {1}", HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"], url));

  // integration calls measurement
  HttpContext.Current.Items.Add("wcfElapsed", new TimeSpan());

}

protected void Application_EndRequest(Object sender, EventArgs e)
{
  string url = "";
  if (HttpContext.Current != null)  // this should alway be true
    url = HttpContext.Current.Request.Url.ToString();

  Dbg.WriteLine(String.Format("End request: {0} {1}", HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"], url));
}

This is our log file. Urls are omitted The 00013 column is thread id.

  14.12.10 21:41:25.042 00013 00000            Request: 172.23.26.41
  14.12.10 21:41:25.068 00013 00000            End request: 172.23.26.41
  14.12.10 21:41:25.212 00013 00000            Request: 172.23.26.41
  14.12.10 21:41:25.223 00013 00000            End request: 172.23.26.41
  14.12.10 21:41:30.974 00013 00000            End request: 172.23.26.88

You can see that there are two "End request" in the last two lines, but there is no (Begin) Request for the last log line.

Our Dbg.WriteLine uses System.Diagnostics trace listeners to ouput data to the file.

Environment: Windows Server 2008 R2, ASP.NET 3.5

This only happens when performin stress test. CPU utilization is around 60%, there are max 10 concurent requests executing.

Any ideas, what could be wrong?

UPDATE: I have found out that some other also did have similar problems (althoug in different configuration: http://forums.iis.net/t/1154954.aspx)
Matej

UPDATE#2: This night be related to fact, that Thread.GetHashCode() which is used to print out the thread identifier in our log fies could change. See ASP.NET - Thread.GetHashCode() changes


问:
ffind leaf nodes of the binary search tree
i was asked in a interview question that given the preorder traversal of a binary search tree , find out the leaf nodes without constructing the original tree.  i know the property that binary search tree has to satisfy but i cannot find any relation into how can it be done utilising this property . only thing i can identify is that the first node in th preorder traversal will be always be root. also google search did not yield any result for this problem. i do not want the code just a simple hint to begin with would be sufficient.

EDIT: after trying out a lot i got this solution:

```<code>#include<iostream>
#include<vector>
#include<string>
using namespace std;

void fl(vector<int> &v, int lo, int hi){
  if (lo>hi) return;
  if (lo == hi) { cout<<"leaf ^^^^^^^ "<< v[hi]<<"\n"; return; }
  int root = v[lo];
  int i;
  for(i = lo+1 ; i <= hi ; i++) if (v[i] > root) break;
  fl(v, lo+1, i -1);
  fl(v, i , hi);
}

int main(){
vector<int> v1 = {8, 3, 1, 6, 4, 7, 10, 14, 13};
vector<int> v2 = {27, 14, 10, 19, 35, 31, 42};
vector<int> v3 = {9,8,7,6,5,4,3,2,1};
fl(v3,0,v3.size()-1);
return 0;
}
</code>```

any suggestions for improvement other than variable names will be very helpful

答:
```<code>def getLeafNodes(data):
    if data:
        root=data[0]
        leafNodes=[]
        process(data[1:],root,leafNodes)
        return leafNodes

def process(data,root,leafNodes):
    if data:
        left=[]
        right=[]
        for i in range(len(data)):
            if data[i]<root:
                left.append(data[i])
            if data[i]>root:
                right.append(data[i])

        if len(left)==0 and len(right)==0:
            leafNodes.append(root)
            return
        if len(left)>0:
            process(left[1:],left[0],leafNodes)
        if len(right)>0:
            process(right[1:],right[0],leafNodes)
    else:
        leafNodes.append(root)

#--Run--
print getLeafNodes([890,325,290,530,965])
</code>```

Body:
i was asked in a interview question that given the preorder traversal of a binary search tree , find out the leaf nodes without constructing the original tree.  i know the property that binary search tree has to satisfy but i cannot find any relation into how can it be done utilising this property . only thing i can identify is that the first node in th preorder traversal will be always be root. also google search did not yield any result for this problem. i do not want the code just a simple hint to begin with would be sufficient.

EDIT: after trying out a lot i got this solution:

#include<iostream>
#include<vector>
#include<string>
using namespace std;

void fl(vector<int> &v, int lo, int hi){
  if (lo>hi) return;
  if (lo == hi) { cout<<"leaf ^^^^^^^ "<< v[hi]<<"\n"; return; }
  int root = v[lo];
  int i;
  for(i = lo+1 ; i <= hi ; i++) if (v[i] > root) break;
  fl(v, lo+1, i -1);
  fl(v, i , hi);
}

int main(){
vector<int> v1 = {8, 3, 1, 6, 4, 7, 10, 14, 13};
vector<int> v2 = {27, 14, 10, 19, 35, 31, 42};
vector<int> v3 = {9,8,7,6,5,4,3,2,1};
fl(v3,0,v3.size()-1);
return 0;
}

any suggestions for improvement other than variable names will be very helpful


问:
Null values in access vb.net
When I try getting data from Access db And there is actually an empty cell, vs gives me an error . I already tried "tostring()" method but It made thing more complicated

code:

```<code>     While reader.Read
        txtname.Text = reader.GetString(4)
        txtnotes.Text = reader.GetString(5)
    End While
</code>```

Help would be appreciated.

答:
For VBA, check out the IsNull() function. https://msdn.microsoft.com/en-us/library/office/gg278616.aspx

So you would have something like:
If IsNull(reader.get string(4)) then txtname.text="" else txtname.Text = reader.GetString(4)

For VB, I would  do something like this:
If IsDBNull(reader.get string(4)) then txtname.text="" else txtname.Text = reader.GetString(4)

For more info: https://msdn.microsoft.com/en-us/library/tckcces5(v=vs.90).aspx

You could also use the phrase variable is dbnull.value but it's a bit clunky.

Title: Null values in access vb.net

Body:
When I try getting data from Access db And there is actually an empty cell, vs gives me an error . I already tried "tostring()" method but It made thing more complicated

code:

     While reader.Read
        txtname.Text = reader.GetString(4)
        txtnotes.Text = reader.GetString(5)
    End While

Help would be appreciated.


问:
How does Python's triple-quote string work?
How should this function be changed to return "123456"?

```<code>def f():
    s = """123
    456"""
    return s
</code>```

UPDATE: Everyone, the question is about understanding how to not have \t or whatever when having a multiline comment, not how to use the re module.

答:
You might want to check this str.splitlines([keepends])

Return a list of the lines in the string, breaking at line boundaries.
This method uses the universal newlines approach to splitting lines.
Line breaks are not included in the resulting list unless keepends is
given and true.

Python recognizes "\r", "\n", and "\r\n" as line boundaries for 8-bit strings.

So, for the problem at hand ... we could do somehting like this..

```<code>>>> s = """123
... 456"""
>>> s
'123\n456'
>>> ''.join(s.splitlines())
'123456'
</code>```

Body:
How should this function be changed to return "123456"?

def f():
    s = """123
    456"""
    return s

UPDATE: Everyone, the question is about understanding how to not have \t or whatever when having a multiline comment, not how to use the re module.

Body:
You might want to check this str.splitlines([keepends])

Return a list of the lines in the string, breaking at line boundaries.
This method uses the universal newlines approach to splitting lines.
Line breaks are not included in the resulting list unless keepends is
given and true.

Python recognizes "\r", "\n", and "\r\n" as line boundaries for 8-bit strings.

So, for the problem at hand ... we could do somehting like this..

>>> s = """123
... 456"""
>>> s
'123\n456'
>>> ''.join(s.splitlines())
'123456'


答:
in your index.php page

Put this

```<code>echo $_SESSION['message'] != '' ? $_SESSION['message'] : 'No messages';
</code>```

Title: Undefined index in session

Body:
in your index.php page

Put this

echo $_SESSION['message'] != '' ? $_SESSION['message'] : 'No messages';


问:
Bootstrap grid clipping bug
Check out the code for this
https://codepen.io/bran112299/pen/RgrGLQ

if you scroll down the text clips the nav bar
if you remove the bootstrap grid on line 13 it doesn't clip anymore

```<code><p style="font-size: 30px" class="col-xs-10 col-xs-offset-1">
</code>```

Can anyone help so I can keep the bootstrap grid and have no clipping?

答:
hi try this increase the z-index of nav

```<code>nav
{
 z-index:200;
}
</code>```

hope this helps..

Title: Bootstrap grid clipping bug

Body:
Check out the code for this
https://codepen.io/bran112299/pen/RgrGLQ

if you scroll down the text clips the nav bar
if you remove the bootstrap grid on line 13 it doesn't clip anymore

Can anyone help so I can keep the bootstrap grid and have no clipping?

Body:
hi try this increase the z-index of nav

nav
{
 z-index:200;
}

hope this helps..


问:
Windows 10 mobile emulator
I am trying install windows 10 mobile emulator on my lap top the version is 14393. And i have downloaded the installer of size 1.1 mb from official site. it downloaded another file of size about 2.2 gb and it finished but it is not installed properly. it shows up in control panel but not visual studio and hyper-v manager. Uninstall and change options in control panel doesn't do anything but repair will open and after few time it will end up with a fatal error. now what should i do? unable to uninstall or change

Screenshot of error while repairing

答:
According to your situation that the setup was corrupted after installation and, therefore, fails with above error during un-installation, you may need to fix it firstly and un-install. For how to do this please download Program Install and Uninstall troubleshooter and fix.Then empty all temporary folders and try re-install again.

If still have issues, please try the resolutions on this article. You may need to install the package to another drive and grant Full Control permissions to the SYSTEM account as the document mentioned.

If you still have issues after then, please try to provide the installer logs. For how to enable windows install logging please reference this article.

Title: Windows 10 mobile emulator