问:
Overriding class variables in python
I'm trying to understand a bit how Python (2.6) deals with class, instances and so on, and at a certain point, I tried this code:

```<code>#/usr/bin/python2.6

class Base(object):
    default = "default value in base"

    def __init__(self):
        super(Base, self).__init__()

    @classmethod
    def showDefaultValue(cls, defl = default):
        print "defl == %s" % (defl)

class Descend(Base):
    default = "default value in descend"

    def __init__(self):
        super(Descend, self).__init__()

if __name__ == "__main__":
    Descend.showDefaultValue()
</code>```

The output is: "default value in base"

I was wondering why the "default" field is not overwirtten by the Descend class... Is there any way to overwrite it? Why isn't it being overwritten?

Any hint (or link to an explanatory page will be appreciated). Thank you!

答:
The class variable is being overwritten. Try

```<code>@classmethod
def showDefaultValue(cls):
    print "defl == %s" % (cls.default,)
</code>```

The reason your way doesn't work has more to do with the way Python treats default arguments to functions than with class attributes. The default value for defl is evaluated at the time Python defines the binding for showDefaultValue and this is done exactly once. When you call your method the default value used is what was evaluated at the time of definition.

In your case, defl was bound to the value of the default variable as it was during the execution of the class body form of Base. Regardless of how you call showDefaultValue later on (i.e., whether via Base or via Descend) that value remains fixed in all subsequent invocations of showDefaultValue.

Title: Overriding class variables in python

Body:
I'm trying to understand a bit how Python (2.6) deals with class, instances and so on, and at a certain point, I tried this code:

#/usr/bin/python2.6

class Base(object):
    default = "default value in base"

    def __init__(self):
        super(Base, self).__init__()

    @classmethod
    def showDefaultValue(cls, defl = default):
        print "defl == %s" % (defl)

class Descend(Base):
    default = "default value in descend"

    def __init__(self):
        super(Descend, self).__init__()

if __name__ == "__main__":
    Descend.showDefaultValue()

The output is: "default value in base"

I was wondering why the "default" field is not overwirtten by the Descend class... Is there any way to overwrite it? Why isn't it being overwritten?

Any hint (or link to an explanatory page will be appreciated). Thank you!

Body:
The class variable is being overwritten. Try

@classmethod
def showDefaultValue(cls):
    print "defl == %s" % (cls.default,)

The reason your way doesn't work has more to do with the way Python treats default arguments to functions than with class attributes. The default value for defl is evaluated at the time Python defines the binding for showDefaultValue and this is done exactly once. When you call your method the default value used is what was evaluated at the time of definition.

In your case, defl was bound to the value of the default variable as it was during the execution of the class body form of Base. Regardless of how you call showDefaultValue later on (i.e., whether via Base or via Descend) that value remains fixed in all subsequent invocations of showDefaultValue.


来源: stackexchange

问:
How to change indentation mode in Atom?
I haven't been able to figure this out yet. Atom seems to use spaces as the default indentation mode. I prefer to have tabs instead though. Sublime Text has built in functionality for switching and converting indentation.

Anyone found out how to change the indentation mode of Atom?

Some screenshots from Sublime Text:

答:
If you're using Babel you may also want to make sure to update your "Language Babel" package.  For me, even though I had the Tab Length set to 2 in my core editor settings, the Same setting in the Language Babel config was overriding it with 4.

Atom -> Preferences -> Packages -> (Search for Babel) -> Grammar -> Tab Length

Make sure the appropriate Grammar, There's "Babel ES6 Javascript Grammar", "language-babel-extension Grammar" as well as "Regular Expression".  You probably want to update all of them to be consistent.

ContentLicense: CC BY-SA 3.0

Title: How to change indentation mode in Atom?


问:
Error with pip install MySQL-python
I have been trying for a few days to fix this, looking at other questions but I can't find a question wth the same error that I am getting.

I have been attempting to follow this tutorial https://realpython.com/learn/start-django/ and get to this point:

Database settings
First, install MySQL-python, which is a database connector for Python:

```<code>$ pip install MySQL-python
</code>```

Everything has worked okay up to here but when I try and install MySQL-python I get the following error:

```<code>(env) Camerons-MacBook-Pro:django15_project camrail$ pip install MySQL-python
Collecting MySQL-python
  Using cached MySQL-python-1.2.5.zip
    Complete output from command python setup.py egg_info:
    sh: mysql_config: command not found
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/3v/czm4shrx0yg5jts39qktf6t00000gn/T/pip-build-2rNsQQ/MySQL-python/setup.py", line 17, in <module>
        metadata, options = get_config()
      File "/private/var/folders/3v/czm4shrx0yg5jts39qktf6t00000gn/T/pip-build-2rNsQQ/MySQL-python/setup_posix.py", line 43, in get_config
        libs = mysql_config("libs_r")
      File "/private/var/folders/3v/czm4shrx0yg5jts39qktf6t00000gn/T/pip-build-2rNsQQ/MySQL-python/setup_posix.py", line 25, in mysql_config
        raise EnvironmentError("%s not found" % (mysql_config.path,))
    EnvironmentError: mysql_config not found
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/3v/czm4shrx0yg5jts39qktf6t00000gn/T/pip-build-2rNsQQ/MySQL-python/
(env) Camerons-MacBook-Pro:django15_project camrail$
</code>```

I found this answer https://opensourcehacker.com/2011/03/02/installing-mysql-python-connector-on-osx/ that says the MySQL utilities are not made available, so I followed their advice to fix it but to no avail.  I have also tried installing developer tools xcode-select --install as some have suggested.  I have tried reinstalling ez_setup.

Not really sure where to go from here, any help greatly appreciated.

答:
I run the following commands and it worked smooth in Ubuntu 17.10</p>

```<code>sudo apt-get install libmysqlclient-dev
pip3 install mysqlclient
</code>```

Title: Error with pip install MySQL-python

Body:
I have been trying for a few days to fix this, looking at other questions but I can't find a question wth the same error that I am getting.

I have been attempting to follow this tutorial https://realpython.com/learn/start-django/ and get to this point:

Database settings
First, install MySQL-python, which is a database connector for Python:

$ pip install MySQL-python

Everything has worked okay up to here but when I try and install MySQL-python I get the following error:

(env) Camerons-MacBook-Pro:django15_project camrail$ pip install MySQL-python
Collecting MySQL-python
  Using cached MySQL-python-1.2.5.zip
    Complete output from command python setup.py egg_info:
    sh: mysql_config: command not found
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/3v/czm4shrx0yg5jts39qktf6t00000gn/T/pip-build-2rNsQQ/MySQL-python/setup.py", line 17, in <module>
        metadata, options = get_config()
      File "/private/var/folders/3v/czm4shrx0yg5jts39qktf6t00000gn/T/pip-build-2rNsQQ/MySQL-python/setup_posix.py", line 43, in get_config
        libs = mysql_config("libs_r")
      File "/private/var/folders/3v/czm4shrx0yg5jts39qktf6t00000gn/T/pip-build-2rNsQQ/MySQL-python/setup_posix.py", line 25, in mysql_config
        raise EnvironmentError("%s not found" % (mysql_config.path,))
    EnvironmentError: mysql_config not found
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/3v/czm4shrx0yg5jts39qktf6t00000gn/T/pip-build-2rNsQQ/MySQL-python/
(env) Camerons-MacBook-Pro:django15_project camrail$

I found this answer https://opensourcehacker.com/2011/03/02/installing-mysql-python-connector-on-osx/ that says the MySQL utilities are not made available, so I followed their advice to fix it but to no avail.  I have also tried installing developer tools xcode-select --install as some have suggested.  I have tried reinstalling ez_setup.

Not really sure where to go from here, any help greatly appreciated.

Body:
I run the following commands and it worked smooth in Ubuntu 17.10

sudo apt-get install libmysqlclient-dev
pip3 install mysqlclient


问:
oracle PLSQL- Only provide hour, minute and second from timestamp
Is there a way to only extract HOUR,MINUTES and Seconds from timestamp.. Along with date ofc but i dont want it to show fractional_seconds_precision with it.. So for example when I type the following:

```<code>TO_TIMESTAMP('2017-12-02 05:00:00', 'YYYY-MM-DD HH24:MI:SS')
</code>```

I only want what i specified in the format to be shown, I dont want FF to be shown but whenever I check the output, FF always comes along with it. How do I remove it? Also, I wanted to ask, Is there a way to compare the dates typed using timestamp to be compared with dates typed using TO_DATE? what if I want one to be timestamp and other to be in a TO_DATE format? Thanks

答:
Your question doesn't really make sense, but I understand why you're asking it.

Essentially, you're saying "I have this string "1" but when I parse it as a number it has loads of numbers after the decimal: 1.0000000000000. How can I store it without those extra zeroes"

And the answer is, you can't: 1 and 1.000000000 are the same thing, they're stored the same way, and it's not up to you to decide how it's stored. What you're seeing as an output of 1.000000000 is because you haven't asked for the internal numeric 1 to be output in a particular format (like $1.00), so you're just getting it in the default format for either the database or the query tool you're using

Ultimately, don't worry about it - hiding or showing those zeroes as a developer isn't going to matter a jot. Including them or not when you're querying your timestamp again isn't going to matter. When your front end app is dumping stuff to a report, it should retrieve the timestamp as is from Oracle and do the formatting itself; store $1 as a number 1, not a string "$1". When it comes time to put it on a report, format it as $1.00 in the code that makes the report.

If you're running queries that use the timestamp fields, you can compare with dates just fine... Just remember that dates and timestamps have a time component too, so query them using a range. For example to get all rows whose timestamp is today:

```<code>select * from t where mytimestamp >= trunc(sysdate) and mytimestamp < trunc(sysdate)+1
</code>```

This is better than doing:

```<code>select * from t where trunc(mytimestamp) = trunc(sysdate)
</code>```

Because trunc(mystimestamp) means you're manipulating table data to run your query. Unless you have specifically indexed the output of trunc(mytimestamp) then this query could run like a dog, as an index on mytimestamp column cannot be used if the query calls for table data to be manipulated before it is compared

It may help you to consider that internally, dates are typically stored as the number of days since a certain point in history. Times are fractions of a day. Internally 01-jan-1970 00:00 might be 0, and 01-jan-1970 18:00 i.e. 6pm, is three quarters the way through the day, so it'll be stored as 0.75. 02-jan-1970 would hence be stored as 1. When you use trunc you chop off the decimal part. This is why trunc "removes" the time froma  date. It doesn't "remove" it - you can't remove a time froma  date, because everything that happens, happens at some point in time.. But it does reduce the time component to midnight, so trunc()ing all the adtes in a table effectively makes them all happen at midnight on the day in question.

