问:
Datepicker Example at jqueryui.com doesn't work
Try this:

Navigate to:  http://jqueryui.com/datepicker/

Cut/Paste the code in "view source" to your own new HTML page and see if it actually works.

Tried this in Chrome and Firefox.

One thing I noticed is that they don't wrap the function in '$(document).ready(function ()'

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script>
  $(function() {
    $( "#datepicker" ).datepicker();
  });
  </script>
</head>
<body>

<p>Date: <input type="text" id="datepicker"></p>

</body>
</html>
</code>```

答:
Here is my solution:

$(document).ready(function () {
  var userLang = navigator.language || navigator.userLanguage;

  var options = $.extend({},
    $.datepicker.regional["ja"], {
      dateFormat: "yy/mm/dd",
      changeMonth: true,
      changeYear: true,
      highlightWeek: true
    }
  );

  $("#japaneseCalendar").datepicker(options);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#ui-datepicker-div {
  font-size: 14px;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css"
          href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.min.css">

Japanese JQuery UI Datepicker

<input type="text" id="japaneseCalendar"/>

```

Body:
Try this:

Navigate to:  http://jqueryui.com/datepicker/

Cut/Paste the code in "view source" to your own new HTML page and see if it actually works.

Tried this in Chrome and Firefox.

One thing I noticed is that they don't wrap the function in '$(document).ready(function ()'

<!doctype html>

  <meta charset="utf-8">
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">

  <link rel="stylesheet" href="/resources/demos/style.css">

Date: <input type="text" id="datepicker">

Body:
Here is my solution:

$(document).ready(function () {
  var userLang = navigator.language || navigator.userLanguage;

  var options = $.extend({},
    $.datepicker.regional["ja"], {
      dateFormat: "yy/mm/dd",
      changeMonth: true,
      changeYear: true,
      highlightWeek: true
    }
  );

  $("#japaneseCalendar").datepicker(options);
});

#ui-datepicker-div {
  font-size: 14px;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css"
          href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.min.css">
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>
</head>
<body>
<h3>Japanese JQuery UI Datepicker</h3>
<input type="text" id="japaneseCalendar"/>

</body>
</html>


来源: stackexchange

问:
Equivalent to ember engines in react
In ember.js Ember Engines let you compose multiple standalone applications into a single application. Is there an equivalent in react.js?

What I want to do is provide a generic login page and serve different applications depending on which customer signes in.

答: You'd need to handle including the appropriate bundle / script tag yourself. From what I've seen / heard, Engines are uniquely an Ember thing. </p>

ContentLicense: CC BY-SA 3.0

Title: Equivalent to ember engines in react


问:
Conversion to Dalvik format failed with error 1 in Android 4?
In my Android appliction in eclipse I get the following error:

```<code>[2011-11-03 19:39:12 - MiniPauker 1.0] Dx
trouble processing "java/crcis/pauker/AddCardActivity$1.class":

Ill-advised or mistaken usage of a core class (java.* or javax.*)
when not building a core library.

This is often due to inadvertently including a core library file
in your application's project, when using an IDE (such as
Eclipse). If you are sure you're not intentionally defining a
core class, then this is the most likely explanation of what's
going on.

However, you might actually be trying to define a class in a core
namespace, the source of which you may have taken, for example,
from a non-Android virtual machine project. This will most
assuredly not work. At a minimum, it jeopardizes the
compatibility of your app with future versions of the platform.
It is also often of questionable legality.

If you really intend to build a core library -- which is only
appropriate as part of creating a full virtual machine
distribution, as opposed to compiling an application -- then use
the "--core-library" option to suppress this error message.

If you go ahead and use "--core-library" but are in fact
building an application, then be forewarned that your application
will still fail to build or run, at some point. Please be
prepared for angry customers who find, for example, that your
application ceases to function once they upgrade their operating
system. You will be to blame for this problem.

If you are legitimately using some code that happens to be in a
core package, then the easiest safe alternative you have is to
repackage that code. That is, move the classes in question into
your own package namespace. This means that they will never be in
conflict with core system classes. JarJar is a tool that may help
you in this endeavor. If you find that you cannot do this, then
that is an indication that the path you are on will ultimately
lead to pain, suffering, grief, and lamentation.

[2011-11-03 19:39:12 - MiniPauker 1.0] Dx 1 error; aborting
[2011-11-03 19:39:12 - MiniPauker 1.0] Conversion to Dalvik format failed with error 1
</code>```

this error only appears when run my project. I search long time to the right solution but all possible solutions don't work. I use android 4.0 and Eclipse 3.6,now

by the way, this project worked in Android 2.1 but in Android 4.0 No!!!

答:
Modify the error caused by the jar package's scope attribute, from compile-> provided, this operation can be modified in File-> Project Structure-> Dependencies or in the project view app folder in the build.gradle file there dependencies , The corresponding jar package compile modified
like this:
enter image description here</p>

Body:
In my Android appliction in eclipse I get the following error:

[2011-11-03 19:39:12 - MiniPauker 1.0] Dx
trouble processing "java/crcis/pauker/AddCardActivity$1.class":

Ill-advised or mistaken usage of a core class (java.* or javax.*)
when not building a core library.

This is often due to inadvertently including a core library file
in your application's project, when using an IDE (such as
Eclipse). If you are sure you're not intentionally defining a
core class, then this is the most likely explanation of what's
going on.

However, you might actually be trying to define a class in a core
namespace, the source of which you may have taken, for example,
from a non-Android virtual machine project. This will most
assuredly not work. At a minimum, it jeopardizes the
compatibility of your app with future versions of the platform.
It is also often of questionable legality.

If you really intend to build a core library -- which is only
appropriate as part of creating a full virtual machine
distribution, as opposed to compiling an application -- then use
the "--core-library" option to suppress this error message.

If you go ahead and use "--core-library" but are in fact
building an application, then be forewarned that your application
will still fail to build or run, at some point. Please be
prepared for angry customers who find, for example, that your
application ceases to function once they upgrade their operating
system. You will be to blame for this problem.

If you are legitimately using some code that happens to be in a
core package, then the easiest safe alternative you have is to
repackage that code. That is, move the classes in question into
your own package namespace. This means that they will never be in
conflict with core system classes. JarJar is a tool that may help
you in this endeavor. If you find that you cannot do this, then
that is an indication that the path you are on will ultimately
lead to pain, suffering, grief, and lamentation.

[2011-11-03 19:39:12 - MiniPauker 1.0] Dx 1 error; aborting
[2011-11-03 19:39:12 - MiniPauker 1.0] Conversion to Dalvik format failed with error 1

this error only appears when run my project. I search long time to the right solution but all possible solutions don't work. I use android 4.0 and Eclipse 3.6,now

by the way, this project worked in Android 2.1 but in Android 4.0 No!!!


问:
Select the number of days a record is present within a certain year/month
In sql server I have a table with start and end dates for job postings. Given a month and a year by the user I need to find the amount of days between the start and end date that fall in the given year/month for that posting.

So if the posting Start Date is 2010/11/15 and End Date is 2010/12/05
Then output should be:

```<code>November  16 days
December  5 days
Total     21 days
</code>```

I've been beating my head against the wall with this one and am fresh out of ideas.

答:
This is kinda hard in SQL but this will create a table with the month (in integer) and the number of days.

I'll leave it to you to convert the integer to the month and add the total

```<code>SET NOCOUNT on

Declare @StartDate datetime
Declare @EndDate datetime
Declare @StartDateNormalized datetime
Declare @EndDateNormalized datetime

SET @StartDate = '2010/11/15'
SET @EndDate = '2011/2/05'

declare @result table ( month int, days int)

--Normalize the Inputs

SET @StartDateNormalized = cast(Month(@startDate) as varchar) + '/1/' + cast(year(@startDate) as varchar)
SET @EndDateNormalized = cast(Month(@EndDate) as varchar) + '/1/' + cast(year(@EndDate) as varchar)

insert into @result
values
(   MONTH(@StartDateNormalized),
    DateDiff(Day, @StartDate, DateAdd(month, 1, @StartDateNormalized ) )
)

SET @StartDateNormalized = DateAdd(month, 1, @StartDateNormalized )

WHILE (@StartDateNormalized < @EndDateNormalized)
BEGIN

insert into @result
values
(   MONTH(@StartDateNormalized),
   DateDiff(Day, @StartDateNormalized, DateAdd(month, 1, @StartDateNormalized ) )
)

   SET @StartDateNormalized = DateAdd(month, 1, @StartDateNormalized )
END

insert into @result
values
(   MONTH(@EndDateNormalized),
   DateDiff(Day, @EndDateNormalized, @EndDate    ) + 1
)

select * from @result
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In sql server I have a table with start and end dates for job postings. Given a month and a year by the user I need to find the amount of days between the start and end date that fall in the given year/month for that posting.

So if the posting Start Date is 2010/11/15 and End Date is 2010/12/05
Then output should be:

November  16 days
December  5 days
Total     21 days

I've been beating my head against the wall with this one and am fresh out of ideas.

Body:
This is kinda hard in SQL but this will create a table with the month (in integer) and the number of days.

I'll leave it to you to convert the integer to the month and add the total

SET NOCOUNT on

Declare @StartDate datetime
Declare @EndDate datetime
Declare @StartDateNormalized datetime
Declare @EndDateNormalized datetime

SET @StartDate = '2010/11/15'
SET @EndDate = '2011/2/05'

declare @result table ( month int, days int)

--Normalize the Inputs

SET @StartDateNormalized = cast(Month(@startDate) as varchar) + '/1/' + cast(year(@startDate) as varchar)
SET @EndDateNormalized = cast(Month(@EndDate) as varchar) + '/1/' + cast(year(@EndDate) as varchar)

insert into @result
values
(   MONTH(@StartDateNormalized),
    DateDiff(Day, @StartDate, DateAdd(month, 1, @StartDateNormalized ) )
)

SET @StartDateNormalized = DateAdd(month, 1, @StartDateNormalized )

WHILE (@StartDateNormalized < @EndDateNormalized)
BEGIN

insert into @result
values
(   MONTH(@StartDateNormalized),
   DateDiff(Day, @StartDateNormalized, DateAdd(month, 1, @StartDateNormalized ) )
)

   SET @StartDateNormalized = DateAdd(month, 1, @StartDateNormalized )
END

insert into @result
values
(   MONTH(@EndDateNormalized),
   DateDiff(Day, @EndDateNormalized, @EndDate    ) + 1
)

select * from @result


问:
Google Auto Complete Places not setting state to empty when Input are cleared

I am using react-native-google-places-autocomplete for auto completion of places. I get the result there is no problem in input and getting the Autocomplete searched places.

But, when I click on certain result and then again I clear the GooglePlacesAutocomplete input text, the value still remains the previous
 clicked result item.

Whenever I select a location and I click on Set Camp button below is console log.

Here is other screen shot whenever I clear the input text and again click on button I wish to get console log of undefined or empty string but I get the previous result. Here is screenshot.

Below is the code I am working on:

SetCampScreen.js

```<code>  import React, { Component } from 'react';
  import { View,
    Text,
    ScrollView,
    TextInput
  } from 'react-native';
  import * as actions from '../../actions';
  import { connect } from 'react-redux';
  import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';

  class SetCampScreen extends Component {
    static navigationOptions = {
            header: null,
          };
    gotoPatientRegistrationScreen = () => {
      console.log('At Patient Registration method.', this.props.description);

    }
    sendData = (data) => {
      console.log('From send Data: ',data);
      this.props.setLocation(data);
    }
    render() {
      return (
        <ScrollView contentContainerStyle={{flexGrow : 1, justifyContent : 'center'}}>
            <View style={styles.container}>

              <GooglePlacesAutocomplete
              placeholder="Where are you?"
              minLength={2} // minimum length of text to search
              autoFocus={false}
              returnKeyType={'search'} // Can be left out for default return key https://facebook.github.io/react-native/docs/textinput.html#returnkeytype
              listViewDisplayed="auto" // true/false/undefined
              fetchDetails={true}
              enablePoweredByContainer={false}
              renderDescription={row => row.description}
              styles={{
              textInputContainer: {
                height: 50,
              },
              textInput: {
                borderRadius: 0,
                marginLeft: 0,
                marginRight: 0,
                marginTop: 0,
                height: 50,
                borderWidth: 1,
                borderColor: '#000',
              },
              predefinedPlacesDescription: {
                color: '#1faadb',
              },
              }} // custom description render
              onPress={(data, details = null) => {
              // 'details' is provided when fetchDetails = true
              this.sendData(data);

              }}
              getDefaultValue={() => {
              return ''; // text input default value
              }}
              query={{
              // available options: https://developers.google.com/places/web-service/autocomplete
              key: 'API_KEY',
              language: 'en', // language of the results
              }}

              currentLocation={false} // Will add a 'Current location' button at the top of the predefined places list
              currentLocationLabel="Current location"
              nearbyPlacesAPI="GooglePlacesSearch" // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
              GoogleReverseGeocodingQuery={{

              }}
              debounce={200}
              />
              <Button
                title="Set Camp"
                onPress={this.gotoPatientRegistrationScreen}
              />
            </View>
        </ScrollView>
      );
    }
  }
  const styles = {
    container: {
        flex: 1,
        backgroundColor: '#fff',
        justifyContent: 'center'
    },
    textInputStyle: {
      fontSize: 16,
      paddingLeft: 8,
      paddingBottom: 3,
      paddingRight: 8,
      height: 60,
    },
  };
  const mapStateToProps = state => {
    return {
         description: state.location.locationResponse
       };
  }
  export default connect(mapStateToProps, actions)(SetCampScreen);
</code>```

actions/location_action.js

```<code>  import axios from 'axios';
  import { NO_INTERNET, SET_LOCATION } from './types';
  import { NetInfo } from 'react-native';

  export const setLocation = (place) => async dispatch => {
    const { description } = place;
    console.log('Description from setLocation: ',description);
    let netState = await NetInfo.isConnected.fetch();
    console.log('Net state', netState);
    if(!netState) {
      return dispatch({ type: NO_INTERNET });
    }
    try {
      dispatch ({ type: SET_LOCATION, payload: description });
    } catch(exp) {
      console.log(exp);
    }
  };
</code>```

actions/index.js

```<code>export * from './location_action';
</code>```

actions/types.js

```<code>export const NO_INTERNET = 'no_internet';
export const SET_LOCATION = 'set_location';
</code>```

reducers/location_reducers.js

```<code>import { NO_INTERNET, SET_LOCATION } from '../actions/types';

export default function(state = {}, action) {
  switch(action.type) {
    case SET_LOCATION:
      return { locationResponse: action.payload };

    default:
      return state;
  }
}
</code>```

reducers/index.js

```<code>import { combineReducers } from 'redux';
import locationResponse from './location_reducer';

export default combineReducers({
  location: locationResponse,
});
</code>```

I expect whenever I clear the InputText the props value of description should also be cleared. Someone please point me out to achieve this. Thank you.

答:
The GooglePlacesAutocomplete has a textInputProps props which accepts an onChangeText handler

Usage:

```<code>textInputProps={{
 onChangeText: (text) => { console.log(text) }
}}
</code>```

Body:
I am using react-native-google-places-autocomplete for auto completion of places. I get the result there is no problem in input and getting the Autocomplete searched places.

But, when I click on certain result and then again I clear the GooglePlacesAutocomplete input text, the value still remains the previous
 clicked result item.

Whenever I select a location and I click on Set Camp button below is console log.

Here is other screen shot whenever I clear the input text and again click on button I wish to get console log of undefined or empty string but I get the previous result. Here is screenshot.

Below is the code I am working on:

SetCampScreen.js

  import React, { Component } from 'react';
  import { View,
    Text,
    ScrollView,
    TextInput
  } from 'react-native';
  import * as actions from '../../actions';
  import { connect } from 'react-redux';
  import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';

  class SetCampScreen extends Component {
    static navigationOptions = {
            header: null,
          };
    gotoPatientRegistrationScreen = () => {
      console.log('At Patient Registration method.', this.props.description);

    }
    sendData = (data) => {
      console.log('From send Data: ',data);
      this.props.setLocation(data);
    }
    render() {
      return (
        <ScrollView contentContainerStyle={{flexGrow : 1, justifyContent : 'center'}}>
            <View style={styles.container}>

              <GooglePlacesAutocomplete
              placeholder="Where are you?"
              minLength={2} // minimum length of text to search
              autoFocus={false}
              returnKeyType={'search'} // Can be left out for default return key https://facebook.github.io/react-native/docs/textinput.html#returnkeytype
              listViewDisplayed="auto" // true/false/undefined
              fetchDetails={true}
              enablePoweredByContainer={false}
              renderDescription={row => row.description}
              styles={{
              textInputContainer: {
                height: 50,
              },
              textInput: {
                borderRadius: 0,
                marginLeft: 0,
                marginRight: 0,
                marginTop: 0,
                height: 50,
                borderWidth: 1,
                borderColor: '#000',
              },
              predefinedPlacesDescription: {
                color: '#1faadb',
              },
              }} // custom description render
              onPress={(data, details = null) => {
              // 'details' is provided when fetchDetails = true
              this.sendData(data);

              }}
              getDefaultValue={() => {
              return ''; // text input default value
              }}
              query={{
              // available options: https://developers.google.com/places/web-service/autocomplete
              key: 'API_KEY',
              language: 'en', // language of the results
              }}

              currentLocation={false} // Will add a 'Current location' button at the top of the predefined places list
              currentLocationLabel="Current location"
              nearbyPlacesAPI="GooglePlacesSearch" // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
              GoogleReverseGeocodingQuery={{

              }}
              debounce={200}
              />
              <Button
                title="Set Camp"
                onPress={this.gotoPatientRegistrationScreen}
              />
            </View>
        </ScrollView>
      );
    }
  }
  const styles = {
    container: {
        flex: 1,
        backgroundColor: '#fff',
        justifyContent: 'center'
    },
    textInputStyle: {
      fontSize: 16,
      paddingLeft: 8,
      paddingBottom: 3,
      paddingRight: 8,
      height: 60,
    },
  };
  const mapStateToProps = state => {
    return {
         description: state.location.locationResponse
       };
  }
  export default connect(mapStateToProps, actions)(SetCampScreen);

actions/location_action.js

  import axios from 'axios';
  import { NO_INTERNET, SET_LOCATION } from './types';
  import { NetInfo } from 'react-native';

  export const setLocation = (place) => async dispatch => {
    const { description } = place;
    console.log('Description from setLocation: ',description);
    let netState = await NetInfo.isConnected.fetch();
    console.log('Net state', netState);
    if(!netState) {
      return dispatch({ type: NO_INTERNET });
    }
    try {
      dispatch ({ type: SET_LOCATION, payload: description });
    } catch(exp) {
      console.log(exp);
    }
  };

actions/index.js

export * from './location_action';

actions/types.js

export const NO_INTERNET = 'no_internet';
export const SET_LOCATION = 'set_location';

reducers/location_reducers.js

import { NO_INTERNET, SET_LOCATION } from '../actions/types';

export default function(state = {}, action) {
  switch(action.type) {
    case SET_LOCATION:
      return { locationResponse: action.payload };

    default:
      return state;
  }
}

reducers/index.js

import { combineReducers } from 'redux';
import locationResponse from './location_reducer';

export default combineReducers({
  location: locationResponse,
});

I expect whenever I clear the InputText the props value of description should also be cleared. Someone please point me out to achieve this. Thank you.

Body:
The GooglePlacesAutocomplete has a textInputProps props which accepts an onChangeText handler

Usage:

textInputProps={{
 onChangeText: (text) => { console.log(text) }
}}


问:
Creating a new instance of a class and accessing its instance variables in Python
So, I'm building a turing machine in Python, and I've gotten to a point where I need to instantiate my Turing Machine class inside of my parser, but I can't seem to get the syntax right.

Here is the way I'm  defining my TM:

```<code>class TM(object):
def __init__(self, states, start, accept, reject, alpha, tAlpa, tape,
transition, head):
    self.states = []
    self.start = start
    self.accept = accept
    self.reject = reject
    self.alpha = []
    self.tAlpha =[]
    self.tape = LinkedList(tape)
    self.transitions = []
    self.head = head
    return;
</code>```

So I need to create an instance in my Parser class:
for example:

```<code>class Parser:
*some other logic*

tm = TM()
tm.states.append(something)
</code>```

答:
Very quick example to show you the effect of required positional arguments:

```<code>>>> class Temp:
    def __init__(self, **kwargs):
        if kwargs:
            self.temp = kwargs['temp']

>>> t = Temp()
>>> class Temp2:
    def __init__(self, opt1 = None, opt2 = None):
        self.opt1 = opt1
        self.opt2 = opt2

>>> t2 = Temp2()
>>> class Temp3:
    def __init__(self, req, opt1 = None, opt2 = None):
        self.req = req
        self.opt1 = opt1
        self.opt2 = opt2

>>> t3 = Temp3()
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    t3 = Temp3()
TypeError: __init__() missing 1 required positional argument: 'req'
>>>
</code>```

In the first class, **kwargs allows me to instantiate and pass any keyword arguments I want. This is a week example, but gets the point across that you can do some initialization checks for existance and then subchecks for key names.

In the second class, by using ... = None I default the parameter if it isnt supplied. So again, the interpreter is happy because all the parameters received a value!

In the last class, we see the error. Notice that req is not defined with a default value. Thus the interpreter demands it receive one to instantiate it. When I dont supply it, you get the TypeError telling you so.

In short, without properly instantiating a class, you wont be able to access any of its attributes or use its member functions!

Edit: Wanted to explain it in more detail

Further, in OOP/D, try to find ways to steer clear of long __init__() function headers. Try something like this instead:

```<code>>>> class TM:
    def __init__(self, **kwargs):
        init_args = {'states': [],
                 'start': None,
                 'accept': None,
                 'reject': None,
                 'alpha': [],
                 'tAlpha': [],
                 'tape': None, # make later
                 'transitions': [],
                 'head': None}
        for arg, default in init_args.items():
            setattr(self, arg, kwargs.get(arg, default))

>>> tm = TM()
</code>```

Again, using the **kwargs to determine when I want to supply values to the object at initialization, but I default it using a pre-defined listing! Breaking it down some:

init_args is a ready made dictionary (just like kwargs. Dont let the ** scare you, its just the dictionaries unpacking operator. Lists have one as well, its literally one *.

for arg, default ... setattr(self, arg, kwargs.get(arg, default)) iterates over our pre-defined arguments container, and then creates a self.[insert_arg] attribute with the value from kwargs.get(). It looks for arg and if it doesnt find it, uses default which we already have!

So later when you want to do you single attribute accessing in your Parser class:

```<code>>>> class TM:
    def __init__(self, **kwargs):
        init_args = {'states': [],
                 'start': None,
                 'accept': None,
                 'reject': None,
                 'alpha': [],
                 'tAlpha': [],
                 'tape': None, # make later
                 'transitions': [],
                 'head': None}
        for arg, default in init_args.items():
            setattr(self, arg, kwargs.get(arg, default))

>>> tm = TM()
>>> tm.states.append('it works!')
>>> tm.states
['it works!']
>>>
</code>```

Body:
So, I'm building a turing machine in Python, and I've gotten to a point where I need to instantiate my Turing Machine class inside of my parser, but I can't seem to get the syntax right.

Here is the way I'm  defining my TM:

class TM(object):
def __init__(self, states, start, accept, reject, alpha, tAlpa, tape,
transition, head):
    self.states = []
    self.start = start
    self.accept = accept
    self.reject = reject
    self.alpha = []
    self.tAlpha =[]
    self.tape = LinkedList(tape)
    self.transitions = []
    self.head = head
    return;

So I need to create an instance in my Parser class:
for example:

class Parser:
*some other logic*

tm = TM()
tm.states.append(something)

Body:
Very quick example to show you the effect of required positional arguments:

>>> class Temp:
    def __init__(self, **kwargs):
        if kwargs:
            self.temp = kwargs['temp']

>>> t = Temp()
>>> class Temp2:
    def __init__(self, opt1 = None, opt2 = None):
        self.opt1 = opt1
        self.opt2 = opt2

>>> t2 = Temp2()
>>> class Temp3:
    def __init__(self, req, opt1 = None, opt2 = None):
        self.req = req
        self.opt1 = opt1
        self.opt2 = opt2

>>> t3 = Temp3()
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    t3 = Temp3()
TypeError: __init__() missing 1 required positional argument: 'req'
>>>

In the first class, **kwargs allows me to instantiate and pass any keyword arguments I want. This is a week example, but gets the point across that you can do some initialization checks for existance and then subchecks for key names.

In the second class, by using ... = None I default the parameter if it isnt supplied. So again, the interpreter is happy because all the parameters received a value!

In the last class, we see the error. Notice that req is not defined with a default value. Thus the interpreter demands it receive one to instantiate it. When I dont supply it, you get the TypeError telling you so.

In short, without properly instantiating a class, you wont be able to access any of its attributes or use its member functions!

Edit: Wanted to explain it in more detail

Further, in OOP/D, try to find ways to steer clear of long __init__() function headers. Try something like this instead:

>>> class TM:
    def __init__(self, **kwargs):
        init_args = {'states': [],
                 'start': None,
                 'accept': None,
                 'reject': None,
                 'alpha': [],
                 'tAlpha': [],
                 'tape': None, # make later
                 'transitions': [],
                 'head': None}
        for arg, default in init_args.items():
            setattr(self, arg, kwargs.get(arg, default))

>>> tm = TM()

Again, using the **kwargs to determine when I want to supply values to the object at initialization, but I default it using a pre-defined listing! Breaking it down some:

init_args is a ready made dictionary (just like kwargs. Dont let the ** scare you, its just the dictionaries unpacking operator. Lists have one as well, its literally one *.

for arg, default ... setattr(self, arg, kwargs.get(arg, default)) iterates over our pre-defined arguments container, and then creates a self.[insert_arg] attribute with the value from kwargs.get(). It looks for arg and if it doesnt find it, uses default which we already have!

So later when you want to do you single attribute accessing in your Parser class:

>>> class TM:
    def __init__(self, **kwargs):
        init_args = {'states': [],
                 'start': None,
                 'accept': None,
                 'reject': None,
                 'alpha': [],
                 'tAlpha': [],
                 'tape': None, # make later
                 'transitions': [],
                 'head': None}
        for arg, default in init_args.items():
            setattr(self, arg, kwargs.get(arg, default))

>>> tm = TM()
>>> tm.states.append('it works!')
>>> tm.states
['it works!']
>>>


问:
Datatable Enable onclick on a specific column
I have a datatable and I want the 2nd column to be the only clickable column.
Here is a picture of the design.

I intended the Reference ID column (2ndcolumn) to be the one to be clickable in Javascript form please.
When clicked it will get the data from the column just that.

My table is just the usual

.
I also want it to be dynamic so when I have to insert an array from my database the click for the 2nd column will still work.

答:
You could try this.</p>

```<code>$('#exampleTable tbody tr').on('click', 'td:eq(1)', function () {
 /* Your function code here */
} );
</code>```

Body:
You could try this.

$('#exampleTable tbody tr').on('click', 'td:eq(1)', function () {
 /* Your function code here */
} );


问:
How to specify which version of perl to use on CentOS
I am running CentOS 5.4 which only has version 5.8 of perl available by default, and I have a program which requires perl 5.10, so I compiled perl 5.10 on CentOS.  How do I specify which perl I want to run the program with because the perl command uses 5.8 by default.</p>

答:
There is a tool called alternatives that was designed to deal effectively with exactly this kind of problem. It basically gives you an easy way of switching between different version of applications by manipulating symbolic links in e.g. your bin directories.

Say "man alternatives" in a terminal (or yum install alternatives, if you don't have it installed).


问:
UI5 remove duplicate feed list items
I have a Feed List for posting comments in my UI5 xml view

```<code><layout:content>
    <m:FeedInput post="onFeedPost" class="sapUiSmallMarginTopBottom"/>
    <m:List id="feedList" showSeparators="Inner" items="{path: '/table', sorter: {path: 'DATE', descending: true}}">
        <m:FeedListItem sender="{MEMBERID}" timestamp="{DATE}" text="{COMMENT}" convertLinksToAnchorTags="All"/>
    </m:List>
</layout:content>
</code>```

I want to not display duplicate comments that have the same text and date, but keep them in the database. My idea was to in the controller iterate over over the items to do this, but I am not sure what to do with the resulting array

```<code>var results = [];
var comments = feed.getItems();

for (var n = 0; n < comments.length - 1; n++) {
    var contained = false;

    for (var m = n + 1; m < comments.length; m++) {
        if (comments[n].getText() === comments[m].getText() &&
            comments[n].getDate() === comments[m].getDate()) {
            comments.pop(m);

            contained = true;

            if (!results.includes(comments[n])) {
                results.push(comments[n]);
            }
        }
    }

    if (!contained && !results.includes(comments[n])) {
        results.push(comments[n]);
    }
}

// replace list items with results array
</code>```

I can't figure out how to replace the feed list's items with the new array as there is a getItems function but not a setItems function. It occurs to me there is probably a simpler more idiomatic UI5 way to do this but I haven't found it yet.

答:
Here is one approach :

Do not directly bind the list to your oData.
You can create a JSON model which will be the resulting model after removing duplicate items.

Bind the JSON model to the List as such:

var oList = this.getView().byId("feedList");
oList.bindAggregation("items", "pathToJsonArray", template);

(The template is feedlistitem in this case).

Title: UI5 remove duplicate feed list items

Body:
I have a Feed List for posting comments in my UI5 xml view

<layout:content>
    <m:FeedInput post="onFeedPost" class="sapUiSmallMarginTopBottom"/>
    <m:List id="feedList" showSeparators="Inner" items="{path: '/table', sorter: {path: 'DATE', descending: true}}">
        <m:FeedListItem sender="{MEMBERID}" timestamp="{DATE}" text="{COMMENT}" convertLinksToAnchorTags="All"/>
    </m:List>
</layout:content>

I want to not display duplicate comments that have the same text and date, but keep them in the database. My idea was to in the controller iterate over over the items to do this, but I am not sure what to do with the resulting array

var results = [];
var comments = feed.getItems();

for (var n = 0; n < comments.length - 1; n++) {
    var contained = false;

    for (var m = n + 1; m < comments.length; m++) {
        if (comments[n].getText() === comments[m].getText() &&
            comments[n].getDate() === comments[m].getDate()) {
            comments.pop(m);

            contained = true;

            if (!results.includes(comments[n])) {
                results.push(comments[n]);
            }
        }
    }

    if (!contained && !results.includes(comments[n])) {
        results.push(comments[n]);
    }
}

// replace list items with results array

I can't figure out how to replace the feed list's items with the new array as there is a getItems function but not a setItems function. It occurs to me there is probably a simpler more idiomatic UI5 way to do this but I haven't found it yet.


问:
Filtering the duplicates in subset sum combinations
Given an array, I've found all the combinations of subsets that equal a targeted sum, that's because I want the largest array possible.

For instance, the array [1, 2, 2, 2] for the target sum of "4" returns [[2, 2], [2, 2], [2, 2]].

```<code>subsets = []

def subset_sum(numbers, target, partial=[]):
    s = sum(partial)
    if s == target:
        subsets.append(partial)
    if s >= target:
        return
    for i in range(len(numbers)):
        n = numbers[i]
        remaining = numbers[i + 1:]
        subset_sum(remaining, target, partial + [n])

subsets.sort()
subsets.reversed()
</code>```

How can I remove values that are once mentioned in the subsets' list?
In the example above, how can I hay only one [2,2].

And that, show the values of the initial array that are not in this final list?
In the example above [1].

答:
You can do something like this:

Data is :

```<code>data=[1, 2, 2,2]
import itertools
your_target=4
</code>```

One line solution:

```<code>print(set([k for k in itertools.combinations(data,r=2) if sum(k)==your_target]))
</code>```

output:

```<code>{(2, 2)}
</code>```

or better if you use a function:

```<code>def targeted_sum(data,your_target):
    result=set([k for k in itertools.combinations(data,r=2) if sum(k)==your_target])
    return result

print(targeted_sum(data,4))
</code>```

Body:
Given an array, I've found all the combinations of subsets that equal a targeted sum, that's because I want the largest array possible.

For instance, the array [1, 2, 2, 2] for the target sum of "4" returns [[2, 2], [2, 2], [2, 2]].

subsets = []

def subset_sum(numbers, target, partial=[]):
    s = sum(partial)
    if s == target:
        subsets.append(partial)
    if s >= target:
        return
    for i in range(len(numbers)):
        n = numbers[i]
        remaining = numbers[i + 1:]
        subset_sum(remaining, target, partial + [n])

subsets.sort()
subsets.reversed()

How can I remove values that are once mentioned in the subsets' list?
In the example above, how can I hay only one [2,2].

And that, show the values of the initial array that are not in this final list?
In the example above [1].

Body:
You can do something like this:

Data is :

data=[1, 2, 2,2]
import itertools
your_target=4

One line solution:

print(set([k for k in itertools.combinations(data,r=2) if sum(k)==your_target]))

output:

{(2, 2)}

or better if you use a function:

def targeted_sum(data,your_target):
    result=set([k for k in itertools.combinations(data,r=2) if sum(k)==your_target])
    return result

print(targeted_sum(data,4))


问:
one way and two way data binding in angularJs
while building a very large scale angular application i came across a performance issue. all my components and views heavily depend on data bindings, there ng-repeats everywhere. so i decided to remove all the 2 way databindings by adding     <code>{{::scopevariableName}}</code>, now since there is no 2 way data binding my question is will the view update if modal value is changed in the controller? </p>

```<code>function myCtr(){
   var that=this;
   this.scopevariableName='hannad'
   this.someFunction=function(){
     someEvent(function(callbackData){
        if(callbackData){
           that.scopevariableName='new value for scope variable'
       }
  });
 }
}

<p ng-bind="::$ctrl.somevariableName"></p>
</code>```

答:
from the docs: One-time expressions
  will stop recalculating once they are stable, which happens after the
  first digest if the expression result is a non-undefined value.

My understanding of one-time binding is after the first initialization of the scope variable if the object value changes the view will NOT change.
because the watchers are not in effect.
ex

```<code>$scope.myVar=null;
<p>{{::myVar}}</p>
</code>```

if the there are any changes to $scope.myVar those will not effect in the view
because it will take only its first initialization value. thats null.

Body:
while building a very large scale angular application i came across a performance issue. all my components and views heavily depend on data bindings, there ng-repeats everywhere. so i decided to remove all the 2 way databindings by adding     {{::scopevariableName}}, now since there is no 2 way data binding my question is will the view update if modal value is changed in the controller?

function myCtr(){
   var that=this;
   this.scopevariableName='hannad'
   this.someFunction=function(){
     someEvent(function(callbackData){
        if(callbackData){
           that.scopevariableName='new value for scope variable'
       }
  });
 }
}

Body:
from the docs: One-time expressions
  will stop recalculating once they are stable, which happens after the
  first digest if the expression result is a non-undefined value.

My understanding of one-time binding is after the first initialization of the scope variable if the object value changes the view will NOT change.
because the watchers are not in effect.
ex

$scope.myVar=null;
<p>{{::myVar}}</p>

if the there are any changes to $scope.myVar those will not effect in the view
because it will take only its first initialization value. thats null.


问:
Aligning Image Caption
Currently, I have a problem with an image slideshow caption not positioning itself relative to the parent container. This may be a simple fix with the DIV floating but for the life of me I can't figure it out. The problem is the text does not stay within the constraints of the container that houses the image; and as such transforms differently upon resizing the webpage (basically moves off the visible area of the page). I'm hoping to set the height of the container housing the text to that of the parent container (the one housing the image) before formatting it to stay at the top 1/3 of the image in the center of the page. The text is based in an UL and transitions between items on the list as an overlay over the image.

This is the code on Codepen.As seen when the CSS transitions the Text (and the white background used for example) both are outside the bounds of the .container DIV (the UL with the dropshadow where I'm hoping to constrain the Text to.

Any help would be grately appreciated.

This is the HTML

```<code><div class="container" >
<ul class="imageBanner">
<li>
<span>Image 01</span>
<div>
<h2>Ahoy.</h2>
</div>
</li>
<li><span>Image 02</span>
<div>
<h2>Welcome.</h2>
</div></li>
<li><span>Image 03</span>
<div>
<h2>Bonjour.</h2>
</div></li>
</ul>
</div>
</code>```

This is the CSS

```<code>    .container {
  /* Full height*/
    height: 100%;
    box-shadow: 0px 8px 5px #888888;
    background:#ccc;
}

/* Image Slideshow Banner */

.imageBanner li span {
   width: 100%;
   height: 100%;
   position: absolute;
   top: 0px;
   color: transparent;
   background-size: cover;
   background-position: 30%;
   background-repeat: none;
   opacity: 0;
   z-index: 0;
   animation: imageAnimation 18s linear infinite 0s;
 }
 .imageBanner li div {
     z-index: 1;
     position: absolute;
     top:0px;
     width: 100%;
     text-align: center;
     opacity: 0;
     animation: titleAnimation 18s linear infinite 0s;
 }
 .imageBanner li div h2 {

     font-family:Calibri, Arial, sans-serif;
     background: #fff;
     font-size: 7em;
     color: rgb(46,105,163);

     line-height: 6em;
 }
.imageBanner li:nth-child(1) span {
 background-image: url('./images/iron_giant.jpg');
}
.imageBanner li:nth-child(2) span {
   background-image: url("./images/lonely_island.jpg");
   animation-delay: 6s;
}
.imageBanner li:nth-child(3) span {
   background-image: url("./images/mountain_range.jpg");
   animation-delay: 12s;
}

.imageBanner li:nth-child(2) div {
   animation-delay: 6s;
}
.imageBanner li:nth-child(3) div {
   animation-delay: 12s;
}
   @keyframes imageAnimation {
     0% { opacity: 0; animation-timing-function: ease-in; }
     8% { opacity: 1; animation-timing-function: ease-out; }
     17% { opacity: 1 }
     35% { opacity: 0 }
     100% { opacity: 0 }
 }
 @keyframes titleAnimation {
     0% { opacity: 0 }
     8% { opacity: 1 }
     17% { opacity: 1 }
     35% { opacity: 0 }
     100% { opacity: 0 }
 }
</code>```

答:
It was a little hard to find out what final result you seek without a live example, but every time your child elements place in a location that is not desirable, its mean they are not follow their parents. In this situation you had to work with parents first and then modify children.

I checked your css file and there is not even a single relative positioned parent. So i recommend you to edit your css file to this version and read the link i putted down below.

P.S If you didn't get what you was looking for please make and screen shot/jsfiddle of you situation.

```<code><div class="container" >
    <ul class="imageBanner">
      <li>
        <span>Image 01</span>
        <div>
          <h3>Ahoy.</h3>
        </div>
      </li>
      <li><span>Image 02</span>
        <div>
          <h3>Welcome.</h3>
        </div>
      </li>
      <li><span>Image 03</span>
        <div>
          <h3>Bonjour.</h3>
        </div>
      </li>
    </ul>
</div>
</code>```

CSS: (this is just part of css that changed/modified)

```<code>.container {height: 100vh;box-shadow: 0px 8px 5px #888888;background:#CCC;display:block;position: relative;width: 100%;}
.imageBanner {position: relative;display: block;width: 100%;height: 100%;padding: 0 0 0;margin: 0 0 0;}
.imageBanner li {position: absolute;display: block;width: 100%;height: 100%;top:0;left:0;}
.imageBanner li span {font-family:Calibri, Arial, sans-serif;text-align: center;width: 100%;height: 100%;position: absolute;top: 15%;color: #000000;background-size: cover;background-repeat: none;opacity: 0;z-index: 50;font-size: 2em;animation: imageAnimation 18s linear infinite 0s;}
.imageBanner li div {z-index: 1;position: absolute;top:0px;width: 100%;height: 100%;text-align: center;opacity: 0;animation: titleAnimation 18s linear infinite 0s;}
.imageBanner li div h3 {font-family:Calibri, Arial, sans-serif;background: #fff;font-size: 7em;color: rgb(46,105,163);padding: 0 0 0;margin: 0 0 0;line-height: 6em;}
</code>```

CSS Pos Tutorials

CSS Positions

Edit

CodePen

Title: Aligning Image Caption

Body:
Currently, I have a problem with an image slideshow caption not positioning itself relative to the parent container. This may be a simple fix with the DIV floating but for the life of me I can't figure it out. The problem is the text does not stay within the constraints of the container that houses the image; and as such transforms differently upon resizing the webpage (basically moves off the visible area of the page). I'm hoping to set the height of the container housing the text to that of the parent container (the one housing the image) before formatting it to stay at the top 1/3 of the image in the center of the page. The text is based in an UL and transitions between items on the list as an overlay over the image.

This is the code on Codepen.As seen when the CSS transitions the Text (and the white background used for example) both are outside the bounds of the .container DIV (the UL with the dropshadow where I'm hoping to constrain the Text to.

Any help would be grately appreciated.

This is the HTML

Image 01

Ahoy.

Image 02

Welcome.

Image 03

Bonjour.

This is the CSS

    .container {
  /* Full height*/
    height: 100%;
    box-shadow: 0px 8px 5px #888888;
    background:#ccc;
}

/* Image Slideshow Banner */

.imageBanner li span {
   width: 100%;
   height: 100%;
   position: absolute;
   top: 0px;
   color: transparent;
   background-size: cover;
   background-position: 30%;
   background-repeat: none;
   opacity: 0;
   z-index: 0;
   animation: imageAnimation 18s linear infinite 0s;
 }
 .imageBanner li div {
     z-index: 1;
     position: absolute;
     top:0px;
     width: 100%;
     text-align: center;
     opacity: 0;
     animation: titleAnimation 18s linear infinite 0s;
 }
 .imageBanner li div h2 {

     font-family:Calibri, Arial, sans-serif;
     background: #fff;
     font-size: 7em;
     color: rgb(46,105,163);

     line-height: 6em;
 }
.imageBanner li:nth-child(1) span {
 background-image: url('./images/iron_giant.jpg');
}
.imageBanner li:nth-child(2) span {
   background-image: url("./images/lonely_island.jpg");
   animation-delay: 6s;
}
.imageBanner li:nth-child(3) span {
   background-image: url("./images/mountain_range.jpg");
   animation-delay: 12s;
}

.imageBanner li:nth-child(2) div {
   animation-delay: 6s;
}
.imageBanner li:nth-child(3) div {
   animation-delay: 12s;
}
   @keyframes imageAnimation {
     0% { opacity: 0; animation-timing-function: ease-in; }
     8% { opacity: 1; animation-timing-function: ease-out; }
     17% { opacity: 1 }
     35% { opacity: 0 }
     100% { opacity: 0 }
 }
 @keyframes titleAnimation {
     0% { opacity: 0 }
     8% { opacity: 1 }
     17% { opacity: 1 }
     35% { opacity: 0 }
     100% { opacity: 0 }
 }

Body:
It was a little hard to find out what final result you seek without a live example, but every time your child elements place in a location that is not desirable, its mean they are not follow their parents. In this situation you had to work with parents first and then modify children.

I checked your css file and there is not even a single relative positioned parent. So i recommend you to edit your css file to this version and read the link i putted down below.

P.S If you didn't get what you was looking for please make and screen shot/jsfiddle of you situation.

<div class="container" >
    <ul class="imageBanner">
      <li>
        <span>Image 01</span>
        <div>
          <h3>Ahoy.</h3>
        </div>
      </li>
      <li><span>Image 02</span>
        <div>
          <h3>Welcome.</h3>
        </div>
      </li>
      <li><span>Image 03</span>
        <div>
          <h3>Bonjour.</h3>
        </div>
      </li>
    </ul>
</div>

CSS: (this is just part of css that changed/modified)

.container {height: 100vh;box-shadow: 0px 8px 5px #888888;background:#CCC;display:block;position: relative;width: 100%;}
.imageBanner {position: relative;display: block;width: 100%;height: 100%;padding: 0 0 0;margin: 0 0 0;}
.imageBanner li {position: absolute;display: block;width: 100%;height: 100%;top:0;left:0;}
.imageBanner li span {font-family:Calibri, Arial, sans-serif;text-align: center;width: 100%;height: 100%;position: absolute;top: 15%;color: #000000;background-size: cover;background-repeat: none;opacity: 0;z-index: 50;font-size: 2em;animation: imageAnimation 18s linear infinite 0s;}
.imageBanner li div {z-index: 1;position: absolute;top:0px;width: 100%;height: 100%;text-align: center;opacity: 0;animation: titleAnimation 18s linear infinite 0s;}
.imageBanner li div h3 {font-family:Calibri, Arial, sans-serif;background: #fff;font-size: 7em;color: rgb(46,105,163);padding: 0 0 0;margin: 0 0 0;line-height: 6em;}

CSS Pos Tutorials

CSS Positions

Edit

CodePen


问:
How to create a custom UITableViewCell programmatically using AutoLayout
I'm trying to implement a UITableView that will behave similarly to the timeline of a twitter client. Right now I'm simply attempting to get two labels inside a UITableViewCell. As recommended by this Stack Overflow answer, I'm using a different reuseIdentifier for each layouts. My layouts are simple, consisting of either a single label or two labels. Eventually I will be adjusting the height of the UITableViewCells but first I need to get the cells populated with content.

I can get the labels so show up if I set their frame with initWithFrame:, however the constraints aren't being implemented.

Question: What is preventing the labels and constraints from appearing? I'm clearly missing something in my implementation of the UITableViewCell but I have no idea what it is.

Secondary question: Am I registering the UITableViewCell class correctly for each reuseIdentifier in viewDidLoad?

This might come across as being difficult but Interface Builder confuses me, I would like to accomplish this all in code.

Here is the code for the custom UITableViewCell named TVTCell.h:

```<code>static NSString * const kCellIDTitle = @"CellWithTitle";
static NSString * const kCellIDTitleMain = @"CellWithTitleMain";

@interface TVTCell : UITableViewCell
{
    NSString *reuseID;
}

@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *mainLabel;

@end
</code>```

And TVTCell.m:

```<code>- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        reuseID = reuseIdentifier;

        nameLabel = [[UILabel alloc] init];
        [nameLabel setTextColor:[UIColor blackColor]];
        [nameLabel setBackgroundColor:[UIColor colorWithHue:32 saturation:100 brightness:63 alpha:1]];
        [nameLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0f]];
        [nameLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.contentView addSubview:nameLabel];

        mainLabel = [[UILabel alloc] init];
        [mainLabel setTextColor:[UIColor blackColor]];
        [mainLabel setBackgroundColor:[UIColor colorWithHue:66 saturation:100 brightness:63 alpha:1]];
        [mainLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0f]];
        [mainLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.contentView addSubview:mainLabel];

        [self.contentView setTranslatesAutoresizingMaskIntoConstraints:NO];

    }
    return self;
}

