问:
Rails undefined method "to_time_preserves_timezone"
Something was broken and now no one generator is not works but i'm nothing change after i'm using rails generator last time. That's i got in a console

```<code>/home/sanua/ct/config/initializers/new_framework_defaults.rb:15:in `<top (required)>': undefined method `to_time_preserves_timezone=' for ActiveSupport:Module (NoMethodError)
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `load'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `block in load'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:240:in `load_dependency'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `load'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:652:in `block in load_config_initializer'
 from /usr/lib/ruby/vendor_ruby/active_support/notifications.rb:166:in `instrument'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:651:in `load_config_initializer'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:616:in `block (2 levels) in <class:Engine>'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:615:in `each'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:615:in `block in <class:Engine>'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:30:in `instance_exec'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:30:in `run'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:55:in `block in run_initializers'
 from /usr/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each'
 from /usr/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:422:in `block (2 levels) in each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:421:in `block in each_strongly_connected_component_from'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:44:in `each'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:44:in `tsort_each_child'
 from /usr/lib/ruby/2.3.0/tsort.rb:415:in `call'
 from /usr/lib/ruby/2.3.0/tsort.rb:415:in `each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `each'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `call'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each'
 from /usr/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:54:in `run_initializers'
 from /usr/lib/ruby/vendor_ruby/rails/application.rb:352:in `initialize!'
 from /home/sanua/ct/config/environment.rb:5:in `<top (required)>'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `require'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `block in require'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:240:in `load_dependency'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `require'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:92:in `preload'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:143:in `serve'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:131:in `block in run'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:125:in `loop'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:125:in `run'
 from /usr/lib/ruby/vendor_ruby/spring/application/boot.rb:18:in `<top (required)>'
 from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from -e:1:in `<main>'/home/sanua/ct/config/initializers/new_framework_defaults.rb:15:in `<top (required)>': undefined method `to_time_preserves_timezone=' for ActiveSupport:Module (NoMethodError)
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `load'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `block in load'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:240:in `load_dependency'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `load'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:652:in `block in load_config_initializer'
 from /usr/lib/ruby/vendor_ruby/active_support/notifications.rb:166:in `instrument'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:651:in `load_config_initializer'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:616:in `block (2 levels) in <class:Engine>'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:615:in `each'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:615:in `block in <class:Engine>'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:30:in `instance_exec'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:30:in `run'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:55:in `block in run_initializers'
 from /usr/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each'
 from /usr/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:422:in `block (2 levels) in each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:421:in `block in each_strongly_connected_component_from'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:44:in `each'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:44:in `tsort_each_child'
 from /usr/lib/ruby/2.3.0/tsort.rb:415:in `call'
 from /usr/lib/ruby/2.3.0/tsort.rb:415:in `each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `each'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `call'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each'
 from /usr/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:54:in `run_initializers'
 from /usr/lib/ruby/vendor_ruby/rails/application.rb:352:in `initialize!'
 from /home/sanua/ct/config/environment.rb:5:in `<top (required)>'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `require'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `block in require'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:240:in `load_dependency'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `require'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:92:in `preload'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:143:in `serve'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:131:in `block in run'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:125:in `loop'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:125:in `run'
 from /usr/lib/ruby/vendor_ruby/spring/application/boot.rb:18:in `<top (required)>'
 from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from -e:1:in `<main>'
</code>```

I constantly see this message whatever i write(rails generate controller, model...)

答: you need to delete the Gemfile.lock and bundle install after that, as the correct version will then be fetched.

Body:
Something was broken and now no one generator is not works but i'm nothing change after i'm using rails generator last time. That's i got in a console

/home/sanua/ct/config/initializers/new_framework_defaults.rb:15:in `<top (required)>': undefined method `to_time_preserves_timezone=' for ActiveSupport:Module (NoMethodError)
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `load'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `block in load'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:240:in `load_dependency'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `load'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:652:in `block in load_config_initializer'
 from /usr/lib/ruby/vendor_ruby/active_support/notifications.rb:166:in `instrument'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:651:in `load_config_initializer'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:616:in `block (2 levels) in <class:Engine>'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:615:in `each'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:615:in `block in <class:Engine>'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:30:in `instance_exec'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:30:in `run'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:55:in `block in run_initializers'
 from /usr/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each'
 from /usr/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:422:in `block (2 levels) in each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:421:in `block in each_strongly_connected_component_from'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:44:in `each'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:44:in `tsort_each_child'
 from /usr/lib/ruby/2.3.0/tsort.rb:415:in `call'
 from /usr/lib/ruby/2.3.0/tsort.rb:415:in `each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `each'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `call'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each'
 from /usr/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:54:in `run_initializers'
 from /usr/lib/ruby/vendor_ruby/rails/application.rb:352:in `initialize!'
 from /home/sanua/ct/config/environment.rb:5:in `<top (required)>'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `require'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `block in require'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:240:in `load_dependency'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `require'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:92:in `preload'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:143:in `serve'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:131:in `block in run'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:125:in `loop'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:125:in `run'
 from /usr/lib/ruby/vendor_ruby/spring/application/boot.rb:18:in `<top (required)>'
 from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from -e:1:in `<main>'/home/sanua/ct/config/initializers/new_framework_defaults.rb:15:in `<top (required)>': undefined method `to_time_preserves_timezone=' for ActiveSupport:Module (NoMethodError)
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `load'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `block in load'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:240:in `load_dependency'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `load'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:652:in `block in load_config_initializer'
 from /usr/lib/ruby/vendor_ruby/active_support/notifications.rb:166:in `instrument'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:651:in `load_config_initializer'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:616:in `block (2 levels) in <class:Engine>'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:615:in `each'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:615:in `block in <class:Engine>'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:30:in `instance_exec'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:30:in `run'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:55:in `block in run_initializers'
 from /usr/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each'
 from /usr/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:422:in `block (2 levels) in each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:421:in `block in each_strongly_connected_component_from'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:44:in `each'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:44:in `tsort_each_child'
 from /usr/lib/ruby/2.3.0/tsort.rb:415:in `call'
 from /usr/lib/ruby/2.3.0/tsort.rb:415:in `each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `each'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `call'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each'
 from /usr/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:54:in `run_initializers'
 from /usr/lib/ruby/vendor_ruby/rails/application.rb:352:in `initialize!'
 from /home/sanua/ct/config/environment.rb:5:in `<top (required)>'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `require'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `block in require'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:240:in `load_dependency'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `require'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:92:in `preload'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:143:in `serve'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:131:in `block in run'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:125:in `loop'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:125:in `run'
 from /usr/lib/ruby/vendor_ruby/spring/application/boot.rb:18:in `<top (required)>'
 from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from -e:1:in `'

I constantly see this message whatever i write(rails generate controller, model...)


来源: stackexchange

问:
Syntax error Django(1.10.1) when doing py -3.5 manage.py runserver
`

```<code>PS C:\Users\yoyoma207\Documents\UPriderfinder\up-ride-finder> py manage.py runserver
Traceback (most recent call last):
  File "manage.py", line 23, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\ma
y", line 367, in execute_from_command_line
    utility.execute()
  File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\ma
y", line 316, in execute
    settings.INSTALLED_APPS
  File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\conf\__
, in __getattr__
    self._setup(name)
  File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\conf\__
, in _setup
    self._wrapped = Settings(settings_module)
  File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\conf\__
, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\importlib\__init__.py", line
ule
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "C:\Users\yoyoma207\Documents\UPriderfinder\up-ride-finder\config\settings\local.py", line 15,
    from .common import *  # noqa
  File "C:\Users\yoyoma207\Documents\UPriderfinder\up-ride-finder\config\settings\common.py", line 13
    import environ
  File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\site-packages\environ.py", l
    raise ValueError, "No frame marked with %s." % fname
                    ^
SyntaxError: invalid syntax`
</code>```

Been trying to start a new Django project using Python 3.5 but I just cannot figure out what is causing this problem, maybe it's because of where my environ.py is stored? I'm really not sure, all help is appreciated!

答: Install 'django-environ', not 'environ'</p>

ContentLicense: CC BY-SA 3.0

Body:
`

PS C:\Users\yoyoma207\Documents\UPriderfinder\up-ride-finder> py manage.py runserver
Traceback (most recent call last):
  File "manage.py", line 23, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\ma
y", line 367, in execute_from_command_line
    utility.execute()
  File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\ma
y", line 316, in execute
    settings.INSTALLED_APPS
  File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\conf\__
, in __getattr__
    self._setup(name)
  File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\conf\__
, in _setup
    self._wrapped = Settings(settings_module)
  File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\conf\__
, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\importlib\__init__.py", line
ule
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "C:\Users\yoyoma207\Documents\UPriderfinder\up-ride-finder\config\settings\local.py", line 15,
    from .common import *  # noqa
  File "C:\Users\yoyoma207\Documents\UPriderfinder\up-ride-finder\config\settings\common.py", line 13
    import environ
  File "C:\Users\yoyoma207\AppData\Local\Programs\Python\Python35-32\lib\site-packages\environ.py", l
    raise ValueError, "No frame marked with %s." % fname
                    ^
