问:
populate dropdown list from a list of objects
In an attempt of building a 3-tier architecture c# asp.net application, I've started building a class that is database which is used for the connecting to the database, another class that is City which has a method for each column in the table cities, and a Cities class in which I have the GetCities method that creates a list of City objects and then use the DataSource wizard to set the control to use the data from GetCities().
All I get is blanks in the dropdown list. Any idea why?

```<code>        public List<City> GetCities()
    {
        List<City> cities = new List<City>();
        Database db = new Database();
        SqlConnection conn = db.GetConnection();
        String sql = "SELECT * FROM CITIES";
        SqlCommand cmd = new SqlCommand(sql, conn);
        SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            City c = new City(reader.GetInt32(0), reader.GetString(1).ToString());
            cities.Add(c);
        }

        db.CloseConnection();
        return cities;
    }
</code>```

thanks

答:
The issue resided in the City class which after a close inspection I've realised that the constructor was assigning the parameter received incorrectly. It's now working. Thanks!</p>

```<code>public class City
{
    int id;
    string name;

    public City(int id, string name)
    {
        this.id = id;
        this.name = name;

    }

    public int Id
    {
        get { return id; }
        set { id = value; }
    }
    public String Name
    {
        get { return name; }
        set { name = value; }
    }

}
</code>```

Body:
In an attempt of building a 3-tier architecture c# asp.net application, I've started building a class that is database which is used for the connecting to the database, another class that is City which has a method for each column in the table cities, and a Cities class in which I have the GetCities method that creates a list of City objects and then use the DataSource wizard to set the control to use the data from GetCities().
All I get is blanks in the dropdown list. Any idea why?

        public List<City> GetCities()
    {
        List<City> cities = new List<City>();
        Database db = new Database();
        SqlConnection conn = db.GetConnection();
        String sql = "SELECT * FROM CITIES";
        SqlCommand cmd = new SqlCommand(sql, conn);
        SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            City c = new City(reader.GetInt32(0), reader.GetString(1).ToString());
            cities.Add(c);
        }

        db.CloseConnection();
        return cities;
    }

thanks

Body:
The issue resided in the City class which after a close inspection I've realised that the constructor was assigning the parameter received incorrectly. It's now working. Thanks!

public class City
{
    int id;
    string name;

    public City(int id, string name)
    {
        this.id = id;
        this.name = name;

    }

    public int Id
    {
        get { return id; }
        set { id = value; }
    }
    public String Name
    {
        get { return name; }
        set { name = value; }
    }

}


来源: stackexchange

问:
How to add custom controller to extension in vender folder in yii2?
I have an extension yii2-admin for RBAC, and I would like to add to this extension another controllers, views, models etc. Because in this module I would like to keep all operations who admin like CRUD for User table and for another.

What is the right way to add it? Because to add custom file in folder vendor it's bad way.

答:
If you are using a module for manage the authorization control  you can do this way

assuming you module is name auth

in you config/main.php you assign the module  for auth

```<code> 'modules' => [
            .....
    'auth'=> [    // your module for authorization (rbac)
        'class' => 'vendor\your_vendor_name\auth\Module',
    ],
</code>```

then in vendor\your_vendor_name\auth\Module.php
you should have this code for set the controllerNamespace for all the controller related  to auth module

```<code>  namespace vendor\your_vendor_name\auth;

  use \yii\base\Module as BaseModule;

  /**
   * This is the main module class for the    auth .
   *
   *
   *
   */
  class Module extends BaseModule
  {
      public $controllerNamespace = 'vendor\your_vendor_name\auth\controllers';

      const VERSION = '1.0.0-dev';

      public function init()
      {
          parent::init();

          // custom initialization code goes here
      }
  }
</code>```

at this point you can add  all the controller you need in

```<code> `vendor\your_vendor_name\auth\controllers\`
</code>```

and model in

```<code> `vendor\your_vendor_name\auth\models\`
</code>```

and views

in

```<code>     `vendor\your_vendor_name\auth\views\`
</code>```

eg: for controller in   vendor\your_vendor_name\auth\controllers\  i have

```<code>  AuthAssignmentController.php
  AuthItemChildController.php
  AuthItemController.php
  AuthRuleController.php
  DefaultController.php
</code>```

each of this manage the CRUD for the related  model

ContentLicense: CC BY-SA 3.0

Body:
If you are using a module for manage the authorization control  you can do this way

assuming you module is name auth