- (void)updateConstraints
{
    [super updateConstraints];

    NSDictionary *views = NSDictionaryOfVariableBindings(nameLabel, mainLabel);
    if (reuseID == kCellIDTitle) {
        NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[nameLabel]|"
                                                options: NSLayoutFormatAlignAllCenterX
                                                metrics:nil
                                                  views:views];
        [self.contentView addConstraints:constraints];
        constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[nameLabel]|"
                                                              options: NSLayoutFormatAlignAllCenterX
                                                              metrics:nil
                                                                views:views];
        [self.contentView addConstraints:constraints];
    }
    if (reuseID == kCellIDTitleMain) {
        NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[nameLabel]|"
                                                                       options: NSLayoutFormatAlignAllCenterX
                                                                       metrics:nil
                                                                         views:views];
        [self.contentView addConstraints:constraints];

        constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[mainLabel]|"
                                                                       options: NSLayoutFormatAlignAllCenterX
                                                                       metrics:nil
                                                                         views:views];
        [self.contentView addConstraints:constraints];

        constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[nameLabel][mainLabel]|"
                                                              options: NSLayoutFormatAlignAllLeft
                                                              metrics:nil
                                                                views:views];
        [self.contentView addConstraints:constraints];

        [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:nameLabel
                                     attribute:NSLayoutAttributeHeight
                                     relatedBy:NSLayoutRelationEqual
                                        toItem:nil
                                     attribute:NSLayoutAttributeNotAnAttribute
                                    multiplier:0.0
                                      constant:44.0]];
        [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:nameLabel
                                                                     attribute:NSLayoutAttributeWidth
                                                                     relatedBy:NSLayoutRelationEqual
                                                                        toItem:self.contentView
                                                                     attribute:NSLayoutAttributeNotAnAttribute
                                                                    multiplier:0.0
                                                                      constant:1]];
    }
}
</code>```

Sorry, ton of code. Here's my UITableView's tableView:cellForRowAtIndexPath:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0 || indexPath.row == 2 || indexPath.row == 3) {
        TVTCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIDTitle forIndexPath:indexPath];

        [[cell nameLabel] setText:[nameArray objectAtIndex:indexPath.row]];

        return cell;
    } else if (indexPath.row == 1 || indexPath.row == 4 || indexPath.row == 5) {
        TVTCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIDTitleMain forIndexPath:indexPath];

        [[cell nameLabel] setText:[nameArray objectAtIndex:indexPath.row]];
        [[cell mainLabel] setText:[dataArray objectAtIndex:indexPath.row]];

        return cell;
    } else
    {
        UITableViewCell *badCell = [[UITableViewCell alloc] init];
        NSLog(@"Warning! returning a cell that shouldnt be here");
        badCell.textLabel.text = @"Warning!";
        return badCell;
    }
}
</code>```