SyntaxError: invalid syntax`

Been trying to start a new Django project using Python 3.5 but I just cannot figure out what is causing this problem, maybe it's because of where my environ.py is stored? I'm really not sure, all help is appreciated!

Body: Install 'django-environ', not 'environ'


问:
Pythonic way to sort the records with multiple columns
Let's say we have a lot of records in a file in the following fashion.

10.10.10.10(tcp/443) : Some SSL Vulnerability : Medium : Patched

10.10.10.11(tcp/888) : Some RCE Vulnerability : High : Not Patched

These records have the 3rd column with values Critical, High, Medium, Low.

What's the best possible pythonic way to sort these records in this manner :
1. Critical, 2.High, 3.Medium 4. Low ?

答:
If you can transform your table into a pandas data frame (for example, using pandas.read_csv), then this will do the job:

```<code>import pandas as pd
df=pd.DataFrame({'a':[1,2,3,4,5,6],'b':['a','b','c','d','e','f'],'val':['critical','high','low','medium','critical','low']})
df['val'] = pd.Categorical(df['val'],['critical','high','medium','low'])
df.sort_values(by='val',inplace=True)
</code>```

Then at the beginning df was

```<code>    a   b   val
0   1   a   critical
1   2   b   high
2   3   c   low
3   4   d   medium
4   5   e   critical
5   6   f   low
</code>```

and in the end df is

```<code>    a   b   val
0   1   a   critical
4   5   e   critical
1   2   b   high
3   4   d   medium
2   3   c   low
5   6   f   low
</code>```

In the code above, the line that specified the order was

```<code>df['val'] = pd.Categorical(df['val'],['critical','high','medium','low'])
</code>```

Body:
If you can transform your table into a pandas data frame (for example, using pandas.read_csv), then this will do the job:

import pandas as pd
df=pd.DataFrame({'a':[1,2,3,4,5,6],'b':['a','b','c','d','e','f'],'val':['critical','high','low','medium','critical','low']})
df['val'] = pd.Categorical(df['val'],['critical','high','medium','low'])
df.sort_values(by='val',inplace=True)

Then at the beginning df was

    a   b   val
0   1   a   critical
1   2   b   high
2   3   c   low
3   4   d   medium
4   5   e   critical
5   6   f   low

and in the end df is

    a   b   val
0   1   a   critical
4   5   e   critical
1   2   b   high
3   4   d   medium
2   3   c   low
5   6   f   low

In the code above, the line that specified the order was

df['val'] = pd.Categorical(df['val'],['critical','high','medium','low'])


问:
IAP SKErrorDomain Code=0 Swift
I know posts related to this error are numerous, though non of them proposed a solution working for me. I'm trying to do the in-app purchase tutorial of Ray Wenderlinch : everytime I try to perform a purchase with a Sandbox account, I get the following error right after I entered my account ID ad before the "confirm purchase" alert controller appears (showing by the way that I'm running in sandbox environment).

```<code>Transaction Error: Optional("Connexion à l’iTunes Store impossible"),
0, [AnyHashable("NSLocalizedDescription"): Connexion à l’iTunes Store impossible],
Error Domain=SKErrorDomain Code=0 "Connexion à l’iTunes Store impossible"
UserInfo={NSLocalizedDescription=Connexion à l’iTunes Store impossible}
</code>```

I've tried these already without success :

iTunes Connect account configured, Paid Applications contract is in Effect;

BundleID, IAP ID entered in Xcode both match the ones on iTunes;

I've been unlogged from AppStore before running the app;

App purchase is clear for purchase;

I've waited several hours after creating both the IAP and the Sandbox account;

the payment added in SKPaymentQueue has the right product with the right productIdentifier (which again matches the one set up in iTunes);

Version set in Xcode matches the one on iTunes (1.0);

I've tried setting the Localization native development region to France so it matches the sandbox account localization;

(I may have forgotten things that I tried but these are the solutions proposed in the other posts plus own ideas)

The code should be correct as it's the final project proposed on the website (link below), modulo the IDs, which has been corrected for swift 3 and iOS 10. I'm running it on my iPhone iOS 10 also.

Here is the link for the code :

https://www.raywenderlich.com/122144/in-app-purchase-tutorial

Thank you in advance for your help !!

Jonathan

答: It appears that the problem came from Apple : the Sandbox system was down.</p>

Title: IAP SKErrorDomain Code=0 Swift

Body:
I know posts related to this error are numerous, though non of them proposed a solution working for me. I'm trying to do the in-app purchase tutorial of Ray Wenderlinch : everytime I try to perform a purchase with a Sandbox account, I get the following error right after I entered my account ID ad before the "confirm purchase" alert controller appears (showing by the way that I'm running in sandbox environment).

Transaction Error: Optional("Connexion à l’iTunes Store impossible"),
0, [AnyHashable("NSLocalizedDescription"): Connexion à l’iTunes Store impossible],
Error Domain=SKErrorDomain Code=0 "Connexion à l’iTunes Store impossible"
UserInfo={NSLocalizedDescription=Connexion à l’iTunes Store impossible}

I've tried these already without success :

iTunes Connect account configured, Paid Applications contract is in Effect;

BundleID, IAP ID entered in Xcode both match the ones on iTunes;

I've been unlogged from AppStore before running the app;

App purchase is clear for purchase;

I've waited several hours after creating both the IAP and the Sandbox account;

the payment added in SKPaymentQueue has the right product with the right productIdentifier (which again matches the one set up in iTunes);

Version set in Xcode matches the one on iTunes (1.0);

I've tried setting the Localization native development region to France so it matches the sandbox account localization;

(I may have forgotten things that I tried but these are the solutions proposed in the other posts plus own ideas)

The code should be correct as it's the final project proposed on the website (link below), modulo the IDs, which has been corrected for swift 3 and iOS 10. I'm running it on my iPhone iOS 10 also.

Here is the link for the code :

https://www.raywenderlich.com/122144/in-app-purchase-tutorial

Thank you in advance for your help !!

Jonathan


问:
Why aJqgrid[0].grid.headers[i].el.hidden≠aJqgrid.getGridParam('colModel')[i].hidden
How can I get a visible table header？for example: I have 10 columns, after columnchooser (sort and hide) after 8 columns, how can I get the current table header information, I wrote getGridParam ('colModel'), these Object sets are not sorted.</p>

答:
The el property (aJqgrid[0].grid.headers[i].el in your case) is HTMLTableHeaderCellElement (see here). It's DOM element. Thus to test, whether the element is hidden, you can use the style property:

```<code> aJqgrid[0].grid.headers[i].el.style.display === "none"
</code>```

or

```<code>$(aJqgrid[0].grid.headers[i].el).is(":hidden")
</code>```

The value should be the same as the value of hidden property of colModel.

Body:
The el property (aJqgrid[0].grid.headers[i].el in your case) is HTMLTableHeaderCellElement (see here). It's DOM element. Thus to test, whether the element is hidden, you can use the style property:

 aJqgrid[0].grid.headers[i].el.style.display === "none"

or

$(aJqgrid[0].grid.headers[i].el).is(":hidden")

The value should be the same as the value of hidden property of colModel.


问:
Why does returning lambdas between branches of ternary operator work for some lambdas?
I want to choose a lambda depending on some conditional, but the compiler, for some lambdas, says that the types of the lambdas do not match between the branches of the ternary operator.

The following code compiles:

```<code>int flag = 4;
auto result = flag % 2
    ? [](int x) {
        return x + x;
    }
    : [](int x) {
        return x * x;
    };
</code>```

but the following 2 snippets do not compile:

```<code>int flag = 4;
auto result = flag % 2
    ? [flag](int x) {
        return x + flag;
    }
    : [flag](int x) {
        return x - flag;
    };

auto result2 = flag % 2
    ? [](auto x) {
        return x + x;
    }
    : [](auto x) {
        return x * x;
    };