Oracle can trunc to other things when it comes to dates, like truncing to the start of the month, but for now, remember that internally theyre fractional numbers, query them using ranges (so "between 01 jan 1970 and 02 jan 1970" is really saying "between 0 and 1" - which is what 0.75 i.e 6pm on 01 jan 1970, is)

Body:
Is there a way to only extract HOUR,MINUTES and Seconds from timestamp.. Along with date ofc but i dont want it to show fractional_seconds_precision with it.. So for example when I type the following:

TO_TIMESTAMP('2017-12-02 05:00:00', 'YYYY-MM-DD HH24:MI:SS')

I only want what i specified in the format to be shown, I dont want FF to be shown but whenever I check the output, FF always comes along with it. How do I remove it? Also, I wanted to ask, Is there a way to compare the dates typed using timestamp to be compared with dates typed using TO_DATE? what if I want one to be timestamp and other to be in a TO_DATE format? Thanks

Body:
Your question doesn't really make sense, but I understand why you're asking it.

Essentially, you're saying "I have this string "1" but when I parse it as a number it has loads of numbers after the decimal: 1.0000000000000. How can I store it without those extra zeroes"

And the answer is, you can't: 1 and 1.000000000 are the same thing, they're stored the same way, and it's not up to you to decide how it's stored. What you're seeing as an output of 1.000000000 is because you haven't asked for the internal numeric 1 to be output in a particular format (like $1.00), so you're just getting it in the default format for either the database or the query tool you're using

Ultimately, don't worry about it - hiding or showing those zeroes as a developer isn't going to matter a jot. Including them or not when you're querying your timestamp again isn't going to matter. When your front end app is dumping stuff to a report, it should retrieve the timestamp as is from Oracle and do the formatting itself; store $1 as a number 1, not a string "$1". When it comes time to put it on a report, format it as $1.00 in the code that makes the report.

If you're running queries that use the timestamp fields, you can compare with dates just fine... Just remember that dates and timestamps have a time component too, so query them using a range. For example to get all rows whose timestamp is today:

select * from t where mytimestamp >= trunc(sysdate) and mytimestamp < trunc(sysdate)+1

This is better than doing:

select * from t where trunc(mytimestamp) = trunc(sysdate)

Because trunc(mystimestamp) means you're manipulating table data to run your query. Unless you have specifically indexed the output of trunc(mytimestamp) then this query could run like a dog, as an index on mytimestamp column cannot be used if the query calls for table data to be manipulated before it is compared

It may help you to consider that internally, dates are typically stored as the number of days since a certain point in history. Times are fractions of a day. Internally 01-jan-1970 00:00 might be 0, and 01-jan-1970 18:00 i.e. 6pm, is three quarters the way through the day, so it'll be stored as 0.75. 02-jan-1970 would hence be stored as 1. When you use trunc you chop off the decimal part. This is why trunc "removes" the time froma  date. It doesn't "remove" it - you can't remove a time froma  date, because everything that happens, happens at some point in time.. But it does reduce the time component to midnight, so trunc()ing all the adtes in a table effectively makes them all happen at midnight on the day in question.

Oracle can trunc to other things when it comes to dates, like truncing to the start of the month, but for now, remember that internally theyre fractional numbers, query them using ranges (so "between 01 jan 1970 and 02 jan 1970" is really saying "between 0 and 1" - which is what 0.75 i.e 6pm on 01 jan 1970, is)


问:
rspec - rails routes to wrong controller when using namespaces but only sometimes
Please bear with me, I've tried a lot of things before posting this and I'm not sure what exactly you need to be able to help me with this. Just let me know and I'll update the code.

I have an issue with randomly failing specs so I ran the --bisect command with rspec to find out why the specs are failing.
It seems that if I run 2 specs in a certain order the specs fails.

The command I'm running is this:

```<code>be rspec './spec/features/scheduling/scheduler_spec.rb[1:3:1,1:3:2:1,1:3:2:2:1,1:3:2:2:2,1:3:3,1:3:4,1:3:5,1:3:6]' './spec/requests/api/v1/shifts_spec.rb[1:1:2]' --seed 16251
</code>```

The routing engine seem to think that the following link should go to the Api::ShifsController when it instead should go to ShiftsController:

```<code>= link_to new_shift_path(date: date.to_date, user_id: user.try(:id)), remote: true do
    = fa_icon "plus fw"
</code>```

routes:

```<code>Rails.application.routes.draw do
  root 'landing_page#index'
  ..
  resources :shifts, only: [:new, :create, :destroy]
  # API
  namespace :api, defaults: { format: 'json' } do
    scope :v1 do
      resources :locations, only: [:index] do
        resources :shifts, only: [:index]
      end
    end
  end
</code>```

Gemfile:

```<code>ruby '2.4.1'
..
gem 'rails', '~> 5.0.2'
gem 'capybara', '~> 2.16'
gem 'selenium-webdriver', '~> 3.7.0'
..
</code>```

The error I'm getting is this:

```<code>Failure/Error: raise ActionNotFound, "The action '#{action}' could not be found for #{self.class.name}"
AbstractController::ActionNotFound:
The action 'new' could not be found for Api::ShiftsController
</code>```

Note! This only happens sometimes when running the specs. It never happens in development or in production. Well, I haven't experienced yet.
If I comment out the line resources :shifts, only: [:new, :create, :destroy] from the routes file, everything goes back to normal.
I have no idea how to proceed.

答:
This is probably caused by Rails autoloading getting confused between ShiftsController and API::ShiftsController (or Shifts and API::Shifts models if they exist) depending on which is used first in a test, and then thinking it doesn't need to load the other.  To fix this try requiring the specific controller and/or model definition files, being used in each spec, at the top of the spec files.

Like this:

```<code># spec/features/scheduling/scheduler_spec.rb
require "#{Rails.root}/app/controllers/shifts_controller"

# spec/features/api/shifts_spec.rb
require "#{Rails.root}/app/controllers/api/shifts_controller"
</code>```

Body:
Please bear with me, I've tried a lot of things before posting this and I'm not sure what exactly you need to be able to help me with this. Just let me know and I'll update the code.

I have an issue with randomly failing specs so I ran the --bisect command with rspec to find out why the specs are failing.
It seems that if I run 2 specs in a certain order the specs fails.

The command I'm running is this:

be rspec './spec/features/scheduling/scheduler_spec.rb[1:3:1,1:3:2:1,1:3:2:2:1,1:3:2:2:2,1:3:3,1:3:4,1:3:5,1:3:6]' './spec/requests/api/v1/shifts_spec.rb[1:1:2]' --seed 16251

The routing engine seem to think that the following link should go to the Api::ShifsController when it instead should go to ShiftsController:

= link_to new_shift_path(date: date.to_date, user_id: user.try(:id)), remote: true do
    = fa_icon "plus fw"

routes:

Rails.application.routes.draw do
  root 'landing_page#index'
  ..
  resources :shifts, only: [:new, :create, :destroy]
  # API
  namespace :api, defaults: { format: 'json' } do
    scope :v1 do
      resources :locations, only: [:index] do
        resources :shifts, only: [:index]
      end
    end
  end

Gemfile:

ruby '2.4.1'
..
gem 'rails', '~> 5.0.2'
gem 'capybara', '~> 2.16'
gem 'selenium-webdriver', '~> 3.7.0'
..

The error I'm getting is this:

Failure/Error: raise ActionNotFound, "The action '#{action}' could not be found for #{self.class.name}"
AbstractController::ActionNotFound:
The action 'new' could not be found for Api::ShiftsController

Note! This only happens sometimes when running the specs. It never happens in development or in production. Well, I haven't experienced yet.
If I comment out the line resources :shifts, only: [:new, :create, :destroy] from the routes file, everything goes back to normal.
I have no idea how to proceed.

Body:
This is probably caused by Rails autoloading getting confused between ShiftsController and API::ShiftsController (or Shifts and API::Shifts models if they exist) depending on which is used first in a test, and then thinking it doesn't need to load the other.  To fix this try requiring the specific controller and/or model definition files, being used in each spec, at the top of the spec files.

Like this:

# spec/features/scheduling/scheduler_spec.rb
require "#{Rails.root}/app/controllers/shifts_controller"

# spec/features/api/shifts_spec.rb
require "#{Rails.root}/app/controllers/api/shifts_controller"


问:
Exposing Swagger-UI documentation through Google Cloud Endpoints
I am trying to publish my API docs in the same Nodejs application as my API, using Google Cloud Endpoints.

It looks easy following this guide:
Adding Swagger UI

The tricky part is exposing the /docs path via Google Cloud Endpoints (it also uses the same openapi.yaml).

I have tried defining the /docs path in my openapi.yaml like this:

```<code>"/docs":
    get:
      description: "Swagger UI API documentation"
      operationId: "docs"
      produces:
        - "text/html"
      responses:
        200:
          description: "Swagger UI"
</code>```

The HTML page itself gets served but any assets like swagger-ui.css are not found.

It looks to me I am doing this wrong, as documentation is not an API endpoint. However I haven't been able to find a nice solution. Is there a way to proxy all traffic for /docs path?

答: I think you're going to find that there is no nice way of doing this. Your best bet is going to be to break off documentation publishing as a separate step in your deployment pipeline. That, or wait 6 months. Google Cloud is evolving rapidly and they've probably got this on their roadmap.</p>

Body:
I am trying to publish my API docs in the same Nodejs application as my API, using Google Cloud Endpoints.

It looks easy following this guide:
Adding Swagger UI

The tricky part is exposing the /docs path via Google Cloud Endpoints (it also uses the same openapi.yaml).

I have tried defining the /docs path in my openapi.yaml like this:

"/docs":
    get:
      description: "Swagger UI API documentation"
      operationId: "docs"
      produces:
        - "text/html"
      responses:
        200:
          description: "Swagger UI"

The HTML page itself gets served but any assets like swagger-ui.css are not found.

It looks to me I am doing this wrong, as documentation is not an API endpoint. However I haven't been able to find a nice solution. Is there a way to proxy all traffic for /docs path?


问:
How to avoid multiple implementation of class functions
I am new to C++ and hence need some help.
Here is the code:

```<code>class InterfaceVehicle
{
  virtual int door() = 0;
  virtual int seats() = 0;
  virtual int enginepower() = 0;
}
class minicar: public InterfaceVehicle
{
    int door () {return 4;}
    int seats () {return 2;}
    int enginepower () {return 10;}
}

class bigcar: public InterfaceVehicle
{
    int door () {return 4;}
    int seats () {return 5;}
    int engine () {return 20;}
}

class truck: public InterfaceVehicle
{
    int door () {return 2;}
    int seats () {return 1;}
    int engine () {return 50;}
}
</code>```