And lastly, the UITableView's viewDidLoad method:

```<code>- (void)viewDidLoad
{
    [super viewDidLoad];

    [[self tableView] registerClass:[TVTCell class] forCellReuseIdentifier:kCellIDTitle];
    [[self tableView] registerClass:[TVTCell class] forCellReuseIdentifier:kCellIDTitleMain];
}
</code>```

答:
You can create UITableViewCell programatically in swift 4 using auto-layout like below. It's not exactly the solution of your above problem as you specified in question, It's more generic implementation how to create Tableview cell programatically in swift using auto-layout :

```<code>class ViewController: UITableViewController {

override func viewDidLoad() {
   super.viewDidLoad()
   tableView.register(CustomCell2.self, forCellReuseIdentifier: "cell")
}

override func numberOfSections(in tableView: UITableView) -> Int {
  return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  return 2
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? CustomCell2 else { return UITableViewCell() }
  cell.model = CellModel(labelString: "set constriant by code")
  return cell
  }
  }
</code>```

Define Model :

```<code>struct CellModel {
  let labelString : String
 }
</code>```

Define Custom Cell :

```<code>class CustomCell2 : UITableViewCell {
private let label : UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false // enable auto layout
    label.backgroundColor = .green // to visualize the background of label
    label.textAlignment = .center // center text alignment
    return label
}()

private func addLabel() {
    addSubview(label)
    NSLayoutConstraint.activate([
        // label width is 70% of cell width
        label.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.7),
        // label is horizontally center of cell
        label.centerXAnchor.constraint(equalTo: centerXAnchor)
    ])
}

var model : CellModel? {
    didSet {
        label.text = model?.labelString ?? ""
    }
}

// Init
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    addLabel()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}
</code>```