in you config/main.php you assign the module  for auth

 'modules' => [
            .....
    'auth'=> [    // your module for authorization (rbac)
        'class' => 'vendor\your_vendor_name\auth\Module',
    ],

then in vendor\your_vendor_name\auth\Module.php
you should have this code for set the controllerNamespace for all the controller related  to auth module

  namespace vendor\your_vendor_name\auth;

  use \yii\base\Module as BaseModule;

  /**
   * This is the main module class for the    auth .
   *
   *
   *
   */
  class Module extends BaseModule
  {
      public $controllerNamespace = 'vendor\your_vendor_name\auth\controllers';

      const VERSION = '1.0.0-dev';

      public function init()
      {
          parent::init();

          // custom initialization code goes here
      }
  }

at this point you can add  all the controller you need in

 `vendor\your_vendor_name\auth\controllers\`

and model in

 `vendor\your_vendor_name\auth\models\`

and views

in

     `vendor\your_vendor_name\auth\views\`

eg: for controller in   vendor\your_vendor_name\auth\controllers\  i have

  AuthAssignmentController.php
  AuthItemChildController.php
  AuthItemController.php
  AuthRuleController.php
  DefaultController.php

each of this manage the CRUD for the related  model


问:
Windows event, when wifi connection attempt is made
I want to create an application(in c++), which tells me about access point authentication algorithm. And also warns me, if I tries to connect to wifi, which doesn't use WPA2 AES encryption algo.

If I get widows event information, while connection attempt is made, probably I can write a hook to check the encryption algorithm.

答:
You can use WlanRegisterNotification() to listen for WiFi events.

You can use WlanGetAvailableNetworkList() to get a list of available WiFi networks and their details, including authorization algorithm+cipher and current connection state.


问:
How to update multiple records in same table using .AfterUpdate data macro without error "A data macro resource limit was hit."
I have a table tblItems with a list of inventory items. The table has many columns to describe these items, including columns for SupplierName, SupplierOrderNumber and PredictedArrivalDate.

If I order several new items from a supplier, I will record each item separately in the table with the same supplier name, order number and a predicted arrival date.

I would like to add a data macro, so that if I update the PredictedArrivalDate for one record, the value will be copied to the PredictedArrivalDate column of other records/items with the same SupplierName AND SupplierOrderNumber.

The closest I've got is:

```<code>SetLocalVar (MySupplierName, [SupplierName])
SetLocalVar (MySupplierOrderNumber , [SupplierOrderNumber ])
SetLocalVar (MyPredictedArrivalDate, [PredictedArrivalDate])

For Each Record in tblItems
    Where Condition = [SupplierOrderNumber] Like [MySupplierOrderNumber] And [SupplierName] Like [MySupplierName] And [PredictedArrivalDate]<>[MyPredictedArrivalDate]
    Alias OtherRecords

EditRecord
    SetField ([OtherRecords].[PredictedArrivalDate], [MyPredictedArrivalDate])
End EditRecord
</code>```

However, when I run this, only 5 records update, and the error log reports error -20341:

"A data macro resource limit was hit. This may be caused by a data
  macro recursively calling itself. The Updated() function may be
  used to detect which field in a record has been updated to help
  prevent recursive calls."

How can I get this working?

答:
I'm not one for using macro's to do anything, so I'd use VBA and recordsets/an action query to do the updating.

You can call a user-defined function inside a data macro by setting a local var equal to its result.

Access doesn't like data macros triggering themselves (which you are doing, you're using an on update macro and updating fields in the same table on a different record), because there is a risk of accidentally creating endless loops. Looks like you triggered a measure that's made to prevent this. I'd try to avoid that as much as possible.

Note: using user-defined functions inside data macros can cause problems when you're linking to the table from outside of Access (via ODBC for example).

Body:
I have a table tblItems with a list of inventory items. The table has many columns to describe these items, including columns for SupplierName, SupplierOrderNumber and PredictedArrivalDate.

If I order several new items from a supplier, I will record each item separately in the table with the same supplier name, order number and a predicted arrival date.

I would like to add a data macro, so that if I update the PredictedArrivalDate for one record, the value will be copied to the PredictedArrivalDate column of other records/items with the same SupplierName AND SupplierOrderNumber.

The closest I've got is:

SetLocalVar (MySupplierName, [SupplierName])
SetLocalVar (MySupplierOrderNumber , [SupplierOrderNumber ])
SetLocalVar (MyPredictedArrivalDate, [PredictedArrivalDate])

For Each Record in tblItems
    Where Condition = [SupplierOrderNumber] Like [MySupplierOrderNumber] And [SupplierName] Like [MySupplierName] And [PredictedArrivalDate]<>[MyPredictedArrivalDate]
    Alias OtherRecords

EditRecord
    SetField ([OtherRecords].[PredictedArrivalDate], [MyPredictedArrivalDate])
End EditRecord

However, when I run this, only 5 records update, and the error log reports error -20341:

"A data macro resource limit was hit. This may be caused by a data
  macro recursively calling itself. The Updated() function may be
  used to detect which field in a record has been updated to help
  prevent recursive calls."

How can I get this working?


问:
how to display multiple images from database to blade view, by Laravel 5.3?
I have a multiple images in "Images" column in DB, and I need to display all Images in:

```<code>@foreach(explode(',', $posts->images) as $images)
<div class="col-lg-2 col-md-2 col-sm-2">
    <a href="{{ URL::to('img/offers/'.$images)}}"
       class="portfolio-box">
        <img src="{{ URL::to('img/offers/'.$images)}}"
             class="img-responsive" alt="--">
        <div class="portfolio-box-caption">
            <div class="portfolio-box-caption-content">
            <span class="glyphicon glyphicon-zoom-in"
                  style="font-size: 80px"></span>
            </div>
        </div>
    </a>
</div>
@endforeach
</code>```

but it not working because link show like:

```<code>http://localhost:8000/img/offers/["149939592986Dynamic-Web.png"
</code>```

and next image show like:

```<code>http://localhost:8000/img/offers/"149938949479Static-Web.png"]
</code>```

now, what i do to display all images ?

my column in BD show like an array:

```<code>["149938949418Dynamic-Web.png","149938949479Static-Web.png"]
</code>```

thank you.

答:
You have json encoded data so you have to decode. So,
you can use json_decode() to extract array of image file names as:

```<code> $images = json_decode($posts->images,true);
</code>```

After this you can use simple for loop to show all images,

```<code> @foreach($images as $image)
     <div>
          <--! Write code to display image -->
     </div>
 @endforeach
</code>```

Body:
I have a multiple images in "Images" column in DB, and I need to display all Images in:

@foreach(explode(',', $posts->images) as $images)

@endforeach

but it not working because link show like:

http://localhost:8000/img/offers/["149939592986Dynamic-Web.png"

and next image show like:

http://localhost:8000/img/offers/"149938949479Static-Web.png"]

now, what i do to display all images ?

my column in BD show like an array:

["149938949418Dynamic-Web.png","149938949479Static-Web.png"]

thank you.

Body:
You have json encoded data so you have to decode. So,
you can use json_decode() to extract array of image file names as:

 $images = json_decode($posts->images,true);

After this you can use simple for loop to show all images,

 @foreach($images as $image)
     <div>
          <--! Write code to display image -->
     </div>
 @endforeach


问:
How do I use ArrayAdapter to display a list view?
I want to display a list view in my application. Each row should contain a text and an image. I have used ArrayAdapter to display this but how to insert an image after the text.
Here is the code:

```<code>String lvr[]={"Android","iPhone","BlackBerry","AndroidPeople"};
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list1 = (ListView) findViewById(R.id.cg_listview1);
list1.setAdapter(new ArrayAdapter<String>(this,R.layout.alerts , lvr));
</code>```

Here alerts is my layout which contains only a textView.

答:
If you want to have control over how the layout of items look in a list view, you should make your own custom implementation of ArrayAdapter:

A ListAdapter that manages a ListView
  backed by an array of arbitrary
  objects. (...) To use something other
  than TextViews for the array display,
  for instance, ImageViews, or to have
  some of data besides toString()
  results fill the views, override
  getView(int, View, ViewGroup) to
  return the type of view you want.

If you just google for custom arrayadapter example, you should find enough examples showing you how to implement this. Two such examples are:

http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/

http://android-er.blogspot.com/2010/06/custom-arrayadapter-with-with-different.html

Good luck :)

ContentLicense: CC BY-SA 4.0

Body:
I want to display a list view in my application. Each row should contain a text and an image. I have used ArrayAdapter to display this but how to insert an image after the text.
Here is the code:

String lvr[]={"Android","iPhone","BlackBerry","AndroidPeople"};
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list1 = (ListView) findViewById(R.id.cg_listview1);
list1.setAdapter(new ArrayAdapter<String>(this,R.layout.alerts , lvr));

Here alerts is my layout which contains only a textView.

ContentLicense: CC BY-SA 2.5


问:
Moment JS not recognising ISO 8601 date
So I've got two dates I'd like to get the difference of:

```<code>console.log(new Date(Date.now()).toISOString()); //2017-07-07T16:55:30.471Z
console.log(asset.past[i].date); //2017-07-06T20:29:00.670Z
var a = moment([new Date(Date.now()).toISOString()]);
console.log(a); //Moment Date:Sun Jan 01 2017 00:00:00 GMT+0000
var b = moment([asset.past[i].date]);
console.log(b); //Moment Date:Sun Jan 01 2017 00:00:00 GMT+0000
console.log(a.diff(b, 'seconds', true)); //0
console.log(a.diff(b, 'days', true)); //0
console.log(a.diff(b, 'months', true)); //0
</code>```

I've put the out put of the console logs as comments afterwards. I assume it doesn't recognize the date format as ISO 8601 and defaults to Sun Jan 01 2017 00:00:00 GMT+0000. Either way, any idea how to fix it?

Cheers, Ed.

答:
Why are you passing in an array to the moment constructor? What do you want a to actually be, just the current date? If so just do moment(). If you want to pass in a string do it like you correctly did on line 1.

Here are just the 2 fixes where I removed the square brackets. Again, you can just do moment() to get a moment that points to now.

```<code>// var a = moment(new Date(Date.now()).toISOString());
var a = moment();
var b = moment(asset.past[i].date);
</code>```

Title: Moment JS not recognising ISO 8601 date

Body:
So I've got two dates I'd like to get the difference of:

console.log(new Date(Date.now()).toISOString()); //2017-07-07T16:55:30.471Z
console.log(asset.past[i].date); //2017-07-06T20:29:00.670Z
var a = moment([new Date(Date.now()).toISOString()]);
console.log(a); //Moment Date:Sun Jan 01 2017 00:00:00 GMT+0000
var b = moment([asset.past[i].date]);
console.log(b); //Moment Date:Sun Jan 01 2017 00:00:00 GMT+0000
console.log(a.diff(b, 'seconds', true)); //0
console.log(a.diff(b, 'days', true)); //0
console.log(a.diff(b, 'months', true)); //0

I've put the out put of the console logs as comments afterwards. I assume it doesn't recognize the date format as ISO 8601 and defaults to Sun Jan 01 2017 00:00:00 GMT+0000. Either way, any idea how to fix it?

Cheers, Ed.

Body:
Why are you passing in an array to the moment constructor? What do you want a to actually be, just the current date? If so just do moment(). If you want to pass in a string do it like you correctly did on line 1.

Here are just the 2 fixes where I removed the square brackets. Again, you can just do moment() to get a moment that points to now.

// var a = moment(new Date(Date.now()).toISOString());
var a = moment();
var b = moment(asset.past[i].date);


问:
Is there ever a time when only an octopus merge will do?
The octopus merge looks vaguely terrifying. Is it ever the only way to get something done, or is it purely, um, a convenience function?</p>

答:
First, let me make one more assumption: we're not considering the -s ours strategy (which ignores all but one head and therefore invalidates the parenthetical mark below).

The short answer is "no": the final result of any octopus merge of N heads can be represented by no more than ceil(log2(N)) merges of two heads at a time.  (Or, more simply, by N-1 linear merges.)  The drawback, of course, is that these are stored as multiple merge commits rather than a single merge commit, so they can be split apart and then they do not represent the entire merge.  But in terms of effect, both on merge bases and on source trees, you can always use multiple merges.

(The opposite is not true: some number M of sequential merges, M > 1, of various heads, cannot always be performed as a single octopus merge of all of those heads.  This is because you can resolve merge conflicts in any pairwise merge, but not in octopus merges.  If all of those M merges were conflict-free, the octopus merge will succeed.)


问:
Render map not displaying data on screen
I can't seem to get my renderJob mapping to render out properly.  I have no errors in the console and can't figure out while nothing is showing up.  Is there a problem with the way I'm mapping the object to the index?</p>

```<code>import React, { Component } from 'react'
import PropTypes from 'prop-types'

const jbSampleData = [
    {
        name: 'A place',
        location: 'USA',
        engineer: "Contact Engineer",
        service: "Last install"
    },
]

class Job extends Component {
    render() {

        const renderJob = this.props.data.map((obj, idx) => {
            return (
                <div key={idx}>
                    <div>
                        <p>
                            <span>Name:</span> {obj.name} < br/>
                            <span>Location:</span> {obj.location} <br />
                            <span>Engineer Contact:</span> {obj.engineer} <br />
                            <span>Service:</span> {obj.service} <br />
                        </p>
                    </div>
                </div>
            );
        });

        return (
            <div>
                <renderJob />
                Hello
            </div>
        )
    }
}

Job.propTypes = {
    data: PropTypes.arrayOf(
        PropTypes.object
    )
}

Job.defaultProps = {
    data: jbSampleData
}
export default Job;
</code>```

答:
You are storing the map result basically an array in a variable renderJob, that is not a react component.

You need to render it like this:

```<code>return (
    <div>
        {renderJob}
        Hello
    </div>
)
</code>```

Basically <renderJob> will get converted into:

```<code>React.createElement(renderJob, null);    //new custom element
</code>```

But in case of {renderJob}  its value will get replaced, and all the ui items that variable is having will get rendered.

Why it is not throwing the error with <renderJob/> ?

Because name is stated with small letter so it will be considered as a built-in component like div etc, if you use <RenderJob/> it will throw error that RenderJob is not defined.

As per DOC:

When an element type starts with a lowercase letter, it refers to a
  built-in component like
 or  and results in a string 'div'
  or 'span' passed to React.createElement. Types that start with a
  capital letter like <Foo /> compile to React.createElement(Foo) and
  correspond to a component defined or imported in your JavaScript file.

Body:
I can't seem to get my renderJob mapping to render out properly.  I have no errors in the console and can't figure out while nothing is showing up.  Is there a problem with the way I'm mapping the object to the index?

import React, { Component } from 'react'
import PropTypes from 'prop-types'

const jbSampleData = [
    {
        name: 'A place',
        location: 'USA',
        engineer: "Contact Engineer",
        service: "Last install"
    },
]

class Job extends Component {
    render() {

        const renderJob = this.props.data.map((obj, idx) => {
            return (

                            Name: {obj.name}

                            Location: {obj.location}

                            Engineer Contact: {obj.engineer}

                            Service: {obj.service}

            );
        });

        return (

                <renderJob />
                Hello

        )
    }
}

Job.propTypes = {
    data: PropTypes.arrayOf(
        PropTypes.object
    )
}

Job.defaultProps = {
    data: jbSampleData
}
export default Job;

Body:
You are storing the map result basically an array in a variable renderJob, that is not a react component.

You need to render it like this:

return (
    <div>
        {renderJob}
        Hello
    </div>
)

Basically <renderJob> will get converted into:

React.createElement(renderJob, null);    //new custom element

But in case of {renderJob}  its value will get replaced, and all the ui items that variable is having will get rendered.

Why it is not throwing the error with <renderJob/> ?

Because name is stated with small letter so it will be considered as a built-in component like div etc, if you use <RenderJob/> it will throw error that RenderJob is not defined.

As per DOC:

When an element type starts with a lowercase letter, it refers to a
  built-in component like <div> or <span> and results in a string 'div'
  or 'span' passed to React.createElement. Types that start with a
  capital letter like <Foo /> compile to React.createElement(Foo) and
  correspond to a component defined or imported in your JavaScript file.


问:
Spring Authentication filter not working
I am implementing custom authentication filter as below. But it always returns 404 not found. For Ex: http://localhost:8082/InstaHelpers/api/user/registration.

WebSecurityConfig.java

```<code> @Configuration
                    @EnableWebSecurity
                    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
                        public static final String JWT_TOKEN_HEADER_PARAM = "X-Authorization";
                        public static final String FORM_BASED_LOGIN_ENTRY_POINT = "/api/auth/login";
                        public static final String TOKEN_BASED_AUTH_ENTRY_POINT = "/api/**";
                        public static final String TOKEN_REFRESH_ENTRY_POINT = "/api/auth/token";

                        @Autowired
                        private RestAuthenticationEntryPoint authenticationEntryPoint;
                        @Autowired
                        private JwtAuthenticationSuccessHandler successHandler;
                        @Autowired
                        private JwtAuthenticationFailureHandler failureHandler;
                        @Autowired
                        private AjaxAuthenticationProvider ajaxAuthenticationProvider;
                        @Autowired
                        private JwtAuthenticationProvider jwtAuthenticationProvider;

                        @Autowired
                        private TokenExtractor tokenExtractor;

                        @Autowired
                        private AuthenticationManager authenticationManager;

                        private ObjectMapper objectMapper = new ObjectMapper();

                        protected AjaxLoginProcessingFilter buildAjaxLoginProcessingFilter() throws Exception {
                            AjaxLoginProcessingFilter filter = new AjaxLoginProcessingFilter(FORM_BASED_LOGIN_ENTRY_POINT, successHandler,
                                    failureHandler, objectMapper);
                            filter.setAuthenticationManager(this.authenticationManager);
                            return filter;
                        }

                        protected JwtTokenAuthenticationProcessingFilter buildJwtTokenAuthenticationProcessingFilter() throws Exception {
                            List<String> pathsToSkip = Arrays.asList(TOKEN_REFRESH_ENTRY_POINT, FORM_BASED_LOGIN_ENTRY_POINT);
                            SkipPathRequestMatcher matcher = new SkipPathRequestMatcher(pathsToSkip, TOKEN_BASED_AUTH_ENTRY_POINT);
                            JwtTokenAuthenticationProcessingFilter filter = new JwtTokenAuthenticationProcessingFilter(failureHandler,
                                    tokenExtractor, matcher);
                            filter.setAuthenticationManager(this.authenticationManager);
                            return filter;
                        }

                        @Bean
                        @Override
                        public AuthenticationManager authenticationManagerBean() throws Exception {
                            return super.authenticationManagerBean();
                        }

                        @Override
                        protected void configure(AuthenticationManagerBuilder auth) {
                            auth.authenticationProvider(ajaxAuthenticationProvider);
                            auth.authenticationProvider(jwtAuthenticationProvider);
                        }

                        @Override
                        protected void configure(HttpSecurity http) throws Exception {
                            http.csrf().disable() // We don't need CSRF for JWT based authentication
                                    .exceptionHandling().authenticationEntryPoint(this.authenticationEntryPoint)

                                    .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)

                                    .and().authorizeRequests().antMatchers(FORM_BASED_LOGIN_ENTRY_POINT).permitAll() // Login
                                                                                // end-point
                                    .antMatchers(TOKEN_REFRESH_ENTRY_POINT).permitAll() // Token
                                                                                // refresh
                                                                                // end-point
                                    .antMatchers("/console").permitAll() // H2 Console Dash-board -
                                                                            // only for testing
                                    .and().authorizeRequests().antMatchers(TOKEN_BASED_AUTH_ENTRY_POINT).authenticated() // Protected
                                                                                // API
                                                                                // End-points
                                    .and().addFilterBefore(new CustomCorsFilter(), UsernamePasswordAuthenticationFilter.class)
                                    .addFilterBefore(buildAjaxLoginProcessingFilter(), UsernamePasswordAuthenticationFilter.class)
                                    .addFilterBefore(buildJwtTokenAuthenticationProcessingFilter(),
                                            UsernamePasswordAuthenticationFilter.class);
                        }
                    }