</code>```

resulting in the following errors respectively:

```<code>test.cpp: In function 'auto f(int)':
test.cpp:8:9: error: operands to ?: have different types 'f(int)::<lambda(int)>' and 'f(int)::<lambda(int)>'
         ? [flag](int x) {

test.cpp: In function 'auto f(int)':
test.cpp:10:9: error: operands to ?: have different types 'f(int)::<lambda(auto:1)>' and 'f(int)::<lambda(auto:2)>'
         ? [](auto x) {
         ^
</code>```

Why do the last 2 snippets not compile?

答:
Ternary Expression type is a common type for both true and false branch. Operator tries to find this type by trying to convert both branches, using complicated rules. But two different lambdas have different, distinct, non-compatible types. Generally, they are not convertible to each other, so you got an erron for your second and third try.

However, certain kind of lambdas (non-campuring, non-templated) can be converted to function pointer. If you have two lambdas, convertible to same function ponter type, ternary operator deduces that pointer to be the common type.

Body:
I want to choose a lambda depending on some conditional, but the compiler, for some lambdas, says that the types of the lambdas do not match between the branches of the ternary operator.

The following code compiles:

int flag = 4;
auto result = flag % 2
    ? [](int x) {
        return x + x;
    }
    : [](int x) {
        return x * x;
    };

but the following 2 snippets do not compile:

int flag = 4;
auto result = flag % 2
    ? [flag](int x) {
        return x + flag;
    }
    : [flag](int x) {
        return x - flag;
    };

auto result2 = flag % 2
    ? [](auto x) {
        return x + x;
    }
    : [](auto x) {
        return x * x;
    };

resulting in the following errors respectively:

test.cpp: In function 'auto f(int)':
test.cpp:8:9: error: operands to ?: have different types 'f(int)::<lambda(int)>' and 'f(int)::<lambda(int)>'
         ? [flag](int x) {

test.cpp: In function 'auto f(int)':
test.cpp:10:9: error: operands to ?: have different types 'f(int)::<lambda(auto:1)>' and 'f(int)::<lambda(auto:2)>'
         ? [](auto x) {
         ^

Why do the last 2 snippets not compile?


问:
PeekMessage don't get any message
I am trying to create a rendering loop inside a C++/CLI library for a .NET Windows Form application but the PeekMessage never get any messages. So my render loop is infinite and the form appear frozen.

I have tried several way of doing it but here is my last try.

To start the rendering loop :

```<code>Application::Idle += gcnew EventHandler(this, &TECore::AppIdleHandler);
</code>```

Code that handle it :

```<code>void TECore::AppIdleHandler(Object^ object, EventArgs^ e)
    {
        while (IsAppIdle())
            RenderLoopCallBack();
    }

    bool TECore::IsAppIdle()
    {
        LPMSG msg = {};
        return !PeekMessage(msg, (HWND)_targetForm->Handle.ToInt32(), 0, 0, 0);
    }
</code>```

So if I am not doing anything wrong, I am constantly checking for message from my windows handle (also have tried with NULL) otherwise I do render stuff. But the window is frozen because I never get any message, IsAppIdle always return true. I can't focus the windows, resize it or anything..

Thank a lot for help.

EDIT 1 :
It's working if I do Application::DoEvent() in each frame. But what's the performance drawback ?

EDIT 2 :

I am now pretty sure that my PeekMessage don't get any message because the RenderLoop is in the class library and not directly in the WindowForm. PeekMessage work fine directly in the form code. Is that a normal behaviors ? Maybe C# when loading a CLI assembly automaticly load it on another thread ? So my PeekMessage is looking on the wrong thread ?

答:
I found my problem... Just a syntax error. Intellisense was asking for LPMSG as first parameter for PeekMessage (never used that before) and in fact I needed to pass a MSG pointer. So PeekMessage was probably failing in silence...

With the correct syntax it work fine.

WRONG SYNTAX

```<code>bool TECore::IsAppIdle()
{
    LPMSG msg = {};
    return !PeekMessage(msg, NULL, 0, 0, 0);
}
</code>```

RIGHT SYNTAX

```<code>bool TECore::IsAppIdle()
{
    MSG msg = {};
    return !PeekMessage(&msg, NULL, 0, 0, 0);
}
</code>```

Title: PeekMessage don't get any message

Body:
I am trying to create a rendering loop inside a C++/CLI library for a .NET Windows Form application but the PeekMessage never get any messages. So my render loop is infinite and the form appear frozen.

I have tried several way of doing it but here is my last try.

To start the rendering loop :

Application::Idle += gcnew EventHandler(this, &TECore::AppIdleHandler);

Code that handle it :

void TECore::AppIdleHandler(Object^ object, EventArgs^ e)
    {
        while (IsAppIdle())
            RenderLoopCallBack();
    }

    bool TECore::IsAppIdle()
    {
        LPMSG msg = {};
        return !PeekMessage(msg, (HWND)_targetForm->Handle.ToInt32(), 0, 0, 0);
    }

So if I am not doing anything wrong, I am constantly checking for message from my windows handle (also have tried with NULL) otherwise I do render stuff. But the window is frozen because I never get any message, IsAppIdle always return true. I can't focus the windows, resize it or anything..

Thank a lot for help.

EDIT 1 :
It's working if I do Application::DoEvent() in each frame. But what's the performance drawback ?

EDIT 2 :

I am now pretty sure that my PeekMessage don't get any message because the RenderLoop is in the class library and not directly in the WindowForm. PeekMessage work fine directly in the form code. Is that a normal behaviors ? Maybe C# when loading a CLI assembly automaticly load it on another thread ? So my PeekMessage is looking on the wrong thread ?

Body:
I found my problem... Just a syntax error. Intellisense was asking for LPMSG as first parameter for PeekMessage (never used that before) and in fact I needed to pass a MSG pointer. So PeekMessage was probably failing in silence...

With the correct syntax it work fine.

WRONG SYNTAX

bool TECore::IsAppIdle()
{
    LPMSG msg = {};
    return !PeekMessage(msg, NULL, 0, 0, 0);
}

RIGHT SYNTAX

bool TECore::IsAppIdle()
{
    MSG msg = {};
    return !PeekMessage(&msg, NULL, 0, 0, 0);
}


问:
Kubernetes: single POD with many container, or many Pod with single container
I've rather a teoretical question which I can't answer  with the reousrces found online. The question is: what's the rule to decide how to compose containers in POD? . Let me explain with an example.

I've these microservices:

Authentication

Authorization

Serving content

(plus) OpenResty to forward the calls form one to the other and orhcestarate the flow. (is there a possibility to do so natively in K8?, it seems to have services base on nginx+lua, but not sure how it works)

For the sake of the example I avoid Databases and co, I assume they are external and not managed by kubernetes

Now, what's the correct way here LEFT or RIGHT of the image?

LEFT : this seems easier to make it working, everything works on "localhost" , the downside is that it looses a bit the benefit of the microservices. For example, if the auth become slows and it would need more instances, I've to duplicate the whole pod and not just that service.

RIGHT seems a bit more complex, need services to expose each POD to the other PODs. Yet, here, I could duplicate auth as I need without duplicating the other containers. On the other hand I'll have a lot of pods since each pod is basically a container.

答: Should choose the right side of the structure, on the grounds that the deployment of the left side of the architecture model is tight coupling is not conducive to a module according to the actual needs of the business expansion capacity.</p>


答:
The first snippet compiles because both lambdas are implicitly convertible to int(*)(int), so the compiler can use that as the type of the ?: expression and thus to deduce the  type of result.

If the capture list is non-empty (case 2) no such conversion to pointer-to-function exists (5.1.2/6 in N4141), so we end up with two unrelated types with no common implicit conversion target as the 2nd and 3rd operand of operator?: and thus the type of the ternary expression can no longer be deduced.

In case 3 we have a generic lambda, which, if the capture list is empty, has a conversion operator with a so called invented template-parameter-list which defines a set possible conversions. In our specific case here, the generic lambdas are convertible to T2(*)(T1), where T1 is the type deduced for the argument and T2 is lambda's deduced return type. Long story short: There is no rule to pick a "best conversion" from that set, so again, the compiler cannot deduce a type for our ternary expression.

Title: Why does returning lambdas between branches of ternary operator work for some lambdas?


问:
CSS based on Condition

/* BOC - GRID VIEW */
.ribbongrid {
   position: absolute;
   left: 10px; top: -5px;
   z-index: 1;
   overflow: hidden;
   width: 75px; height: 75px;
   text-align: right;
}
.ribbongrid span {
   font-size: 10px;
   color: #fff;
   text-transform: uppercase;
   text-align: center;
   font-weight: bold; line-height: 20px;
   transform: rotate(-45deg);
   width: 100px; display: block;
   background: #79A70A;
   background: linear-gradient(#9BC90D 0%, #79A70A 100%);
   box-shadow: 0 3px 10px -5px rgba(0, 0, 0, 1);
   position: absolute;
   top: 19px; left: -21px;
}
.ribbongrid span::before {
   content: '';
   position: absolute;
   left: 0px; top: 100%;
   z-index: -1;
   border-left: 3px solid #79A70A;
   border-right: 3px solid transparent;
   border-bottom: 3px solid transparent;
   border-top: 3px solid #79A70A;
}
.ribbongrid span::after {
   content: '';
   position: absolute;
   right: 0%; top: 100%;
   z-index: -1;
   border-right: 3px solid #79A70A;
   border-left: 3px solid transparent;
   border-bottom: 3px solid transparent;
   border-top: 3px solid #79A70A;
}
.red span {background: linear-gradient(#F70505 0%, #8F0808 100%);}
.red span::before {border-left-color: #8F0808; border-top-color: #8F0808;}
.red span::after {border-right-color: #8F0808; border-top-color: #8F0808;}

.blue span {background: linear-gradient(#2989d8 0%, #1e5799 100%);}
.blue span::before {border-left-color: #1e5799; border-top-color: #1e5799;}
.blue span::after {border-right-color: #1e5799; border-top-color: #1e5799;}
/* EOC - GRID VIEW */

/* BOC - LIST VIEW */
.ribbonlist {
   position: absolute;
   left: 10px; top: 5px;
   z-index: 1;
   overflow: hidden;
   width: 75px; height: 75px;
   text-align: right;
}
.ribbonlist span {
   font-size: 10px;
   color: #fff;
   text-transform: uppercase;
   text-align: center;
   font-weight: bold; line-height: 20px;
   transform: rotate(-45deg);
   width: 100px; display: block;
   background: #79A70A;
   background: linear-gradient(#9BC90D 0%, #79A70A 100%);
   box-shadow: 0 3px 10px -5px rgba(0, 0, 0, 1);
   position: absolute;
   top: 19px; left: -21px;
}
.ribbonlist span::before {
   content: '';
   position: absolute;
   left: 0px; top: 100%;
   z-index: -1;
   border-left: 3px solid #79A70A;
   border-right: 3px solid transparent;
   border-bottom: 3px solid transparent;
   border-top: 3px solid #79A70A;
}
.ribbonlist span::after {
   content: '';
   position: absolute;
   right: 0%; top: 100%;
   z-index: -1;
   border-right: 3px solid #79A70A;
   border-left: 3px solid transparent;
   border-bottom: 3px solid transparent;
   border-top: 3px solid #79A70A;
}
.red span {background: linear-gradient(#F70505 0%, #8F0808 100%);}
.red span::before {border-left-color: #8F0808; border-top-color: #8F0808;}
.red span::after {border-right-color: #8F0808; border-top-color: #8F0808;}

.blue span {background: linear-gradient(#2989d8 0%, #1e5799 100%);}
.blue span::before {border-left-color: #1e5799; border-top-color: #1e5799;}
.blue span::after {border-right-color: #1e5799; border-top-color: #1e5799;}
/* EOC - LIST VIEW */```
<pre class="snippet-code-html lang-html prettyprint-override"><code>if (Grid_View = 'True') {
  <div class="ribbongrid blue"><span>Special</span></div>
} else {
  <div class="ribbonlist blue"><span>Special</span></div>
}</code>```

The only difference between the two css is changing the height from grid        left: 10px; top: -5px; ---------->       list left: 10px; top: 5px;

This was just an example. Is there a way of combining the two css just to optimise the code rather copying and pasting several times?

答:
Just create two new classes(for changing the height from grid left: 10px; top: -5px; ----------> list left: 10px; top: 5px;) and have a common CSS for everything else. And then use JavaScript to switch between those 2 classes.

FOR EXAMPLE:

The code given by you can be modified like this,

CSS:

```<code>/*RIBBON GRID*/
.ribbon_grid {
   left: 10px;
   top: -5px;
}

/*RIBBON LIST*/
.ribbon_list {
   left: 10px;
   top: 5px;
}

/*COMMON CODE FOR BOTH RIBBONS*/
.ribbon {
   position: absolute;
   z-index: 1;
   overflow: hidden;
   width: 75px; height: 75px;
   text-align: right;
}
.ribbon span {
   font-size: 10px;
   color: #fff;
   text-transform: uppercase;
   text-align: center;
   font-weight: bold; line-height: 20px;
   transform: rotate(-45deg);
   width: 100px; display: block;
   background: #79A70A;
   background: linear-gradient(#9BC90D 0%, #79A70A 100%);
   box-shadow: 0 3px 10px -5px rgba(0, 0, 0, 1);
   position: absolute;
   top: 19px; left: -21px;
}
.ribbon span::before {
   content: '';
   position: absolute;
   left: 0px; top: 100%;
   z-index: -1;
   border-left: 3px solid #79A70A;
   border-right: 3px solid transparent;
   border-bottom: 3px solid transparent;
   border-top: 3px solid #79A70A;
}
.ribbon span::after {
   content: '';
   position: absolute;
   right: 0%; top: 100%;
   z-index: -1;
   border-right: 3px solid #79A70A;
   border-left: 3px solid transparent;
   border-bottom: 3px solid transparent;
   border-top: 3px solid #79A70A;
}
.red span {background: linear-gradient(#F70505 0%, #8F0808 100%);}
.red span::before {border-left-color: #8F0808; border-top-color: #8F0808;}
.red span::after {border-right-color: #8F0808; border-top-color: #8F0808;}

.blue span {background: linear-gradient(#2989d8 0%, #1e5799 100%);}
.blue span::before {border-left-color: #1e5799; border-top-color: #1e5799;}
.blue span::after {border-right-color: #1e5799; border-top-color: #1e5799;}
</code>```

JAVASCRIPT:

```<code>if (Grid_View = 'True') {
  <div class="ribbon ribbon_grid blue"><span>Special</span></div>
} else {
  <div class="ribbon ribbon_list blue"><span>Special</span></div>
}
</code>```

Hope this helps :)

Title: CSS based on Condition

Body:
/* BOC - GRID VIEW */
.ribbongrid {
   position: absolute;
   left: 10px; top: -5px;
   z-index: 1;
   overflow: hidden;
   width: 75px; height: 75px;
   text-align: right;
}
.ribbongrid span {
   font-size: 10px;
   color: #fff;
   text-transform: uppercase;
   text-align: center;
   font-weight: bold; line-height: 20px;
   transform: rotate(-45deg);
   width: 100px; display: block;
   background: #79A70A;
   background: linear-gradient(#9BC90D 0%, #79A70A 100%);
   box-shadow: 0 3px 10px -5px rgba(0, 0, 0, 1);
   position: absolute;
   top: 19px; left: -21px;
}
.ribbongrid span::before {
   content: '';
   position: absolute;
   left: 0px; top: 100%;
   z-index: -1;
   border-left: 3px solid #79A70A;
   border-right: 3px solid transparent;
   border-bottom: 3px solid transparent;
   border-top: 3px solid #79A70A;
}
.ribbongrid span::after {
   content: '';
   position: absolute;
   right: 0%; top: 100%;
   z-index: -1;
   border-right: 3px solid #79A70A;
   border-left: 3px solid transparent;
   border-bottom: 3px solid transparent;
   border-top: 3px solid #79A70A;
}
.red span {background: linear-gradient(#F70505 0%, #8F0808 100%);}
.red span::before {border-left-color: #8F0808; border-top-color: #8F0808;}
.red span::after {border-right-color: #8F0808; border-top-color: #8F0808;}

.blue span {background: linear-gradient(#2989d8 0%, #1e5799 100%);}
.blue span::before {border-left-color: #1e5799; border-top-color: #1e5799;}
.blue span::after {border-right-color: #1e5799; border-top-color: #1e5799;}
/* EOC - GRID VIEW */

/* BOC - LIST VIEW */
.ribbonlist {
   position: absolute;
   left: 10px; top: 5px;
   z-index: 1;
   overflow: hidden;
   width: 75px; height: 75px;
   text-align: right;
}
.ribbonlist span {
   font-size: 10px;
   color: #fff;
   text-transform: uppercase;
   text-align: center;
   font-weight: bold; line-height: 20px;
   transform: rotate(-45deg);
   width: 100px; display: block;
   background: #79A70A;
   background: linear-gradient(#9BC90D 0%, #79A70A 100%);
   box-shadow: 0 3px 10px -5px rgba(0, 0, 0, 1);
   position: absolute;
   top: 19px; left: -21px;
}
.ribbonlist span::before {
   content: '';
   position: absolute;
   left: 0px; top: 100%;
   z-index: -1;
   border-left: 3px solid #79A70A;
   border-right: 3px solid transparent;
   border-bottom: 3px solid transparent;
   border-top: 3px solid #79A70A;
}
.ribbonlist span::after {
   content: '';
   position: absolute;
   right: 0%; top: 100%;
   z-index: -1;
   border-right: 3px solid #79A70A;
   border-left: 3px solid transparent;
   border-bottom: 3px solid transparent;
   border-top: 3px solid #79A70A;
}
.red span {background: linear-gradient(#F70505 0%, #8F0808 100%);}
.red span::before {border-left-color: #8F0808; border-top-color: #8F0808;}
.red span::after {border-right-color: #8F0808; border-top-color: #8F0808;}

.blue span {background: linear-gradient(#2989d8 0%, #1e5799 100%);}
.blue span::before {border-left-color: #1e5799; border-top-color: #1e5799;}
.blue span::after {border-right-color: #1e5799; border-top-color: #1e5799;}
/* EOC - LIST VIEW */

if (Grid_View = 'True') {

Special

} else {

Special

}

The only difference between the two css is changing the height from grid        left: 10px; top: -5px; ---------->       list left: 10px; top: 5px;

This was just an example. Is there a way of combining the two css just to optimise the code rather copying and pasting several times?

Body:
Just create two new classes(for changing the height from grid left: 10px; top: -5px; ----------> list left: 10px; top: 5px;) and have a common CSS for everything else. And then use JavaScript to switch between those 2 classes.

FOR EXAMPLE:

The code given by you can be modified like this,

CSS:

/*RIBBON GRID*/
.ribbon_grid {
   left: 10px;
   top: -5px;
}

/*RIBBON LIST*/
.ribbon_list {
   left: 10px;
   top: 5px;
}

/*COMMON CODE FOR BOTH RIBBONS*/
.ribbon {
   position: absolute;
   z-index: 1;
   overflow: hidden;
   width: 75px; height: 75px;
   text-align: right;
}
.ribbon span {
   font-size: 10px;
   color: #fff;
   text-transform: uppercase;
   text-align: center;
   font-weight: bold; line-height: 20px;
   transform: rotate(-45deg);
   width: 100px; display: block;
   background: #79A70A;
   background: linear-gradient(#9BC90D 0%, #79A70A 100%);
   box-shadow: 0 3px 10px -5px rgba(0, 0, 0, 1);
   position: absolute;
   top: 19px; left: -21px;
}
.ribbon span::before {
   content: '';
   position: absolute;
   left: 0px; top: 100%;
   z-index: -1;
   border-left: 3px solid #79A70A;
   border-right: 3px solid transparent;
   border-bottom: 3px solid transparent;
   border-top: 3px solid #79A70A;
}
.ribbon span::after {
   content: '';
   position: absolute;
   right: 0%; top: 100%;
   z-index: -1;
   border-right: 3px solid #79A70A;
   border-left: 3px solid transparent;
   border-bottom: 3px solid transparent;
   border-top: 3px solid #79A70A;
}
.red span {background: linear-gradient(#F70505 0%, #8F0808 100%);}
.red span::before {border-left-color: #8F0808; border-top-color: #8F0808;}
.red span::after {border-right-color: #8F0808; border-top-color: #8F0808;}

.blue span {background: linear-gradient(#2989d8 0%, #1e5799 100%);}
.blue span::before {border-left-color: #1e5799; border-top-color: #1e5799;}
.blue span::after {border-right-color: #1e5799; border-top-color: #1e5799;}

JAVASCRIPT:

if (Grid_View = 'True') {
  <div class="ribbon ribbon_grid blue"><span>Special</span></div>
} else {
  <div class="ribbon ribbon_list blue"><span>Special</span></div>
}

Hope this helps :)


问:
Where is the place for altering validation?
Sometimes I need not to simply validate smth in my app, but also alter it before/after validating.
I.e.

```<code> class Channel < ActiveRecord::Base
  validate :validate_url
  ...
  private
  def validate_url
    url = "rtmp://#{url}" if server_url[0..6] != "rtmp://" #alter cause need this prefix
    unless /rtmp:\/\/[a-z0-9]{1,3}\.pscp\.tv:80\/[a-z0-9]\/[a-z0-9]{1,3}\//.match url
      errors.add(:url, "...")
    end
  end
end
</code>```

or smth like this

```<code>class Channel < ActiveRecord::Base
  validate :validate_restreams
  ...
  private
  def validate_restreams
    self.left_restreams = self.left_restreams - self.restreams #to be sure there's no intersections
  end
end
</code>```

But I feel it's not a right place for such things, so I need to know what's the way to do it right?

答:
You can create a custom validator for a rails model. You should make a class, inherit it from ActiveModel::Validator, and define a validate(record) method there, which will add errors to the record. For example:

This is your validator class:

```<code>class MyValidator < ActiveModel::Validator
  def validate(record)
    unless url_valid?(record[:url])
      record.errors.add(:url, 'is invalid')
    end
  end

  private

  def url_valid?(url)
    # validate url and return bool
  end
end
</code>```

And now simply add this to the model:

```<code>validates_with MyValidator
</code>```

Body:
Sometimes I need not to simply validate smth in my app, but also alter it before/after validating.
I.e.

 class Channel < ActiveRecord::Base
  validate :validate_url
  ...
  private
  def validate_url
    url = "rtmp://#{url}" if server_url[0..6] != "rtmp://" #alter cause need this prefix
    unless /rtmp:\/\/[a-z0-9]{1,3}\.pscp\.tv:80\/[a-z0-9]\/[a-z0-9]{1,3}\//.match url
      errors.add(:url, "...")
    end
  end
end

or smth like this

class Channel < ActiveRecord::Base
  validate :validate_restreams
  ...
  private
  def validate_restreams
    self.left_restreams = self.left_restreams - self.restreams #to be sure there's no intersections
  end
end

But I feel it's not a right place for such things, so I need to know what's the way to do it right?

Body:
You can create a custom validator for a rails model. You should make a class, inherit it from ActiveModel::Validator, and define a validate(record) method there, which will add errors to the record. For example:

This is your validator class:

class MyValidator < ActiveModel::Validator
  def validate(record)
    unless url_valid?(record[:url])
      record.errors.add(:url, 'is invalid')
    end
  end

  private

  def url_valid?(url)
    # validate url and return bool
  end
end

And now simply add this to the model:

validates_with MyValidator


问:
Shared preference value is null in my second acivity
I need to use string data inside OnReceivedDataMethod into second activity in order to save those string data into file but currently i have empty data into my file

```<code> SharedPreferences sp;
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
    @Override
    public void onReceivedData(byte[] arg0) {

        try {
            data = new String(arg0, "UTF-8");
            data.concat("/n");
             sp = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
            SharedPreferences.Editor et = sp.edit();
            et.putString("key",data);
            et.apply();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
};
</code>```

In second activity

```<code>    protected void onCreate(Bundle savedInstanceState) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    desiredPreference =  sharedPreferences.getString("key","data");
    Toast.makeText(this,"spdata"+desiredPreference,Toast.LENGTH_LONG).show();

}
</code>```

答:
Do something like this,

For storing

```<code>    SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString("key", data);
    editor.commit();
</code>```

for Retriving

```<code>  SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
  String checkDate = sharedPref.getString("key","");
</code>```

Body:
I need to use string data inside OnReceivedDataMethod into second activity in order to save those string data into file but currently i have empty data into my file

 SharedPreferences sp;
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
    @Override
    public void onReceivedData(byte[] arg0) {

        try {
            data = new String(arg0, "UTF-8");
            data.concat("/n");
             sp = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
            SharedPreferences.Editor et = sp.edit();
            et.putString("key",data);
            et.apply();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
};

In second activity

    protected void onCreate(Bundle savedInstanceState) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    desiredPreference =  sharedPreferences.getString("key","data");
    Toast.makeText(this,"spdata"+desiredPreference,Toast.LENGTH_LONG).show();

}

Body:
Do something like this,

For storing

    SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString("key", data);
    editor.commit();

for Retriving

  SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
  String checkDate = sharedPref.getString("key","");


问:
Build a React App in Elastic Beanstalk
I followed these instructions and I made a hello world app with React. I uploaded the development files in my EBS and it worked.

After that I used the command npm run build, I followed the instructions, I installed the push-state and I tested using localhost. Everything worked fine.

But I uploaded the build files to my EBS and it complains that the app does not have the package.json file and the app does not work.

What do I have to do to put in package.json to deploy my react app using Elastic Beanstalk? How to deploy the build files generated by npm run build in EBS?

答:
I recently deployed my react node based app using the EB CLI. I had to run eb init in my project directory which walks you through setting up the eb config. Here's the steps:

npm init to setup package.json (which you've done)

git init to setup a git repo

eb init to setup elastic beanstalk settings through its CLI

commit code

deploy to eb with eb deploy

AWS walks you through these steps assuming you're serving your app with node (which you didn't say, but it's likely).

As a bonus, you might want to setup CI so that AWS builds your app when your tests pass on code push. See the travis yaml file I use to do this.

Title: Build a React App in Elastic Beanstalk


问:
Drop down menu with fixed navbar
I have fixed navigation in my site, but when i scroll down page mouse hover, drop down open but with a gap and as soon as i put mouse hover on it, that drop down go top around 10px. Can any one solve my issue please? my link is

http://blackrovermedia.com/demo/

答:
Here's a screenshot of the modifications I did : http://prntscr.com/er46v9

Basically, when you hover the link the sub-UL has a top of 52px but you forgot to remove (to those 52px) the paddingTop of 11px of the A itself therefore there's a gap ;) !

Title: Drop down menu with fixed navbar


问:
The "metadata.json" file for the box 'ubuntu/trusty64' was not found
when i run vagrant up command i got the following error

$ vagrant up
The "metadata.json" file for the box 'ubuntu/trusty64' was not found.
Boxes require this file in order for Vagrant to determine the
provider it was made for. If you made the box, please add a
"metadata.json" file to it. If someone else made the box, please
notify the box creator that the box is corrupt. Documentation for
box file format can be found at the URL below:

https://www.vagrantup.com/docs/boxes/format.html

答: Try vagrant box add ubuntu/trusty64 before vagrant up


问:
Sort an array without using loops in java
How to get second maximum value from array without using nested loops in java?
For eg: int [] arr = {2,4,1,6,5,9,0,7}
        Output : 7</p>

答:
Try this:</p>

```<code>import java.util.Arrays;
...
Arrays.sort(arr);
result = arr[arr.length - 2];
</code>```

Body:
Try this:

import java.util.Arrays;
...
Arrays.sort(arr);
result = arr[arr.length - 2];


问:
Spring Boot Shutting Down After Adding JPA
I have a spring boot 1.5.2.RELEASE project that was very simple and just had a few Rest Services.
When I added spring-boot-starter-data-jpa - all of a sudden the server just wont stay active
I have added these logs for example (note - i have commented out the configuration of the datasource and this still happens - tomcat shutsdown after starting up)

```<code>2017-04-01 12:10:25 <> DEBUG logging:19 - Logging Provider: org.jboss.logging.Log4jLoggerProvider
2017-04-01 12:10:25 <> INFO  Version:30 - HV000001: Hibernate Validator 5.3.4.Final
2017-04-01 12:10:25 <> DEBUG DefaultTraversableResolver:103 - Found javax.persistence.Persistence on classpath containing 'getPersistenceUtil'. Assuming JPA 2 environment. Trying to instantiate JPA aware TraversableResolver
2017-04-01 12:10:25 <> DEBUG DefaultTraversableResolver:114 - Instantiated JPA aware TraversableResolver of type org.hibernate.validator.internal.engine.resolver.JPATraversableResolver.
2017-04-01 12:10:26 <> DEBUG DefaultTraversableResolver:103 - Found javax.persistence.Persistence on classpath containing 'getPersistenceUtil'. Assuming JPA 2 environment. Trying to instantiate JPA aware TraversableResolver
2017-04-01 12:10:26 <> DEBUG DefaultTraversableResolver:114 - Instantiated JPA aware TraversableResolver of type org.hibernate.validator.internal.engine.resolver.JPATraversableResolver.
2017-04-01 12:10:26 <> DEBUG DefaultTraversableResolver:103 - Found javax.persistence.Persistence on classpath containing 'getPersistenceUtil'. Assuming JPA 2 environment. Trying to instantiate JPA aware TraversableResolver
2017-04-01 12:10:26 <> DEBUG DefaultTraversableResolver:114 - Instantiated JPA aware TraversableResolver of type org.hibernate.validator.internal.engine.resolver.JPATraversableResolver.
2017-04-01 12:10:26 <> DEBUG ConfigurationImpl:163 - Setting custom MessageInterpolator of type org.springframework.validation.beanvalidation.LocaleContextMessageInterpolator
2017-04-01 12:10:26 <> DEBUG ConfigurationImpl:185 - Setting custom ConstraintValidatorFactory of type org.springframework.validation.beanvalidation.SpringConstraintValidatorFactory
2017-04-01 12:10:26 <> DEBUG ConfigurationImpl:199 - Setting custom ParameterNameProvider of type com.sun.proxy.$Proxy44
2017-04-01 12:10:26 <> DEBUG ValidationXmlParser:91 - Trying to load META-INF/validation.xml for XML based Validator configuration.
2017-04-01 12:10:26 <> DEBUG ResourceLoaderHelper:47 - Trying to load META-INF/validation.xml via user class loader
2017-04-01 12:10:26 <> DEBUG ResourceLoaderHelper:54 - Trying to load META-INF/validation.xml via TCCL
2017-04-01 12:10:26 <> DEBUG ResourceLoaderHelper:60 - Trying to load META-INF/validation.xml via Hibernate Validator's class loader
2017-04-01 12:10:26 <> DEBUG ValidationXmlParser:98 - No META-INF/validation.xml found. Using annotation based configuration only.
2017-04-01 12:10:26 <> DEBUG DefaultTraversableResolver:103 - Found javax.persistence.Persistence on classpath containing 'getPersistenceUtil'. Assuming JPA 2 environment. Trying to instantiate JPA aware TraversableResolver
2017-04-01 12:10:26 <> DEBUG DefaultTraversableResolver:114 - Instantiated JPA aware TraversableResolver of type org.hibernate.validator.internal.engine.resolver.JPATraversableResolver.
2017-04-01 12:10:26 <> DEBUG DefaultTraversableResolver:103 - Found javax.persistence.Persistence on classpath containing 'getPersistenceUtil'. Assuming JPA 2 environment. Trying to instantiate JPA aware TraversableResolver
2017-04-01 12:10:26 <> DEBUG DefaultTraversableResolver:114 - Instantiated JPA aware TraversableResolver of type org.hibernate.validator.internal.engine.resolver.JPATraversableResolver.
2017-04-01 12:10:26 <> DEBUG ConfigurationImpl:163 - Setting custom MessageInterpolator of type org.springframework.validation.beanvalidation.LocaleContextMessageInterpolator
2017-04-01 12:10:26 <> DEBUG ConfigurationImpl:185 - Setting custom ConstraintValidatorFactory of type org.springframework.validation.beanvalidation.SpringConstraintValidatorFactory
2017-04-01 12:10:26 <> DEBUG ConfigurationImpl:199 - Setting custom ParameterNameProvider of type com.sun.proxy.$Proxy44
2017-04-01 12:10:26 <> DEBUG ValidationXmlParser:91 - Trying to load META-INF/validation.xml for XML based Validator configuration.
2017-04-01 12:10:26 <> DEBUG ResourceLoaderHelper:47 - Trying to load META-INF/validation.xml via user class loader
2017-04-01 12:10:26 <> DEBUG ResourceLoaderHelper:54 - Trying to load META-INF/validation.xml via TCCL
2017-04-01 12:10:26 <> DEBUG ResourceLoaderHelper:60 - Trying to load META-INF/validation.xml via Hibernate Validator's class loader
2017-04-01 12:10:26 <> DEBUG ValidationXmlParser:98 - No META-INF/validation.xml found. Using annotation based configuration only.
Apr 01, 2017 12:10:27 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Tomcat
Apr 01, 2017 12:10:27 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.5.11
Apr 01, 2017 12:10:27 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring embedded WebApplicationContext
Apr 01, 2017 12:10:27 PM org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service Tomcat
</code>```

Can anyone offer any insight into how I can stop this behaviour?
Full loggign output is available here - https://pastebin.com/3yqkex6i
Thanks
Damien

答:
This was an application error
I am deploying my application on Amazon lambda and need to use log4j2

Hence I had the following in my pom

```<code><dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</code>```

By removing the exclusion - it showed me what the application error was and I was able then to quickly resolve it (damn you log4j2 :) )

Body:
I have a spring boot 1.5.2.RELEASE project that was very simple and just had a few Rest Services.
When I added spring-boot-starter-data-jpa - all of a sudden the server just wont stay active
I have added these logs for example (note - i have commented out the configuration of the datasource and this still happens - tomcat shutsdown after starting up)

2017-04-01 12:10:25 <> DEBUG logging:19 - Logging Provider: org.jboss.logging.Log4jLoggerProvider
2017-04-01 12:10:25 <> INFO  Version:30 - HV000001: Hibernate Validator 5.3.4.Final
2017-04-01 12:10:25 <> DEBUG DefaultTraversableResolver:103 - Found javax.persistence.Persistence on classpath containing 'getPersistenceUtil'. Assuming JPA 2 environment. Trying to instantiate JPA aware TraversableResolver
2017-04-01 12:10:25 <> DEBUG DefaultTraversableResolver:114 - Instantiated JPA aware TraversableResolver of type org.hibernate.validator.internal.engine.resolver.JPATraversableResolver.
2017-04-01 12:10:26 <> DEBUG DefaultTraversableResolver:103 - Found javax.persistence.Persistence on classpath containing 'getPersistenceUtil'. Assuming JPA 2 environment. Trying to instantiate JPA aware TraversableResolver
2017-04-01 12:10:26 <> DEBUG DefaultTraversableResolver:114 - Instantiated JPA aware TraversableResolver of type org.hibernate.validator.internal.engine.resolver.JPATraversableResolver.
2017-04-01 12:10:26 <> DEBUG DefaultTraversableResolver:103 - Found javax.persistence.Persistence on classpath containing 'getPersistenceUtil'. Assuming JPA 2 environment. Trying to instantiate JPA aware TraversableResolver
2017-04-01 12:10:26 <> DEBUG DefaultTraversableResolver:114 - Instantiated JPA aware TraversableResolver of type org.hibernate.validator.internal.engine.resolver.JPATraversableResolver.
2017-04-01 12:10:26 <> DEBUG ConfigurationImpl:163 - Setting custom MessageInterpolator of type org.springframework.validation.beanvalidation.LocaleContextMessageInterpolator
2017-04-01 12:10:26 <> DEBUG ConfigurationImpl:185 - Setting custom ConstraintValidatorFactory of type org.springframework.validation.beanvalidation.SpringConstraintValidatorFactory
2017-04-01 12:10:26 <> DEBUG ConfigurationImpl:199 - Setting custom ParameterNameProvider of type com.sun.proxy.$Proxy44
2017-04-01 12:10:26 <> DEBUG ValidationXmlParser:91 - Trying to load META-INF/validation.xml for XML based Validator configuration.
2017-04-01 12:10:26 <> DEBUG ResourceLoaderHelper:47 - Trying to load META-INF/validation.xml via user class loader
2017-04-01 12:10:26 <> DEBUG ResourceLoaderHelper:54 - Trying to load META-INF/validation.xml via TCCL
2017-04-01 12:10:26 <> DEBUG ResourceLoaderHelper:60 - Trying to load META-INF/validation.xml via Hibernate Validator's class loader
2017-04-01 12:10:26 <> DEBUG ValidationXmlParser:98 - No META-INF/validation.xml found. Using annotation based configuration only.
2017-04-01 12:10:26 <> DEBUG DefaultTraversableResolver:103 - Found javax.persistence.Persistence on classpath containing 'getPersistenceUtil'. Assuming JPA 2 environment. Trying to instantiate JPA aware TraversableResolver
2017-04-01 12:10:26 <> DEBUG DefaultTraversableResolver:114 - Instantiated JPA aware TraversableResolver of type org.hibernate.validator.internal.engine.resolver.JPATraversableResolver.
2017-04-01 12:10:26 <> DEBUG DefaultTraversableResolver:103 - Found javax.persistence.Persistence on classpath containing 'getPersistenceUtil'. Assuming JPA 2 environment. Trying to instantiate JPA aware TraversableResolver
2017-04-01 12:10:26 <> DEBUG DefaultTraversableResolver:114 - Instantiated JPA aware TraversableResolver of type org.hibernate.validator.internal.engine.resolver.JPATraversableResolver.
2017-04-01 12:10:26 <> DEBUG ConfigurationImpl:163 - Setting custom MessageInterpolator of type org.springframework.validation.beanvalidation.LocaleContextMessageInterpolator
2017-04-01 12:10:26 <> DEBUG ConfigurationImpl:185 - Setting custom ConstraintValidatorFactory of type org.springframework.validation.beanvalidation.SpringConstraintValidatorFactory
2017-04-01 12:10:26 <> DEBUG ConfigurationImpl:199 - Setting custom ParameterNameProvider of type com.sun.proxy.$Proxy44
2017-04-01 12:10:26 <> DEBUG ValidationXmlParser:91 - Trying to load META-INF/validation.xml for XML based Validator configuration.
2017-04-01 12:10:26 <> DEBUG ResourceLoaderHelper:47 - Trying to load META-INF/validation.xml via user class loader
2017-04-01 12:10:26 <> DEBUG ResourceLoaderHelper:54 - Trying to load META-INF/validation.xml via TCCL
2017-04-01 12:10:26 <> DEBUG ResourceLoaderHelper:60 - Trying to load META-INF/validation.xml via Hibernate Validator's class loader
2017-04-01 12:10:26 <> DEBUG ValidationXmlParser:98 - No META-INF/validation.xml found. Using annotation based configuration only.
Apr 01, 2017 12:10:27 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Tomcat
Apr 01, 2017 12:10:27 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.5.11
Apr 01, 2017 12:10:27 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring embedded WebApplicationContext
Apr 01, 2017 12:10:27 PM org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service Tomcat

Can anyone offer any insight into how I can stop this behaviour?
Full loggign output is available here - https://pastebin.com/3yqkex6i
Thanks
Damien

Body:
This was an application error
I am deploying my application on Amazon lambda and need to use log4j2

Hence I had the following in my pom

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

By removing the exclusion - it showed me what the application error was and I was able then to quickly resolve it (damn you log4j2 :) )


问:
How to force checkbox to behave like radiobutton, double loop
I have checkboxes in 2 for loops. I want to force them to behave like radiobuttons. There should be only one option chosen for each Q (first loop).
I have a peace of code, but it doesn't work. How to change it?</p>

```<code>script type="text/javascript">

    var classes = $('.myDiv').map(function () {
        return $(this).attr('class');
    }).get();

    $.each(classes, function(i) {
        $(classes[i]).change(function() {
            var checked = $(this).is(':checked');
            $(classes[i]).prop('checked',false);
            if(checked[i]) {
                $(this).prop('checked',true);
            }
        });
    });
</code>```

答:
Add a common class to the checkbox input and then use that class like below

$("input:checkbox").change(function() {
      $(this).siblings().prop('checked', false);
      $(this).prop('checked', true);
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
 <tr>
  <td>
      <input type="checkbox" value="1" />
   <input type="checkbox" value="1" />
   <input type="checkbox" value="1" />
  </td>
 </tr>
 <tr>
  <td>
   <input type="checkbox" value="1" />
   <input type="checkbox" value="1" />
   <input type="checkbox" value="1" />
  </td>
 </tr>
</table></code>```

Body:
I have checkboxes in 2 for loops. I want to force them to behave like radiobuttons. There should be only one option chosen for each Q (first loop).
I have a peace of code, but it doesn't work. How to change it?

script type="text/javascript">

    var classes = $('.myDiv').map(function () {
        return $(this).attr('class');
    }).get();

    $.each(classes, function(i) {
        $(classes[i]).change(function() {
            var checked = $(this).is(':checked');
            $(classes[i]).prop('checked',false);
            if(checked[i]) {
                $(this).prop('checked',true);
            }
        });
    });

Body:
Add a common class to the checkbox input and then use that class like below

$("input:checkbox").change(function() {
      $(this).siblings().prop('checked', false);
      $(this).prop('checked', true);
  });

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

<table>
 <tr>
  <td>
      <input type="checkbox" value="1" />
   <input type="checkbox" value="1" />
   <input type="checkbox" value="1" />
  </td>
 </tr>
 <tr>
  <td>
   <input type="checkbox" value="1" />
   <input type="checkbox" value="1" />
   <input type="checkbox" value="1" />
  </td>
 </tr>
</table>


问:
Numpy to reorder such that every nth row from the current row is appended to it
I want to reshape the Numpy array A, not by appending normal next row, but by appending every Nth row that comes after it.

Ex:

```<code>A = [[1  2  3  4]
[5  6  7  8]
[9  10 11 12]
[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]
</code>```

Now, I want to construct an array of size 2x12 like this from A

```<code> A = [[1 2 3 4 9 10 11 12 17 18 19 10]
 [5 6 7 8 13 14 15 16 21 22 23 24]]
</code>```

Here You can see that every 2nd row from the current row is appended to it and formed the new reshaped array.

Body:
I want to reshape the Numpy array A, not by appending normal next row, but by appending every Nth row that comes after it.

Ex:

A = [[1  2  3  4]
[5  6  7  8]
[9  10 11 12]
[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]

Now, I want to construct an array of size 2x12 like this from A

 A = [[1 2 3 4 9 10 11 12 17 18 19 10]
 [5 6 7 8 13 14 15 16 21 22 23 24]]

Here You can see that every 2nd row from the current row is appended to it and formed the new reshaped array.

Body:
You can use a simple indexing, array.ravel() and np.vstack():

In [37]: np.vstack((A[::2].ravel(), A[1::2].ravel()))
Out[37]:
array([[ 1,  2,  3,  4,  9, 10, 11, 12, 17, 18, 19, 20],
       [ 5,  6,  7,  8, 13, 14, 15, 16, 21, 22, 23, 24]])


问:
Getting "Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch" on Nodejs
I'm developing an API on NodeJS using express and I'm getting this error while trying to deploy it to Heroku:

Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch

I am using the process.env.PORT variable, as I found here on SO, but it is still not working. Here's the index.js code:

```<code>var express = require('express');
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.json());
var router = require("./router");
app.use('/viatges', router);

app.listen(3000 || process.env.PORT,function(){
    console.log("up and running on port "+process.env.PORT);
});
</code>```

Do you have any idea of what could be causing this issue?

On the heroku logs i see this line

2017-04-01T11:44:07.091181+00:00 app[web.1]: up and running on port 27583

so I assume the PORT enviornment variable is correctly set up...

答:
Nevermind, i just fixed it. I changed the order of the operands in the OR, I assume javascript just went with the first as it was defined.

It now looks like this:

```<code>app.listen(process.env.PORT || 3000 ,function(){
    console.log("up and running on port "+process.env.PORT);
});
</code>```

Body:
I'm developing an API on NodeJS using express and I'm getting this error while trying to deploy it to Heroku:

Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch

I am using the process.env.PORT variable, as I found here on SO, but it is still not working. Here's the index.js code:

var express = require('express');
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.json());
var router = require("./router");
app.use('/viatges', router);

app.listen(3000 || process.env.PORT,function(){
    console.log("up and running on port "+process.env.PORT);
});

Do you have any idea of what could be causing this issue?

On the heroku logs i see this line

2017-04-01T11:44:07.091181+00:00 app[web.1]: up and running on port 27583

so I assume the PORT enviornment variable is correctly set up...

Body:
Nevermind, i just fixed it. I changed the order of the operands in the OR, I assume javascript just went with the first as it was defined.

It now looks like this:

app.listen(process.env.PORT || 3000 ,function(){
    console.log("up and running on port "+process.env.PORT);
});


问:
RTL animation Expression
I have an issue with animate my text with an expression but right to left,here is the code:
Expression Selector Based On : Characters

```<code>delay = .1;
myDelay = delay*textIndex;
t = (time - inPoint) - myDelay;
if (t >= 0){
  freq =2;
  amplitude = 07;
  decay = 8.0;
  s = amplitude*Math.cos(freq*t*2*Math.PI)/Math.exp(decay*t);
  [s,s]
}else{
  value
}
</code>```

The problem is my text animates from left to right, I want it to be from right to left.How can I ?

答:
Try replace myDelay by:</p>

```<code>myDelay = delay*(thisLayer.text.sourceText.length+1-textIndex);
</code>```

Title: RTL animation Expression

Body:
I have an issue with animate my text with an expression but right to left,here is the code:
Expression Selector Based On : Characters

delay = .1;
myDelay = delay*textIndex;
t = (time - inPoint) - myDelay;
if (t >= 0){
  freq =2;
  amplitude = 07;
  decay = 8.0;
  s = amplitude*Math.cos(freq*t*2*Math.PI)/Math.exp(decay*t);
  [s,s]
}else{
  value
}

The problem is my text animates from left to right, I want it to be from right to left.How can I ?

Body:
Try replace myDelay by:

myDelay = delay*(thisLayer.text.sourceText.length+1-textIndex);


答:
You can achieve it this way:

```<code>if (Grid_View = 'True') {
  <div class="ribbongrid blue"><span>Special</span></div>
} else {
  <div class="ribbongrid ribbonlist blue"><span>Special</span></div>
}
</code>```

and your css:

```<code>.ribbongrid {
  position: absolute;
  left: 10px;
  top: -5px;
  z-index: 1;
  overflow: hidden;
  width: 75px; height: 75px;
  text-align: right;
}

.ribbongrid.ribbonlist {
  top: 5px;
}
</code>```

This will override your top from -5px to 5px

Title: CSS based on Condition

Body:
/* BOC - GRID VIEW */
.ribbongrid {
   position: absolute;
   left: 10px; top: -5px;
   z-index: 1;
   overflow: hidden;
   width: 75px; height: 75px;
   text-align: right;
}
.ribbongrid span {
   font-size: 10px;
   color: #fff;
   text-transform: uppercase;
   text-align: center;
   font-weight: bold; line-height: 20px;
   transform: rotate(-45deg);
   width: 100px; display: block;
   background: #79A70A;
   background: linear-gradient(#9BC90D 0%, #79A70A 100%);
   box-shadow: 0 3px 10px -5px rgba(0, 0, 0, 1);
   position: absolute;
   top: 19px; left: -21px;
}
.ribbongrid span::before {
   content: '';
   position: absolute;
   left: 0px; top: 100%;
   z-index: -1;
   border-left: 3px solid #79A70A;
   border-right: 3px solid transparent;
   border-bottom: 3px solid transparent;
   border-top: 3px solid #79A70A;
}
.ribbongrid span::after {
   content: '';
   position: absolute;
   right: 0%; top: 100%;
   z-index: -1;
   border-right: 3px solid #79A70A;
   border-left: 3px solid transparent;
   border-bottom: 3px solid transparent;
   border-top: 3px solid #79A70A;
}
.red span {background: linear-gradient(#F70505 0%, #8F0808 100%);}
.red span::before {border-left-color: #8F0808; border-top-color: #8F0808;}
.red span::after {border-right-color: #8F0808; border-top-color: #8F0808;}

.blue span {background: linear-gradient(#2989d8 0%, #1e5799 100%);}
.blue span::before {border-left-color: #1e5799; border-top-color: #1e5799;}
.blue span::after {border-right-color: #1e5799; border-top-color: #1e5799;}
/* EOC - GRID VIEW */

/* BOC - LIST VIEW */
.ribbonlist {
   position: absolute;
   left: 10px; top: 5px;
   z-index: 1;
   overflow: hidden;
   width: 75px; height: 75px;
   text-align: right;
}
.ribbonlist span {
   font-size: 10px;
   color: #fff;
   text-transform: uppercase;
   text-align: center;
   font-weight: bold; line-height: 20px;
   transform: rotate(-45deg);
   width: 100px; display: block;
   background: #79A70A;
   background: linear-gradient(#9BC90D 0%, #79A70A 100%);
   box-shadow: 0 3px 10px -5px rgba(0, 0, 0, 1);
   position: absolute;
   top: 19px; left: -21px;
}
.ribbonlist span::before {
   content: '';
   position: absolute;
   left: 0px; top: 100%;
   z-index: -1;
   border-left: 3px solid #79A70A;
   border-right: 3px solid transparent;
   border-bottom: 3px solid transparent;
   border-top: 3px solid #79A70A;
}
.ribbonlist span::after {
   content: '';
   position: absolute;
   right: 0%; top: 100%;
   z-index: -1;
   border-right: 3px solid #79A70A;
   border-left: 3px solid transparent;
   border-bottom: 3px solid transparent;
   border-top: 3px solid #79A70A;
}
.red span {background: linear-gradient(#F70505 0%, #8F0808 100%);}
.red span::before {border-left-color: #8F0808; border-top-color: #8F0808;}
.red span::after {border-right-color: #8F0808; border-top-color: #8F0808;}

.blue span {background: linear-gradient(#2989d8 0%, #1e5799 100%);}
.blue span::before {border-left-color: #1e5799; border-top-color: #1e5799;}
.blue span::after {border-right-color: #1e5799; border-top-color: #1e5799;}
/* EOC - LIST VIEW */

if (Grid_View = 'True') {

Special

} else {

Special

}

The only difference between the two css is changing the height from grid        left: 10px; top: -5px; ---------->       list left: 10px; top: 5px;

This was just an example. Is there a way of combining the two css just to optimise the code rather copying and pasting several times?

Body:
You can achieve it this way:

if (Grid_View = 'True') {
  <div class="ribbongrid blue"><span>Special</span></div>
} else {
  <div class="ribbongrid ribbonlist blue"><span>Special</span></div>
}

and your css:

.ribbongrid {
  position: absolute;
  left: 10px;
  top: -5px;
  z-index: 1;
  overflow: hidden;
  width: 75px; height: 75px;
  text-align: right;
}

.ribbongrid.ribbonlist {
  top: 5px;
}

This will override your top from -5px to 5px


问:
Game scoreboard on Azure
could you please recommend me an alternative solution for storing game scores on Azure cloud? I am looking for a managed, cheap to run and easily scalable up and down storage option.

Input data: { "player": 1, "score": 10 } (the score may be already calculated, no need to sum up.)

There should be an option to make 2 types of queries:

1. Get player's position in the scoreboard.

2. Get positions (player and score) between position X and Y.

The application can not tell the position of player in the scoreboard during the write time - the back-end database solution should provide that information, or the data layout should allow fast computation of position between all players.
Non real-time accuracy is acceptable.

Current back-end technology choice: Azure Web App (.NET Core), Storage (Table, Blob, Queues).

With SQL server it obvious how to do that, but I would like to avoid bringing the SQL server to the technology stack. Keeping in memory is also not an option because of multiple web servers.

Do you have any idea how such data may be stored and retrieved using any other Azure service? DocumentDB, Data Lake, any other?

答:
The problem with calculating position in a list is that ranking (and window operations in general) is difficult to do when your data can be distributed across multiple servers. It becomes an expensive operation as your data grows, and doesn't scale well.

Data Lake does support window functions, including RANK() and DENSE_RANK(). You'll want to give this a good test with some representative data to see what performance is like.

The other option is to pre-calculate the rankings at certain intervals and "cache" the full scoreboard into Table Storage; if it's acceptable for there to be a delay to users (e.g. you could say the rankings refresh every hour)

Then you could have a scheduled WebJob that:

Reads all the score records where score is higher than a threshold, ordered on score

Creates a new table for player rank e.g. player-scores-170401-124200

Creates a new table for overall ranking e.g. scoreboard-170401-124200

Writes the ranked scoreboard into the new tables in batches

In this way, you can query player-scores on PartitionKey=player to get an individual ranking, and query scoreboard with an inequality filter to get a window of positions.

Querying (which is the operation you probably should optimise for) becomes very cheap and easy, as it's a single transaction for each piece of info.

Running the calculation also isn't too expensive, and transaction costs are the thing you'll want to keep an eye on. Assuming n score records:

You can read in batches of 100. Transactions ~= n / 100

You can write to the same partition in batches of 100. Transactions ~= 2n / 100

You can choose to keep historic rankings, or drop the entire table in a single transaction

So your total transactions for 1M records is:

1000000*3/100 = 30,000 per run

Do that every hour for a day (720k transactions), and it'll cost you roughly 2-3 cents a day (not including storage costs, of course). That counts as cheap to run in my book :-)

Title: Game scoreboard on Azure


问:
Remove rows with empty values when evaluating eclat and apriori itemsets
I am working in R and have a dataset which looks like the following

```<code>[1, 2, 3, ""]
[1, 2, "", 4]
[1,"", "", ""]
</code>```

I am reading these values into a transaction object and then passing them to eclat or apriori for frequent itemset evaluation.  The problem arises when my frequent itemsets look like the following:

```<code>{1,""}
{2,3,""}
</code>```

I would like to remove these rows from the calculation as I think it's slowing down the processing and also doesn't make any sense from a prediction standpoint.  Can you please help?  My R code is below.

```<code>tr <- read.transactions("Items.csv", rm.duplicates=TRUE, format="basket",sep=",")

dataset1 <- as.vector(t(dataset1))

frequentItems <- eclat (tr, parameter = list(supp = 0.03, minlen=2, maxlen = 4))

inspect(frequentItems)
</code>```

Thanks,
Matt

答:
The problem you have, boils down to arules thinking that "" is an item. So if you don't want that, you'll have to remove all these values from your data first. The likely culprit is the original csv file. It contains empty fields, and they're translated to an "" item.

So the best way to get rid of this, is make sure that your csv file actually has a correct format. It should look like this:

```<code>item1, item2
item1
item2, item3
</code>```

And not this

```<code>"item1", "item2"
"item1", ""
"item2", "item3"
</code>```

To solve the problem in code, convert to a list first:

```<code>thelist <- as(tr, "list")

thelist <- lapply(thelist, function(i){
  i[i != ""]
})

trnew <- as(thelist, "transactions")
</code>```

En example showing you how it works:

```<code>library(arules)
# Example data
a_list <- list(
  c("item1","item2"),
  c("item1",""),
  c("item2","item3"),
  c("","item3")
  )

tr <- as(a_list, "transactions")

frequentItems <- eclat (tr, parameter = list(supp = 0.03, minlen=2, maxlen = 4))
inspect(frequentItems)

#>    items         support
#>[1] {item2,item3} 0.25
#>[2] {,item3}      0.25
#>[3] {,item1}      0.25
#>[4] {item1,item2} 0.25

# Conversion
thelist <- as(tr, "list")
thelist <- lapply(thelist, function(i){
  i[i != ""]
})
trnew <- as(thelist, "transactions")

frequentItems <- eclat (trnew, parameter = list(supp = 0.03, minlen=2, maxlen = 4))
inspect(frequentItems)

#>    items         support
#>[1] {item2,item3} 0.25
#>[2] {item1,item2} 0.25
</code>```

Body:
I am working in R and have a dataset which looks like the following

[1, 2, 3, ""]
[1, 2, "", 4]
[1,"", "", ""]

I am reading these values into a transaction object and then passing them to eclat or apriori for frequent itemset evaluation.  The problem arises when my frequent itemsets look like the following:

{1,""}
{2,3,""}

I would like to remove these rows from the calculation as I think it's slowing down the processing and also doesn't make any sense from a prediction standpoint.  Can you please help?  My R code is below.

tr <- read.transactions("Items.csv", rm.duplicates=TRUE, format="basket",sep=",")

dataset1 <- as.vector(t(dataset1))

frequentItems <- eclat (tr, parameter = list(supp = 0.03, minlen=2, maxlen = 4))

inspect(frequentItems)

Thanks,
Matt

Body:
The problem you have, boils down to arules thinking that "" is an item. So if you don't want that, you'll have to remove all these values from your data first. The likely culprit is the original csv file. It contains empty fields, and they're translated to an "" item.

So the best way to get rid of this, is make sure that your csv file actually has a correct format. It should look like this:

item1, item2
item1
item2, item3

And not this

"item1", "item2"
"item1", ""
"item2", "item3"

To solve the problem in code, convert to a list first:

thelist <- as(tr, "list")

thelist <- lapply(thelist, function(i){
  i[i != ""]
})

trnew <- as(thelist, "transactions")

En example showing you how it works:

library(arules)
# Example data
a_list <- list(
  c("item1","item2"),
  c("item1",""),
  c("item2","item3"),
  c("","item3")
  )

tr <- as(a_list, "transactions")

frequentItems <- eclat (tr, parameter = list(supp = 0.03, minlen=2, maxlen = 4))
inspect(frequentItems)

#>    items         support
#>[1] {item2,item3} 0.25
#>[2] {,item3}      0.25
#>[3] {,item1}      0.25
#>[4] {item1,item2} 0.25

# Conversion
thelist <- as(tr, "list")
thelist <- lapply(thelist, function(i){
  i[i != ""]
})
trnew <- as(thelist, "transactions")

frequentItems <- eclat (trnew, parameter = list(supp = 0.03, minlen=2, maxlen = 4))
inspect(frequentItems)

#>    items         support
#>[1] {item2,item3} 0.25
#>[2] {item1,item2} 0.25


问:
Is there a way map/set utm parameters in gtm?
I currently have a bunch of traffic going to my website with a query string like so:  www.mywebsite.com/?source=facebook

I've installed GTM on my website and also from GTM fire a Google Analytics Page View etc.  What i'm wondering is through GTM, is there a way to grab the source (facebook) from the url and set utm_source=facebook when firing the pageview tag.

Or is my only option to change all the links going to my site to be:
www.mywebsite.com/?utm_source=facebook instead?

Thank you everyone for your expert advice.  Really Appreciate it.

答: You can fetch the parameters via an url type variable, and then use the "set fields" option in your GA tag to populate the "campaignSource" and "campaignMedium" fields. If the parameters are not present the url query variables default to "undefined", and undefined fields are not sent, so you do not need to check if values are present.</p>


问:
ReactJS - Change Component in parent depending on nested route
I have my App wrapped in a component which renders a Header, Footer and any routed child components.

I am trying to replace the  component with </HeaderAdmin/> when at /admin.

Routes

```<code><Route path='/' component={SiteWrapper} >
  <IndexRoute component={Home} />
  <Route path="admin" component={Admin}>
    <Route path="dashboard" component={Dashboard}/>
  </Route>
</Route>
</code>```

SiteWrapper Comp

```<code>export default class SiteWrapper extends React.Component {
    render() {
        return (
            <div>
                <Header/> // Want to replace with <AdminHeader /> if on /admin
                <div className="container">
                    {this.props.children.props.route.header ? <PageHeader header={this.props.children.props.route.header} /> : null}
                    {this.props.children}
                </div>
                <Footer/>
            </div>
        )
    }
}
</code>```

答:
For that, I think you can check the route by window.location or this.props.location.pathname, it will contain the route names, if the route name is /admin then render the Header component otherwise render the AdminHeader component.

Write it like this:

```<code>{ this.prop.location.pathname === '/admin'? <AdminHeader/>: <Header/>}
</code>```

Body:
I have my App wrapped in a component which renders a Header, Footer and any routed child components.

I am trying to replace the  component with </HeaderAdmin/> when at /admin.

Routes

<Route path='/' component={SiteWrapper} >
  <IndexRoute component={Home} />
  <Route path="admin" component={Admin}>
    <Route path="dashboard" component={Dashboard}/>
  </Route>
</Route>

SiteWrapper Comp

export default class SiteWrapper extends React.Component {
    render() {
        return (

                 // Want to replace with <AdminHeader /> if on /admin

                    {this.props.children.props.route.header ? <PageHeader header={this.props.children.props.route.header} /> : null}
                    {this.props.children}

        )
    }
}

Body:
For that, I think you can check the route by window.location or this.props.location.pathname, it will contain the route names, if the route name is /admin then render the Header component otherwise render the AdminHeader component.

Write it like this:

{ this.prop.location.pathname === '/admin'? <AdminHeader/>: <Header/>}


答:
```<code>if (arr.length > 1)
{
    Collections.Arrays.sort(arr);
    int secondMax = arr[arr.length - 2];
}
</code>```

Inspired by this question.

Title: Sort an array without using loops in java

Body:
How to get second maximum value from array without using nested loops in java?
For eg: int [] arr = {2,4,1,6,5,9,0,7}
        Output : 7

Body:
if (arr.length > 1)
{
    Collections.Arrays.sort(arr);
    int secondMax = arr[arr.length - 2];
}

Inspired by this question.


问:
Ambiguous type variable error msg
I don't think it is a bug, but I am a bit puzzled as to why that doesn't work. A bonus question is why does it mention variable e? There is no variable e.

```
    Prelude> :m +Control.Exception
    Prelude Control.Exception> handle (\_-> return "err") undefined

    <interactive>:1:0:
        Ambiguous type variable `e' in the constraint:
          `Exception e'
            arising from a use of `handle' at <interactive>:1:0-35
        Probable fix: add a type signature that fixes these type variable(s)
    Prelude Control.Exception>
```

Apparently it works fine in ghci 6.8, I am using 6.10.1.

Edit: I have minimized the code. I expect that to have the same result in both 6.8 and 6.10

```<code>class C a

foo :: C a => (a -> Int)-> Int
foo _ = 1

arg :: C a => a -> Int
arg _ = 2

bar :: Int
bar = foo arg
</code>```

trying to compile it:

```
[1 of 1] Compiling Main             ( /tmp/foo.hs, interpreted )

/tmp/foo.hs:12:10:
    Ambiguous type variable `a' in the constraint:
      `C a' arising from a use of `arg' at /tmp/foo.hs:12:10-12
    Probable fix: add a type signature that fixes these type variable(s)
Failed, modules loaded: none.
Prelude Control.Exception>
```

答:
"Exception e" is likely from the type signature of "handle".

The documentation
says:

```<code>handle :: Exception e => (e -> IO a) -> IO a -> IO a
</code>```

In GHC 6.8 it used to be different, which would explain why I don't get that error.

```<code>handle :: (Exception -> IO a) -> IO a -> IO a
</code>```

Seems you're running into the monomorphism restriction. That "_"-Pattern must be monomorphic (which it is with ghc 6.8) or explicitly typed. A "workaround" is to put the pattern on the left hand side of a definition, where it constitutes a "simple pattern binding" as specified by the Haskell Report.

Try this:

```<code>let f _ = return "err"
handle f undefined
</code>```

http://www.haskell.org/haskellwiki/Monomorphism_restriction

OwnerDisplayName: luntain

ContentLicense: CC BY-SA 2.5

Title: Ambiguous type variable error msg

Body:
I don't think it is a bug, but I am a bit puzzled as to why that doesn't work. A bonus question is why does it mention variable e? There is no variable e.

    Prelude> :m +Control.Exception
    Prelude Control.Exception> handle (\_-> return "err") undefined

    <interactive>:1:0:
        Ambiguous type variable `e' in the constraint:
          `Exception e'
            arising from a use of `handle' at <interactive>:1:0-35
        Probable fix: add a type signature that fixes these type variable(s)
    Prelude Control.Exception>

Apparently it works fine in ghci 6.8, I am using 6.10.1.

Edit: I have minimized the code. I expect that to have the same result in both 6.8 and 6.10

class C a

foo :: C a => (a -> Int)-> Int
foo _ = 1

arg :: C a => a -> Int
arg _ = 2

bar :: Int
bar = foo arg

trying to compile it:

[1 of 1] Compiling Main             ( /tmp/foo.hs, interpreted )

/tmp/foo.hs:12:10:
    Ambiguous type variable `a' in the constraint:
      `C a' arising from a use of `arg' at /tmp/foo.hs:12:10-12
    Probable fix: add a type signature that fixes these type variable(s)
Failed, modules loaded: none.
Prelude Control.Exception>

LastEditorDisplayName: luntain

Body:
"Exception e" is likely from the type signature of "handle".

The documentation
says:

handle :: Exception e => (e -> IO a) -> IO a -> IO a

In GHC 6.8 it used to be different, which would explain why I don't get that error.

handle :: (Exception -> IO a) -> IO a -> IO a

Seems you're running into the monomorphism restriction. That "_"-Pattern must be monomorphic (which it is with ghc 6.8) or explicitly typed. A "workaround" is to put the pattern on the left hand side of a definition, where it constitutes a "simple pattern binding" as specified by the Haskell Report.

Try this:

let f _ = return "err"
handle f undefined

http://www.haskell.org/haskellwiki/Monomorphism_restriction

OwnerDisplayName: Waquo

LastEditorDisplayName: Waquo