This is the output of above program.

This is the actual project, you can check out.

Body:
I'm trying to implement a UITableView that will behave similarly to the timeline of a twitter client. Right now I'm simply attempting to get two labels inside a UITableViewCell. As recommended by this Stack Overflow answer, I'm using a different reuseIdentifier for each layouts. My layouts are simple, consisting of either a single label or two labels. Eventually I will be adjusting the height of the UITableViewCells but first I need to get the cells populated with content.

I can get the labels so show up if I set their frame with initWithFrame:, however the constraints aren't being implemented.

Question: What is preventing the labels and constraints from appearing? I'm clearly missing something in my implementation of the UITableViewCell but I have no idea what it is.

Secondary question: Am I registering the UITableViewCell class correctly for each reuseIdentifier in viewDidLoad?

This might come across as being difficult but Interface Builder confuses me, I would like to accomplish this all in code.

Here is the code for the custom UITableViewCell named TVTCell.h:

static NSString * const kCellIDTitle = @"CellWithTitle";
static NSString * const kCellIDTitleMain = @"CellWithTitleMain";

@interface TVTCell : UITableViewCell
{
    NSString *reuseID;
}

@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *mainLabel;

@end

And TVTCell.m:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        reuseID = reuseIdentifier;

        nameLabel = [[UILabel alloc] init];
        [nameLabel setTextColor:[UIColor blackColor]];
        [nameLabel setBackgroundColor:[UIColor colorWithHue:32 saturation:100 brightness:63 alpha:1]];
        [nameLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0f]];
        [nameLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.contentView addSubview:nameLabel];

        mainLabel = [[UILabel alloc] init];
        [mainLabel setTextColor:[UIColor blackColor]];
        [mainLabel setBackgroundColor:[UIColor colorWithHue:66 saturation:100 brightness:63 alpha:1]];
        [mainLabel setFont:[UIFont fontWithName:@"HelveticaNeue" size:18.0f]];
        [mainLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.contentView addSubview:mainLabel];

        [self.contentView setTranslatesAutoresizingMaskIntoConstraints:NO];

    }
    return self;
}