I have an interface base class named Vehicle and three different classes that implements all the functions of the interface class. Here i want to avoid the same implementation of the door function.
I got some suggestions to have a new class that implements this door function and this class will be aggregated into bigcar and minicar. This way i can avoid this copy paste implementation of door(); I like this idea!

Can some please give an example on how i can implement that?
I read a lot about aggregation but did not understand how to implement that in my case.

答:
I don't have the reputation to comment yet so I'm adding this as an answer instead.

Look at this stackoverflow answer: How to call a parent class function from derived class function?

You'll want to create a parent class that implements your interface and defines door but leaves the other two functions as virtual functions. Then inherit that class and define the rest of the functions in the child classes.  You can then call the door function in the parent class from the child classes.

Body:
I am new to C++ and hence need some help.
Here is the code:

class InterfaceVehicle
{
  virtual int door() = 0;
  virtual int seats() = 0;
  virtual int enginepower() = 0;
}
class minicar: public InterfaceVehicle
{
    int door () {return 4;}
    int seats () {return 2;}
    int enginepower () {return 10;}
}

class bigcar: public InterfaceVehicle
{
    int door () {return 4;}
    int seats () {return 5;}
    int engine () {return 20;}
}

class truck: public InterfaceVehicle
{
    int door () {return 2;}
    int seats () {return 1;}
    int engine () {return 50;}
}

I have an interface base class named Vehicle and three different classes that implements all the functions of the interface class. Here i want to avoid the same implementation of the door function.
I got some suggestions to have a new class that implements this door function and this class will be aggregated into bigcar and minicar. This way i can avoid this copy paste implementation of door(); I like this idea!

Can some please give an example on how i can implement that?
I read a lot about aggregation but did not understand how to implement that in my case.


问:
node and reactjs axios server request returning index.html file instead of json
I have setup my project with a react frontend being compiled by webpack and the server running on node and express.

When I deploy to production my requests to the server are returning the index.html file in the 'dist' folder rather than the json with the data.

My webpack compiled output is at the location ./dist.

Here is the routing part of my server.js file:

```<code>if (process.env.NODE_ENV === 'production') {
  app.use(express.static('dist'));
  const path = require('path');
  app.get('/', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
  });
}
// Use our router configuration when we call /
app.use('/', router);
</code>```

Here is part of my webpack config file:

```<code>var HtmlWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
  template: __dirname + '/client/index.html',
  filename: 'index.html',
  inject: 'body'
});

module.exports = {
  entry: [
    './client/index.js'
  ],
  output: {
    path: __dirname + '/dist',
    filename: 'index_bundle.js'
  },
  devServer: {
    inline: true,
    contentBase: './dist',
    port: 8080,
    proxy: { '/api/**': { target: 'http://localhost:3000', secure: false } }
  },
  module: {
    loaders: [
      {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: {presets: ['es2015','react'], plugins: ['transform-es2015-destructuring', 'transform-object-rest-spread']}},
        {test: /\.jpe?g$|\.gif$|\.svg$|\.png$/i, loader: 'file-loader?name=/images/[name].[ext]'},
        {test: /\.css$/, loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader','resolve-url-loader']},
        {test: /\.scss$/, loaders: ['style-loader', 'css-loader','postcss-loader', 'sass-loader','resolve-url-loader']}
        ]
  },
  plugins: [HTMLWebpackPluginConfig]
};
</code>```