</code>```

Web.xml

```<code>            <?xml version="1.0" encoding="UTF-8"?>
            <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xmlns:sec="http://www.springframework.org/schema/security"
                xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd
                http://www.springframework.org/schema/security
                http://www.springframework.org/schema/security/spring-
                security-4.2.xsd">

                <context-param>
                    <param-name>contextConfigLocation</param-name>
                    <param-value>/WEB-INF/spring/*.xml</param-value>
                </context-param>

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

                <servlet>
                    <servlet-name>appServlet</servlet-name>
                    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
                    <init-param>
                        <param-name>contextConfigLocation</param-name>
                        <param-value>/WEB-INF/spring/appServlet/servlet- context.xml</param-value>
                    </init-param>
                    <load-on-startup>1</load-on-startup>
                </servlet>

                <servlet-mapping>
                    <servlet-name>appServlet</servlet-name>
                    <url-pattern>/</url-pattern>
                </servlet-mapping>
             </web-app>
</code>```

Dependencies

```<code>                <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-core</artifactId>
                <version>4.2.2.RELEASE</version>
            </dependency>

            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-config</artifactId>
                <version>4.2.2.RELEASE</version>
            </dependency>

            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-web</artifactId>
                <version>4.2.2.RELEASE</version>
            </dependency>
</code>```

I am aware solution to such issue is listed in other questions but it is not solving the issue.

答:
You need to either create class which extends AbstractSecurityWebApplicationInitializer it will load the springSecurityFilterChain automatically.

```<code>import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {

}
</code>```

or provide spring security filter chain in web.xml like below

```<code><filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy
                </filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
</code>```

( I can also notice one space in servlet- context.xml, correct this as well).

Other thing you might have incorrect mapping in your view resolver, kindly post code for that as well

Body:
I am implementing custom authentication filter as below. But it always returns 404 not found. For Ex: http://localhost:8082/InstaHelpers/api/user/registration.

WebSecurityConfig.java

 @Configuration
                    @EnableWebSecurity
                    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
                        public static final String JWT_TOKEN_HEADER_PARAM = "X-Authorization";
                        public static final String FORM_BASED_LOGIN_ENTRY_POINT = "/api/auth/login";
                        public static final String TOKEN_BASED_AUTH_ENTRY_POINT = "/api/**";
                        public static final String TOKEN_REFRESH_ENTRY_POINT = "/api/auth/token";

                        @Autowired
                        private RestAuthenticationEntryPoint authenticationEntryPoint;
                        @Autowired
                        private JwtAuthenticationSuccessHandler successHandler;
                        @Autowired
                        private JwtAuthenticationFailureHandler failureHandler;
                        @Autowired
                        private AjaxAuthenticationProvider ajaxAuthenticationProvider;
                        @Autowired
                        private JwtAuthenticationProvider jwtAuthenticationProvider;

                        @Autowired
                        private TokenExtractor tokenExtractor;

                        @Autowired
                        private AuthenticationManager authenticationManager;

                        private ObjectMapper objectMapper = new ObjectMapper();

                        protected AjaxLoginProcessingFilter buildAjaxLoginProcessingFilter() throws Exception {
                            AjaxLoginProcessingFilter filter = new AjaxLoginProcessingFilter(FORM_BASED_LOGIN_ENTRY_POINT, successHandler,
                                    failureHandler, objectMapper);
                            filter.setAuthenticationManager(this.authenticationManager);
                            return filter;
                        }

                        protected JwtTokenAuthenticationProcessingFilter buildJwtTokenAuthenticationProcessingFilter() throws Exception {
                            List<String> pathsToSkip = Arrays.asList(TOKEN_REFRESH_ENTRY_POINT, FORM_BASED_LOGIN_ENTRY_POINT);
                            SkipPathRequestMatcher matcher = new SkipPathRequestMatcher(pathsToSkip, TOKEN_BASED_AUTH_ENTRY_POINT);
                            JwtTokenAuthenticationProcessingFilter filter = new JwtTokenAuthenticationProcessingFilter(failureHandler,
                                    tokenExtractor, matcher);
                            filter.setAuthenticationManager(this.authenticationManager);
                            return filter;
                        }

                        @Bean
                        @Override
                        public AuthenticationManager authenticationManagerBean() throws Exception {
                            return super.authenticationManagerBean();
                        }

                        @Override
                        protected void configure(AuthenticationManagerBuilder auth) {
                            auth.authenticationProvider(ajaxAuthenticationProvider);
                            auth.authenticationProvider(jwtAuthenticationProvider);
                        }

                        @Override
                        protected void configure(HttpSecurity http) throws Exception {
                            http.csrf().disable() // We don't need CSRF for JWT based authentication
                                    .exceptionHandling().authenticationEntryPoint(this.authenticationEntryPoint)

                                    .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)

                                    .and().authorizeRequests().antMatchers(FORM_BASED_LOGIN_ENTRY_POINT).permitAll() // Login
                                                                                // end-point
                                    .antMatchers(TOKEN_REFRESH_ENTRY_POINT).permitAll() // Token
                                                                                // refresh
                                                                                // end-point
                                    .antMatchers("/console").permitAll() // H2 Console Dash-board -
                                                                            // only for testing
                                    .and().authorizeRequests().antMatchers(TOKEN_BASED_AUTH_ENTRY_POINT).authenticated() // Protected
                                                                                // API
                                                                                // End-points
                                    .and().addFilterBefore(new CustomCorsFilter(), UsernamePasswordAuthenticationFilter.class)
                                    .addFilterBefore(buildAjaxLoginProcessingFilter(), UsernamePasswordAuthenticationFilter.class)
                                    .addFilterBefore(buildJwtTokenAuthenticationProcessingFilter(),
                                            UsernamePasswordAuthenticationFilter.class);
                        }
                    }

Web.xml

            <?xml version="1.0" encoding="UTF-8"?>
            <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xmlns:sec="http://www.springframework.org/schema/security"
                xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd
                http://www.springframework.org/schema/security
                http://www.springframework.org/schema/security/spring-
                security-4.2.xsd">

                <context-param>
                    <param-name>contextConfigLocation</param-name>
                    <param-value>/WEB-INF/spring/*.xml</param-value>
                </context-param>

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

                <servlet>
                    <servlet-name>appServlet</servlet-name>
                    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
                    <init-param>
                        <param-name>contextConfigLocation</param-name>
                        <param-value>/WEB-INF/spring/appServlet/servlet- context.xml</param-value>
                    </init-param>
                    <load-on-startup>1</load-on-startup>
                </servlet>

                <servlet-mapping>
                    <servlet-name>appServlet</servlet-name>
                    <url-pattern>/</url-pattern>
                </servlet-mapping>
             </web-app>

Dependencies

                <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-core</artifactId>
                <version>4.2.2.RELEASE</version>
            </dependency>

            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-config</artifactId>
                <version>4.2.2.RELEASE</version>
            </dependency>

            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-web</artifactId>
                <version>4.2.2.RELEASE</version>
            </dependency>

I am aware solution to such issue is listed in other questions but it is not solving the issue.

Body:
You need to either create class which extends AbstractSecurityWebApplicationInitializer it will load the springSecurityFilterChain automatically.

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {

}

or provide spring security filter chain in web.xml like below

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy
                </filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

( I can also notice one space in servlet- context.xml, correct this as well).

Other thing you might have incorrect mapping in your view resolver, kindly post code for that as well


问:
why to import React
I have code which works only after importing React but I'm not using React anywhere I'm using reactDom instead

```<code>import ReactDOM from 'react-dom'
import React, {Component} from 'react'

class App extends Component {
  render () {
    return (
      <div>comp </div>
    )
  }
}

//ReactDOM.render(<App/>, document.getElementById('root'))
ReactDOM.render(<div>sv</div>, document.getElementById('root'))
</code>```

why its require to import React ??

答:
This is a really interesting question, since you're right that the code doesn't look like it's using React, but it's being tricky.

Any time you use the shorthand <Component /> code what's actually happening is the JSX is transpiled by Babel into something that is regular Javascript.

```<code><Component/>
// Is turned into
React.createElement(...)
</code>```

Therefore the code does indeed need React to be imported, although it's not obvious to the reader

Title: why to import React

Body:
I have code which works only after importing React but I'm not using React anywhere I'm using reactDom instead

import ReactDOM from 'react-dom'
import React, {Component} from 'react'

class App extends Component {
  render () {
    return (

comp

    )
  }
}

//ReactDOM.render(<App/>, document.getElementById('root'))
ReactDOM.render(
sv
, document.getElementById('root'))

why its require to import React ??

Body:
This is a really interesting question, since you're right that the code doesn't look like it's using React, but it's being tricky.

Any time you use the shorthand <Component /> code what's actually happening is the JSX is transpiled by Babel into something that is regular Javascript.

<Component/>
// Is turned into
React.createElement(...)

Therefore the code does indeed need React to be imported, although it's not obvious to the reader


问:
ImportError: No module named time
I'm trying to get a Google app up and running on my local machine, however, am facing an issue when running the setup scripts. The script errors out and tells me that there is no module time and seems to be breaking in the google-cloud-sdk....

Things I've tried:

Importing time in Python (it works)

Trying this to no avail: https://apple.stackexchange.com/questions/96308/python-installation-messed-up

```<code>Traceback (most recent call last):
  File "/Users/kennethryan/Projects/go-edu-store/y/google-cloud-sdk/platform/google_appengine/_python_runtime.py", line 83, in <module>
_run_file(__file__, globals())
  File "/Users/kennethryan/Projects/go-edu-store/y/google-cloud-sdk/platform/google_appengine/_python_runtime.py", line 79, in _run_file
execfile(_PATHS.script_file(script_name), globals_)
  File "/Users/kennethryan/Projects/go-edu-store/y/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/runtime.py", line 175, in <module>
main()
  File "/Users/kennethryan/Projects/go-edu-store/y/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/runtime.py", line 155, in main
sandbox.enable_sandbox(config)
  File "/Users/kennethryan/Projects/go-edu-store/y/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", line 183, in enable_sandbox
__import__('%s.threading' % dist27.__name__)
  File "/Users/kennethryan/Projects/go-edu-store/y/google-cloud-sdk/platform/google_appengine/google/appengine/dist27/threading.py", line 13, in <module>
from time import time as _time, sleep as _sleep
  File "/Users/kennethryan/Projects/go-edu-store/y/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", line 984, in load_module
raise ImportError('No module named %s' % fullname)
  ImportError: No module named time
</code>```

Here is my current $PATH:

```<code>/Users/kennethryan/Projects/go-edu-store/y/google-cloud-sdk/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
</code>```

答:
Seeing as this is an inactive year old issue, we can assume that updating the Google Cloud tools to their latest versions by running 'gcloud components update' will fix this.

Also ensuring that you are using the Python installation provided by GCloud, and that there are no conflicting 'CLOUDSDK_PYTHON' environment variables should prevent this.

If this issue is seen again in the future, it is recommended to directly report this to the Google Public Issue Tracker so that this can be properly handled and triaged to the GCloud engineering team.

Title: ImportError: No module named time

Body:
I'm trying to get a Google app up and running on my local machine, however, am facing an issue when running the setup scripts. The script errors out and tells me that there is no module time and seems to be breaking in the google-cloud-sdk....

Things I've tried:

Importing time in Python (it works)

Trying this to no avail: https://apple.stackexchange.com/questions/96308/python-installation-messed-up

Traceback (most recent call last):
  File "/Users/kennethryan/Projects/go-edu-store/y/google-cloud-sdk/platform/google_appengine/_python_runtime.py", line 83, in <module>
_run_file(__file__, globals())
  File "/Users/kennethryan/Projects/go-edu-store/y/google-cloud-sdk/platform/google_appengine/_python_runtime.py", line 79, in _run_file
execfile(_PATHS.script_file(script_name), globals_)
  File "/Users/kennethryan/Projects/go-edu-store/y/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/runtime.py", line 175, in <module>
main()
  File "/Users/kennethryan/Projects/go-edu-store/y/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/runtime.py", line 155, in main
sandbox.enable_sandbox(config)
  File "/Users/kennethryan/Projects/go-edu-store/y/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", line 183, in enable_sandbox
__import__('%s.threading' % dist27.__name__)
  File "/Users/kennethryan/Projects/go-edu-store/y/google-cloud-sdk/platform/google_appengine/google/appengine/dist27/threading.py", line 13, in <module>
from time import time as _time, sleep as _sleep
  File "/Users/kennethryan/Projects/go-edu-store/y/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", line 984, in load_module
raise ImportError('No module named %s' % fullname)
  ImportError: No module named time

Here is my current $PATH:

/Users/kennethryan/Projects/go-edu-store/y/google-cloud-sdk/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin


问:
Common serializer for php and java Object
I'd like to serialize an object from java and to unserialize this object in PhP. I saw different classes in java that does this but they are not able to serialize not primitive object.

By the way, do you know where I can read the details of the language generated by the function 'serialize' of php?

Thank you very much

Bat

答:
When unserializing an object in PHP, PHP needs to have the class definition of that object. I doubt you'll get very far if the original class is a Java class.

I'd suggest you go for a language neutral data encapsulation format like JSON. This can be json_decoded into a stdClass object.


问:
How to add custom styles to 3rd party components?
What is the recommended way to customize styles for a 3rd party component that I have downloaded via npm?

For example the component ng2-tag-input. I run a webpack build that bundles all the 3rd party js-files into a vendor.js and all the 3rd party css into a vendor.css.

Since this is generated upon build, I don't want to make changes to vendor.css or commit it.

Say that I want to add my own styles to ng2-tag-input, how does one best do that? Should I just override its styles in my own site.css or is there another way?

答:
You can use :host >>> .third-party-class.

Use the /deep/ and >>> selectors only with emulated view encapsulation.

source: https://angular.io/guide/component-styles#deep


问:
Beautiful Soup - Blank screen for a long time without any output
I am quite new to python and am working on a scraping based project- where I am supposed to extract all the contents from links containing a particular search term and place them in a csv file. As a first step, I wrote this code to extract all the links from a website based on a search term entered. I only get a blank screen as output and I am unable to find my mistake.</p>

```<code>import urllib
import mechanize
from bs4 import BeautifulSoup
import datetime

def searchAP(searchterm):
    newlinks = []
    browser = mechanize.Browser()
    browser.set_handle_robots(False)
    browser.addheaders = [('User-agent', 'Firefox')]
    text = ""
    start = 0

    while "There were no matches for your search" not in text:
        url = "http://www.marketing-interactive.com/"+"?s="+searchterm
        text = urllib.urlopen(url).read()
        soup = BeautifulSoup(text, "lxml")
        results = soup.findAll('a')
        for r in results:
            if "rel=bookmark" in r['href'] :
                newlinks.append("http://www.marketing-interactive.com"+ str(r["href"]))
        start +=10
                return newlinks
       print searchAP("digital marketing")
</code>```

答:
You made four mistakes:

You are defining start but you never use it. (Nor can you, as far as I can see on http://www.marketing-interactive.com/?s=something. There is no url based pagination.) So you endlessly looping over the first set of results.

"There were no matches for your search" is not the no-results string returned by that site. So it would go on forever anyway.

You are appending the link, including http://www.marketing-interactive.com to http://www.marketing-interactive.com. So you would end up with http://www.marketing-interactive.comhttp://www.marketing-interactive.com/astro-launches-digital-marketing-arm-blaze-digital/

Concerning rel=bookmark selection: arifs solution  is the proper way to go. But if you really want to do it this way you'd need to something like this:

```<code>for r in results:
    if r.attrs.get('rel') and r.attrs['rel'][0] == 'bookmark':
        newlinks.append(r["href"])
</code>```

This first checks if rel exists and then checks if its first child is "bookmark", as r['href'] simply does not contain the rel. That's not how BeautifulSoup structures things.

To scrape this specific site you can do two things:

You could do something with Selenium or something else that supports Javascript and press that "Load more" button. But this is quite a hassle.

You can use this loophole: http://www.marketing-interactive.com/wp-content/themes/MI/library/inc/loop_handler.php?pageNumber=1&postType=search&searchValue=digital+marketing
This is the url that feeds the list. It has pagination, so you can easily loop over all results.

Body:
I am quite new to python and am working on a scraping based project- where I am supposed to extract all the contents from links containing a particular search term and place them in a csv file. As a first step, I wrote this code to extract all the links from a website based on a search term entered. I only get a blank screen as output and I am unable to find my mistake.

import urllib
import mechanize
from bs4 import BeautifulSoup
import datetime

def searchAP(searchterm):
    newlinks = []
    browser = mechanize.Browser()
    browser.set_handle_robots(False)
    browser.addheaders = [('User-agent', 'Firefox')]
    text = ""
    start = 0

    while "There were no matches for your search" not in text:
        url = "http://www.marketing-interactive.com/"+"?s="+searchterm
        text = urllib.urlopen(url).read()
        soup = BeautifulSoup(text, "lxml")
        results = soup.findAll('a')
        for r in results:
            if "rel=bookmark" in r['href'] :
                newlinks.append("http://www.marketing-interactive.com"+ str(r["href"]))
        start +=10
                return newlinks
       print searchAP("digital marketing")

Body:
You made four mistakes:

You are defining start but you never use it. (Nor can you, as far as I can see on http://www.marketing-interactive.com/?s=something. There is no url based pagination.) So you endlessly looping over the first set of results.

"There were no matches for your search" is not the no-results string returned by that site. So it would go on forever anyway.

You are appending the link, including http://www.marketing-interactive.com to http://www.marketing-interactive.com. So you would end up with http://www.marketing-interactive.comhttp://www.marketing-interactive.com/astro-launches-digital-marketing-arm-blaze-digital/

Concerning rel=bookmark selection: arifs solution  is the proper way to go. But if you really want to do it this way you'd need to something like this:

for r in results:
    if r.attrs.get('rel') and r.attrs['rel'][0] == 'bookmark':
        newlinks.append(r["href"])

This first checks if rel exists and then checks if its first child is "bookmark", as r['href'] simply does not contain the rel. That's not how BeautifulSoup structures things.

To scrape this specific site you can do two things:

You could do something with Selenium or something else that supports Javascript and press that "Load more" button. But this is quite a hassle.

You can use this loophole: http://www.marketing-interactive.com/wp-content/themes/MI/library/inc/loop_handler.php?pageNumber=1&postType=search&searchValue=digital+marketing
This is the url that feeds the list. It has pagination, so you can easily loop over all results.


问:
Dynamic Loading of a DIV
I have multiple check boxes which are formed based on the iteration from the collection by the foreach loop of the core tags in jsp with two parameters ID(which is the id of the textbox) and key .Both Id and key are populated dynamically based on iteration . Oncheck, it calls a function having AJAX code .and  the response from ajax which is a JSON and the JSON is populated dynamically on same div based on the key.I am using tabed view similar to what you can find in,https://www.w3schools.com/howto/howto_js_tabs.asp. These tabs are also dynamically controlled by id's of checkboxes. If checkbox is clicked,button is visible and vice-versa.(Note:Button also fires ajax call)The problem which I am facing right now is, if i am disabling the checkbox,the div is retaining the value of the old key.I know the problem is with design of my code.Can any one say how can it be re-designed.I will attach the code for reference:

```<code>function enableButton(id, key) {
        openError(key);
        if (!flag) {
            document.getElementById("resultTab").style.display = 'block';
        }
        if (flag){
            document.getElementById(id).checked = false;
        }
        var lastCharacterOfId = document.getElementById(id).id.charAt(document
                .getElementById(id).id.length - 1);
        var checkBox = document.getElementById(id);
        var button = document.getElementById("btn_" + lastCharacterOfId);
        if (checkBox.checked) {
            $("#good").html('');
            button.style.display = 'block';
            button.disabled = false;
            counterForScript++;
            //openError(key);
        } else {
            $("#good").html('');
            button.style.display = 'none'
            button.disabled = true;
            if(!flag){
            counterForScript--;
            }
            if (counterForScript > 0) {
                console.log(checkBoxKeyArray[counterForScript]);
            }
        }
        if (counterForScript == 0) {
            document.getElementById("resultTab").style.display = 'none';
        }
</code>```

function openError(key) {

```<code>    if ($("#aFile").get(0).files.length == 0) {
        alert("Please select a file ");
        flag = true;
        return false;
    }

    if ($("#aFile").val().substring($("#aFile").val().lastIndexOf(".") + 1,
            $("#aFile").val().length) != 'log') {
        alert("Please select only Log Files");
        flag = true;
        return false;
    }

    $("#good").html('');
    var length = 0;
    $(document)
            .ready(
                    function() {

                        $.ajax({
                                    type : "POST",
                                    enctype : 'multipart/form-data',
                                    url : "uploadServlet",
                                    data : formData,
                                    processData : false,
                                    contentType : false,
                                    cache : false,
                                    timeout : 600000,
                                    dataType : 'json',

                                    success : function(data) {

                                        $("#good").append("<br><span align=\"left\" style=\"margin-left:1%\">Total Number of occurences of the search string <font style=\"font-weight: bold; text-transform: uppercase;\">"
                                                                + key
                                                                + "</font>: "
                                                                + data.length
                                                                + "</span>");
                                        if (data.length > 0) {$("#good").append(
                                                            "<p align=\"left\" style=\"margin-left:1%;margin-top:4%\">Your search string <font style=\"font-weight: bold; text-transform: uppercase;\">"
                                                                    + key
                                                                    + "</font> can be found in Line Numbers:");
                                        }
                                        $
                                                .each(
                                                        data,
                                                        function(id,
                                                                element) {
                                                            $("#good")
                                                                    .append(
                                                                            "<span style=\"margin-left:1%;\">"
                                                                                + element
                                                                                + "</span></p>");
                                                        });

                                    },
                                });
                    });
}
</code>```

HTML CODE:

                                        FILE:

```<code>                            <p>
                                <font style="font-weight: bold;">SEARCH:</font>
                                <c:forEach var="hm" items="${logAnalysisHashMap}">
                                    <c:set var="count" value="${count + 1}" scope="page" />
                                    <input type="checkbox" id="cb_${count}"
                                        onchange="enableButton(this.id,'${hm.key}');" />
                                    <font style="font-weight: bold; text-transform: uppercase;">
                                        ${hm.key} </font>
                                </c:forEach>
                            </p>
                        </div>

                        <div class="tab" id="resultTab"
                            style="width: 90%; margin-left: 5%; height: 40%; margin-top: 2%; position: relative; overflow: auto; display: none">

                            <div style="display: block; clear: both;">
                                <c:forEach var="hm" items="${logAnalysisHashMap}">
                                    <c:set var="countbtn" value="${countbtn + 1}" scope="page" />
                                    <button class="tablinks" id="btn_${countbtn}"
                                        onclick='openError("${hm.key}");' style="display: none;"
                                        disabled>
                                        <font style="font-weight: bold; text-transform: uppercase;">${hm.key}
                                        </font>
                                    </button>
                                </c:forEach>
                            </div>
</code>```

答:
The problem which I am facing right now is, if i am disabling the checkbox,the div is retaining the value of the old key.

You can use jQuery change event of checkbox and remove its value when the checkbox is disabled. For Example -

```<code>$(document).ready(function() {

    $('#checkbox1').change(function() {  //Detecting change!!
        if(this.checked) {               //When checkbox is clicked
            var returnVal = confirm("Are you sure?");
        }

        else{
            //check box is unchecked!!
            //Remove your div key value..
        }
    });
});
</code>```

See this for more details on .change() (jQuery)

Title: Dynamic Loading of a DIV

Body:
I have multiple check boxes which are formed based on the iteration from the collection by the foreach loop of the core tags in jsp with two parameters ID(which is the id of the textbox) and key .Both Id and key are populated dynamically based on iteration . Oncheck, it calls a function having AJAX code .and  the response from ajax which is a JSON and the JSON is populated dynamically on same div based on the key.I am using tabed view similar to what you can find in,https://www.w3schools.com/howto/howto_js_tabs.asp. These tabs are also dynamically controlled by id's of checkboxes. If checkbox is clicked,button is visible and vice-versa.(Note:Button also fires ajax call)The problem which I am facing right now is, if i am disabling the checkbox,the div is retaining the value of the old key.I know the problem is with design of my code.Can any one say how can it be re-designed.I will attach the code for reference:

function enableButton(id, key) {
        openError(key);
        if (!flag) {
            document.getElementById("resultTab").style.display = 'block';
        }
        if (flag){
            document.getElementById(id).checked = false;
        }
        var lastCharacterOfId = document.getElementById(id).id.charAt(document
                .getElementById(id).id.length - 1);
        var checkBox = document.getElementById(id);
        var button = document.getElementById("btn_" + lastCharacterOfId);
        if (checkBox.checked) {
            $("#good").html('');
            button.style.display = 'block';
            button.disabled = false;
            counterForScript++;
            //openError(key);
        } else {
            $("#good").html('');
            button.style.display = 'none'
            button.disabled = true;
            if(!flag){
            counterForScript--;
            }
            if (counterForScript > 0) {
                console.log(checkBoxKeyArray[counterForScript]);
            }
        }
        if (counterForScript == 0) {
            document.getElementById("resultTab").style.display = 'none';
        }

function openError(key) {

    if ($("#aFile").get(0).files.length == 0) {
        alert("Please select a file ");
        flag = true;
        return false;
    }

    if ($("#aFile").val().substring($("#aFile").val().lastIndexOf(".") + 1,
            $("#aFile").val().length) != 'log') {
        alert("Please select only Log Files");
        flag = true;
        return false;
    }

    $("#good").html('');
    var length = 0;
    $(document)
            .ready(
                    function() {

                        $.ajax({
                                    type : "POST",
                                    enctype : 'multipart/form-data',
                                    url : "uploadServlet",
                                    data : formData,
                                    processData : false,
                                    contentType : false,
                                    cache : false,
                                    timeout : 600000,
                                    dataType : 'json',

                                    success : function(data) {

                                        $("#good").append("
Total Number of occurences of the search string "
                                                                + key
                                                                + ": "
                                                                + data.length
                                                                + "");
                                        if (data.length > 0) {$("#good").append(
                                                            "
Your search string "
                                                                    + key
                                                                    + " can be found in Line Numbers:");
                                        }
                                        $
                                                .each(
                                                        data,
                                                        function(id,
                                                                element) {
                                                            $("#good")
                                                                    .append(
                                                                            ""
                                                                                + element
                                                                                + "
");
                                                        });

                                    },
                                });
                    });
}

HTML CODE:

                                        FILE:

                                SEARCH:
                                <c:forEach var="hm" items="${logAnalysisHashMap}">
                                    <c:set var="count" value="${count + 1}" scope="page" />
                                    <input type="checkbox" id="cb_${count}"
                                        onchange="enableButton(this.id,'${hm.key}');" />

                                        ${hm.key}
                                </c:forEach>

                                <c:forEach var="hm" items="${logAnalysisHashMap}">
                                    <c:set var="countbtn" value="${countbtn + 1}" scope="page" />
                                    <button class="tablinks" id="btn_${countbtn}"
                                        onclick='openError("${hm.key}");' style="display: none;"
                                        disabled>
                                        ${hm.key}

                                    </button>
                                </c:forEach>

Body:
The problem which I am facing right now is, if i am disabling the checkbox,the div is retaining the value of the old key.

You can use jQuery change event of checkbox and remove its value when the checkbox is disabled. For Example -

$(document).ready(function() {

    $('#checkbox1').change(function() {  //Detecting change!!
        if(this.checked) {               //When checkbox is clicked
            var returnVal = confirm("Are you sure?");
        }

        else{
            //check box is unchecked!!
            //Remove your div key value..
        }
    });
});

See this for more details on .change() (jQuery)


问:
Creating a WiFi application
I have to write an Application which shares data over an Wireless Ad Hoc Network.

And I have No Idea how to do this. I am good at C# so I am thinking to choose C# for writting the Application

First question- How to read Data Received over WiFi or How to send Data over WiFi... Means is there any Port to which I should Read/Write?

Second Question- All the Protocol Management stuff is done by Adapter or my Application should that?

And also suggest some reading which I should go for! I read basics of WiFi and how it works and all!

Regards!

答: You need to start reading about Native Wifi for Windows XP SP3/Win2k/Vista/7.</p>

Title: Creating a WiFi application


问:
Android - Changing item title in bottom navigation bar
I have 2 fragments between which I can navigate with a bottom navigation bar. I also have an overflow menu with an item which shows an edittext dialog.

I want that when I write and validate text in the dialog, the currently displayed fragment's item on the nav bar changes of title. I don't know how to change text of a specific item.

I hope my question is understandable. I have been searching through SO but I didn't find any corresponding answers.

答: If you define an id for the item you want to change in the layouts menu (add the line android:id="@+id/myid"), you can find that item in the code by using findViewById (R.id.myid). Then, just set the new the title depending on what the item is.</p>


问:
VBA Random Number in Simulation
I'm trying to create a baseball post season simulator to see how much a bad pitcher impacts a team's championship odds. So I basically created a simulator for the playoffs (3 rounds, first is best of 5, next two are best of 7). And I can see how much a SP would hurt the team if he pitches every third game and he decreases the chance of winning by 10%.

To make sure I did this write, I first ran my simulation without any adjustment so every game both teams would have a 50% chance of winning... (a team would therefore have a 12.5% chance of winning the world series in a 3 round playoff) however, I was getting consistently higher than 12.5.

I have a feeling the problem was with the Rnd function, so I played with that a bit (added a function, tried to vary the time ect.), now my simulation comes out to be <12.5%. I then tried to trouble shoot and noticed that in each round was not being won 50% of the time... which was the case each time I re-ran the simulation (Like round 1 would have a 47% success then round two 51% then round three 58%... then the next run would return 46%, 52%, 59%.

Am I do something wrong, or is this just something the rnd function is not great at handling?

```<code>Public Function wRandomNumber(lowerbound, upperbound, Optional rndType = 1) As Double
Dim rndVariable As Double
'Const ms As Double = 0.000000011574

Randomize Timer
'Application.Wait Now + ms * 1
rndVariable = Rnd
If rndType = 1 Then
    wRandomNumber = Int((upperbound - lowerbound + 1) * rndVariable + lowerbound)
ElseIf rndType = 2 Then
    If (upperbound - lowerbound + 1) * rndVariable + lowerbound <= upperbound Then
        wRandomNumber = (upperbound - lowerbound + 1) * rndVariable + lowerbound
    Else
        Do While (upperbound - lowerbound + 1) * rndVariable + lowerbound > upperbound
            rndVariable = Rnd
            If (upperbound - lowerbound + 1) * rndVariable + lowerbound <= upperbound Then
                wRandomNumber = (upperbound - lowerbound + 1) * rndVariable + lowerbound
            End If
        Loop
    End If
End If
End Function

Public Sub Playoff_sim()

Dim game_num As Integer
Dim lds_wins_stros As Integer
Dim lds_loss_stros As Integer
Dim lcs_wins_stros As Integer
Dim lcs_loss_stros As Integer
Dim ws_wins_stros As Integer
Dim ws_loss_stros As Integer
Dim p As Double
Dim outcome1 As Single
Dim outcome2 As Single
Dim outcome3 As Single
Dim i As Double
Dim iter As Double
Dim CHAMPS As Double
Dim Loser As Double
Dim p_bad As Double
Dim p_norm As Double
Dim lds_champs As Double
Dim lcs_champs As Double
Dim r As Double
Const ms As Double = 0.000000011574

iter = 100000
CHAMPS = 0
Loser = 0
lds_champs = 0
lcs_champs = 0
p_bad = 0.5
p_norm = 0.5
r = 0
For i = 1 To iter

game_num = 1
lds_wins_stros = 0
lds_loss_stros = 0
lcs_wins_stros = 0
lcs_loss_stros = 0
ws_loss_stros = 0
ws_wins_stros = 0

Do Until lds_wins_stros = 3 Or lds_loss_stros = 3

outcome1 = wRandomNumber(0, 1, 2)
    If game_num = 3 Then
        p = p_bad
    Else
        p = p_norm
    End If

    If p > outcome1 Then
        lds_wins_stros = lds_wins_stros + 1
    Else
        lds_loss_stros = lds_loss_stros + 1
    End If
    r = r + 1
    'Worksheets("Playoff_Sim").Cells(r, 15).Value = outcome1

game_num = game_num + 1
Loop

If lds_wins_stros = 3 Then

    outcome2 = wRandomNumber(0, 1, 2)
    lds_champs = 1 + lds_champs
    Do Until lcs_wins_stros = 4 Or lcs_loss_stros = 4

    If game_num = 3 Or 6 Or 9 Or 12 Or 15 Or 18 Or 21 Then
        p = p_bad
    Else
        p = p_norm
    End If

    If p > outcome2 Then
        lcs_wins_stros = lcs_wins_stros + 1
    Else
        lcs_loss_stros = lcs_loss_stros + 1
    End If

    game_num = game_num + 1

    Loop

    If lcs_wins_stros = 4 Then
        lcs_champs = lcs_champs + 1

        outcome3 = wRandomNumber(0, 1, 2)
        Do Until ws_wins_stros = 4 Or ws_loss_stros = 4

            If game_num = 3 Or 6 Or 9 Or 12 Or 15 Or 18 Or 21 Then
                p = p_bad
            Else
                p = p_norm
            End If

            If p > outcome3 Then
                ws_wins_stros = ws_wins_stros + 1
            Else
                ws_loss_stros = ws_loss_stros + 1
            End If
        'r = r + 1
        game_num = game_num + 1
        'Worksheets("Playoff_Sim").Cells(r, 15).Value = outcome3
        Loop

        If ws_wins_stros = 4 Then
            CHAMPS = CHAMPS + 1
        Else
            Loser = Loser + 1
        End If

    Else
        Loser = Loser + 1
    End If

Else
    Loser = Loser + 1
End If

Next i

Worksheets("Playoff_Sim").Cells(2, 1).Value = CHAMPS
Worksheets("Playoff_Sim").Cells(2, 2).Value = Loser
Worksheets("Playoff_Sim").Cells(2, 3).Value = lds_champs
Worksheets("Playoff_Sim").Cells(2, 4).Value = lcs_champs
</code>```

End Sub

答:
The problem isn't just in the random numbers (which can be addressed by the suggestion of @A.S.H to use Application.RandBetween) but is also in the logic of your simulation. The twice-repeated code fragment

```<code>If game_num = 3 Or 6 Or 9 Or 12 Or 15 Or 18 Or 21 Then
    p = p_bad
Else
    p = p_norm
End If
</code>```

is equivalent to the single line p = p_bad. This is because the condition game_num = 3 Or 6 Or 9 Or 12 Or 15 Or 18 Or 21 always evaluates to True since you are only comparing game_num to 3 but then forcing VBA to interpret the remaining numbers (6,9,15,18,21) as True by using the Or operator with them. Instead, just do:

```<code>If game_num Mod 3 = 0 Then
    p = p_bad
Else
    p = p_norm
End If
</code>```

There might be other problems as well, though this should be enough to get you started.

Title: VBA Random Number in Simulation

Body:
I'm trying to create a baseball post season simulator to see how much a bad pitcher impacts a team's championship odds. So I basically created a simulator for the playoffs (3 rounds, first is best of 5, next two are best of 7). And I can see how much a SP would hurt the team if he pitches every third game and he decreases the chance of winning by 10%.

To make sure I did this write, I first ran my simulation without any adjustment so every game both teams would have a 50% chance of winning... (a team would therefore have a 12.5% chance of winning the world series in a 3 round playoff) however, I was getting consistently higher than 12.5.

I have a feeling the problem was with the Rnd function, so I played with that a bit (added a function, tried to vary the time ect.), now my simulation comes out to be <12.5%. I then tried to trouble shoot and noticed that in each round was not being won 50% of the time... which was the case each time I re-ran the simulation (Like round 1 would have a 47% success then round two 51% then round three 58%... then the next run would return 46%, 52%, 59%.

Am I do something wrong, or is this just something the rnd function is not great at handling?

Public Function wRandomNumber(lowerbound, upperbound, Optional rndType = 1) As Double
Dim rndVariable As Double
'Const ms As Double = 0.000000011574

Randomize Timer
'Application.Wait Now + ms * 1
rndVariable = Rnd
If rndType = 1 Then
    wRandomNumber = Int((upperbound - lowerbound + 1) * rndVariable + lowerbound)
ElseIf rndType = 2 Then
    If (upperbound - lowerbound + 1) * rndVariable + lowerbound <= upperbound Then
        wRandomNumber = (upperbound - lowerbound + 1) * rndVariable + lowerbound
    Else
        Do While (upperbound - lowerbound + 1) * rndVariable + lowerbound > upperbound
            rndVariable = Rnd
            If (upperbound - lowerbound + 1) * rndVariable + lowerbound <= upperbound Then
                wRandomNumber = (upperbound - lowerbound + 1) * rndVariable + lowerbound
            End If
        Loop
    End If
End If
End Function

Public Sub Playoff_sim()

Dim game_num As Integer
Dim lds_wins_stros As Integer
Dim lds_loss_stros As Integer
Dim lcs_wins_stros As Integer
Dim lcs_loss_stros As Integer
Dim ws_wins_stros As Integer
Dim ws_loss_stros As Integer
Dim p As Double
Dim outcome1 As Single
Dim outcome2 As Single
Dim outcome3 As Single
Dim i As Double
Dim iter As Double
Dim CHAMPS As Double
Dim Loser As Double
Dim p_bad As Double
Dim p_norm As Double
Dim lds_champs As Double
Dim lcs_champs As Double
Dim r As Double
Const ms As Double = 0.000000011574

iter = 100000
CHAMPS = 0
Loser = 0
lds_champs = 0
lcs_champs = 0
p_bad = 0.5
p_norm = 0.5
r = 0
For i = 1 To iter

game_num = 1
lds_wins_stros = 0
lds_loss_stros = 0
lcs_wins_stros = 0
lcs_loss_stros = 0
ws_loss_stros = 0
ws_wins_stros = 0

Do Until lds_wins_stros = 3 Or lds_loss_stros = 3

outcome1 = wRandomNumber(0, 1, 2)
    If game_num = 3 Then
        p = p_bad
    Else
        p = p_norm
    End If

    If p > outcome1 Then
        lds_wins_stros = lds_wins_stros + 1
    Else
        lds_loss_stros = lds_loss_stros + 1
    End If
    r = r + 1
    'Worksheets("Playoff_Sim").Cells(r, 15).Value = outcome1

game_num = game_num + 1
Loop

If lds_wins_stros = 3 Then

    outcome2 = wRandomNumber(0, 1, 2)
    lds_champs = 1 + lds_champs
    Do Until lcs_wins_stros = 4 Or lcs_loss_stros = 4

    If game_num = 3 Or 6 Or 9 Or 12 Or 15 Or 18 Or 21 Then
        p = p_bad
    Else
        p = p_norm
    End If

    If p > outcome2 Then
        lcs_wins_stros = lcs_wins_stros + 1
    Else
        lcs_loss_stros = lcs_loss_stros + 1
    End If

    game_num = game_num + 1

    Loop

    If lcs_wins_stros = 4 Then
        lcs_champs = lcs_champs + 1

        outcome3 = wRandomNumber(0, 1, 2)
        Do Until ws_wins_stros = 4 Or ws_loss_stros = 4

            If game_num = 3 Or 6 Or 9 Or 12 Or 15 Or 18 Or 21 Then
                p = p_bad
            Else
                p = p_norm
            End If

            If p > outcome3 Then
                ws_wins_stros = ws_wins_stros + 1
            Else
                ws_loss_stros = ws_loss_stros + 1
            End If
        'r = r + 1
        game_num = game_num + 1
        'Worksheets("Playoff_Sim").Cells(r, 15).Value = outcome3
        Loop

        If ws_wins_stros = 4 Then
            CHAMPS = CHAMPS + 1
        Else
            Loser = Loser + 1
        End If

    Else
        Loser = Loser + 1
    End If

Else
    Loser = Loser + 1
End If

Next i

Worksheets("Playoff_Sim").Cells(2, 1).Value = CHAMPS
Worksheets("Playoff_Sim").Cells(2, 2).Value = Loser
Worksheets("Playoff_Sim").Cells(2, 3).Value = lds_champs
Worksheets("Playoff_Sim").Cells(2, 4).Value = lcs_champs

End Sub

Body:
The problem isn't just in the random numbers (which can be addressed by the suggestion of @A.S.H to use Application.RandBetween) but is also in the logic of your simulation. The twice-repeated code fragment

If game_num = 3 Or 6 Or 9 Or 12 Or 15 Or 18 Or 21 Then
    p = p_bad
Else
    p = p_norm
End If

is equivalent to the single line p = p_bad. This is because the condition game_num = 3 Or 6 Or 9 Or 12 Or 15 Or 18 Or 21 always evaluates to True since you are only comparing game_num to 3 but then forcing VBA to interpret the remaining numbers (6,9,15,18,21) as True by using the Or operator with them. Instead, just do:

If game_num Mod 3 = 0 Then
    p = p_bad
Else
    p = p_norm
End If

There might be other problems as well, though this should be enough to get you started.


问:
Conditional formatting derived from formula
In cell D11, I have a date derived from a formula. (IF&Vlookup)

I have tried to insert a basic conditional formatting to highlight D11 if the date is before today's date. The format of cell D11 is date.
The conditional formatting works if I type in the date but won't if it is derived from a formula.

```<code>=IFERROR(TEXT(VLOOKUP($D$10,'Lookup data'!G6:I52,3,FALSE),"dd/mm/yyyy"),"  " )
</code>```

The conditonal formatting formula is:

```<code>=D11>TODAY()
</code>```

答:
Change your formula to:

```<code>=IFERROR(DATEVALUE(TEXT(VLOOKUP($D$10,'Lookup Data'!$G$6:$I$52,3,FALSE),"dd/mm/yyyy")),"")
</code>```

For conditional Formatting use:

```<code>=AND(D11>TODAY(),D11<>"")
</code>```

and format as you like

Like Gotham said the Text() formula convert your date in Vlookup to Text that you cannot compare to Today() date

One is text and the other is Date

The new formula use Datevalue to convert Text() to Date and " "  iferror to just "" empty.

D11 if empty or "" result iferror should not format the cell, that is why I changed the Conditional Formatting Formula

Body:
In cell D11, I have a date derived from a formula. (IF&Vlookup)

I have tried to insert a basic conditional formatting to highlight D11 if the date is before today's date. The format of cell D11 is date.
The conditional formatting works if I type in the date but won't if it is derived from a formula.

=IFERROR(TEXT(VLOOKUP($D$10,'Lookup data'!G6:I52,3,FALSE),"dd/mm/yyyy"),"  " )

The conditonal formatting formula is:

=D11>TODAY()

Body:
Change your formula to:

=IFERROR(DATEVALUE(TEXT(VLOOKUP($D$10,'Lookup Data'!$G$6:$I$52,3,FALSE),"dd/mm/yyyy")),"")

For conditional Formatting use:

=AND(D11>TODAY(),D11<>"")

and format as you like

Like Gotham said the Text() formula convert your date in Vlookup to Text that you cannot compare to Today() date

One is text and the other is Date

The new formula use Datevalue to convert Text() to Date and " "  iferror to just "" empty.

D11 if empty or "" result iferror should not format the cell, that is why I changed the Conditional Formatting Formula


问:
When and where should we use these keras LSTM models
I know how a RNN, LSTM, neural nets,activation function works but from various available LSTM models I dont know what should I use for which data and when. I created these 5 models as a sample of different varites of LSTM models I have seen but I dont know which optimal sequence dataset should use. I have most of my confussion in the second/third lines of these models.  Are model1 and model4 are same? Why is model1.add(LSTM(10, input_shape=(max_len, 1), return_sequences=False)) different from model4.add(Embedding(X_train.shape[1], 128, input_length=max_len)) . I would much appreciate If some one can explain these five models in simple english.

```<code>from keras.layers import Dense, Dropout, Embedding, LSTM, Bidirectional
from keras.models import Sequential
from keras.layers.wrappers import TimeDistributed

#model1
model1 = Sequential()
model1.add(LSTM(10, input_shape=(max_len, 1), return_sequences=False))
model1.add(Dense(1, activation='sigmoid'))
model1.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

print model1.summary()

#model2
model2 = Sequential()
model2.add(LSTM(10, batch_input_shape=(1, 1, 1), return_sequences=False, stateful=True))
model2.add(Dense(1, activation='sigmoid'))
model2.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

print model2.summary()

#model3
model3 = Sequential()
model3.add(TimeDistributed(Dense(X_train.shape[1]), input_shape=(X_train.shape[1],1)))
model3.add(LSTM(10, return_sequences=False))
model3.add(Dense(1, activation='sigmoid'))
model3.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

print model3.summary()

#model4
model4 = Sequential()
model4.add(Embedding(X_train.shape[1], 128, input_length=max_len))
model4.add(LSTM(10))
model4.add(Dense(1, activation='sigmoid'))
model4.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

print model4.summary()

#model5
model5 = Sequential()
model5.add(Embedding(X_train.shape[1], 128, input_length=max_len))
model5.add(Bidirectional(LSTM(10)))
model5.add(Dense(1, activation='sigmoid'))
model5.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

print model5.summary()
</code>```

答:
So:

First network is the best one for classification. It's simply analysing the whole sequence - and once all input steps are fed to a model - it's able to perform a decision. There are other variants of this architecture (using e.g. GlobalAveragePooling1D or max one) which are pretty similiar from a conceptual point of view.

Second network - from a design point of view is quite similar to a first architecture. What differs them is the fact that in a first approach two consequent fit and predict calls are totally independent, whereas here - the starting state for second call is the same to the last one in a first. This enables a lot of cool scenarios like e.g. varying length sequences analysis or e.g. decision making processes thanks to the fact that you could effecitively stop inference / training process - affect network or input and come back to it with actualized state.

Is the best one when you don't want to use recurrent network at all stages of your computations. Especially - when your network is big - introducing a recurrent layers is quite costly from a parameter number point of view (introducing a recurrent connection usually increases the number of parameter by a factor of at least 2). So you could apply a static network as a preprocessing stage - and then you feed results to a recurrent part. This makes training easier.

Model is a special case of case 3. Here - you have a sequence of tokens which are coded by a one-hot encoding and then transformed using Embedding. This makes the process less memory consuming.

Bidrectional network provides you an advantage of knowing at each step not only a sequence previous history - but also further steps. This is at computational cost and also you are losing the possibilty of a sequential data feed - as you need to have a full sequence when analysis is performed.

Body:
I know how a RNN, LSTM, neural nets,activation function works but from various available LSTM models I dont know what should I use for which data and when. I created these 5 models as a sample of different varites of LSTM models I have seen but I dont know which optimal sequence dataset should use. I have most of my confussion in the second/third lines of these models.  Are model1 and model4 are same? Why is model1.add(LSTM(10, input_shape=(max_len, 1), return_sequences=False)) different from model4.add(Embedding(X_train.shape[1], 128, input_length=max_len)) . I would much appreciate If some one can explain these five models in simple english.

from keras.layers import Dense, Dropout, Embedding, LSTM, Bidirectional
from keras.models import Sequential
from keras.layers.wrappers import TimeDistributed

#model1
model1 = Sequential()
model1.add(LSTM(10, input_shape=(max_len, 1), return_sequences=False))
model1.add(Dense(1, activation='sigmoid'))
model1.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

print model1.summary()

#model2
model2 = Sequential()
model2.add(LSTM(10, batch_input_shape=(1, 1, 1), return_sequences=False, stateful=True))
model2.add(Dense(1, activation='sigmoid'))
model2.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

print model2.summary()

#model3
model3 = Sequential()
model3.add(TimeDistributed(Dense(X_train.shape[1]), input_shape=(X_train.shape[1],1)))
model3.add(LSTM(10, return_sequences=False))
model3.add(Dense(1, activation='sigmoid'))
model3.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

print model3.summary()

#model4
model4 = Sequential()
model4.add(Embedding(X_train.shape[1], 128, input_length=max_len))
model4.add(LSTM(10))
model4.add(Dense(1, activation='sigmoid'))
model4.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

print model4.summary()

#model5
model5 = Sequential()
model5.add(Embedding(X_train.shape[1], 128, input_length=max_len))
model5.add(Bidirectional(LSTM(10)))
model5.add(Dense(1, activation='sigmoid'))
model5.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

print model5.summary()


问:
node js Array.push() not working using mongoose
I am beginner in meanstack development. I am trying to push value inside an array in foreach loop but last i am getting empty array.

My code:

```<code>router.get("/", function(req, res) {

 ourpackage.find({}).sort({_id:1}).exec(function(err,resdoc){

  var rest = [];
  resdoc.forEach(function(doc){
    masterRoomimage.find({ourpackageId:doc._id},function(err,ourpackageimagevalue){
      if(err) res.send(err);
      var ourpackagedetail = JSON.parse(JSON.stringify(doc));
      var stringifyimages = JSON.parse(JSON.stringify(ourpackageimagevalue));
      var ourpackage = _.merge({},ourpackagedetail,{masterRoomimages:stringifyimages});
      rest.push(ourpackageimagevalue);
             //print all rest array value
             console.log(rest);
           });
  });
      //print empty rest array value
      console.log(rest);
      res.send(rest);
    });
});
</code>```

ourpackage Schema

```<code>  {
            "_id": "58e396d4215bc61338d2c06e",
            "first_title": "test 1",
            "berief_text": "<p>testing </p>",
   }
</code>```

ourpackagesimages Schema

```<code>[
            {
                "_id": "59424d49fcc8100050916bf4",
                "imageLocation": "first.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            },
            {
                "_id": "59424d49fcc8100050916bf5",
                "imageLocation": "third.jpg",
                "ourpackageId": "58e396d4215bc61338d2c077",
                "__v": 0
            },
            {
                "_id": "59490ad44e26c13324906433",
                "imageLocation": "second.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            }
    ]
</code>```

expected output

```<code>[
    {
        "_id": "58e396d4215bc61338d2c06e",
        "first_title": "test 1",
        "berief_text": "<p>testing </p>",
        "ourpackagesimages": [
            {
                "_id": "59424d49fcc8100050916bf4",
                "imageLocation": "first.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            },
            {
                "_id": "59490ad44e26c13324906433",
                "imageLocation": "second.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            }

        ]
    }
]
</code>```

obtained output empty

```<code>[]
</code>```

答:
simply,
Declare an array
    rest = [];

```<code>rest[] = ourpackageimagevalue;
</code>```

I hope it helps,

Body:
I am beginner in meanstack development. I am trying to push value inside an array in foreach loop but last i am getting empty array.

My code:

router.get("/", function(req, res) {

 ourpackage.find({}).sort({_id:1}).exec(function(err,resdoc){

  var rest = [];
  resdoc.forEach(function(doc){
    masterRoomimage.find({ourpackageId:doc._id},function(err,ourpackageimagevalue){
      if(err) res.send(err);
      var ourpackagedetail = JSON.parse(JSON.stringify(doc));
      var stringifyimages = JSON.parse(JSON.stringify(ourpackageimagevalue));
      var ourpackage = _.merge({},ourpackagedetail,{masterRoomimages:stringifyimages});
      rest.push(ourpackageimagevalue);
             //print all rest array value
             console.log(rest);
           });
  });
      //print empty rest array value
      console.log(rest);
      res.send(rest);
    });
});

ourpackage Schema

  {
            "_id": "58e396d4215bc61338d2c06e",
            "first_title": "test 1",
            "berief_text": "
testing
",
   }

ourpackagesimages Schema

[
            {
                "_id": "59424d49fcc8100050916bf4",
                "imageLocation": "first.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            },
            {
                "_id": "59424d49fcc8100050916bf5",
                "imageLocation": "third.jpg",
                "ourpackageId": "58e396d4215bc61338d2c077",
                "__v": 0
            },
            {
                "_id": "59490ad44e26c13324906433",
                "imageLocation": "second.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            }
    ]

expected output

[
    {
        "_id": "58e396d4215bc61338d2c06e",
        "first_title": "test 1",
        "berief_text": "
testing
",
        "ourpackagesimages": [
            {
                "_id": "59424d49fcc8100050916bf4",
                "imageLocation": "first.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            },
            {
                "_id": "59490ad44e26c13324906433",
                "imageLocation": "second.jpg",
                "ourpackageId": "58e396d4215bc61338d2c06e",
                "__v": 0
            }

        ]
    }
]

obtained output empty

[]

Body:
simply,
Declare an array
    rest = [];

rest[] = ourpackageimagevalue;

I hope it helps,