- (void)updateConstraints
{
    [super updateConstraints];

    NSDictionary *views = NSDictionaryOfVariableBindings(nameLabel, mainLabel);
    if (reuseID == kCellIDTitle) {
        NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[nameLabel]|"
                                                options: NSLayoutFormatAlignAllCenterX
                                                metrics:nil
                                                  views:views];
        [self.contentView addConstraints:constraints];
        constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[nameLabel]|"
                                                              options: NSLayoutFormatAlignAllCenterX
                                                              metrics:nil
                                                                views:views];
        [self.contentView addConstraints:constraints];
    }
    if (reuseID == kCellIDTitleMain) {
        NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[nameLabel]|"
                                                                       options: NSLayoutFormatAlignAllCenterX
                                                                       metrics:nil
                                                                         views:views];
        [self.contentView addConstraints:constraints];

        constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[mainLabel]|"
                                                                       options: NSLayoutFormatAlignAllCenterX
                                                                       metrics:nil
                                                                         views:views];
        [self.contentView addConstraints:constraints];

        constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[nameLabel][mainLabel]|"
                                                              options: NSLayoutFormatAlignAllLeft
                                                              metrics:nil
                                                                views:views];
        [self.contentView addConstraints:constraints];

        [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:nameLabel
                                     attribute:NSLayoutAttributeHeight
                                     relatedBy:NSLayoutRelationEqual
                                        toItem:nil
                                     attribute:NSLayoutAttributeNotAnAttribute
                                    multiplier:0.0
                                      constant:44.0]];
        [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:nameLabel
                                                                     attribute:NSLayoutAttributeWidth
                                                                     relatedBy:NSLayoutRelationEqual
                                                                        toItem:self.contentView
                                                                     attribute:NSLayoutAttributeNotAnAttribute
                                                                    multiplier:0.0
                                                                      constant:1]];
    }
}