My request is as follows (the api route /api/chefs returns a json with user profiles (tested in development):

```<code>export function listChefs() {
  return function (dispatch) {
    axios.get('/api/chefs')
      .then((response) => {
        dispatch({
          type: LIST_CHEFS,
          payload: response.data
        });
      })
      .catch((err) => {
        errorHandler(dispatch, 'There was a problem. Please refresh and try again.');
      });
  };
}
</code>```

It seems as though the call that I am making from my client using axios is actually hitting the api url that isn't being recognised and therefore is being redirected to simply server the index.html file.

Any help?

Cheers

答:
perhaps this is the offending line:

```<code>app.get('/*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
});
</code>```

becuase this catches all your requests. If you change /* to / does that fix it?

I think the request can't make it to your router because /* catches all requests and returns the index.html page.

try:

```<code>app.get('/', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
});
</code>```

Body:
I have setup my project with a react frontend being compiled by webpack and the server running on node and express.

When I deploy to production my requests to the server are returning the index.html file in the 'dist' folder rather than the json with the data.

My webpack compiled output is at the location ./dist.

Here is the routing part of my server.js file:

if (process.env.NODE_ENV === 'production') {
  app.use(express.static('dist'));
  const path = require('path');
  app.get('/', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
  });
}
// Use our router configuration when we call /
app.use('/', router);

Here is part of my webpack config file:

var HtmlWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
  template: __dirname + '/client/index.html',
  filename: 'index.html',
  inject: 'body'
});

module.exports = {
  entry: [
    './client/index.js'
  ],
  output: {
    path: __dirname + '/dist',
    filename: 'index_bundle.js'
  },
  devServer: {
    inline: true,
    contentBase: './dist',
    port: 8080,
    proxy: { '/api/**': { target: 'http://localhost:3000', secure: false } }
  },
  module: {
    loaders: [
      {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: {presets: ['es2015','react'], plugins: ['transform-es2015-destructuring', 'transform-object-rest-spread']}},
        {test: /\.jpe?g$|\.gif$|\.svg$|\.png$/i, loader: 'file-loader?name=/images/[name].[ext]'},
        {test: /\.css$/, loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader','resolve-url-loader']},
        {test: /\.scss$/, loaders: ['style-loader', 'css-loader','postcss-loader', 'sass-loader','resolve-url-loader']}
        ]
  },
  plugins: [HTMLWebpackPluginConfig]
};

My request is as follows (the api route /api/chefs returns a json with user profiles (tested in development):

export function listChefs() {
  return function (dispatch) {
    axios.get('/api/chefs')
      .then((response) => {
        dispatch({
          type: LIST_CHEFS,
          payload: response.data
        });
      })
      .catch((err) => {
        errorHandler(dispatch, 'There was a problem. Please refresh and try again.');
      });
  };
}

It seems as though the call that I am making from my client using axios is actually hitting the api url that isn't being recognised and therefore is being redirected to simply server the index.html file.

Any help?

Cheers

Body:
perhaps this is the offending line:

app.get('/*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
});

becuase this catches all your requests. If you change /* to / does that fix it?

I think the request can't make it to your router because /* catches all requests and returns the index.html page.

try:

app.get('/', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
});


问:
How to display two local images side by side in jupyter?
I want to display two images, that I have them saved locally, in one single makedown cell side-by-side?  I found previous post but it uses HTML() not Image() method.

The way I tried was:

```<code>from IPython.core.display import Image, display
display(Image('/whateverfile/counts1.png',width=100,height=100), Image('/whateverfile/counts2',width=100, height=100))
</code>```

But that did not work.

Any ideas how to solve this?

Thanks

答:
```<code>from IPython.display import HTML, display
display(HTML("<table><tr><td><img src='/image/counts1.png'></td><td><img src='/image/counts2'></td></tr></table>"))
</code>```

Set other parameters as you like.

Or maybe using nbextensions and splitting the cell in two (having 2 outputs side by side) would fit your needs?

Body:
I want to display two images, that I have them saved locally, in one single makedown cell side-by-side?  I found previous post but it uses HTML() not Image() method.

The way I tried was:

from IPython.core.display import Image, display
display(Image('/whateverfile/counts1.png',width=100,height=100), Image('/whateverfile/counts2',width=100, height=100))

But that did not work.

Any ideas how to solve this?

Thanks

Body:
from IPython.display import HTML, display
display(HTML("<table><tr><td><img src='/image/counts1.png'></td><td><img src='/image/counts2'></td></tr></table>"))

Set other parameters as you like.

Or maybe using nbextensions and splitting the cell in two (having 2 outputs side by side) would fit your needs?


问:
Subclass UISlider: override or disable built-in haptic feedback?
I have a subclass of UISlider and I wish to override (specifically, disable) the built-in haptic feedback that it generates whenever the thumb reaches the ends of the track. I have my own methods of feedback that I have put into it and they obviously conflict.

I almost always post code with my question but I don't know if that would be of any use because I don't know where this would be done if it's even possible (without creating a slider from absolute scratch by subclassing UIControl). I can post the entire slider subclass but that doesn't seem like it would help but I will if asked.

答: This does not appear to be possible. I would checkout some open source copies of UISlider or build your own from scratch. I have built them from scratch before and they are not too complicated. Here is a list of some open source implementations.</p>


问:
ArcGIS runtime for WPF - A missing assembly reference?
I have installed the ArcGIS Runtime SDK for .NET (100.1.0)

I created a WPF app from the ArcGIS template (that should come with all the necessary assembly references...).

I have a "MapView" (my XAML file) containing a map to which I would simply like to add a layer to. I used the example from the API documentation. My XAML is as follows:

```<code><Page x:Class="WpfApplication1.Views.MapView"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:local="clr-namespace:WpfApplication1.Views"
  xmlns:esri="http://schemas.esri.com/arcgis/runtime/2013"
  mc:Ignorable="d"
  d:DesignHeight="300" d:DesignWidth="300"
  Title="MapView">

<Grid>
    <Grid.Resources>
        <esri:SimpleLineSymbol x:Key="SLS" Color="Transparent" Width="1"/>
        <esri:SimpleLineSymbol x:Key="BlackSLS" Color="Black" Width="1"/>
    </Grid.Resources>
    <Grid>
        <esri:MapView x:Name="MyMapView" />
    </Grid>
</Grid>
</Page>
</code>```

In code behind, I do the following after calling the InitializeComponent() method:

```<code>LocalMapService localMapService = new LocalMapService(@"..\..\..\samples-data\maps\water-distribution-network.mpk");
await localMapService.StartAsync();

ArcGISDynamicMapServiceLayer arcGISDynamicMapServiceLayer = new
ArcGISDynamicMapServiceLayer()
{
    ID = "arcGISDynamicMapServiceLayer",
    ServiceUri = localMapService.UrlMapService,
};

MyMapView.Map.Layers.Add(arcGISDynamicMapServiceLayer);
</code>```

At this point Visual Studio warns me "Map does not contain a definition of layer [...] are you missing a using directive or assembly reference?"

If I instead decide to add my layer directly from the XAML without writing any code behind:

```<code> <Page x:Class="WpfApplication1.Views.MapView"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:local="clr-namespace:WpfApplication1.Views"
  xmlns:esri="http://schemas.esri.com/arcgis/runtime/2013"
  mc:Ignorable="d"
  d:DesignHeight="300" d:DesignWidth="300"
  Title="MapView">

<Grid>
    <Grid.Resources>
        <esri:SimpleLineSymbol x:Key="SLS" Color="Transparent" Width="1"/>
        <esri:SimpleLineSymbol x:Key="BlackSLS" Color="Black" Width="1"/>
    </Grid.Resources>
    <Grid>
        <esri:MapView x:Name="MyMapView">`enter code here`
            <esri:Map>
                <esri:ArcGISDynamicMapServiceLayer Url=... />
            </esri:Map>
        </esri:MapView>
    </Grid>
</Grid>
</Page>
</code>```

The designer now warns "the name ArcGISDynamicMapServiceLayer does not exist in namespace http://schemas.esri.com/arcgis/runtime/2013"

What am I doing wrong? It looks I'm not loading all the appropriate components of the API even though I'm using the SDK's WPF template... I'm confused.

I'm running Visual Studio 2015 Update 2 on MS Windows Server 2012 (if that is of any relevance!)

答: The code that you are using is for 10.2 version of the ArcGIS Runtime for .NET. You can see https://developers.arcgis.com/net/latest/wpf/guide/local-server.htm how to work with the local server in 100.1 release.</p>

Body:
I have installed the ArcGIS Runtime SDK for .NET (100.1.0)

I created a WPF app from the ArcGIS template (that should come with all the necessary assembly references...).

I have a "MapView" (my XAML file) containing a map to which I would simply like to add a layer to. I used the example from the API documentation. My XAML is as follows:

<Page x:Class="WpfApplication1.Views.MapView"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:local="clr-namespace:WpfApplication1.Views"
  xmlns:esri="http://schemas.esri.com/arcgis/runtime/2013"
  mc:Ignorable="d"
  d:DesignHeight="300" d:DesignWidth="300"
  Title="MapView">

<Grid>
    <Grid.Resources>
        <esri:SimpleLineSymbol x:Key="SLS" Color="Transparent" Width="1"/>
        <esri:SimpleLineSymbol x:Key="BlackSLS" Color="Black" Width="1"/>
    </Grid.Resources>
    <Grid>
        <esri:MapView x:Name="MyMapView" />
    </Grid>
</Grid>
</Page>

In code behind, I do the following after calling the InitializeComponent() method:

LocalMapService localMapService = new LocalMapService(@"..\..\..\samples-data\maps\water-distribution-network.mpk");
await localMapService.StartAsync();

ArcGISDynamicMapServiceLayer arcGISDynamicMapServiceLayer = new
ArcGISDynamicMapServiceLayer()
{
    ID = "arcGISDynamicMapServiceLayer",
    ServiceUri = localMapService.UrlMapService,
};

MyMapView.Map.Layers.Add(arcGISDynamicMapServiceLayer);

At this point Visual Studio warns me "Map does not contain a definition of layer [...] are you missing a using directive or assembly reference?"

If I instead decide to add my layer directly from the XAML without writing any code behind:

 <Page x:Class="WpfApplication1.Views.MapView"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:local="clr-namespace:WpfApplication1.Views"
  xmlns:esri="http://schemas.esri.com/arcgis/runtime/2013"
  mc:Ignorable="d"
  d:DesignHeight="300" d:DesignWidth="300"
  Title="MapView">

<Grid>
    <Grid.Resources>
        <esri:SimpleLineSymbol x:Key="SLS" Color="Transparent" Width="1"/>
        <esri:SimpleLineSymbol x:Key="BlackSLS" Color="Black" Width="1"/>
    </Grid.Resources>
    <Grid>
        <esri:MapView x:Name="MyMapView">`enter code here`
            <esri:Map>
                <esri:ArcGISDynamicMapServiceLayer Url=... />
            </esri:Map>
        </esri:MapView>
    </Grid>
</Grid>
</Page>

The designer now warns "the name ArcGISDynamicMapServiceLayer does not exist in namespace http://schemas.esri.com/arcgis/runtime/2013"

What am I doing wrong? It looks I'm not loading all the appropriate components of the API even though I'm using the SDK's WPF template... I'm confused.

I'm running Visual Studio 2015 Update 2 on MS Windows Server 2012 (if that is of any relevance!)


问:
fancyBox3 trigger an iframe
In a old fancyboxversion i open a iframe with this code

```<code>$.fancybox({
                'padding':  20,
                'width':    '650px',
                'type':     'iframe',
                'href':     '....php?anchor=' + xyz,
                'autoDimensions': true,
                'autoScale': true,
                'centerOnScroll': true,
                'scrolling'     : 'no',
                afterClose : function(){
                    location.reload();
                }
            });
</code>```

in a new version is it not possible.
Any ideas?

答:
Just take a look at docs/API. It would be like this:

```<code>$.fancybox.open({
    src : 'https://codepen.io/',
    type : 'iframe',
    opts : {
        iframe : {
            css : {
                width: '500px'
            },
            attr : {
                scrolling : 'no'
            }
        },
        afterClose : function() {
            alert('done!');
        }
    }
});
</code>```

Demo - https://codepen.io/anon/pen/BmbmJX?editors=1010

Title: fancyBox3 trigger an iframe

Body:
In a old fancyboxversion i open a iframe with this code

$.fancybox({
                'padding':  20,
                'width':    '650px',
                'type':     'iframe',
                'href':     '....php?anchor=' + xyz,
                'autoDimensions': true,
                'autoScale': true,
                'centerOnScroll': true,
                'scrolling'     : 'no',
                afterClose : function(){
                    location.reload();
                }
            });

in a new version is it not possible.
Any ideas?

Body:
Just take a look at docs/API. It would be like this:

$.fancybox.open({
    src : 'https://codepen.io/',
    type : 'iframe',
    opts : {
        iframe : {
            css : {
                width: '500px'
            },
            attr : {
                scrolling : 'no'
            }
        },
        afterClose : function() {
            alert('done!');
        }
    }
});

Demo - https://codepen.io/anon/pen/BmbmJX?editors=1010


问:
VS2010 C++ variadic template example
I have a class template and I can't seem to figure out how to perform a Variadic Template style instantiation.

Here is the "code" so far of what I'm looking for:

```<code>template<typename _Classname, typename... Args>
class CFunctorStartExT
{
  friend class CXXFactory;
protected:
  template<typename U>
  CFunctorStartExT(typename U& _functor, Args&... args) :
    m_Functor(_functor),
    m_args(args)
  {
  }
  virtual bool ProcessLoop(CSomeClass* pThread)
  {
    return m_Functor(pThread, m_args);
  }

protected:
  _Classname& m_Functor;
  Args... m_args;
};
</code>```

Obviously this won't compile :). The idea is to create a class that can store the values passed in (if any.. it might just have _Classname/U defined) on the constructor so they can be retrieved later to pass to m_Functor in another function.

First: can Variadic Template even be done in VS2010? I am getting compile problems just with the template declaration error C2143: syntax error : missing ',' before '...' from the line template<typename _Classname, typename... Args>

Second, can what I am trying to accomplish be done? Thanks!

答: Visual C++ 2010 does not support variadic templates.</p>

ContentLicense: CC BY-SA 2.5

Title: VS2010 C++ variadic template example

Body:
I have a class template and I can't seem to figure out how to perform a Variadic Template style instantiation.

Here is the "code" so far of what I'm looking for:

template<typename _Classname, typename... Args>
class CFunctorStartExT
{
  friend class CXXFactory;
protected:
  template<typename U>
  CFunctorStartExT(typename U& _functor, Args&... args) :
    m_Functor(_functor),
    m_args(args)
  {
  }
  virtual bool ProcessLoop(CSomeClass* pThread)
  {
    return m_Functor(pThread, m_args);
  }

protected:
  _Classname& m_Functor;
  Args... m_args;
};

Obviously this won't compile :). The idea is to create a class that can store the values passed in (if any.. it might just have _Classname/U defined) on the constructor so they can be retrieved later to pass to m_Functor in another function.

First: can Variadic Template even be done in VS2010? I am getting compile problems just with the template declaration error C2143: syntax error : missing ',' before '...' from the line template<typename _Classname, typename... Args>

Second, can what I am trying to accomplish be done? Thanks!


问:
realm permit -g not limiting login groups
I've set up a Raspberry Pi 2 b with a Fedora 23 distro, I've been able to successfully join to our active directory domain using realmd's realm join. I am attempting to limit who may log in by active directory group. After running:

```<code># realm permit -g adgroup@domain
</code>```

Anyone with a domain account is able to log in regardless of if they are members of the group.  I've run realm list and verified the login-policy is set to allow-permitted-logins and the desired group is part of permitted-groups.

The specific linux distro is Fedora-23-remix-rpi2-xfce-1-raw

If anyone else has run into this problem, I would greatly appreciate the help.

答:
As Rajneesh Gadge said you would have to deny first.

Then the good behaviour will be with the right ad group name.

For example, in AD the group "Domain Administrators" will be catched with :

```<code>realm permit --groups domain\ admins
</code>```

And does not work with : realm permit --groups Domain\ Administrators

BTW I don't really know how to retrieve this "short name" for groups...

Body:
I've set up a Raspberry Pi 2 b with a Fedora 23 distro, I've been able to successfully join to our active directory domain using realmd's realm join. I am attempting to limit who may log in by active directory group. After running:

# realm permit -g adgroup@domain

Anyone with a domain account is able to log in regardless of if they are members of the group.  I've run realm list and verified the login-policy is set to allow-permitted-logins and the desired group is part of permitted-groups.

The specific linux distro is Fedora-23-remix-rpi2-xfce-1-raw

If anyone else has run into this problem, I would greatly appreciate the help.

Body:
As Rajneesh Gadge said you would have to deny first.

Then the good behaviour will be with the right ad group name.

For example, in AD the group "Domain Administrators" will be catched with :

realm permit --groups domain\ admins

And does not work with : realm permit --groups Domain\ Administrators

BTW I don't really know how to retrieve this "short name" for groups...


问:
How can a call to suprocess.checkoutput() return nothing when I just echo a string
In python, I try to run some command but I can't get it work, to sum up here is a script that should execute four simple commands via subproscess, store theirs respective outputs and then display them.

```<code>#!/usr/bin/python
import subprocess

output_1 = None
output_2 = None
output_3 = None
output_4 = None

print "Start"
try:
    output_1 = subprocess.check_output(["ls", "-al"], shell=True, stderr=subprocess.STDOUT)
    output_2 = subprocess.check_output(["echo", "'Hi'"], shell=True, stderr=subprocess.STDOUT)
    output_3 = subprocess.check_output(["echo", "\"Hi\""], shell=True, stderr=subprocess.STDOUT)
    output_4 = subprocess.check_output(["echo", "Hi"], shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as ex:
    print "Command '%s' return exit code %s:\n\n%s" % (ex.cmd, ex.returncode, ex.output)

print "Out 1: '%s'" % output_1
print "Out 2: '%s'" % output_2
print "Out 3: '%s'" % output_3
print "Out 4: '%s'" % output_4
</code>```

I do not undestand why there is no 'Hi' in my outputs... Here is the output I get:

```<code>Start
Out 1: '
test
undefined10_error.png
undefined20_error.png
undefined35_error.png
undefined40_error.png
'
Out 2: '
'
Out 3: '
'
Out 4: '
'
</code>```

答:
By passing the shell=True argument, you are telling the interpreter to execute the command as a single string. This means that the first argument needs to be a string. If you look at the output of your first command you'll notice that you're not getting the flags am, but just a standard ls.

If you want to use shell=True, pass the argument as a str:

```<code>> subprocess.check_output("echo 'Hello World!'", shell=True, stderr=subprocess.STDOUT)
b'Hello World!\n'
</code>```

If you're planning on using variables, you'll need to escape them yourself with shelex.quote.

To use a local variable:

```<code>>>> import shlex
>>> local_variable = 'Hi \'world"'
>>> command = 'echo {}'.format(shlex.quote(local_variable))
>>> subprocess.check_output(command,shell=True, stderr=subprocess.STDOUT)
b'Hi \'world"\n'
</code>```

Body:
In python, I try to run some command but I can't get it work, to sum up here is a script that should execute four simple commands via subproscess, store theirs respective outputs and then display them.

#!/usr/bin/python
import subprocess

output_1 = None
output_2 = None
output_3 = None
output_4 = None

print "Start"
try:
    output_1 = subprocess.check_output(["ls", "-al"], shell=True, stderr=subprocess.STDOUT)
    output_2 = subprocess.check_output(["echo", "'Hi'"], shell=True, stderr=subprocess.STDOUT)
    output_3 = subprocess.check_output(["echo", "\"Hi\""], shell=True, stderr=subprocess.STDOUT)
    output_4 = subprocess.check_output(["echo", "Hi"], shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as ex:
    print "Command '%s' return exit code %s:\n\n%s" % (ex.cmd, ex.returncode, ex.output)

print "Out 1: '%s'" % output_1
print "Out 2: '%s'" % output_2
print "Out 3: '%s'" % output_3
print "Out 4: '%s'" % output_4

I do not undestand why there is no 'Hi' in my outputs... Here is the output I get:

Start
Out 1: '
test
undefined10_error.png
undefined20_error.png
undefined35_error.png
undefined40_error.png
'
Out 2: '
'
Out 3: '
'
Out 4: '
'

Body:
By passing the shell=True argument, you are telling the interpreter to execute the command as a single string. This means that the first argument needs to be a string. If you look at the output of your first command you'll notice that you're not getting the flags am, but just a standard ls.

If you want to use shell=True, pass the argument as a str:

> subprocess.check_output("echo 'Hello World!'", shell=True, stderr=subprocess.STDOUT)
b'Hello World!\n'

If you're planning on using variables, you'll need to escape them yourself with shelex.quote.

To use a local variable:

>>> import shlex
>>> local_variable = 'Hi \'world"'
>>> command = 'echo {}'.format(shlex.quote(local_variable))
>>> subprocess.check_output(command,shell=True, stderr=subprocess.STDOUT)
b'Hi \'world"\n'


问:
How to implement “select all” check box
i have invoice page and customer select the invoice and pay. invoice page if invoices are multiple then customer need to select check box each then click on Generate Invoice for payment. i want if invoice are multiple customer should check All then its work customer dont have choice select single. he should select All the check boxes then its work.

i think on page javascript code is below:

```<code><script language="JavaScript">

function checkAll(theForm, cName) {
  for (i=0,n=theForm.elements.length;i<n;i++)
    if (theForm.elements[i].className.indexOf(cName) !=-1)
      if (theForm.elements[i].checked == true) {
        theForm.elements[i].checked = false;
      } else {
        theForm.elements[i].checked = true;
      }
}
</script>
</code>```

on invoice page i have also option select All check box
 code is below:

```<code><input type="checkbox" name="kk" id="kk"  onClick="checkAll(document.getElementById('form4'), 'chk1');" >
</code>```

when invoice are more multiple from database check code is:

```<code><input name="orderNo[]" <?php  if ($SQLRow["priceStatus"]=="Received") { ?> disabled="disabled"<?php } ?> type="checkbox" id="orderNo[]" value="<?php echo $SQLRow["orderNo"];?>" class="chk1" />
</code>```

i just want one help if all the check boxes are selected then its work.

答:
Try this

```<code>$('#kk').on('click', function() {
   if($(this).prop("checked")){
            $('input:checkbox').each(function() {
                $(this).attr("checked", "checked");
                $(this).prop("checked", true);

            });
        }
        else{
            $('input:checkbox').each(function() {
                $(this).removeAttr("checked", "checked");
                $(this).prop("checked", false);
            });
        }
});
</code>```

Jsfiddle is here

Title: How to implement “select all” check box

Body:
i have invoice page and customer select the invoice and pay. invoice page if invoices are multiple then customer need to select check box each then click on Generate Invoice for payment. i want if invoice are multiple customer should check All then its work customer dont have choice select single. he should select All the check boxes then its work.

i think on page javascript code is below:

on invoice page i have also option select All check box
 code is below:

<input type="checkbox" name="kk" id="kk"  onClick="checkAll(document.getElementById('form4'), 'chk1');" >

when invoice are more multiple from database check code is:

<input name="orderNo[]" <?php  if ($SQLRow["priceStatus"]=="Received") { ?> disabled="disabled"<?php } ?> type="checkbox" id="orderNo[]" value="<?php echo $SQLRow["orderNo"];?>" class="chk1" />

i just want one help if all the check boxes are selected then its work.

Body:
Try this

$('#kk').on('click', function() {
   if($(this).prop("checked")){
            $('input:checkbox').each(function() {
                $(this).attr("checked", "checked");
                $(this).prop("checked", true);

            });
        }
        else{
            $('input:checkbox').each(function() {
                $(this).removeAttr("checked", "checked");
                $(this).prop("checked", false);
            });
        }
});

Jsfiddle is here


问:
ASP.NET MVC - adding action filters programmatically
I've been doing a bit of research regarding action filters and wondered if there was a way to add them programmatically to controllers??

To give some context, I'd like to add a logging filter if logging is configured in the web.config, otherwise I don't want the filter to exist in the execution chain of each action method.

I appreciate I can put a check in the actual filter code itself to see if logging is enabled but don't want to have to do this is possible.

Many thanks!

答:
A better solution would be to use the null object pattern.

Your filter would log normally (its job is to log, not to decide how to log or what to log to, necessarily), but by default the actual logger would be an implementation that does nothing.  If it's configured, the logger instance will be an implementation that logs as configured.

A simple factory could make the decision of which logger implementation to deliver to the filter or any IOC container could be configured to handle it.

OwnerDisplayName: Tim Peel

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: Matt Hinze


问:
Overriding class variables in python
I'm trying to understand a bit how Python (2.6) deals with class, instances and so on, and at a certain point, I tried this code:

```<code>#/usr/bin/python2.6

class Base(object):
    default = "default value in base"

    def __init__(self):
        super(Base, self).__init__()

    @classmethod
    def showDefaultValue(cls, defl = default):
        print "defl == %s" % (defl)

class Descend(Base):
    default = "default value in descend"

    def __init__(self):
        super(Descend, self).__init__()

if __name__ == "__main__":
    Descend.showDefaultValue()
</code>```

The output is: "default value in base"

I was wondering why the "default" field is not overwirtten by the Descend class... Is there any way to overwrite it? Why isn't it being overwritten?

Any hint (or link to an explanatory page will be appreciated). Thank you!

答:
```<code>def showDefaultValue(cls, defl=default):
</code>```

means that default gets evaluated when the function is defined, as usual in Python. So the definition looks like this then:

```<code>def showDefaultValue(cls, defl="default value in base"):
</code>```

This value of defl is stored as a default argument on the function object and used when you call the method without arguments. You can look at the defaults of a function like print Descend.showDefaultValue.im_self.default to validate this.

If you want to get the default from the current class then you have get it from there:

```<code>@classmethod
def showDefaultValue(cls, defl=None):
    if defl is None:
        defl = cls.default
    print "defl == %s" % (defl)
</code>```

Title: Overriding class variables in python

Body:
I'm trying to understand a bit how Python (2.6) deals with class, instances and so on, and at a certain point, I tried this code:

#/usr/bin/python2.6

class Base(object):
    default = "default value in base"

    def __init__(self):
        super(Base, self).__init__()

    @classmethod
    def showDefaultValue(cls, defl = default):
        print "defl == %s" % (defl)

class Descend(Base):
    default = "default value in descend"

    def __init__(self):
        super(Descend, self).__init__()

if __name__ == "__main__":
    Descend.showDefaultValue()

The output is: "default value in base"

I was wondering why the "default" field is not overwirtten by the Descend class... Is there any way to overwrite it? Why isn't it being overwritten?

Any hint (or link to an explanatory page will be appreciated). Thank you!

Body:
def showDefaultValue(cls, defl=default):

means that default gets evaluated when the function is defined, as usual in Python. So the definition looks like this then:

def showDefaultValue(cls, defl="default value in base"):

This value of defl is stored as a default argument on the function object and used when you call the method without arguments. You can look at the defaults of a function like print Descend.showDefaultValue.im_self.default to validate this.

If you want to get the default from the current class then you have get it from there:

@classmethod
def showDefaultValue(cls, defl=None):
    if defl is None:
        defl = cls.default
    print "defl == %s" % (defl)


问:
Logback config in tomcat
I'm running two web applications in a Tomcat 7.

The Tomcat has a logback-access.xml, which defines two appenders.

I can see that it's being picked up when starting tomcat, and the appender config is parsed correctly.

My question is, how do I let the webapp use the appenders defined in there?

I tried putting <logger> and <root> elements in the logback-access file, but that generates an error:

no applicable action for [logger], current ElementPath  is [[configuration][logger]]

, and similar for root and appender-ref.

I tried putting a logback.xml file in my war files, both WEB-INF/classes and just WEB-INF, but it doesn't seem to be picked up.

So, how am I supposed to properly configure this?

The logback-access.xml in Tomcat:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <append>true</append>
        <file>${catalina.base}/logs/my=app.log</file>
        <encoder>
            <pattern>combined</pattern>
        </encoder>
    </appender>

    <appender name="STASH" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
        <destination>localhost:5044</destination>

        <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
            <providers>

            </providers>
        </encoder>
    </appender>
</configuration>
```

<p>The <code>logback.xml</code> in <code>WEB-INF/classes</code>:</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <logger name="my.package" level="DEBUG"/>
    <logger name="com.amazonaws" level="INFO"/>
<!-- and several more loggers like this -->

    <root level="DEBUG">
        <appender-ref ref="FILE"/>
    </root>
    <root level="TRACE">
        <appender-ref ref="STASH"/>
    </root>
</configuration>
</code>```

答:
Logback-access has nothing to do with Logback in the application;

it has to be managed at Application Server level, by including the following jars (docs):

To use logback-access with Tomcat, after downloading the logback distribution, place the files logback-core-1.2.3.jar and logback-access-1.2.3.jar under $TOMCAT_HOME/lib/ directory, where $TOMCAT_HOME is the folder where you have installed Tomcat.

and configuring it with a different syntax from Logback which doesn't include any logger:

<configuration>

  <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" />

  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>access.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <fileNamePattern>access.%d{yyyy-MM-dd}.log.zip</fileNamePattern>
    </rollingPolicy>

    <encoder>
      <pattern>combined</pattern>
    </encoder>
  </appender>

  <appender-ref ref="FILE" />
</configuration>
```

Does it work ? If it work, try to change it according to your needs for the FILE part.

For the STASH part, that's a different kettle of fish, since it is LogStash - not LogBack - and other integration issues may be involved in there.

Try achieving one step at a time

Title: Logback config in tomcat

Body:
I'm running two web applications in a Tomcat 7.

The Tomcat has a logback-access.xml, which defines two appenders.

I can see that it's being picked up when starting tomcat, and the appender config is parsed correctly.

My question is, how do I let the webapp use the appenders defined in there?

I tried putting <logger> and <root> elements in the logback-access file, but that generates an error:

no applicable action for [logger], current ElementPath  is [[configuration][logger]]

, and similar for root and appender-ref.

I tried putting a logback.xml file in my war files, both WEB-INF/classes and just WEB-INF, but it doesn't seem to be picked up.

So, how am I supposed to properly configure this?

The logback-access.xml in Tomcat:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <append>true</append>
        <file>${catalina.base}/logs/my=app.log</file>
        <encoder>
            <pattern>combined</pattern>
        </encoder>
    </appender>

    <appender name="STASH" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
        <destination>localhost:5044</destination>

        <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
            <providers>

            </providers>
        </encoder>
    </appender>
</configuration>

The logback.xml in WEB-INF/classes:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <logger name="my.package" level="DEBUG"/>
    <logger name="com.amazonaws" level="INFO"/>

    <root level="DEBUG">
        <appender-ref ref="FILE"/>
    </root>
    <root level="TRACE">
        <appender-ref ref="STASH"/>
    </root>
</configuration>

Body:
Logback-access has nothing to do with Logback in the application;

it has to be managed at Application Server level, by including the following jars (docs):

To use logback-access with Tomcat, after downloading the logback distribution, place the files logback-core-1.2.3.jar and logback-access-1.2.3.jar under $TOMCAT_HOME/lib/ directory, where $TOMCAT_HOME is the folder where you have installed Tomcat.

and configuring it with a different syntax from Logback which doesn't include any logger:

<configuration>
  <!-- always a good activate OnConsoleStatusListener -->
  <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" />

  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>access.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <fileNamePattern>access.%d{yyyy-MM-dd}.log.zip</fileNamePattern>
    </rollingPolicy>

    <encoder>
      <pattern>combined</pattern>
    </encoder>
  </appender>

  <appender-ref ref="FILE" />
</configuration>

Does it work ? If it work, try to change it according to your needs for the FILE part.

For the STASH part, that's a different kettle of fish, since it is LogStash - not LogBack - and other integration issues may be involved in there.

Try achieving one step at a time


问:
Php change fatal error format

I would like to try to change the formatting of fatal error but I can only modify the values of message, file and line.

I would expect to be able to change the css and the html of the message.

Thanks in advance.

答:
You can catch fatal errors in PHP. Refer to this answer here:

https://stackoverflow.com/a/4410769/9051466

After determining if its a fatal error, you can just create a custom page, redirect the user to that custom page, then display what error message you want the user to see.

Title: Php change fatal error format


问:
Unexpected behavior when converting double precision to text in PostgreSQL
Came across this weird behavior today..

```<code>select                date_part('year', CURRENT_DATE);
2017
select        to_char(date_part('year', CURRENT_DATE),'9999');
" 2017"
select length(to_char(date_part('year', CURRENT_DATE),'9999'));
5
</code>```

Of course I can directly use to_char(CURRENT_DATE,'YYYY'), but just curious why double precision numbers get a blank space in the beginning when converted into text. Thank you!

Notes:

Data Type Formatting Functions (PostgreSQL 8.2.xx)

Server version: PostgreSQL 8.2.15 (Greenplum Database 4.3.10.0)

答:
This behaviour is documented (see the examples table).  It's leaving space for a - sign for negative values.

It seems that you can avoid this with the FM prefix, i.e. 'FM9999'.

Body:
Came across this weird behavior today..

select                date_part('year', CURRENT_DATE);
2017
select        to_char(date_part('year', CURRENT_DATE),'9999');
" 2017"
select length(to_char(date_part('year', CURRENT_DATE),'9999'));
5

Of course I can directly use to_char(CURRENT_DATE,'YYYY'), but just curious why double precision numbers get a blank space in the beginning when converted into text. Thank you!

Notes:

Data Type Formatting Functions (PostgreSQL 8.2.xx)

Server version: PostgreSQL 8.2.15 (Greenplum Database 4.3.10.0)


问:
In Sublime Text how to copy line without end of line character
It is very useful that in ST3 you can copy a whole line with just ctrl+c, the only problem is that this command also copies the "return" or new line character, so for example when you copy a line and paste in a console it will run the command immediately. This is undesirable because I will want to first edit the command before running it. This forces me to manually highlight the line.

Is there a plugin or an easy way to cope the line where the cursor is without including the new line character?

答:
You can replace the default behavior by creating a Sublime Text macro and  a key bind for it on the Ctrl+C key:

Packages/User/SelectLineNoEOL.sublime-macro

```<code>[
    { "command": "move_to", "args": { "to": "hardbol" } },
    { "command": "move_to", "args": { "to": "eol", "extend": true } },
    { "command": "copy" },
]
</code>```

Default.sublime-keymap

```<code>    { "keys": ["ctrl+c"], "command": "run_macro_file",
        "args": {"file": "res://Packages/User/SelectLineNoEOL.sublime-macro"},
        "context":
        [
            {
                "key": "selection_empty", "operator": "equal",
                "operand": true, "match_all": false,
            },
        ],
    },
</code>```

I think I had saw another thread with a plugin which does this, but I could not find it.

Related threads:

forum#14576 How to disable selecting newline on triple click?

forum#14933 [ST3]Copy blank line using yy;p (Vi), paste one extra line

Body:
You can replace the default behavior by creating a Sublime Text macro and  a key bind for it on the Ctrl+C key:

Packages/User/SelectLineNoEOL.sublime-macro

[
    { "command": "move_to", "args": { "to": "hardbol" } },
    { "command": "move_to", "args": { "to": "eol", "extend": true } },
    { "command": "copy" },
]

Default.sublime-keymap

    { "keys": ["ctrl+c"], "command": "run_macro_file",
        "args": {"file": "res://Packages/User/SelectLineNoEOL.sublime-macro"},
        "context":
        [
            {
                "key": "selection_empty", "operator": "equal",
                "operand": true, "match_all": false,
            },
        ],
    },

I think I had saw another thread with a plugin which does this, but I could not find it.

Related threads:

forum#14576 How to disable selecting newline on triple click?

forum#14933 [ST3]Copy blank line using yy;p (Vi), paste one extra line


问:
preg_split dealing with ' in a surname using php
I am importing a text file with marks for each student into my MySQL database. I am using preg_split to read each line and break the info into separate data which is working except for students with a surname containing a ['] such as O'Neil.

Error: INSERT INTO student_data (studentID,student_number, termID,
  course_number, course_name, storecode, grade, percent) VALUES
  ('13269   3100876170  Jimmy   O'Neil  12  2701    MT11    MATHEMATICS 11  Q1  74  74
  ','','','','','','','') You have an error in your SQL syntax; check
  the manual that corresponds to your MySQL server version for the right
  syntax to use near 'Neil  12  2701    MT11    MATHEMATICS 11  Q1  74  74
  ','','','','','','','')' at line 231093

The code to split the separate the file is:

```<code> ini_set("auto_detect_line_endings", true);

  $file = fopen($target_file,"r");

 while(! feof($file))
  {
 $test= fgets($file);

 $array = preg_split('/\s"+/', $test);
fclose($file);
}
</code>```

I am guessing that the issue is the ('/\s"+/',$test) part of the code. I have looked for clear documentation on what is going on and most of it makes sense but I couldn't find how you include all white spaces but exclude ' from being used as a delineator.

答:
Don't use regular expressions for delimited data. Use a parser, in this case you can use either:

http://php.net/manual/en/function.fgetcsv.php

http://php.net/manual/en/function.str-getcsv.php

The CSV in the name is the default, you can define your delimiter. In your case a space is the delimiter and a double quote is for encapsulation. This will get you half way there. Once you have this data broken out correctly you should use parameterized queries so your mysql driver escapes the data as needed.

Example using str_getcsv:

```<code>$string = '"13269" "3100876170" "Jimmy O\'Neil" "12" "2701" "MT11" "MATHEMATICS" "11" "Q1" "74" "74"';
$data = str_getcsv($string, ' ', '"');
print_r($data);
</code>```

Demo: https://3v4l.org/Phpp7

Parameterized query:

```<code>INSERT INTO student_data (studentID, student_number, termID, course_number, course_name, storecode, grade, percent) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
</code>```

then if using PDO you can pass the $data directly to the execute function.

Body:
I am importing a text file with marks for each student into my MySQL database. I am using preg_split to read each line and break the info into separate data which is working except for students with a surname containing a ['] such as O'Neil.

Error: INSERT INTO student_data (studentID,student_number, termID,
  course_number, course_name, storecode, grade, percent) VALUES
  ('13269   3100876170  Jimmy   O'Neil  12  2701    MT11    MATHEMATICS 11  Q1  74  74
  ','','','','','','','') You have an error in your SQL syntax; check
  the manual that corresponds to your MySQL server version for the right
  syntax to use near 'Neil  12  2701    MT11    MATHEMATICS 11  Q1  74  74
  ','','','','','','','')' at line 231093

The code to split the separate the file is:

 ini_set("auto_detect_line_endings", true);

  $file = fopen($target_file,"r");

 while(! feof($file))
  {
 $test= fgets($file);

 $array = preg_split('/\s"+/', $test);
fclose($file);
}

I am guessing that the issue is the ('/\s"+/',$test) part of the code. I have looked for clear documentation on what is going on and most of it makes sense but I couldn't find how you include all white spaces but exclude ' from being used as a delineator.

Body:
Don't use regular expressions for delimited data. Use a parser, in this case you can use either:

http://php.net/manual/en/function.fgetcsv.php

http://php.net/manual/en/function.str-getcsv.php

The CSV in the name is the default, you can define your delimiter. In your case a space is the delimiter and a double quote is for encapsulation. This will get you half way there. Once you have this data broken out correctly you should use parameterized queries so your mysql driver escapes the data as needed.

Example using str_getcsv:

$string = '"13269" "3100876170" "Jimmy O\'Neil" "12" "2701" "MT11" "MATHEMATICS" "11" "Q1" "74" "74"';
$data = str_getcsv($string, ' ', '"');
print_r($data);

Demo: https://3v4l.org/Phpp7

Parameterized query:

INSERT INTO student_data (studentID, student_number, termID, course_number, course_name, storecode, grade, percent) VALUES (?, ?, ?, ?, ?, ?, ?, ?)

then if using PDO you can pass the $data directly to the execute function.


问:
Break an array into its corresponding value
Break an array with its corresponding value. There is only a single element in the array. I would like to break it with its corresponding values.

```<code>$myarray =   Array ( [manufactured_at Sku status title detail nickname customer_id option_id entity_id storeids] => 2012-12-01 11:04:59 1235-2 0 abc xyz kubeczek pqr 27 3 )
</code>```

I want my result :-

$myarray['manufactured_at'] = 2012-12-01 11:04:59

$myarray['Sku'] = 1235-2

$myarray['status'] = 0

So on

答:
If you want to create an associative array than you need to format your code differently.

The syntax for an associative array is $array = array($key1=>$value1, $key2=>$value2);

If you're trying to get:  $myarray['manufactured_at'] = 2012-12-01 11:04:59 then your array needs to be formatted like this:

```<code>$myarray = array('manufactured_at'=>'2012-12-01 11:04:59', 'SKu'=> '1235-2', 'status'=>0);
</code>```

Body:
Break an array with its corresponding value. There is only a single element in the array. I would like to break it with its corresponding values.

$myarray =   Array ( [manufactured_at Sku status title detail nickname customer_id option_id entity_id storeids] => 2012-12-01 11:04:59 1235-2 0 abc xyz kubeczek pqr 27 3 )

I want my result :-

$myarray['manufactured_at'] = 2012-12-01 11:04:59

$myarray['Sku'] = 1235-2

$myarray['status'] = 0

So on

Body:
If you want to create an associative array than you need to format your code differently.

The syntax for an associative array is $array = array($key1=>$value1, $key2=>$value2);

If you're trying to get:  $myarray['manufactured_at'] = 2012-12-01 11:04:59 then your array needs to be formatted like this:

$myarray = array('manufactured_at'=>'2012-12-01 11:04:59', 'SKu'=> '1235-2', 'status'=>0);


问:
Terraform plugin development, where to specify version? best practices for go applications versioning?
We developed a couple of provider plugins for terraform, we did so without specifying version. Then for our own control we started to version using ldflags at build time:

```<code>go build -ldflags '-X \"main.VersionString=#{VERSION} (#{REVISION})\"' -o '#{WS}/#{PROJECT_NAME}' main.go"
</code>```

and in the code:

```<code>package main

import(
  "github.com/hashicorp/terraform/plugin"
  ...
)

var VersionString = "unversioned"

func main(){
  if len(os.Args) == 2 && os.Args[1] == "--version" {
    fmt.Printf("Version %s\n", VersionString)
    os.Exit(0)
  }

  plugin.Serve(&plugin.ServeOpts{
    ProviderFunc: myprovider.Provider})
}
</code>```

The problem is that terraform is unaware of the version, therefore we are not able to freeze version for our plugins.

What's the correct way to version custom plugins for terraform?

答:
Terraform plugins are not generally aware of their version number within the binary itself, but rather declare it as part of their filename.

For example, q provider plugin called "foo" might have a filename terraform-provider-foo_v1.2.0 which then tells Terraform Core, when it finds that plugin, to treat it as version 1.2.0.

Body:
We developed a couple of provider plugins for terraform, we did so without specifying version. Then for our own control we started to version using ldflags at build time:

go build -ldflags '-X \"main.VersionString=#{VERSION} (#{REVISION})\"' -o '#{WS}/#{PROJECT_NAME}' main.go"

and in the code:

package main

import(
  "github.com/hashicorp/terraform/plugin"
  ...
)

var VersionString = "unversioned"

func main(){
  if len(os.Args) == 2 && os.Args[1] == "--version" {
    fmt.Printf("Version %s\n", VersionString)
    os.Exit(0)
  }

  plugin.Serve(&plugin.ServeOpts{
    ProviderFunc: myprovider.Provider})
}

The problem is that terraform is unaware of the version, therefore we are not able to freeze version for our plugins.

What's the correct way to version custom plugins for terraform?


问:
Where do I find .war files in Aerogear unified push server?
Where can find unifiedpush-server-wildfly.war and unifiedpush-auth-server.war files in unified push server. where can i deploy it?</p>

答:
It's located at {your_jboss_installation_root_folder}/standalone/deployments/, you can just drop your .war files there and JBoss will automatically deploy them.

If the .war is successfully deployed, you will see a file such as unifiedpush-auth-server.war.deployed being generated in the same folder.

Otherwise, files such as unifiedpush-auth-server.war.failed will be generated. It is a text file so open it you will find why it failed to deploy in JBoss.

Hope this helps.


问:
Handling a model returned as json data from a controller in ASP.NET
I have a controller which return a model as json object:

```<code>[HttpGet("{id}")]
[Route("GetById")]
public async Task <JsonResult> GetById([FromQuery]string id)
{
       var myfoo = new {foo="bar", baz="Blech"};
       return Json(myfoo);
}
</code>```

How can handle the returned json object in jQuery?

```<code><script type="text/javascript">
       $('#id').change(function () {
           var id = $('#id').val();
           if (id.length = 17) {
              $.ajax(
                 {
                    url: '/Home/GetById?id=' + id,
                    type: 'GET',
                    jsondata: "",
                    contentType: 'application/json; charset=utf-8',
                    success: function (jsondata) {
                        alert("foo is: " + jsondata ); <---?
                    },
                    error: function () {
                        //alert("error");
                    }
                });
        }
      });
</script>
</code>```

I need to get foo value and assigned to an html control

Thanks in advance

答:
all the time I was using capital letter</p>

```<code>jsondata.foo // not .Foo
</code>```

Body:
I have a controller which return a model as json object:

[HttpGet("{id}")]
[Route("GetById")]
public async Task <JsonResult> GetById([FromQuery]string id)
{
       var myfoo = new {foo="bar", baz="Blech"};
       return Json(myfoo);
}

How can handle the returned json object in jQuery?

I need to get foo value and assigned to an html control

Thanks in advance

Body:
all the time I was using capital letter

jsondata.foo // not .Foo


问:
Replacing slider thumb with PNG?
I'm trying to find a flexible cross-browser solution to implementing a png image as my range input's thumbnail, so I can turn it from this:

to this:

In chrome, the css tag "input[type=range]::-webkit-slider-thumb" lets you select the thumbnail. How is this done in Safari, Firefox and other browsers? Is there a way to handle this elegantly?

答:
Safari and Opera are webkit based like chrome so there it should work too.

For Firefox you can use:

```<code>::-moz-range-thumb
</code>```

For IE 10+

```<code>::-ms-thumb
</code>```

More information on brennaobrien's blog:

http://brennaobrien.com/blog/2014/05/style-input-type-range-in-every-browser.html

Title: Replacing slider thumb with PNG?

Body:
Safari and Opera are webkit based like chrome so there it should work too.

For Firefox you can use:

::-moz-range-thumb

For IE 10+

::-ms-thumb

More information on brennaobrien's blog:

http://brennaobrien.com/blog/2014/05/style-input-type-range-in-every-browser.html


问:
If I have a before action filter, how to set properties so they are available in actions?
In my actions, I want to pre-load the User object and set some other properties, all BEFORE the action loads.

I know there are events where I can do this, but how will these objects that I set be made available in my controller's actions once the filter fires and execution is now at the action level?

example:

public actionresult SomeAction()
{
   string username = this.CurrentUser.username;

}

答:
```<code>public override OnActionExecuting( forgotthesignature filterContext )
{
    this.CurrentUser = whatever;
}
</code>```


问:
What does __flags__ in python type used for
I have been read pickle source code recently.

The following code in copy_reg make me confused:

```<code>_HEAPTYPE = 1<<9

def _reduce_ex(self, proto):
    assert proto < 2
    for base in self.__class__.__mro__:
        if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE:
            break
    else:
        base = object # not really reachable
    if base is object:
        state = None
</code>```

So what does __flags__ using for?

I found it is defined in type object:

```<code>type.__flags__ = 2148423147
</code>```

I was tried to search it in the official doc, but nothing was found.

But interesting thing is that __class__.__flags__ & _HEAPTYPE is always 0 when the __class__ is python internal type. And the result will be 1 when __class__ is a subclass of python internal type.

Can anyone help me to solve this puzzle?

答:
__flags__ is to be viewed as binary, if you want to see the flags.

These type flags are defined here in Python's source code.

Body:
I have been read pickle source code recently.

The following code in copy_reg make me confused:

_HEAPTYPE = 1<<9

def _reduce_ex(self, proto):
    assert proto < 2
    for base in self.__class__.__mro__:
        if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE:
            break
    else:
        base = object # not really reachable
    if base is object:
        state = None

So what does __flags__ using for?

I found it is defined in type object:

type.__flags__ = 2148423147

I was tried to search it in the official doc, but nothing was found.

But interesting thing is that __class__.__flags__ & _HEAPTYPE is always 0 when the __class__ is python internal type. And the result will be 1 when __class__ is a subclass of python internal type.

Can anyone help me to solve this puzzle?


问:
oracle PLSQL- Only provide hour, minute and second from timestamp
Is there a way to only extract HOUR,MINUTES and Seconds from timestamp.. Along with date ofc but i dont want it to show fractional_seconds_precision with it.. So for example when I type the following:

```<code>TO_TIMESTAMP('2017-12-02 05:00:00', 'YYYY-MM-DD HH24:MI:SS')
</code>```

I only want what i specified in the format to be shown, I dont want FF to be shown but whenever I check the output, FF always comes along with it. How do I remove it? Also, I wanted to ask, Is there a way to compare the dates typed using timestamp to be compared with dates typed using TO_DATE? what if I want one to be timestamp and other to be in a TO_DATE format? Thanks

答:
When you convert a string to a timestamp (or date) the result is an internal Oracle format which you don't generally need to worry about. You just need to know that internally it doesn't look anything like what you entered.

When you query a timestamp your client decides how to format the timestamp for display using your NLS settings. While you can modify those it's generally better to not rely on them - as someone else running your code may have different settings - and explicitly convert the timestamp to a string using the to_char() function and a suitable format model. In this case:

```<code>select to_char(your_column, 'YYYY-MM-DD HH24:MI:SS') from your_table
</code>```

But only do that for display purposes; while you're working with timestamp values - adding or removing intervals, for instance - leave it as a timestamp, and avoid doing anything that will cause implicit conversion to a different data type, as that can cause all sort of issues.

In your example the fractional seconds part will be zero, but that may not always be the case. If you actually have values with non-zero fractional seconds, and want to ignore those while doing calculations, you can cast() the value to a slightly different data type, such as a timestamp with restricted precision:

```<code>select cast(to_timestamp('2017-12-02 05:00:00.123', 'YYYY-MM-DD HH24:MI:SS.FF3') as timestamp(0))
from dual;

CAST(TO_TIMESTAMP('2017-12-0
----------------------------
02-DEC-17 05.00.00.000000000
</code>```

(displayed by my client using my NLS settings!), or you can cast to a date instead depending on what kind of calculations you're doing - you may implicitly be doing that already. An Oracle date has the same precision as a timestamp(0) as both can hold values defined down to the second, but they are stored differently.

If you compare a date with a timestamp then Oracle will implicitly convert them, which can have consequences for its ability to utilise indexes.

Body:
Is there a way to only extract HOUR,MINUTES and Seconds from timestamp.. Along with date ofc but i dont want it to show fractional_seconds_precision with it.. So for example when I type the following:

TO_TIMESTAMP('2017-12-02 05:00:00', 'YYYY-MM-DD HH24:MI:SS')

I only want what i specified in the format to be shown, I dont want FF to be shown but whenever I check the output, FF always comes along with it. How do I remove it? Also, I wanted to ask, Is there a way to compare the dates typed using timestamp to be compared with dates typed using TO_DATE? what if I want one to be timestamp and other to be in a TO_DATE format? Thanks

Body:
When you convert a string to a timestamp (or date) the result is an internal Oracle format which you don't generally need to worry about. You just need to know that internally it doesn't look anything like what you entered.

When you query a timestamp your client decides how to format the timestamp for display using your NLS settings. While you can modify those it's generally better to not rely on them - as someone else running your code may have different settings - and explicitly convert the timestamp to a string using the to_char() function and a suitable format model. In this case:

select to_char(your_column, 'YYYY-MM-DD HH24:MI:SS') from your_table

But only do that for display purposes; while you're working with timestamp values - adding or removing intervals, for instance - leave it as a timestamp, and avoid doing anything that will cause implicit conversion to a different data type, as that can cause all sort of issues.

In your example the fractional seconds part will be zero, but that may not always be the case. If you actually have values with non-zero fractional seconds, and want to ignore those while doing calculations, you can cast() the value to a slightly different data type, such as a timestamp with restricted precision:

select cast(to_timestamp('2017-12-02 05:00:00.123', 'YYYY-MM-DD HH24:MI:SS.FF3') as timestamp(0))
from dual;

CAST(TO_TIMESTAMP('2017-12-0
----------------------------
02-DEC-17 05.00.00.000000000

(displayed by my client using my NLS settings!), or you can cast to a date instead depending on what kind of calculations you're doing - you may implicitly be doing that already. An Oracle date has the same precision as a timestamp(0) as both can hold values defined down to the second, but they are stored differently.

If you compare a date with a timestamp then Oracle will implicitly convert them, which can have consequences for its ability to utilise indexes.


问:
URL issue using multiple ids pk1 and pk2
My url is not working I am getting an error :

```<code>TemplateSyntaxError at /website/project/172/
Could not parse the remainder: '=' from '='
</code>```

Here is my url link :

```<code><span class="fa fa-id-card-o" aria-hidden="true"><a href="{% url 'website:EmployeDetails' pk1 = project.id pk2 = member.id %}"> Show Results</a>
</code>```

I guess it is coming from the pk1 = project.id pk2 = member.id but I dont know how to fomulate ir
urs pattern:

```<code>url(r'^project/(?P<pk>[0-9]+)/$',views.ProjectDetailView.as_view(), name='ProjectDetails'),
    url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/$',views.EmployeeDetailView.as_view(), name='EmployeDetails'),
    url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/api/chart/data/$',views.EmployeeChartData.as_view(), name='employeechartdata'),
    url(r'^project/(?P<pk>[0-9]+)/api/chart/data/$', views.ChartData.as_view(), name='chartdata'),
</code>```

views.py:

```<code>class EmployeeDetailView(generic.DetailView, LoginRequiredMixin):
    #import pdb; pdb.set_trace()
    model = MyUser
    template_name = 'Employee_Details.html'

    def get_object(self, queryset=None):
        return get_object_or_404(MyUser, pk=self.kwargs['pk2'], members__project=self.kwargs['pk1'])

    def get_context_data(self, **kwargs):
        context = super(EmployeeDetailView, self).get_context_data(**kwargs)
        employee_name = MyUser.objects.get(id=self.kwargs['pk2'])
        team_list = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all()
        team_list_pop = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all().exclude(id=self.kwargs['pk2'])
        context={
            'employee_name' : employee_name,
            'team_list' : team_list,
            'team_list_pop' : team_list_pop
        }
        return context
</code>```

答: You need to remove the spaces before and after the = signs.

Body:
My url is not working I am getting an error :

TemplateSyntaxError at /website/project/172/
Could not parse the remainder: '=' from '='

Here is my url link :

 Show Results

I guess it is coming from the pk1 = project.id pk2 = member.id but I dont know how to fomulate ir
urs pattern:

url(r'^project/(?P<pk>[0-9]+)/$',views.ProjectDetailView.as_view(), name='ProjectDetails'),
    url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/$',views.EmployeeDetailView.as_view(), name='EmployeDetails'),
    url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/api/chart/data/$',views.EmployeeChartData.as_view(), name='employeechartdata'),
    url(r'^project/(?P<pk>[0-9]+)/api/chart/data/$', views.ChartData.as_view(), name='chartdata'),

views.py:

class EmployeeDetailView(generic.DetailView, LoginRequiredMixin):
    #import pdb; pdb.set_trace()
    model = MyUser
    template_name = 'Employee_Details.html'

    def get_object(self, queryset=None):
        return get_object_or_404(MyUser, pk=self.kwargs['pk2'], members__project=self.kwargs['pk1'])

    def get_context_data(self, **kwargs):
        context = super(EmployeeDetailView, self).get_context_data(**kwargs)
        employee_name = MyUser.objects.get(id=self.kwargs['pk2'])
        team_list = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all()
        team_list_pop = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all().exclude(id=self.kwargs['pk2'])
        context={
            'employee_name' : employee_name,
            'team_list' : team_list,
            'team_list_pop' : team_list_pop
        }
        return context


问:
Logic: is ( A && !(B || C)) || ( B || C ) the same as ( A || B || C )?
I've encountered some obj-c code and I'm wondering if there's a way to simplify it:

```<code>#if ( A && !(B || C)) || ( B || C )
</code>```

is this the same as?

```<code>#if ( A || B || C )
</code>```

If not, is there another way to formulate it that would be easier to read?

[edit]
I tried the truth table before asking the question, but thought I had to be missing something because I doubted that Foundation.framework/Foundation.h would employ this more complex form.   Is there a good reason for it?

Here's the original code (from Foundation.h):

```<code>#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) || (TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)
</code>```

答:
Yes.  Like others said, you can truth table it.  The De Morgan rules can also help.

However, I think the best option is to use a Karnaugh Map.  It takes a few minutes to learn, but Karnaugh Maps allow you to consistently find the most minimal expression for boolean logic.  Truth tables can verify a minimization, but they can't give it to you.

Here's how I got it:

First, the table layout:

```<code>         AB
     00   01   11   10
  0|    |    |    |    |
C 1|    |    |    |    |
</code>```

Now, considering your equation, B || C will always cause a truth:

```<code>         AB
     00   01   11   10
  0|    |  T |  T |    |
C 1|  T |  T |  T |  T |
</code>```

This leaves only two cases.  In either case, the right side evaluates to false.  For 000, the left side also evaluates to false (0 && !(whatever) is false).  For 100, 1 && !(0 ||| 0) evaluates to true.  Thus, the statement is true.  Filling in:

```<code>         AB
     00   01   11   10
  0|  F |  T |  T |  T |
C 1|  T |  T |  T |  T |
</code>```

Now, we only need to "cover" all the truths.  "C" will cover the bottom row.  "B" will cover the middle square (of four values).  Thus, "B || C" covers all but the top right square.  Now, "A" will cover the right four-space square.  It's OK that this is redundant.  Thus, "A || B || C" covers all the true squares and omits the only false one.

Body:
I've encountered some obj-c code and I'm wondering if there's a way to simplify it:

#if ( A && !(B || C)) || ( B || C )

is this the same as?

#if ( A || B || C )

If not, is there another way to formulate it that would be easier to read?

[edit]
I tried the truth table before asking the question, but thought I had to be missing something because I doubted that Foundation.framework/Foundation.h would employ this more complex form.   Is there a good reason for it?

Here's the original code (from Foundation.h):

#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) || (TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)

Body:
Yes.  Like others said, you can truth table it.  The De Morgan rules can also help.

However, I think the best option is to use a Karnaugh Map.  It takes a few minutes to learn, but Karnaugh Maps allow you to consistently find the most minimal expression for boolean logic.  Truth tables can verify a minimization, but they can't give it to you.

Here's how I got it:

First, the table layout:

         AB
     00   01   11   10
  0|    |    |    |    |
C 1|    |    |    |    |

Now, considering your equation, B || C will always cause a truth:

         AB
     00   01   11   10
  0|    |  T |  T |    |
C 1|  T |  T |  T |  T |

This leaves only two cases.  In either case, the right side evaluates to false.  For 000, the left side also evaluates to false (0 && !(whatever) is false).  For 100, 1 && !(0 ||| 0) evaluates to true.  Thus, the statement is true.  Filling in:

         AB
     00   01   11   10
  0|  F |  T |  T |  T |
C 1|  T |  T |  T |  T |

Now, we only need to "cover" all the truths.  "C" will cover the bottom row.  "B" will cover the middle square (of four values).  Thus, "B || C" covers all but the top right square.  Now, "A" will cover the right four-space square.  It's OK that this is redundant.  Thus, "A || B || C" covers all the true squares and omits the only false one.