Sorry, ton of code. Here's my UITableView's tableView:cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0 || indexPath.row == 2 || indexPath.row == 3) {
        TVTCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIDTitle forIndexPath:indexPath];

        [[cell nameLabel] setText:[nameArray objectAtIndex:indexPath.row]];

        return cell;
    } else if (indexPath.row == 1 || indexPath.row == 4 || indexPath.row == 5) {
        TVTCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIDTitleMain forIndexPath:indexPath];

        [[cell nameLabel] setText:[nameArray objectAtIndex:indexPath.row]];
        [[cell mainLabel] setText:[dataArray objectAtIndex:indexPath.row]];

        return cell;
    } else
    {
        UITableViewCell *badCell = [[UITableViewCell alloc] init];
        NSLog(@"Warning! returning a cell that shouldnt be here");
        badCell.textLabel.text = @"Warning!";
        return badCell;
    }
}

And lastly, the UITableView's viewDidLoad method:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[self tableView] registerClass:[TVTCell class] forCellReuseIdentifier:kCellIDTitle];
    [[self tableView] registerClass:[TVTCell class] forCellReuseIdentifier:kCellIDTitleMain];
}

Body:
You can create UITableViewCell programatically in swift 4 using auto-layout like below. It's not exactly the solution of your above problem as you specified in question, It's more generic implementation how to create Tableview cell programatically in swift using auto-layout :

class ViewController: UITableViewController {

override func viewDidLoad() {
   super.viewDidLoad()
   tableView.register(CustomCell2.self, forCellReuseIdentifier: "cell")
}

override func numberOfSections(in tableView: UITableView) -> Int {
  return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  return 2
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? CustomCell2 else { return UITableViewCell() }
  cell.model = CellModel(labelString: "set constriant by code")
  return cell
  }
  }

Define Model :

struct CellModel {
  let labelString : String
 }

Define Custom Cell :

class CustomCell2 : UITableViewCell {
private let label : UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false // enable auto layout
    label.backgroundColor = .green // to visualize the background of label
    label.textAlignment = .center // center text alignment
    return label
}()

private func addLabel() {
    addSubview(label)
    NSLayoutConstraint.activate([
        // label width is 70% of cell width
        label.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.7),
        // label is horizontally center of cell
        label.centerXAnchor.constraint(equalTo: centerXAnchor)
    ])
}

var model : CellModel? {
    didSet {
        label.text = model?.labelString ?? ""
    }
}

// Init
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    addLabel()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
}

This is the output of above program.

This is the actual project, you can check out.


问:
int.Parse is not working with string value (System.FormatException: Input string was not in a correct format )
If a user inputs anything but a number I get Unhandled Exception:

System.FormatException: Input string was not in a correct format.

Can someone explain what I am doing wrong?

Here's my code C# .NET:

```<code>private static int WeightIFeMale()
{
    Console.WriteLine("How Much Do You Weigh?", Environment.NewLine);
    int femaleWeight = int.Parse(Console.ReadLine());

    if
        (0 >= femaleWeight && 80 <= femaleWeight)
    {
        Console.WriteLine("Damn, how much crack are you smoking?", Environment.NewLine);
    }
    else if
        (81 >= femaleWeight && 110 <= femaleWeight)
    {
        Console.WriteLine("What the ****, are you a midget *****?", Environment.NewLine);

    }
    else if
        (111 >= femaleWeight && 140 <= femaleWeight)
    {
        Console.WriteLine("Holy shit, I have some protein bar coupons you can have!", Environment.NewLine);

    }
    else if
        (141 >= femaleWeight && 160 <= femaleWeight)
    {
        Console.WriteLine("Bro you need to hit the Gym, ASAP!", Environment.NewLine);

    }
    else if
        (161 >= femaleWeight && 200 <= femaleWeight)
    {
        Console.WriteLine("Really!!!, can I hit the Gym with you?", Environment.NewLine);

    }
    else if
        (201 >= femaleWeight && 240 <= femaleWeight)
    {
        Console.WriteLine("Do you Have a small ****, Steroids are a mother @#$%^&&", Environment.NewLine);

    }
    else if
        (241 >= femaleWeight && 999 <= femaleWeight)
    {
        Console.WriteLine("My condolences!", Environment.NewLine);
    }
    else if
        (femaleWeight >= 1000)
    {
        Console.WriteLine("There is absolutely no way that you weigh {0} lbs, so stop ******* around!", femaleWeight, Environment.NewLine);
    }
    else
    {
        Console.Write("What the **** is {0} It has to be a number numb nuts, lets try that again!", Environment.NewLine);
        WeightIFeMale();
    }

    return femaleWeight;
}
</code>```

答:
Because of int femaleWeight = int.Parse(Console.ReadLine());

int.Parse method will throw FormatException if input can not be converted to integer.

Body:
If a user inputs anything but a number I get Unhandled Exception:

System.FormatException: Input string was not in a correct format.

Can someone explain what I am doing wrong?

Here's my code C# .NET:

private static int WeightIFeMale()
{
    Console.WriteLine("How Much Do You Weigh?", Environment.NewLine);
    int femaleWeight = int.Parse(Console.ReadLine());

    if
        (0 >= femaleWeight && 80 <= femaleWeight)
    {
        Console.WriteLine("Damn, how much crack are you smoking?", Environment.NewLine);
    }
    else if
        (81 >= femaleWeight && 110 <= femaleWeight)
    {
        Console.WriteLine("What the ****, are you a midget *****?", Environment.NewLine);

    }
    else if
        (111 >= femaleWeight && 140 <= femaleWeight)
    {
        Console.WriteLine("Holy shit, I have some protein bar coupons you can have!", Environment.NewLine);

    }
    else if
        (141 >= femaleWeight && 160 <= femaleWeight)
    {
        Console.WriteLine("Bro you need to hit the Gym, ASAP!", Environment.NewLine);

    }
    else if
        (161 >= femaleWeight && 200 <= femaleWeight)
    {
        Console.WriteLine("Really!!!, can I hit the Gym with you?", Environment.NewLine);

    }
    else if
        (201 >= femaleWeight && 240 <= femaleWeight)
    {
        Console.WriteLine("Do you Have a small ****, Steroids are a mother @#$%^&&", Environment.NewLine);

    }
    else if
        (241 >= femaleWeight && 999 <= femaleWeight)
    {
        Console.WriteLine("My condolences!", Environment.NewLine);
    }
    else if
        (femaleWeight >= 1000)
    {
        Console.WriteLine("There is absolutely no way that you weigh {0} lbs, so stop ******* around!", femaleWeight, Environment.NewLine);
    }
    else
    {
        Console.Write("What the **** is {0} It has to be a number numb nuts, lets try that again!", Environment.NewLine);
        WeightIFeMale();
    }

    return femaleWeight;
}


问:
PHP syntax error could not be converted to string?

Object of class stdClass could not be converted to string

I have no idea what error is it and I am new in PHP.It is telling me error in echo that line.

```<code>   <?php foreach ($results as $value):
    echo '<div class="database">"'.$value.'"</div>' ?>
    <?php endforeach; ?>
</code>```

答:
The variable $value is object. So you should not echo it directly. You can echo its attribute.

So, suppose it has firstname as attribute, then echo it like

```<code>echo '<div class="database">"'.$value->firstname.'"</div>' ?>
</code>```

Or if you want to see what attributes the object has, then you may first print it

```<code>print_r($value);die';
</code>```

Body:
Object of class stdClass could not be converted to string

I have no idea what error is it and I am new in PHP.It is telling me error in echo that line.

   <?php foreach ($results as $value):
    echo '
"'.$value.'"
' ?>
    <?php endforeach; ?>

Body:
The variable $value is object. So you should not echo it directly. You can echo its attribute.

So, suppose it has firstname as attribute, then echo it like

echo '<div class="database">"'.$value->firstname.'"</div>' ?>

Or if you want to see what attributes the object has, then you may first print it

print_r($value);die';


问:
Android Listview search filter (list empty after first search)
I am doing a search filter using filterable. I manage to get the search result when I search by keyword but the listview is empty after the first search. I want it to show all the data when the user input is null.

This is the code I edited. Now I cannot get any search result. Any idea which part still wrong?

```<code>  public class ProductListAdapter extends BaseAdapter implements Filterable {

    private Context context;
    private int layout;
    private ArrayList<Booth> productList= new ArrayList<>();
    private ArrayList<Booth> tempList = new ArrayList<>();
    private ValueFilter mFilter = new ValueFilter();

    public ProductListAdapter(Context context, int layout, ArrayList<Booth> productList) {
        this.context = context;
        this.layout = layout;
        this.productList = productList;
        this.tempList = productList;

    }

    @Override
    public int getCount() {

        return tempList.size();
    }

    public void addItems(ArrayList<Booth> items) {
        productList.addAll(items);
        tempList.addAll(items);
        notifyDataSetChanged();
    }

    @Override
    public Object getItem(int position) {

        return tempList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(
            int position, View view, ViewGroup viewGroup) {
        Typeface face_02 = Typeface.createFromAsset(context.getAssets(), "customfont/grb.otf");
        ViewHolder holder = new ViewHolder();

        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(layout, null);
            holder.Boothname = (TextView) view.findViewById(R.id.Boothname);
            holder.Rating = (TextView) view.findViewById(R.id.Rating);

            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        Booth product = productList.get(position);

        holder.Boothname.setText(product.getBoothName());
        holder.Rating.setText(product.getRating());
        holder.Rating.setTypeface(face_02);
        holder.Boothname.setTypeface(face_02);

        return view;
    }

    @Override
    public Filter getFilter() {
        return mFilter;
    }

    private class ValueFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();

            if (constraint != null && constraint.length() > 0) {
                ArrayList<Booth> filterList = new ArrayList<Booth>();
                constraint = constraint.toString().toLowerCase();

                for (int i = 0; i < productList.size(); i++) {
                    if ((productList.get(i).getBoothName().toLowerCase())
                            .contains(constraint.toString().toLowerCase())) {

                        Booth boothdata = new Booth(productList.get(i)
                                .getBoothName(), productList.get(i)
                                .getRating());

                        filterList.add(boothdata);
                    }
                }
                results.count = filterList.size();
                results.values = filterList;

            } else {
                results.count = productList.size();
                results.values = productList;
            }
            return results;

        }

        @Override
        protected void publishResults(CharSequence constraint,
                                      FilterResults results) {
            tempList = (ArrayList<Booth>) results.values;
            notifyDataSetChanged();
        }
    }
        class ViewHolder {
            TextView Boothname, Rating;

        }
}
</code>```

答:
yes, you got this error. Why? Because after searchings, from times to times, your productList loses its product. So, how to resolve it? You should make filter data for filtering only and you will search in the filter data instead of your productList as below:

```<code>filterList = new List<Product>()// do clone here when you set new data to your list.
// then in the performFiltering(), use filterList instead.
for (int i = 0; i < filterList.size(); i++) {
                if ((filterList.get(i).getBoothName().toLowerCase())
                        .startsWith(constraint.toString().toLowerCase())) {

                    Booth boothdata = new Booth(filterList.get(i)
                            .getBoothName(), filterList.get(i)
                            .getRating());

                    filterList.add(boothdata);
                }
            }
</code>```

This is what you should do.

```<code>    @Override
    protected void publishResults(CharSequence constraint,
                                  FilterResults results) {
        productList = (ArrayList<Booth>) results.values; // if you use templist here, there's no change in getView
        notifyDataSetChanged();
    }
</code>```

Body:
I am doing a search filter using filterable. I manage to get the search result when I search by keyword but the listview is empty after the first search. I want it to show all the data when the user input is null.

This is the code I edited. Now I cannot get any search result. Any idea which part still wrong?

  public class ProductListAdapter extends BaseAdapter implements Filterable {

    private Context context;
    private int layout;
    private ArrayList<Booth> productList= new ArrayList<>();
    private ArrayList<Booth> tempList = new ArrayList<>();
    private ValueFilter mFilter = new ValueFilter();

    public ProductListAdapter(Context context, int layout, ArrayList<Booth> productList) {
        this.context = context;
        this.layout = layout;
        this.productList = productList;
        this.tempList = productList;

    }

    @Override
    public int getCount() {

        return tempList.size();
    }

    public void addItems(ArrayList<Booth> items) {
        productList.addAll(items);
        tempList.addAll(items);
        notifyDataSetChanged();
    }

    @Override
    public Object getItem(int position) {

        return tempList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(
            int position, View view, ViewGroup viewGroup) {
        Typeface face_02 = Typeface.createFromAsset(context.getAssets(), "customfont/grb.otf");
        ViewHolder holder = new ViewHolder();

        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(layout, null);
            holder.Boothname = (TextView) view.findViewById(R.id.Boothname);
            holder.Rating = (TextView) view.findViewById(R.id.Rating);

            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        Booth product = productList.get(position);

        holder.Boothname.setText(product.getBoothName());
        holder.Rating.setText(product.getRating());
        holder.Rating.setTypeface(face_02);
        holder.Boothname.setTypeface(face_02);

        return view;
    }

    @Override
    public Filter getFilter() {
        return mFilter;
    }

    private class ValueFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();

            if (constraint != null && constraint.length() > 0) {
                ArrayList<Booth> filterList = new ArrayList<Booth>();
                constraint = constraint.toString().toLowerCase();

                for (int i = 0; i < productList.size(); i++) {
                    if ((productList.get(i).getBoothName().toLowerCase())
                            .contains(constraint.toString().toLowerCase())) {

                        Booth boothdata = new Booth(productList.get(i)
                                .getBoothName(), productList.get(i)
                                .getRating());

                        filterList.add(boothdata);
                    }
                }
                results.count = filterList.size();
                results.values = filterList;

            } else {
                results.count = productList.size();
                results.values = productList;
            }
            return results;

        }

        @Override
        protected void publishResults(CharSequence constraint,
                                      FilterResults results) {
            tempList = (ArrayList<Booth>) results.values;
            notifyDataSetChanged();
        }
    }
        class ViewHolder {
            TextView Boothname, Rating;

        }
}

Body:
yes, you got this error. Why? Because after searchings, from times to times, your productList loses its product. So, how to resolve it? You should make filter data for filtering only and you will search in the filter data instead of your productList as below:

filterList = new List<Product>()// do clone here when you set new data to your list.
// then in the performFiltering(), use filterList instead.
for (int i = 0; i < filterList.size(); i++) {
                if ((filterList.get(i).getBoothName().toLowerCase())
                        .startsWith(constraint.toString().toLowerCase())) {

                    Booth boothdata = new Booth(filterList.get(i)
                            .getBoothName(), filterList.get(i)
                            .getRating());

                    filterList.add(boothdata);
                }
            }

This is what you should do.

    @Override
    protected void publishResults(CharSequence constraint,
                                  FilterResults results) {
        productList = (ArrayList<Booth>) results.values; // if you use templist here, there's no change in getView
        notifyDataSetChanged();
    }


问:
While clicking on tab i need to load particular component in angular2
I am trying to load components in tab. while clicking on particular tab i need to load the particular component.But it's loading all component while navigating to that component.

.html

```<code><p-tabView orientation="left" (onChange)="onTabChange($event)">
       <p-tabPanel *ngFor="let item of items" style="border: solid 1px; padding: 20px;margin: 20px;" [selected]="activeTabIndex==i">
              <strong> When you click here,
              I should load the <span style="color:red"> {{item.name}} </span>
              component below</strong> <br />

              <ng-container *ngComponentOutlet="childmap[item.name] "></ng-container>

          <br />
        </p-tabPanel>
</p-tabView>
</code>```

.ts

```<code>@Component({
  selector: 'my-app',
  templateUrl:'dashboard.html'
  `
})
export class App {
 activeTabIndex: number = 0;

childmap = {
        'slider': sliderComponent,
        'user': usersComponent,
        'alert danger': AlertDangerComponent
         }

items:Array<any> = [
    {
      name: 'slider'
    },
    {
      name: 'user'
    },
    {
      name: 'alert danger'
    }

      ]
 onTabChange(event: any) {
        this.activeTabIndex = event.index;
    }
  }
</code>```

答:
What you are doing is basically trying to write your own router. The PrimeNg TabView is built to load the menu and all the tab contents first on initialization and then puts an artificial layer of tabs on top of it. However, under menu, there is TabMenu which is actually what you want. The key difference, is a menu allows your list to be MenuItems which can include routerLink as a parameter.

There is an excellent article here that explains the details which I prefer to the official documentation. You should understand this first, and then see how PrimeNg just implements a handy way to build these links for you if you supply routerLink. (See the MenuItems link for better documentation on the MenuItem model. From your code I can't tell if you are at your top level component or not, but I think what you are looking for is along these lines. This solution uses child routes which is slightly more complex, but a more useful example. This assumes you have AppComponent set up as your top level component with just <router-outlet></router-outlet> in the template. This will load your dashboard component as an empty root redirects to dashboard.

app.module.ts

```<code>const myDefinedRoutes: Routes = [
  {path: '', redirectTo: 'dashboard', pathMatch: 'full'},
  {path: 'dashboard', component: DashboardComponent, children: [
      {path: 'slider', component: SliderComponent},
      {path: 'user', component: UserComponent},
      {path: 'alert', component: AlertDangerComponent},
    ]
  }
]

@NgModule({
  // Add this line to imports
    RouterModule.forRoot(myDefinedRoutes)
})
export class AppModule {}
</code>```

dashboard.component.ts

```<code>@Component({
  selector: 'my-app',
  template:`
   <p-tabMenu [model]="items"></p-tabMenu>
   <router-outlet></router-outlet>
  `
})
export class App implements OnInit {
  ngOnInit() {
    this.items = [
      {label: "Slider", routerLink: ['/dashboard', 'slider']},
      {label: "User", routerLink: ['/dashboard', 'user']},
      {label: "Danger", routerLink: ['/dashboard', 'alert']},
    ];
    this.activeItem = this.items[1]
  }
}
</code>```

Make sure you include the router-outlet in your dashboard component too because the other components exist as children which means you will need another outlet because the first outlet is still housing the dashboard component, and inside the dashboard component, you are showing one of the other three components.

Body:
I am trying to load components in tab. while clicking on particular tab i need to load the particular component.But it's loading all component while navigating to that component.

.html

               When you click here,
              I should load the  {{item.name}}
              component below

              <ng-container *ngComponentOutlet="childmap[item.name] "></ng-container>

.ts

@Component({
  selector: 'my-app',
  templateUrl:'dashboard.html'
  `
})
export class App {
 activeTabIndex: number = 0;

childmap = {
        'slider': sliderComponent,
        'user': usersComponent,
        'alert danger': AlertDangerComponent
         }

items:Array<any> = [
    {
      name: 'slider'
    },
    {
      name: 'user'
    },
    {
      name: 'alert danger'
    }

      ]
 onTabChange(event: any) {
        this.activeTabIndex = event.index;
    }
  }

Body:
What you are doing is basically trying to write your own router. The PrimeNg TabView is built to load the menu and all the tab contents first on initialization and then puts an artificial layer of tabs on top of it. However, under menu, there is TabMenu which is actually what you want. The key difference, is a menu allows your list to be MenuItems which can include routerLink as a parameter.

There is an excellent article here that explains the details which I prefer to the official documentation. You should understand this first, and then see how PrimeNg just implements a handy way to build these links for you if you supply routerLink. (See the MenuItems link for better documentation on the MenuItem model. From your code I can't tell if you are at your top level component or not, but I think what you are looking for is along these lines. This solution uses child routes which is slightly more complex, but a more useful example. This assumes you have AppComponent set up as your top level component with just <router-outlet></router-outlet> in the template. This will load your dashboard component as an empty root redirects to dashboard.

app.module.ts

const myDefinedRoutes: Routes = [
  {path: '', redirectTo: 'dashboard', pathMatch: 'full'},
  {path: 'dashboard', component: DashboardComponent, children: [
      {path: 'slider', component: SliderComponent},
      {path: 'user', component: UserComponent},
      {path: 'alert', component: AlertDangerComponent},
    ]
  }
]

@NgModule({
  // Add this line to imports
    RouterModule.forRoot(myDefinedRoutes)
})
export class AppModule {}

dashboard.component.ts

@Component({
  selector: 'my-app',
  template:`
   <p-tabMenu [model]="items"></p-tabMenu>
   <router-outlet></router-outlet>
  `
})
export class App implements OnInit {
  ngOnInit() {
    this.items = [
      {label: "Slider", routerLink: ['/dashboard', 'slider']},
      {label: "User", routerLink: ['/dashboard', 'user']},
      {label: "Danger", routerLink: ['/dashboard', 'alert']},
    ];
    this.activeItem = this.items[1]
  }
}

Make sure you include the router-outlet in your dashboard component too because the other components exist as children which means you will need another outlet because the first outlet is still housing the dashboard component, and inside the dashboard component, you are showing one of the other three components.


问:
jQuery How do set text in a input field then press enter?
jQuery How do set text in a input field then press enter?  I have input field if I manually enter text then submit button will get enabled but if I use jQuery to enter text, then the button won't enabled. How can I make the button enabled?  I am using jQuery with Selenium

Here is what I am looking for verizonwireless.com/support/contact-us on this page, if you enter something in search field, "X" will show up but if you enter using JQuery it won't. So how will I make the "X" show up when I use jquery to enter the text? $('#vgn_q').val('iphone').change(); I tried this but no luck

答:
Do something like this

Change button condition when have some value in input

```<code>var input = $("input");
var target = $("button");

input.on("change keyup",function(){
        if($(this).val() !== ''){
    target.prop("disabled",false);
  }else{
    target.prop("disabled",true);
  }
})
</code>```

jsfiddle : https://jsfiddle.net/synz/uxk87xjb/

Body:
Do something like this

Change button condition when have some value in input

var input = $("input");
var target = $("button");

input.on("change keyup",function(){
        if($(this).val() !== ''){
    target.prop("disabled",false);
  }else{
    target.prop("disabled",true);
  }
})

jsfiddle : https://jsfiddle.net/synz/uxk87xjb/


问:
what should the useragent value be http header for a java client
I am currently writing code to test an REST based API
I am getting a status 404 error when trying to content to the server.
Im pretty sure i have the correct username password base~Url
and account

I dont know what to put in for useragent?
I running a java program on my c drive to connect to the server.
what type of info typically goes into the useragent field?
Is it something to the with my browser.

答:
The version of Java you are running is the preferred User Agent. However, the server may restrict the User Agents to browsers to prevent remote access or site crawling.

For example:

```<code>Java/1.6.0_14
</code>```

Body:
The version of Java you are running is the preferred User Agent. However, the server may restrict the User Agents to browsers to prevent remote access or site crawling.

For example:

Java/1.6.0_14


问:
Combine the SQL queries into one
I am trying to combine two queries into one.

First query:

```<code>select SaleID
from Sales
where InvoiceStatusID = 'OR';
</code>```

Second query:

```<code>select ItemSaleLines.Quantity, Items.CustomField2
from ItemSaleLines
inner join Items on ItemSaleLines.ItemID = Items.ItemID
inner join Sales on ItemSaleLines.SaleID = Sales.SaleID
where (ItemSaleLines.SaleID = {keyProductID}
  and (ItemSaleLines.Quantity > 0)
  and (Items.ItemNumber not like '%tnt%')
  and (Items.ItemNumber not like '%contact%')
  and (Items.ItemNumber <> '')
  and (Items.ItemNumber <> '-' ) )
</code>```

where keyProductID is the SaleID which I am getting from query 1.

I am doing this by storing SaleID first from query 1 and passing to the query 2, but it is not efficient and have too many calls.

Whats the better way to do it?

答:
You can try something like this,</p>

```<code>select ItemSaleLines.Quantity,Items.CustomField2 from ItemSaleLines
inner join Items on ItemSaleLines.ItemID=Items.ItemID
inner join Sales on ItemSaleLines.SaleID=Sales.SaleID
where (ItemSaleLines.SaleID=(select SaleID from Sales where InvoiceStatusID='OR')
AND (ItemSaleLines.Quantity > 0) AND (Items.ItemNumber not
like '%tnt%') AND (Items.ItemNumber not like '%contact%') AND (Items.ItemNumber <> '') AND (Items.ItemNumber <> '-' ) )
</code>```

Title: Combine the SQL queries into one

Body:
I am trying to combine two queries into one.

First query:

select SaleID
from Sales
where InvoiceStatusID = 'OR';

Second query:

select ItemSaleLines.Quantity, Items.CustomField2
from ItemSaleLines
inner join Items on ItemSaleLines.ItemID = Items.ItemID
inner join Sales on ItemSaleLines.SaleID = Sales.SaleID
where (ItemSaleLines.SaleID = {keyProductID}
  and (ItemSaleLines.Quantity > 0)
  and (Items.ItemNumber not like '%tnt%')
  and (Items.ItemNumber not like '%contact%')
  and (Items.ItemNumber <> '')
  and (Items.ItemNumber <> '-' ) )

where keyProductID is the SaleID which I am getting from query 1.

I am doing this by storing SaleID first from query 1 and passing to the query 2, but it is not efficient and have too many calls.

Whats the better way to do it?

Body:
You can try something like this,

select ItemSaleLines.Quantity,Items.CustomField2 from ItemSaleLines
inner join Items on ItemSaleLines.ItemID=Items.ItemID
inner join Sales on ItemSaleLines.SaleID=Sales.SaleID
where (ItemSaleLines.SaleID=(select SaleID from Sales where InvoiceStatusID='OR')
AND (ItemSaleLines.Quantity > 0) AND (Items.ItemNumber not
like '%tnt%') AND (Items.ItemNumber not like '%contact%') AND (Items.ItemNumber <> '') AND (Items.ItemNumber <> '-' ) )