问:
How can i solve KeyError: 'ir.actions.view' odoo?
am a noob to odoo and am trying to build a custom module. I removed the menuitems on some of the views but i still got the same error. I got the error below when i tried to add a submenu to farm_menu. How do i make the menu work like this?
Animals
   *feeds
   *feeding records

Your help is highly appreciated.

Error

```<code>Traceback (most recent call last):
  File "/opt/odoo/odoo/odoo/tools/cache.py", line 88, in lookup
    r = d[key]
  File "/opt/odoo/odoo/odoo/tools/func.py", line 69, in wrapper
    return func(self, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/tools/lru.py", line 44, in __getitem__
    a = self.d[obj].me
KeyError: ('ir.ui.menu', <function IrUiMenu.load_menus at 0x7f3f849090d0>, 2, None, ('en_US',))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/odoo/odoo/odoo/tools/cache.py", line 88, in lookup
    r = d[key]
  File "/opt/odoo/odoo/odoo/tools/func.py", line 69, in wrapper
    return func(self, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/tools/lru.py", line 44, in __getitem__
    a = self.d[obj].me
KeyError: ('ir.ui.menu', <function IrUiMenu._visible_menu_ids at 0x7f3f848fc730>, frozenset({1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38, 39, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 79, 80, 81, 82, 84, 85}), None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/odoo/odoo/odoo/api.py", line 1049, in get
    value = self._data[key][field][record._ids[0]]
KeyError: 62

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/odoo/odoo/odoo/fields.py", line 1005, in __get__
    value = record.env.cache.get(record, self)
  File "/opt/odoo/odoo/odoo/api.py", line 1051, in get
    raise CacheMiss(record, field)
odoo.exceptions.CacheMiss: ('ir.ui.menu(62,).action', None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/mustaf/.local/lib/python3.6/site-packages/werkzeug/serving.py", line 304, in run_wsgi
    execute(self.server.app)
  File "/home/mustaf/.local/lib/python3.6/site-packages/werkzeug/serving.py", line 292, in execute
    application_iter = app(environ, start_response)
  File "/opt/odoo/odoo/odoo/service/server.py", line 434, in app
    return self.app(e, s)
  File "/opt/odoo/odoo/odoo/service/wsgi_server.py", line 142, in application
    return application_unproxied(environ, start_response)
  File "/opt/odoo/odoo/odoo/service/wsgi_server.py", line 117, in application_unproxied
    result = odoo.http.root(environ, start_response)
  File "/opt/odoo/odoo/odoo/http.py", line 1320, in __call__
    return self.dispatch(environ, start_response)
  File "/opt/odoo/odoo/odoo/http.py", line 1293, in __call__
    return self.app(environ, start_wrapped)
  File "/home/mustaf/.local/lib/python3.6/site-packages/werkzeug/middleware/shared_data.py", line 220, in __call__
    return self.app(environ, start_response)
  File "/opt/odoo/odoo/odoo/http.py", line 1488, in dispatch
    result = ir_http._dispatch()
  File "/opt/odoo/odoo/addons/auth_signup/models/ir_http.py", line 19, in _dispatch
    return super(Http, cls)._dispatch()
  File "/opt/odoo/odoo/addons/web_editor/models/ir_http.py", line 22, in _dispatch
    return super(IrHttp, cls)._dispatch()
  File "/opt/odoo/odoo/addons/http_routing/models/ir_http.py", line 403, in _dispatch
    result = super(IrHttp, cls)._dispatch()
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_http.py", line 207, in _dispatch
    return cls._handle_exception(e)
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_http.py", line 177, in _handle_exception
    return request._handle_exception(exception)
  File "/opt/odoo/odoo/odoo/http.py", line 776, in _handle_exception
    return super(HttpRequest, self)._handle_exception(exception)
  File "/opt/odoo/odoo/odoo/http.py", line 314, in _handle_exception
    raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
  File "/opt/odoo/odoo/odoo/tools/pycompat.py", line 87, in reraise
    raise value
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_http.py", line 203, in _dispatch
    result = request.dispatch()
  File "/opt/odoo/odoo/odoo/http.py", line 835, in dispatch
    r = self._call_function(**self.params)
  File "/opt/odoo/odoo/odoo/http.py", line 346, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/service/model.py", line 97, in wrapper
    return f(dbname, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/http.py", line 339, in checked_call
    result = self.endpoint(*a, **kw)
  File "/opt/odoo/odoo/odoo/http.py", line 941, in __call__
    return self.method(*args, **kw)
  File "/opt/odoo/odoo/odoo/http.py", line 519, in response_wrap
    response = f(*args, **kw)
  File "/opt/odoo/odoo/addons/web/controllers/main.py", line 457, in web_client
    context = request.env['ir.http'].webclient_rendering_context()
  File "/opt/odoo/odoo/addons/web/models/ir_http.py", line 17, in webclient_rendering_context
    'menu_data': request.env['ir.ui.menu'].load_menus(request.debug),
  File "</home/mustaf/.local/lib/python3.6/site-packages/decorator.py:decorator-gen-31>", line 2, in load_menus

  File "/opt/odoo/odoo/odoo/tools/cache.py", line 93, in lookup
    value = d[key] = self.method(*args, **kwargs)
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_ui_menu.py", line 234, in load_menus
    menu_roots = self.get_user_roots()
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_ui_menu.py", line 204, in get_user_roots
    return self.search([('parent_id', '=', False)])
  File "/opt/odoo/odoo/odoo/models.py", line 1562, in search
    res = self._search(args, offset=offset, limit=limit, order=order, count=count)
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_ui_menu.py", line 135, in _search
    menus = menus._filter_visible_menus()
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_ui_menu.py", line 125, in _filter_visible_menus
    visible_ids = self._visible_menu_ids(request.debug if request else False)
  File "</home/mustaf/.local/lib/python3.6/site-packages/decorator.py:decorator-gen-28>", line 2, in _visible_menu_ids

  File "/opt/odoo/odoo/odoo/tools/cache.py", line 93, in lookup
    value = d[key] = self.method(*args, **kwargs)
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_ui_menu.py", line 94, in _visible_menu_ids
    action_menus = menus.filtered(lambda m: m.action and m.action.exists())
  File "/opt/odoo/odoo/odoo/models.py", line 4901, in filtered
    return self.browse([rec.id for rec in self if func(rec)])
  File "/opt/odoo/odoo/odoo/models.py", line 4901, in <listcomp>
    return self.browse([rec.id for rec in self if func(rec)])
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_ui_menu.py", line 94, in <lambda>
    action_menus = menus.filtered(lambda m: m.action and m.action.exists())
  File "/opt/odoo/odoo/odoo/fields.py", line 1009, in __get__
    self.determine_value(record)
  File "/opt/odoo/odoo/odoo/fields.py", line 1112, in determine_value
    record._prefetch_field(self)
  File "/opt/odoo/odoo/odoo/models.py", line 2843, in _prefetch_field
    result = records.read([f.name for f in fs], load='_classic_write')
  File "/opt/odoo/odoo/odoo/models.py", line 2781, in read
    self._read_from_database(stored, inherited)
  File "/opt/odoo/odoo/odoo/models.py", line 2934, in _read_from_database
    values = [convert(value, target, validate=False) for value in values]
  File "/opt/odoo/odoo/odoo/models.py", line 2934, in <listcomp>
    values = [convert(value, target, validate=False) for value in values]
  File "/opt/odoo/odoo/odoo/fields.py", line 2032, in convert_to_cache
    if record.env[res_model].browse(int(res_id)).exists():
  File "/opt/odoo/odoo/odoo/api.py", line 831, in __getitem__
    return self.registry[model_name]._browse((), self)
  File "/opt/odoo/odoo/odoo/modules/registry.py", line 176, in __getitem__
    return self.models[model_name]
KeyError: 'ir.actions.view'
</code>```

animals.py

```<code>from odoo import models, fields

class FarmAnimalsFarmAnimals(models.Model):
    _name ='farmanimal.farmanimal'

    name= fields.Char(string='Name', required=True)
    photo = fields.Binary(string='Image')
    sex = fields.Selection([('male','Male'),('female','Female')], string='Sex')
    animal_dob = fields.Date(string='Date of birth/entry')
    animal_type = fields.Selection(
        [('cow','Cow'), ('bull','Bull'), ('goat','Goat'), ('sheep','Sheep'),
        ('fish','Fish'), ('rabbit','Rabbit'), ('chicken','Chicken'), ('turkey','Turkey'),
        ('ducks','Ducks'),('quells','Quells'),('camel','Camel'), ('horse','Horse'),],
        string='Animal Type')
</code>```

feeds.py

```<code>from odoo import models, fields

class FeedsFeeds(models.Model):
    _name ='feed.feed'

    f_name = fields.Char(string='Feed Name', required=True)
    f_photo  = fields.Binary(string='Product Image')
</code>```

feed_records.py

```<code>from odoo import models, fields

class FeedRecordsFeedRecords(models.Model):
    _name ='feedrecord.feedrecord'
    _inherits={'farmanimal.farmanimal','feed.feed'}

    feed_animal =  fields.Many2one( 'farmanimal.farmanimal','feed_animal_default_rel','name', string='Feed Animal',)
    feed_name = fields.Many2many('feed.feed', 'feed_default_rel', 'f_name', string='Consumed Feed(s)',)
    amount  = fields.Integer(string='Amount(In Grams)',)
    feed_date_time = fields.Datetime(string='Date and Time',default=fields.Datetime.now,)
</code>```

vaccines.py

```<code>from odoo import models, fields

class VaccinesVaccines(models.Model):
    _name ='vaccine.vaccine'

    v_name = fields.Char(string='Vaccine Name', required=True)
    v_photo  = fields.Binary(string='Product Image')
</code>```

vaccinations_records.py

```<code>from odoo import models, fields

class VaccinationRecordsVaccinationRecords(models.Model):
    _name ='vaccinationrecord.vaccinationrecord'
    _inherits={'farmanimal.farmanimal','vaccine.vaccine'}

    vaccinated_animal =  fields.Many2one( 'farmanimal.farmanimal','vaccinated_animal_default_rel','name', string='Vacinated Animal',)
    vaccine_name = fields.Many2many('vaccine.vaccine', 'vaccine_default_rel', 'v_name', string='Vaccine(s)',)
    vaccination_date_time = fields.Datetime(string='Date and Time',default=fields.Datetime.now,)
    next_vaccination_date = fields.Date(string='Next Date',)
</code>```

diseases.py

```<code>from odoo import models, fields

class DiseasesDiseases(models.Model):
    _name ='disease.disease'
    _inherits='vaccine.vaccine'

    d_name= fields.Char(string='Name', required=True)
    d_type = fields.Selection(
        [('infectious disease','Infectious Disease'), ('deficiency disease','Deficiency Disease'), ('hereditary disease','Hereditary Disease'), ('physiological diseases','Physiological Diseases')], string='Disease Type')
    s_vector = fields.Selection(
        [('airborne','Airborne'), ('foodborne','Foodborne'), ('infectious','Infectious'), ('lifestyle','Lifestyle'), ('non-communicable','Non-communicable')],
        string='Spread Vector')
    threat_level = fields.Selection(
        [('high','High'), ('medium','Medium'), ('low','Low'), ('immediate quarantine','Immediate Quarantine')], string='Threat Level')
    cure = fields.Many2many('vaccine.vaccine', 'disease_cure_default_rel', 'v_name', string='Cure')
</code>```

farm_view.xml

```<code>    <?xml version="1.0" encoding="UTF-8"?>
    <odoo>
        <data>
            <record id="farm_menu_action" model="ir.actions.act_window">
                <field name="name">Animals</field>
                <field name="res_model">farmanimal.farmanimal</field>
                <field name="view_type">form</field>
                <field name="view_mode">kanban,tree,form</field>
                <field name="domain">[]</field>
                <field name="help" type="html">
                    <p class="or_view_nocontent_create">Create The First Animal

                    </p>
                </field>

            </record>
            <!--farm animals tree view-->
            <record id="farm_tree_view" model="ir.ui.view">
                <field name="name">Animal Tree</field>
                <field name="model">farmanimal.farmanimal</field>
                <field name="arch" type="xml">
                    <tree string="Animals">
                        <field name="name"/>
                        <field name="sex"/>
                        <field name="animal_type"/>
                        <field name="animal_dob"/>
                    </tree>
                </field>
            </record>
            <!--farm animals kanban view-->
            <record id="farm_kanban_view" model="ir.ui.view">
                <field name="name">farmanimal.farmanimal.kanban</field>
                <field name="model">farmanimal.farmanimal</field>
                <field name="arch" type="xml">
                    <kanban class="o_res_farm_kanban">
                        <field name="id"/>
                        <field name="name"/>
                        <field name="sex"/>
                        <field name="animal_type"/>
                        <field name="animal_dob"/>
                        <templates>
                            <t t-name="kanban-box">
                                <div t-attf-class="oe_kanban_global_click">
                                    <div class="o_kanban_image">
                                        <img alt="Avatar" t-att-src="kanban_image('farmanimal.farmanimal','photo',record.id.raw_value)"/>
                                    </div>
                                    <div class="oe_kanban_details">
                                        <strong class="o_kanban_record_title">
                                            <field name="name"/>
                                        </strong>
                                        <div t-if="record.animal_type.value">
                                            <t t-esc="record.animal_type.value"/>
                                        </div>
                                        <div t-if="record.sex.value">
                                            <t t-esc="record.sex.value"/>
                                        </div>
                                        <div t-if="record.animal_dob.value">
                                            <t t-esc="record.animal_dob.value"/>
                                        </div>
                                    </div>
                                </div>

                            </t>
                        </templates>
                    </kanban>
                </field>

            </record>
            <!--farm animals form view-->
            <record id="farm_free_view" model="ir.ui.view">
                <field name="name">Animal Form</field>
                <field name="model">farmanimal.farmanimal</field>
                <field name="arch" type="xml">
                    <form string="Animal">
                        <sheet>
                            <field name="photo" widget="image" class="oe_left oe_avatar" />
                            <div class="oe_title">
                                <h3>
                                    <field name="name"/>
                                </h3>
                            </div>
                            <group>
                                <group>
                                    <field name="animal_type"/>
                                    <field name="sex"/>
                                </group>
                                <group>
                                    <field name="animal_dob"/>
                                </group>
                            </group>
                            <notebook>
                              <page string="Feeding Records">

                              </page>
                              <page string="Vaccination Records">

                              </page>
                            </notebook>

                        </sheet>
                    </form>
                </field>
            </record>

            <menuitem id="farm_menu" name="Farm Management" action="farm_menu_action"/>
            <menuitem id="farm_animal_menu" parent="farm_menu"  name="Farm Animals"/>
        </data>
    </odoo>

farm_records_view.xml
<?xml version="1.0" encoding="UTF-8"?>
<odoo>
    <data>
        <record id="farm_menu_action" model="ir.actions.act_window">
            <field name="name">Animals</field>
            <field name="res_model">farmanimal.farmanimal</field>
            <field name="view_type">form</field>
            <field name="view_mode">kanban,tree,form</field>
            <field name="domain">[]</field>
            <field name="help" type="html">
                <p class="or_view_nocontent_create">Create The First Animal

                </p>
            </field>

        </record>
        <!--farm animals tree view-->
        <record id="farm_tree_view" model="ir.ui.view">
            <field name="name">Animal Tree</field>
            <field name="model">farmanimal.farmanimal</field>
            <field name="arch" type="xml">
                <tree string="Animals">
                    <field name="name"/>
                    <field name="sex"/>
                    <field name="animal_type"/>
                    <field name="animal_dob"/>
                </tree>
            </field>
        </record>
        <!--farm animals kanban view-->
        <record id="farm_kanban_view" model="ir.ui.view">
            <field name="name">farmanimal.farmanimal.kanban</field>
            <field name="model">farmanimal.farmanimal</field>
            <field name="arch" type="xml">
                <kanban class="o_res_farm_kanban">
                    <field name="id"/>
                    <field name="name"/>
                    <field name="sex"/>
                    <field name="animal_type"/>
                    <field name="animal_dob"/>
                    <templates>
                        <t t-name="kanban-box">
                            <div t-attf-class="oe_kanban_global_click">
                                <div class="o_kanban_image">
                                    <img alt="Avatar" t-att-src="kanban_image('farmanimal.farmanimal','photo',record.id.raw_value)"/>
                                </div>
                                <div class="oe_kanban_details">
                                    <strong class="o_kanban_record_title">
                                        <field name="name"/>
                                    </strong>
                                    <div t-if="record.animal_type.value">
                                        <t t-esc="record.animal_type.value"/>
                                    </div>
                                    <div t-if="record.sex.value">
                                        <t t-esc="record.sex.value"/>
                                    </div>
                                    <div t-if="record.animal_dob.value">
                                        <t t-esc="record.animal_dob.value"/>
                                    </div>
                                </div>
                            </div>

                        </t>
                    </templates>
                </kanban>
            </field>

        </record>
        <!--farm animals form view-->
        <record id="farm_free_view" model="ir.ui.view">
            <field name="name">Animal Form</field>
            <field name="model">farmanimal.farmanimal</field>
            <field name="arch" type="xml">
                <form string="Animal">
                    <sheet>
                        <field name="photo" widget="image" class="oe_left oe_avatar" />
                        <div class="oe_title">
                            <h3>
                                <field name="name"/>
                            </h3>
                        </div>
                        <group>
                            <group>
                                <field name="animal_type"/>
                                <field name="sex"/>
                            </group>
                            <group>
                                <field name="animal_dob"/>
                            </group>
                        </group>
                        <notebook>
                          <page string="Feeding Records">

                          </page>
                          <page string="Vaccination Records">

                          </page>
                        </notebook>

                    </sheet>
                </form>
            </field>
        </record>

        <menuitem id="farm_menu" name="Farm Management" action="farm_menu_action"/>
        <menuitem id="farm_animal_menu" parent="farm_menu"  name="Farm Animals"/>
    </data>
</odoo>
</code>```

feed_records_view.py

```<code><?xml version="1.0" encoding="UTF-8"?>
<odoo>
    <data>
        <record id="feeding_menu_action" model="ir.actions.act_window">
            <field name="name">Feeding Record</field>
            <field name="res_model">feedrecord.feedrecord</field>
            <field name="view_type">form</field>
            <field name="view_mode">tree,form</field>
            <field name="domain">[]</field>
            <field name="help" type="html">
                <p class="or_view_nocontent_create">Create The First Feeding Record

                </p>
            </field>
        </record>
        <!--Feed tree view-->
        <record id="feed_tree_view" model="ir.ui.view">
            <field name="name">Feeding Record Tree</field>
            <field name="model">feedrecord.feedrecord</field>
            <field name="arch" type="xml">
                <tree string="Feeding Record">
                    <field name="feed_animal"/>
                    <field name="feed_name"/>
                    <field name="amount"/>
                    <field name="feed_date_time"/>
                </tree>
            </field>
        </record>
        <!--feeding form view-->
        <record id="feeding_free_view" model="ir.ui.view">
            <field name="name">Feeding Record Form</field>
            <field name="model">feedrecords.feedrecords</field>
            <field name="arch" type="xml">
                <form string="Feeding Records">
                    <sheet>
                        <div class="oe_title">
                            <h1>
                                <field name="feed_animal"/>
                            </h1>
                        </div>
                        <group>
                            <group>
                                <field name="feed_name"/>
                                <field name="amount"/>
                                <field name="feed_date_time"/>
                            </group>
                        </group>

                    </sheet>
                </form>
            </field>
        </record>
    </data>
</odoo>
</code>```

feeds_view.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<odoo>
    <data>
        <record id="feeds_menu_action" model="ir.actions.act_window">
            <field name="name">Feeds</field>
            <field name="res_model">feed.feed</field>
            <field name="view_type">form</field>
            <field name="view_mode">kaban,tree,form</field>
            <field name="domain">[]</field>
            <field name="help" type="html">
                <p class="or_view_nocontent_create">Create The First Feed

                </p>
            </field>
        </record>
        <!--Feed tree view-->
        <record id="feed_tree_view" model="ir.ui.view">
            <field name="name">Feeds</field>
            <field name="model">feed.feed</field>
            <field name="arch" type="xml">
                <tree string="Feeds">
                    <field name="f_name"/>
                </tree>
            </field>
        </record>
        <!--feed kanban view-->
        <record id="feed_kanban_view" model="ir.ui.view">
            <field name="name">feed.feed.kanban</field>
            <field name="model">feed.feed</field>
            <field name="arch" type="xml">
                <kanban class="o_res_farm_kanban">
                    <field name="id"/>
                    <field name="f_name"/>
                    <templates>
                        <t t-name="kanban-box">
                            <div t-attf-class="oe_kanban_global_click">
                                <div class="o_kanban_image">
                                    <img alt="Avatar" t-att-src="kanban_image('feed.feed','f_photo',record.id.raw_value)"/>
                                </div>
                                <div class="oe_kanban_details">
                                    <strong class="o_kanban_record_title">
                                        <field name="f_name"/>
                                    </strong>
                                </div>
                            </div>

                        </t>
                    </templates>
                </kanban>
            </field>
        </record>
        <!--feeding form view-->
        <record id="feed_free_view" model="ir.ui.view">
            <field name="name">Feeds</field>
            <field name="model">feed.feed</field>
            <field name="arch" type="xml">
                <form string="Feeds">
                    <sheet>
                        <field name="f_photo" widget="image" class="oe_left oe_avatar" />
                        <div class="oe_title">
                            <h1>
                                <field name="f_name"/>
                            </h1>
                        </div>
                    </sheet>
                </form>
            </field>
        </record>
    </data>
</odoo>
</code>```

答:
You need to revisit how you are defining your menuitems. Look at the Odoo documentation for reference.

The Parent menu(s) should not have any action. Only the final (child) menu should be assigned the action.

For example, instead of what you have currently:

```<code><menuitem id="farm_menu" name="Farm Management"
    action="farm_menu_action"/>
<menuitem id="farm_animal_menu" name="Farm Animals"
    parent="farm_menu"/>
</code>```

You ought to be doing this:

```<code><menuitem id="farm_menu" name="Farm Management"/>
<menuitem id="farm_animal_menu" name="Farm Animals"
    parent="farm_menu"
    action="farm_menu_action"/>
</code>```

Body:
am a noob to odoo and am trying to build a custom module. I removed the menuitems on some of the views but i still got the same error. I got the error below when i tried to add a submenu to farm_menu. How do i make the menu work like this?
Animals
   *feeds
   *feeding records

Your help is highly appreciated.

Error

Traceback (most recent call last):
  File "/opt/odoo/odoo/odoo/tools/cache.py", line 88, in lookup
    r = d[key]
  File "/opt/odoo/odoo/odoo/tools/func.py", line 69, in wrapper
    return func(self, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/tools/lru.py", line 44, in __getitem__
    a = self.d[obj].me
KeyError: ('ir.ui.menu', <function IrUiMenu.load_menus at 0x7f3f849090d0>, 2, None, ('en_US',))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/odoo/odoo/odoo/tools/cache.py", line 88, in lookup
    r = d[key]
  File "/opt/odoo/odoo/odoo/tools/func.py", line 69, in wrapper
    return func(self, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/tools/lru.py", line 44, in __getitem__
    a = self.d[obj].me
KeyError: ('ir.ui.menu', <function IrUiMenu._visible_menu_ids at 0x7f3f848fc730>, frozenset({1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38, 39, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 79, 80, 81, 82, 84, 85}), None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/odoo/odoo/odoo/api.py", line 1049, in get
    value = self._data[key][field][record._ids[0]]
KeyError: 62

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/odoo/odoo/odoo/fields.py", line 1005, in __get__
    value = record.env.cache.get(record, self)
  File "/opt/odoo/odoo/odoo/api.py", line 1051, in get
    raise CacheMiss(record, field)
odoo.exceptions.CacheMiss: ('ir.ui.menu(62,).action', None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/mustaf/.local/lib/python3.6/site-packages/werkzeug/serving.py", line 304, in run_wsgi
    execute(self.server.app)
  File "/home/mustaf/.local/lib/python3.6/site-packages/werkzeug/serving.py", line 292, in execute
    application_iter = app(environ, start_response)
  File "/opt/odoo/odoo/odoo/service/server.py", line 434, in app
    return self.app(e, s)
  File "/opt/odoo/odoo/odoo/service/wsgi_server.py", line 142, in application
    return application_unproxied(environ, start_response)
  File "/opt/odoo/odoo/odoo/service/wsgi_server.py", line 117, in application_unproxied
    result = odoo.http.root(environ, start_response)
  File "/opt/odoo/odoo/odoo/http.py", line 1320, in __call__
    return self.dispatch(environ, start_response)
  File "/opt/odoo/odoo/odoo/http.py", line 1293, in __call__
    return self.app(environ, start_wrapped)
  File "/home/mustaf/.local/lib/python3.6/site-packages/werkzeug/middleware/shared_data.py", line 220, in __call__
    return self.app(environ, start_response)
  File "/opt/odoo/odoo/odoo/http.py", line 1488, in dispatch
    result = ir_http._dispatch()
  File "/opt/odoo/odoo/addons/auth_signup/models/ir_http.py", line 19, in _dispatch
    return super(Http, cls)._dispatch()
  File "/opt/odoo/odoo/addons/web_editor/models/ir_http.py", line 22, in _dispatch
    return super(IrHttp, cls)._dispatch()
  File "/opt/odoo/odoo/addons/http_routing/models/ir_http.py", line 403, in _dispatch
    result = super(IrHttp, cls)._dispatch()
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_http.py", line 207, in _dispatch
    return cls._handle_exception(e)
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_http.py", line 177, in _handle_exception
    return request._handle_exception(exception)
  File "/opt/odoo/odoo/odoo/http.py", line 776, in _handle_exception
    return super(HttpRequest, self)._handle_exception(exception)
  File "/opt/odoo/odoo/odoo/http.py", line 314, in _handle_exception
    raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
  File "/opt/odoo/odoo/odoo/tools/pycompat.py", line 87, in reraise
    raise value
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_http.py", line 203, in _dispatch
    result = request.dispatch()
  File "/opt/odoo/odoo/odoo/http.py", line 835, in dispatch
    r = self._call_function(**self.params)
  File "/opt/odoo/odoo/odoo/http.py", line 346, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/service/model.py", line 97, in wrapper
    return f(dbname, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/http.py", line 339, in checked_call
    result = self.endpoint(*a, **kw)
  File "/opt/odoo/odoo/odoo/http.py", line 941, in __call__
    return self.method(*args, **kw)
  File "/opt/odoo/odoo/odoo/http.py", line 519, in response_wrap
    response = f(*args, **kw)
  File "/opt/odoo/odoo/addons/web/controllers/main.py", line 457, in web_client
    context = request.env['ir.http'].webclient_rendering_context()
  File "/opt/odoo/odoo/addons/web/models/ir_http.py", line 17, in webclient_rendering_context
    'menu_data': request.env['ir.ui.menu'].load_menus(request.debug),
  File "</home/mustaf/.local/lib/python3.6/site-packages/decorator.py:decorator-gen-31>", line 2, in load_menus

  File "/opt/odoo/odoo/odoo/tools/cache.py", line 93, in lookup
    value = d[key] = self.method(*args, **kwargs)
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_ui_menu.py", line 234, in load_menus
    menu_roots = self.get_user_roots()
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_ui_menu.py", line 204, in get_user_roots
    return self.search([('parent_id', '=', False)])
  File "/opt/odoo/odoo/odoo/models.py", line 1562, in search
    res = self._search(args, offset=offset, limit=limit, order=order, count=count)
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_ui_menu.py", line 135, in _search
    menus = menus._filter_visible_menus()
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_ui_menu.py", line 125, in _filter_visible_menus
    visible_ids = self._visible_menu_ids(request.debug if request else False)
  File "</home/mustaf/.local/lib/python3.6/site-packages/decorator.py:decorator-gen-28>", line 2, in _visible_menu_ids

  File "/opt/odoo/odoo/odoo/tools/cache.py", line 93, in lookup
    value = d[key] = self.method(*args, **kwargs)
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_ui_menu.py", line 94, in _visible_menu_ids
    action_menus = menus.filtered(lambda m: m.action and m.action.exists())
  File "/opt/odoo/odoo/odoo/models.py", line 4901, in filtered
    return self.browse([rec.id for rec in self if func(rec)])
  File "/opt/odoo/odoo/odoo/models.py", line 4901, in <listcomp>
    return self.browse([rec.id for rec in self if func(rec)])
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_ui_menu.py", line 94, in <lambda>
    action_menus = menus.filtered(lambda m: m.action and m.action.exists())
  File "/opt/odoo/odoo/odoo/fields.py", line 1009, in __get__
    self.determine_value(record)
  File "/opt/odoo/odoo/odoo/fields.py", line 1112, in determine_value
    record._prefetch_field(self)
  File "/opt/odoo/odoo/odoo/models.py", line 2843, in _prefetch_field
    result = records.read([f.name for f in fs], load='_classic_write')
  File "/opt/odoo/odoo/odoo/models.py", line 2781, in read
    self._read_from_database(stored, inherited)
  File "/opt/odoo/odoo/odoo/models.py", line 2934, in _read_from_database
    values = [convert(value, target, validate=False) for value in values]
  File "/opt/odoo/odoo/odoo/models.py", line 2934, in <listcomp>
    values = [convert(value, target, validate=False) for value in values]
  File "/opt/odoo/odoo/odoo/fields.py", line 2032, in convert_to_cache
    if record.env[res_model].browse(int(res_id)).exists():
  File "/opt/odoo/odoo/odoo/api.py", line 831, in __getitem__
    return self.registry[model_name]._browse((), self)
  File "/opt/odoo/odoo/odoo/modules/registry.py", line 176, in __getitem__
    return self.models[model_name]
KeyError: 'ir.actions.view'

animals.py

from odoo import models, fields

class FarmAnimalsFarmAnimals(models.Model):
    _name ='farmanimal.farmanimal'

    name= fields.Char(string='Name', required=True)
    photo = fields.Binary(string='Image')
    sex = fields.Selection([('male','Male'),('female','Female')], string='Sex')
    animal_dob = fields.Date(string='Date of birth/entry')
    animal_type = fields.Selection(
        [('cow','Cow'), ('bull','Bull'), ('goat','Goat'), ('sheep','Sheep'),
        ('fish','Fish'), ('rabbit','Rabbit'), ('chicken','Chicken'), ('turkey','Turkey'),
        ('ducks','Ducks'),('quells','Quells'),('camel','Camel'), ('horse','Horse'),],
        string='Animal Type')

feeds.py

from odoo import models, fields

class FeedsFeeds(models.Model):
    _name ='feed.feed'

    f_name = fields.Char(string='Feed Name', required=True)
    f_photo  = fields.Binary(string='Product Image')

feed_records.py

from odoo import models, fields

class FeedRecordsFeedRecords(models.Model):
    _name ='feedrecord.feedrecord'
    _inherits={'farmanimal.farmanimal','feed.feed'}

    feed_animal =  fields.Many2one( 'farmanimal.farmanimal','feed_animal_default_rel','name', string='Feed Animal',)
    feed_name = fields.Many2many('feed.feed', 'feed_default_rel', 'f_name', string='Consumed Feed(s)',)
    amount  = fields.Integer(string='Amount(In Grams)',)
    feed_date_time = fields.Datetime(string='Date and Time',default=fields.Datetime.now,)

vaccines.py

from odoo import models, fields

class VaccinesVaccines(models.Model):
    _name ='vaccine.vaccine'

    v_name = fields.Char(string='Vaccine Name', required=True)
    v_photo  = fields.Binary(string='Product Image')

vaccinations_records.py

from odoo import models, fields

class VaccinationRecordsVaccinationRecords(models.Model):
    _name ='vaccinationrecord.vaccinationrecord'
    _inherits={'farmanimal.farmanimal','vaccine.vaccine'}

    vaccinated_animal =  fields.Many2one( 'farmanimal.farmanimal','vaccinated_animal_default_rel','name', string='Vacinated Animal',)
    vaccine_name = fields.Many2many('vaccine.vaccine', 'vaccine_default_rel', 'v_name', string='Vaccine(s)',)
    vaccination_date_time = fields.Datetime(string='Date and Time',default=fields.Datetime.now,)
    next_vaccination_date = fields.Date(string='Next Date',)

diseases.py

from odoo import models, fields

class DiseasesDiseases(models.Model):
    _name ='disease.disease'
    _inherits='vaccine.vaccine'

    d_name= fields.Char(string='Name', required=True)
    d_type = fields.Selection(
        [('infectious disease','Infectious Disease'), ('deficiency disease','Deficiency Disease'), ('hereditary disease','Hereditary Disease'), ('physiological diseases','Physiological Diseases')], string='Disease Type')
    s_vector = fields.Selection(
        [('airborne','Airborne'), ('foodborne','Foodborne'), ('infectious','Infectious'), ('lifestyle','Lifestyle'), ('non-communicable','Non-communicable')],
        string='Spread Vector')
    threat_level = fields.Selection(
        [('high','High'), ('medium','Medium'), ('low','Low'), ('immediate quarantine','Immediate Quarantine')], string='Threat Level')
    cure = fields.Many2many('vaccine.vaccine', 'disease_cure_default_rel', 'v_name', string='Cure')

farm_view.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <odoo>
        <data>
            <record id="farm_menu_action" model="ir.actions.act_window">
                <field name="name">Animals</field>
                <field name="res_model">farmanimal.farmanimal</field>
                <field name="view_type">form</field>
                <field name="view_mode">kanban,tree,form</field>
                <field name="domain">[]</field>
                <field name="help" type="html">

Create The First Animal

                </field>

            </record>

            <record id="farm_tree_view" model="ir.ui.view">
                <field name="name">Animal Tree</field>
                <field name="model">farmanimal.farmanimal</field>
                <field name="arch" type="xml">
                    <tree string="Animals">
                        <field name="name"/>
                        <field name="sex"/>
                        <field name="animal_type"/>
                        <field name="animal_dob"/>
                    </tree>
                </field>
            </record>

            <record id="farm_kanban_view" model="ir.ui.view">
                <field name="name">farmanimal.farmanimal.kanban</field>
                <field name="model">farmanimal.farmanimal</field>
                <field name="arch" type="xml">
                    <kanban class="o_res_farm_kanban">
                        <field name="id"/>
                        <field name="name"/>
                        <field name="sex"/>
                        <field name="animal_type"/>
                        <field name="animal_dob"/>
                        <templates>
                            <t t-name="kanban-box">

                                            <field name="name"/>

                                            <t t-esc="record.animal_type.value"/>

                                            <t t-esc="record.sex.value"/>

                                            <t t-esc="record.animal_dob.value"/>

                            </t>
                        </templates>
                    </kanban>
                </field>

            </record>

            <record id="farm_free_view" model="ir.ui.view">
                <field name="name">Animal Form</field>
                <field name="model">farmanimal.farmanimal</field>
                <field name="arch" type="xml">
                    <form string="Animal">
                        <sheet>
                            <field name="photo" widget="image" class="oe_left oe_avatar" />

                                    <field name="name"/>

                            <group>
                                <group>
                                    <field name="animal_type"/>
                                    <field name="sex"/>
                                </group>
                                <group>
                                    <field name="animal_dob"/>
                                </group>
                            </group>
                            <notebook>
                              <page string="Feeding Records">

                              </page>
                              <page string="Vaccination Records">

                              </page>
                            </notebook>

                        </sheet>
                    </form>
                </field>
            </record>

            <menuitem id="farm_menu" name="Farm Management" action="farm_menu_action"/>
            <menuitem id="farm_animal_menu" parent="farm_menu"  name="Farm Animals"/>
        </data>
    </odoo>

farm_records_view.xml
<?xml version="1.0" encoding="UTF-8"?>
<odoo>
    <data>
        <record id="farm_menu_action" model="ir.actions.act_window">
            <field name="name">Animals</field>
            <field name="res_model">farmanimal.farmanimal</field>
            <field name="view_type">form</field>
            <field name="view_mode">kanban,tree,form</field>
            <field name="domain">[]</field>
            <field name="help" type="html">

Create The First Animal

            </field>

        </record>

        <record id="farm_tree_view" model="ir.ui.view">
            <field name="name">Animal Tree</field>
            <field name="model">farmanimal.farmanimal</field>
            <field name="arch" type="xml">
                <tree string="Animals">
                    <field name="name"/>
                    <field name="sex"/>
                    <field name="animal_type"/>
                    <field name="animal_dob"/>
                </tree>
            </field>
        </record>

        <record id="farm_kanban_view" model="ir.ui.view">
            <field name="name">farmanimal.farmanimal.kanban</field>
            <field name="model">farmanimal.farmanimal</field>
            <field name="arch" type="xml">
                <kanban class="o_res_farm_kanban">
                    <field name="id"/>
                    <field name="name"/>
                    <field name="sex"/>
                    <field name="animal_type"/>
                    <field name="animal_dob"/>
                    <templates>
                        <t t-name="kanban-box">

                                        <field name="name"/>

                                        <t t-esc="record.animal_type.value"/>

                                        <t t-esc="record.sex.value"/>

                                        <t t-esc="record.animal_dob.value"/>

                        </t>
                    </templates>
                </kanban>
            </field>

        </record>

        <record id="farm_free_view" model="ir.ui.view">
            <field name="name">Animal Form</field>
            <field name="model">farmanimal.farmanimal</field>
            <field name="arch" type="xml">
                <form string="Animal">
                    <sheet>
                        <field name="photo" widget="image" class="oe_left oe_avatar" />

                                <field name="name"/>

                        <group>
                            <group>
                                <field name="animal_type"/>
                                <field name="sex"/>
                            </group>
                            <group>
                                <field name="animal_dob"/>
                            </group>
                        </group>
                        <notebook>
                          <page string="Feeding Records">

                          </page>
                          <page string="Vaccination Records">

                          </page>
                        </notebook>

                    </sheet>
                </form>
            </field>
        </record>

        <menuitem id="farm_menu" name="Farm Management" action="farm_menu_action"/>
        <menuitem id="farm_animal_menu" parent="farm_menu"  name="Farm Animals"/>
    </data>
</odoo>

feed_records_view.py

<?xml version="1.0" encoding="UTF-8"?>
<odoo>
    <data>
        <record id="feeding_menu_action" model="ir.actions.act_window">
            <field name="name">Feeding Record</field>
            <field name="res_model">feedrecord.feedrecord</field>
            <field name="view_type">form</field>
            <field name="view_mode">tree,form</field>
            <field name="domain">[]</field>
            <field name="help" type="html">

Create The First Feeding Record

            </field>
        </record>

        <record id="feed_tree_view" model="ir.ui.view">
            <field name="name">Feeding Record Tree</field>
            <field name="model">feedrecord.feedrecord</field>
            <field name="arch" type="xml">
                <tree string="Feeding Record">
                    <field name="feed_animal"/>
                    <field name="feed_name"/>
                    <field name="amount"/>
                    <field name="feed_date_time"/>
                </tree>
            </field>
        </record>

        <record id="feeding_free_view" model="ir.ui.view">
            <field name="name">Feeding Record Form</field>
            <field name="model">feedrecords.feedrecords</field>
            <field name="arch" type="xml">
                <form string="Feeding Records">
                    <sheet>

                                <field name="feed_animal"/>

                        <group>
                            <group>
                                <field name="feed_name"/>
                                <field name="amount"/>
                                <field name="feed_date_time"/>
                            </group>
                        </group>

                    </sheet>
                </form>
            </field>
        </record>
    </data>
</odoo>

feeds_view.xml

<?xml version="1.0" encoding="UTF-8"?>
<odoo>
    <data>
        <record id="feeds_menu_action" model="ir.actions.act_window">
            <field name="name">Feeds</field>
            <field name="res_model">feed.feed</field>
            <field name="view_type">form</field>
            <field name="view_mode">kaban,tree,form</field>
            <field name="domain">[]</field>
            <field name="help" type="html">

Create The First Feed

            </field>
        </record>

        <record id="feed_tree_view" model="ir.ui.view">
            <field name="name">Feeds</field>
            <field name="model">feed.feed</field>
            <field name="arch" type="xml">
                <tree string="Feeds">
                    <field name="f_name"/>
                </tree>
            </field>
        </record>

        <record id="feed_kanban_view" model="ir.ui.view">
            <field name="name">feed.feed.kanban</field>
            <field name="model">feed.feed</field>
            <field name="arch" type="xml">
                <kanban class="o_res_farm_kanban">
                    <field name="id"/>
                    <field name="f_name"/>
                    <templates>
                        <t t-name="kanban-box">

                                        <field name="f_name"/>

                        </t>
                    </templates>
                </kanban>
            </field>
        </record>

        <record id="feed_free_view" model="ir.ui.view">
            <field name="name">Feeds</field>
            <field name="model">feed.feed</field>
            <field name="arch" type="xml">
                <form string="Feeds">
                    <sheet>
                        <field name="f_photo" widget="image" class="oe_left oe_avatar" />

                                <field name="f_name"/>

                    </sheet>
                </form>
            </field>
        </record>
    </data>
</odoo>

Body:
You need to revisit how you are defining your menuitems. Look at the Odoo documentation for reference.

The Parent menu(s) should not have any action. Only the final (child) menu should be assigned the action.

For example, instead of what you have currently:

<menuitem id="farm_menu" name="Farm Management"
    action="farm_menu_action"/>
<menuitem id="farm_animal_menu" name="Farm Animals"
    parent="farm_menu"/>

You ought to be doing this:

<menuitem id="farm_menu" name="Farm Management"/>
<menuitem id="farm_animal_menu" name="Farm Animals"
    parent="farm_menu"
    action="farm_menu_action"/>


来源: stackexchange

问:
Slick Carousel (Next/Prev Button Placement)
Slick Carousel (Next/Prev Button Placement)

```<code><div class="container">
    <div id="carousel" class="carousel">
        <div class="item red"></div>
        <div class="item orange"></div>
        <div class="item green"></div>
        <div class="item blue"></div>
    </div>
</div>

$('#carousel').slick({
    arrows: true,
    slidesToShow: 3
});
</code>```

Link

Everything is working fine , but i wanted to ask is that how do i make the Next Previous button are placed in the box instead of outside (see example below)

What I wanted:
The Button is on the image (like the example below) - DONE + a button with opacity when user hover

Example :

答:
Fiddle

adding below styling to css will move arrows to location in your image.

```<code>/* to align arrow at bottom */

.slick-prev{
    left: 10px;
    z-index: 1;
    top: 100%;
    transform: translateY(-100%);
}

.slick-next{
    right: 10px;
    z-index: 1;
    top: 100%;
    transform: translateY(-100%);
}
</code>```

if you want arrow to be opaced by default and visible on hover add below style.

```<code>/* to add opacity on default and remove it on hover */

.slick-prev,
.slick-next{
  opacity: 0.5;
}

.slick-prev:hover,
.slick-next:hover{
  opacity: 1;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Slick Carousel (Next/Prev Button Placement)

$('#carousel').slick({
    arrows: true,
    slidesToShow: 3
});

Link

Everything is working fine , but i wanted to ask is that how do i make the Next Previous button are placed in the box instead of outside (see example below)

What I wanted:
The Button is on the image (like the example below) - DONE + a button with opacity when user hover

Example :

Body:
Fiddle

adding below styling to css will move arrows to location in your image.

/* to align arrow at bottom */

.slick-prev{
    left: 10px;
    z-index: 1;
    top: 100%;
    transform: translateY(-100%);
}

.slick-next{
    right: 10px;
    z-index: 1;
    top: 100%;
    transform: translateY(-100%);
}

if you want arrow to be opaced by default and visible on hover add below style.

/* to add opacity on default and remove it on hover */

.slick-prev,
.slick-next{
  opacity: 0.5;
}

.slick-prev:hover,
.slick-next:hover{
  opacity: 1;
}


问:
IIS7 and HTTP status code handling
I'm having a hardcore head-ache from trying to get complete programmatic control over rendering of an error in IIS7 (integrated mode). What I want to do is given an error (page not found, internal server error, not authenticated, etc), transfer the whole request to a custom ASPX or HTML (I prefer the latter) with the correct HTTP status code.

What I want is IIS7 to don't give a crap about what I set the HTTP status code to. I don't want its error handling. When I set Response.StatusCode = (int)HttpStatusCode.NotFound, what I want is not IIS to render its own error page, but perhaps transfer the request to another file.

I've gotten this static configuration stuff to work:

```<code><configuration>
  <system.webServer>
    <httpErrors>
      <clear />
      <error statusCode="404" path="/errors/404.html" responseMode="ExecuteURL" />
    </httpErrors>
  </system.webServer>
</configuration>
</code>```

While this works, it doesn't give me programmatic control over what to do with the response, given an error scenario. Configuration is a good fallback, but I'd really like to be able to set Response.StatusCode and render something completely different from the configured 404.html in certain circumstances (like a JSON response if we receive Accept: application/json), but IIS7 won't let me. Not a chance.

So what the heck am I supposed to do? I've tried to set HttpResponse.TrySkipIisCustomErrors Property, but that looks like a huge hack and doesn't seem to work consistently. Is setting this property to true really the recommended best practice to get the behavior I want?

At the moment, the feeling I'm left with is nothing but intense hate towards IIS7. Can anyone please help me remedy this by proving that I'm just being stupid and that I can indeed have full control over the HTTP stack?

答:
Have a look at the following:  IIS7 Overrides customErrors when setting Response.StatusCode?.

You need to set

```<code>  <system.webServer>
    <httpErrors existingResponse="PassThrough" />
  </system.webServer>
</code>```

ContentLicense: CC BY-SA 3.0

Title: IIS7 and HTTP status code handling

Body:
I'm having a hardcore head-ache from trying to get complete programmatic control over rendering of an error in IIS7 (integrated mode). What I want to do is given an error (page not found, internal server error, not authenticated, etc), transfer the whole request to a custom ASPX or HTML (I prefer the latter) with the correct HTTP status code.

What I want is IIS7 to don't give a crap about what I set the HTTP status code to. I don't want its error handling. When I set Response.StatusCode = (int)HttpStatusCode.NotFound, what I want is not IIS to render its own error page, but perhaps transfer the request to another file.

I've gotten this static configuration stuff to work:

<configuration>
  <system.webServer>
    <httpErrors>
      <clear />
      <error statusCode="404" path="/errors/404.html" responseMode="ExecuteURL" />
    </httpErrors>
  </system.webServer>
</configuration>

While this works, it doesn't give me programmatic control over what to do with the response, given an error scenario. Configuration is a good fallback, but I'd really like to be able to set Response.StatusCode and render something completely different from the configured 404.html in certain circumstances (like a JSON response if we receive Accept: application/json), but IIS7 won't let me. Not a chance.

So what the heck am I supposed to do? I've tried to set HttpResponse.TrySkipIisCustomErrors Property, but that looks like a huge hack and doesn't seem to work consistently. Is setting this property to true really the recommended best practice to get the behavior I want?

At the moment, the feeling I'm left with is nothing but intense hate towards IIS7. Can anyone please help me remedy this by proving that I'm just being stupid and that I can indeed have full control over the HTTP stack?

Body:
Have a look at the following:  IIS7 Overrides customErrors when setting Response.StatusCode?.

You need to set

  <system.webServer>
    <httpErrors existingResponse="PassThrough" />
  </system.webServer>


问:
serialize int to vector of bytes using std::vector::reverse_iterator?
Next function works fine:

```<code>std::vector<uint8_t> serialize_bytes(uint32_t ui)
{
    return {(uint8_t*)&ui, (uint8_t*)(&ui+1)};
}
</code>```

But its result depends on endianess of machine.

I also need to serialize bytes in reverse order:

```<code>std::vector<uint8_t> serialize_bytes(uint32_t ui)
{
    std::vector<uint8_t>::reverse_iterator
        begin{(uint8_t*)(&ui+1)-1}
      , end{(uint8_t*)(&ui)-1};  //ERROR: Calling a private constructor
    return {begin, end};
}
</code>```

I know multiple other ways to do serialization. The interest of this Q is to construct reverse_iterator from pointer in manner like first snippet does.

答:
I took the above idea and rewrite it in own manner

```<code>std::vector<uint8_t> serialize_bytes(uint32_t ui)
{
    std::reverse_iterator<uint8_t*> begin{(uint8_t*)(&ui+1)}, end{(uint8_t*)(&ui)};
    return {begin, end};
}
</code>```

thank you @HolyBlackCat

Body:
Next function works fine:

std::vector<uint8_t> serialize_bytes(uint32_t ui)
{
    return {(uint8_t*)&ui, (uint8_t*)(&ui+1)};
}

But its result depends on endianess of machine.

I also need to serialize bytes in reverse order:

std::vector<uint8_t> serialize_bytes(uint32_t ui)
{
    std::vector<uint8_t>::reverse_iterator
        begin{(uint8_t*)(&ui+1)-1}
      , end{(uint8_t*)(&ui)-1};  //ERROR: Calling a private constructor
    return {begin, end};
}

I know multiple other ways to do serialization. The interest of this Q is to construct reverse_iterator from pointer in manner like first snippet does.

Body:
I took the above idea and rewrite it in own manner

std::vector<uint8_t> serialize_bytes(uint32_t ui)
{
    std::reverse_iterator<uint8_t*> begin{(uint8_t*)(&ui+1)}, end{(uint8_t*)(&ui)};
    return {begin, end};
}

thank you @HolyBlackCat


问:
Fourier Transformation of 2D Matrix in Python
So, I have a matrix with 72x72 values, each corresponding to some energy on a triangular lattice with 72x72 sites. I'm trying to Fourier transform the values, but I'm not understanding how to do that with np.fft.fftn .

To illustrate my problem I have written the following basic code with some random values. The triangular gives the lattice x,y coordinates.

```<code>import numpy as np
import matplotlib.pyplot as plt

    def triangular(nsize):
        x=0
        y=0
        X=np.zeros((nsize,nsize))
        Y=np.zeros((nsize,nsize))
        for i in range(nsize):
            for j in range(nsize):
                X[i,j]+=1/2*j+i
                Y[i,j]+=np.sqrt(3)/2*j
        return(X,Y)

xx = triangular(72)[0]
yy = triangular(72)[1]

plt.figure()
plt.pcolormesh(xx, yy, np.reshape(np.random.rand(72**2),(72,72)))
</code>```

I'm not using random data, but I wanted not to make the example that complicated. In fact I see everytime the same plot, when I now use the following FFT:

```<code>matrix = []

matrix.append(triangular(72)[0])

matrix.append(triangular(72)[1])

matrix.append(np.reshape(np.random.rand(72**2),(72,72)))

spectrum_3d = np.fft.fftn(matrix)                # Fourrier transform along x, y, energy

kx = np.linspace(-4*np.pi/3,4*np.pi/3,72)      #this is the range I want to plot

ky = np.linspace(-2*np.pi/np.sqrt(3),2*np.pi/np.sqrt(3),72)

Ky, Kx = np.meshgrid(ky, kx, indexing='ij')       #making a grid

plt.figure(figsize=(11,9))
psd = plt.pcolormesh(Kx, Ky, abs(spectrum_3d[2])**2)
cbar = plt.colorbar(psd)
plt.xlabel('kx')
plt.ylabel('ky')
</code>```

My result looks always the same and I don't know what went wrong. Also for my correlated values, which have a large symmetry the plot looks the same.

答:
You can't 'see' the spectrum because of the DC dominance.

```<code>import numpy as np
import matplotlib.pyplot as p
%matplotlib inline

n=72
x=np.arange(n)
y=np.arange(n)
X,Y= np.meshgrid(x,y)

data=np.reshape(np.random.rand(n**2),(n,n))

data_wo_DC= data- np.mean(data)

spectrum = np.fft.fftshift(np.fft.fft2(data))
spectrum_wo_DC = np.fft.fftshift(np.fft.fft2(data_wo_DC))

freqx=np.fft.fftshift(np.fft.fftfreq(72,1))   #q(n, d=1.0)
freqy=np.fft.fftshift(np.fft.fftfreq(72,1))
fX,fY= np.meshgrid(freqx,freqy)

p.figure(figsize=(20,6))
p.subplot(131)
p.pcolormesh(X,Y, data)
p.colorbar()

p.subplot(132)
p.pcolormesh(fX,fY,np.abs(spectrum))
p.colorbar()
p.title('most data is in the DC')

p.subplot(133)
p.pcolormesh(fX,fY,np.abs(spectrum_wo_DC))
p.colorbar()
p.title('wo DC we can see the structure');
</code>```

Body:
So, I have a matrix with 72x72 values, each corresponding to some energy on a triangular lattice with 72x72 sites. I'm trying to Fourier transform the values, but I'm not understanding how to do that with np.fft.fftn .

To illustrate my problem I have written the following basic code with some random values. The triangular gives the lattice x,y coordinates.

import numpy as np
import matplotlib.pyplot as plt

    def triangular(nsize):
        x=0
        y=0
        X=np.zeros((nsize,nsize))
        Y=np.zeros((nsize,nsize))
        for i in range(nsize):
            for j in range(nsize):
                X[i,j]+=1/2*j+i
                Y[i,j]+=np.sqrt(3)/2*j
        return(X,Y)

xx = triangular(72)[0]
yy = triangular(72)[1]

plt.figure()
plt.pcolormesh(xx, yy, np.reshape(np.random.rand(72**2),(72,72)))

I'm not using random data, but I wanted not to make the example that complicated. In fact I see everytime the same plot, when I now use the following FFT:

matrix = []

matrix.append(triangular(72)[0])

matrix.append(triangular(72)[1])

matrix.append(np.reshape(np.random.rand(72**2),(72,72)))

spectrum_3d = np.fft.fftn(matrix)                # Fourrier transform along x, y, energy

kx = np.linspace(-4*np.pi/3,4*np.pi/3,72)      #this is the range I want to plot

ky = np.linspace(-2*np.pi/np.sqrt(3),2*np.pi/np.sqrt(3),72)

Ky, Kx = np.meshgrid(ky, kx, indexing='ij')       #making a grid

plt.figure(figsize=(11,9))
psd = plt.pcolormesh(Kx, Ky, abs(spectrum_3d[2])**2)
cbar = plt.colorbar(psd)
plt.xlabel('kx')
plt.ylabel('ky')

My result looks always the same and I don't know what went wrong. Also for my correlated values, which have a large symmetry the plot looks the same.

Body:
You can't 'see' the spectrum because of the DC dominance.

import numpy as np
import matplotlib.pyplot as p
%matplotlib inline

n=72
x=np.arange(n)
y=np.arange(n)
X,Y= np.meshgrid(x,y)

data=np.reshape(np.random.rand(n**2),(n,n))

data_wo_DC= data- np.mean(data)

spectrum = np.fft.fftshift(np.fft.fft2(data))
spectrum_wo_DC = np.fft.fftshift(np.fft.fft2(data_wo_DC))

freqx=np.fft.fftshift(np.fft.fftfreq(72,1))   #q(n, d=1.0)
freqy=np.fft.fftshift(np.fft.fftfreq(72,1))
fX,fY= np.meshgrid(freqx,freqy)

p.figure(figsize=(20,6))
p.subplot(131)
p.pcolormesh(X,Y, data)
p.colorbar()

p.subplot(132)
p.pcolormesh(fX,fY,np.abs(spectrum))
p.colorbar()
p.title('most data is in the DC')

p.subplot(133)
p.pcolormesh(fX,fY,np.abs(spectrum_wo_DC))
p.colorbar()
p.title('wo DC we can see the structure');


问:
Rename the same column for all excel files in a folder in R
I have multiple excel files in a folder, so I want to clean each file in the folder, then append all the excel files together. I want to rename the first column of all excel files so I am using the following codes :

```<code>filelist<- list.files(pattern="*.xlsx")
DF <- lapply(filelist,function(i) {
Fu <- read_excel(i, sheet="XX")
colnames(Fu[[i]])[1] <- "Column 1"})
</code>```

However, I got an error message:  Error in colnames<-(*tmp*, value = "SCENARIO_KEY") :
  attempt to set 'colnames' on an object with less than two dimensions. How to fix it? Thank you.

答:
In the lapply, itself, we can rename.  The i in the loop are each of the element of 'filelist'.  It cannot be used for subsetting 'Fu'.  Instead, we can directly subset the column based on the index as 'Fu' is a single data.frame within each list element

```<code>DF <- lapply(filelist,function(i) {
          Fu <- read_excel(i, sheet="XX")
          colnames(Fu)[1] <- "Column 1"
          Fu
     })
</code>```

Even if the index is right, when we subset a data.frame with [[ to get the column, it returns a vector and there is dim or column names attribute for a vector

```<code>mtcars[[1]]
</code>```

is a vector

and doing the assignment returns the error because the colnames is NULL

```<code>colnames(mtcars[[1]])
#NULL

colnames(mtcars[[1]]) <- "new column"
</code>```

Error in colnames<-(*tmp*, value = "new column") :
    attempt to set 'colnames' on an object with less than two dimensions

Body:
I have multiple excel files in a folder, so I want to clean each file in the folder, then append all the excel files together. I want to rename the first column of all excel files so I am using the following codes :

filelist<- list.files(pattern="*.xlsx")
DF <- lapply(filelist,function(i) {
Fu <- read_excel(i, sheet="XX")
colnames(Fu[[i]])[1] <- "Column 1"})

However, I got an error message:  Error in colnames<-(*tmp*, value = "SCENARIO_KEY") :
  attempt to set 'colnames' on an object with less than two dimensions. How to fix it? Thank you.

Body:
In the lapply, itself, we can rename.  The i in the loop are each of the element of 'filelist'.  It cannot be used for subsetting 'Fu'.  Instead, we can directly subset the column based on the index as 'Fu' is a single data.frame within each list element

DF <- lapply(filelist,function(i) {
          Fu <- read_excel(i, sheet="XX")
          colnames(Fu)[1] <- "Column 1"
          Fu
     })

Even if the index is right, when we subset a data.frame with [[ to get the column, it returns a vector and there is dim or column names attribute for a vector

mtcars[[1]]

is a vector

and doing the assignment returns the error because the colnames is NULL

colnames(mtcars[[1]])
#NULL

colnames(mtcars[[1]]) <- "new column"

Error in colnames<-(*tmp*, value = "new column") :
    attempt to set 'colnames' on an object with less than two dimensions


问:
XPath expression in Log4Net
Changing the levelMin and levelMax value of both SmtpAppender and ADONetAppender for web.config transform file.
How to select those particular elements and change the value?

```<code><configuration>
  <log4net>
    <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
      <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="ERROR1" xdt:Transform="Replace" xdt:Locator="XPath(.)"/>
        <levelMax value="FATAL2" xdt:Transform="Replace" xdt:Locator="XPath(.)"/>
      </filter>
    </appender>
    <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
      <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="ERROR3" xdt:Transform="Replace" xdt:Locator="XPath(.)"/>
        <levelMax value="FATAL4" xdt:Transform="Replace" xdt:Locator="XPath(.)"/>
      </filter>
    </appender>
  </log4net>
</configuration>
</code>```

Tried <levelMin value="ERROR" xdt:Transform="Replace" xdt:Locator="configuration/log4net[@name='SmtpAppender']/filter[@providerName='log4net.Filter.LevelRangeFilter']"/>
and many other combinations to pickup the particular element.

How to change the values for those individual elements in web.config transform files?

答:
Resoled the above issue. Adding xdt:Locator="Match(name) helped to resolve the issue.

```<code><configuration>
  <log4net>
    <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender" xdt:Locator="Match(name)">
      <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="ERROR1" xdt:Transform="Replace"/>
        <levelMax value="FATAL2" xdt:Transform="Replace"/>
      </filter>
    </appender>
    <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender" xdt:Locator="Match(name)">
      <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="ERROR3" xdt:Transform="Replace"/>
        <levelMax value="FATAL4" xdt:Transform="Replace"/>
      </filter>
    </appender>
  </log4net>
</configuration>
</code>```

Title: XPath expression in Log4Net

Body:
Changing the levelMin and levelMax value of both SmtpAppender and ADONetAppender for web.config transform file.
How to select those particular elements and change the value?

<configuration>
  <log4net>
    <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
      <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="ERROR1" xdt:Transform="Replace" xdt:Locator="XPath(.)"/>
        <levelMax value="FATAL2" xdt:Transform="Replace" xdt:Locator="XPath(.)"/>
      </filter>
    </appender>
    <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
      <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="ERROR3" xdt:Transform="Replace" xdt:Locator="XPath(.)"/>
        <levelMax value="FATAL4" xdt:Transform="Replace" xdt:Locator="XPath(.)"/>
      </filter>
    </appender>
  </log4net>
</configuration>

Tried <levelMin value="ERROR" xdt:Transform="Replace" xdt:Locator="configuration/log4net[@name='SmtpAppender']/filter[@providerName='log4net.Filter.LevelRangeFilter']"/>
and many other combinations to pickup the particular element.

How to change the values for those individual elements in web.config transform files?

Body:
Resoled the above issue. Adding xdt:Locator="Match(name) helped to resolve the issue.

<configuration>
  <log4net>
    <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender" xdt:Locator="Match(name)">
      <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="ERROR1" xdt:Transform="Replace"/>
        <levelMax value="FATAL2" xdt:Transform="Replace"/>
      </filter>
    </appender>
    <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender" xdt:Locator="Match(name)">
      <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="ERROR3" xdt:Transform="Replace"/>
        <levelMax value="FATAL4" xdt:Transform="Replace"/>
      </filter>
    </appender>
  </log4net>
</configuration>


问:
Binding Button IsEnabled to StackPanel has Children
I'm wondering if I can bind my Button isEnabled to my StackPanel Children (has children). If the stackpanel has children, then my button is enabled, no children my button is disabled. Currently I just handle this in code, but I started wondering if this was something I could bind. Thanks for any thoughts...</p>

答: You could write a simple ValueConverter which does that logic for you. Bind the IsEnabled of the Button to the StackPanel and in your value converter check if it has any children and then return true/false.</p>


问:
After effects: how to make a text follow top of animated bar in bar chart
I want to animate a horizontal bar chart. The bars (squares) start at zero and grow within two easy-ease keyframes from 0 to a specific value. This value is displayed in a text layer. I have set up a slider which goes from zero to the specific value and controls both the text layer (value) and the size of the bar (width of square).

Problem: I want the value to follow the top of the bar chart as in here:

https://www.instagram.com/p/B7_5SOQFrW6/?utm_source=ig_web_copy_link

I tried to set easy-ease keyframes for the text layer too and adjust the values in the diagram editor. Result was too shaky and not nice to look at. Is there a solution with expressions?

source text of text layer for first Bar (1):

```<code>Math.round(thisComp.layer("controler").effect("1")("slider"))
</code>```

source for square (first bar):

```<code>temp = thisComp.layer("controler").effect("1")("slider");
he_ = thisComp.layer("controler").effect("height")("slider");
[temp,wi_]
</code>```

info: width is a slider with which I control the height of the bars.

答:
Check this sample project, with both vertical and horizontal bars: https://url.io/ae_barchart

You can use sourceRectAtTime (like in the sample project), or calculate the position of the top side of your bar, knowing it's height and bottom Y coordinate and then translate it into Composition space from the bar layer`s space, so you can apply it to your Text Layer position.

If you check the position property of "bar_horizontal_text" / "bar_vertical_text" layers you'll see what I mean.

The rest of the setup is extra... just "fooling around". :-)

Body:
I want to animate a horizontal bar chart. The bars (squares) start at zero and grow within two easy-ease keyframes from 0 to a specific value. This value is displayed in a text layer. I have set up a slider which goes from zero to the specific value and controls both the text layer (value) and the size of the bar (width of square).

Problem: I want the value to follow the top of the bar chart as in here:

https://www.instagram.com/p/B7_5SOQFrW6/?utm_source=ig_web_copy_link

I tried to set easy-ease keyframes for the text layer too and adjust the values in the diagram editor. Result was too shaky and not nice to look at. Is there a solution with expressions?

source text of text layer for first Bar (1):

Math.round(thisComp.layer("controler").effect("1")("slider"))

source for square (first bar):

temp = thisComp.layer("controler").effect("1")("slider");
he_ = thisComp.layer("controler").effect("height")("slider");
[temp,wi_]

info: width is a slider with which I control the height of the bars.


问:
Elasticsearch Best Practices Flow
I am using elastic-search for product filtering for products. We have complex logic of product availability. I can see two options

Using elastic to store only product specific data and product availability logic resides in web server part. we first filter data from elastic then check the condition on those result set if it matches the logic of availability.

or We can flatten the data and store it in elastic though for that case there will be duplicates of data.

My concern is if it is good practice to call elastic endpoint from browser. As it does not have any auth system by default. and every query and response will be visible in network log. I believe call should be made from web server to elastic and front end will communicate with elastic unaware of elastic existence.

Any best practice insight will be helpful

答:
Simply create and authenticated endpoint in your backend and send the queries to that endpoint. Do make sure there are some enforced limits such as

size -- You don't want to let anybody download your whole index and

aggregation depth -- you don't want anyone to perform summaries on your whole index/indices to get a competitive advantage.

Regarding the duplicates: I wouldn't worry too much about the storage aspect (many NoSQL approaches will probably have some duplication to facilitate fast queries) but keep in mind that aggregations might yield "wrong" counts and sums. You'd typically perform those aggregations to get, say, the totals in your product categories and you want to make sure they are representative of your warehouse state.

More cannot really be said right now based on the limited information you've provided.

Title: Elasticsearch Best Practices Flow


问:
How to disable line wrapping in Jupyter notebook output cells?
By default longer lines of text in the output cells of a Jupyter notebook will be wrapped. How to stop this behaviour?</p>

答:
I was able to solve this problem by adding a simple CSS rule to the custom/custom.css file in my Jupyter user configuration:

/*Disable code output line wrapping*/
div.output_area pre {
    white-space: pre;
}
```
<p>The result:</p>
<p><img src="https://i.stack.imgur.com/uBeX0.png" alt="enter image description here" /></p>
<p>The <code>div.output_area pre</code> selects the <code>pre</code> preformated text areas of the code output areas for the rule (set of css properties). The <code>white-space</code> property states how the browser should display white spaces in the selected HTML elements with the <code>pre</code> value the browser only breaks at new line characters <code>\n</code> and <code><br></code> elements.</p>
<p>This CSS renders well (with a fine horizontal scrollbar) for my Firefox v70.0 and Chorme v78.0.3904.97, according to Can I Use the <code>white-space: pre</code> property and value should work on all modern desktop browsers.</p>
<p>You can find out where your configuration resides by running the following shell command:</p>
```jupyter --config
```
<p>If you want make further style modifications just play around with the inspector of your favorite browser on Jupyter Notebook tab. where you can modify the CSS without permanent effects.</p>
<h1>Update for Jupyter Lab</h1>
<p>As kiesel commented: In Jupyter Lab the class of the parent div is changed to <code>jp-OutputArea-output</code>. However there is another problem: Jupyter Lab does not read the <code>custom/custom.css</code> file. There is two way around this.</p>
<h2>1. (dirty, fast) edit the theme in use.</h2>
<p>In my case I edited the <code>~/miniconda3/envs/< env name >/share/jupyter/lab/themes/@jupyterlab/theme-dark-extension/index.css</code> file and added the following code.</p>
<pre class="lang-css prettyprint-override"><code>div.jp-OutputArea-output pre {
    white-space: pre
}
</code>```

of course this fix will only work in the one specific environment where you edited the theme index.css. Therefore I do not recommend it.

2. (clean, slow) Use an extension which supports custom CSS

This nice fellow made a theme for Jupyter Lab which allows you to include a custom CSS file.

Body:
I was able to solve this problem by adding a simple CSS rule to the custom/custom.css file in my Jupyter user configuration:

/*Disable code output line wrapping*/
div.output_area pre {
    white-space: pre;
}

The result:

The div.output_area pre selects the pre preformated text areas of the code output areas for the rule (set of css properties). The white-space property states how the browser should display white spaces in the selected HTML elements with the pre value the browser only breaks at new line characters \n and <br> elements.

This CSS renders well (with a fine horizontal scrollbar) for my Firefox v70.0 and Chorme v78.0.3904.97, according to Can I Use the white-space: pre property and value should work on all modern desktop browsers.

You can find out where your configuration resides by running the following shell command:

jupyter --config

If you want make further style modifications just play around with the inspector of your favorite browser on Jupyter Notebook tab. where you can modify the CSS without permanent effects.

Update for Jupyter Lab

As kiesel commented: In Jupyter Lab the class of the parent div is changed to jp-OutputArea-output. However there is another problem: Jupyter Lab does not read the custom/custom.css file. There is two way around this.

1. (dirty, fast) edit the theme in use.

In my case I edited the ~/miniconda3/envs/< env name >/share/jupyter/lab/themes/@jupyterlab/theme-dark-extension/index.css file and added the following code.

div.jp-OutputArea-output pre {
    white-space: pre
}

of course this fix will only work in the one specific environment where you edited the theme index.css. Therefore I do not recommend it.

2. (clean, slow) Use an extension which supports custom CSS

This nice fellow made a theme for Jupyter Lab which allows you to include a custom CSS file.


问:
image border not displaying html email
I am trying to send an html email with an image border as

```<code><p align="center">
    <img src="images/pic1.jpg" width="443" height="148" align="middle"
         style="border: 1px solid grey; padding:10px;" border="1"/>
</p>
</code>```

However, the border just does not display in any of the email clients. How can i fix this?

答:
a little bit off topic but mailchimp has a great tool for translating a normal HTML layout with seperate CSS classes into an inline CSS version

http://beaker.mailchimp.com/inline-css

and also a great tutorial how to code HTML emails the right way

http://kb.mailchimp.com/article/how-to-code-html-emails/

and regarding your CSS problem.

Try wrapping the image in a table cell and give the cell the border.

Unfortunately with HTML E-mails, tables are your friend, yet again.

Have fun

Title: image border not displaying html email

Body:
I am trying to send an html email with an image border as

However, the border just does not display in any of the email clients. How can i fix this?


问:
Nested tables in email
So, I'm totally losing my mind with an email that I'm trying to format.

I think it has to do with a particular nested table.

The main table is 650px wide and the width of the nested table is set to 100%.

What's happening is that, as soon as I plug in the nested tables, the header and footer images are being reduced by 20px(10+10) on the right side(despite both images being 650 pixels wide).

When I modify the nested tables to make the cellspacing on both sides of the nested tables =0(originally 10px on both sides i.e. 20px in total), then the header and footer images line up correctly but, assuming the cellspacing is set to 10 px on each side of the nested table, then the header and footer images get reduced.

Why is the nested table cellspacing affecting my table header and footer images?

```<code>    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>2020 Preferred Share Outlook with Fiera Capital</title>
<style type="text/css">
<!--
html, body {
    font-family: Arial, Helvetica, sans-serif;
    color: #444;
    font-size: 17px;
    line-height:30px;
    background-color: #FAFAFA;
}
img {
    border:none;
}
sup, sub {
  vertical-align: baseline;
  position: relative;
  top: -0.4em;
}

.disclaimer {
    font-family: Arial, Helvetica, sans-serif;
    color: #666;
    font-size: 12px;
    line-height:16px;
}
.title {
    color: #F60;
    font-weight: bold;
    font-size: 18px;
    line-height: 25px;
}
.title2 {
    color: #F60;
    font-weight: bold;
    font-size: 14px;
    line-height: 20px;
}

a:link {
    color: #F60;
}
a:visited {
    color: #F60;
}
a:hover {
    color: #F60;
}
a:active {
    color: #77881c;
}
.orange {
    color: #F60;
}
.disclaimer{
padding:15px;
    }
.table_data {
    font-size: 9px;
    font-family: Arial, Helvetica, sans-serif;
    border-color: #FDFDFD;
    line-height:12px;
}
.disclaimer1 {  font-family: Arial, Helvetica, sans-serif;
    color: #666;
    font-size: 11px;
    line-height:16px;
}
.details {
    font-size: 13px;
    line-height:20px;
}
-->
</style>
</head>

<body style="margin: 0;">
<table width="101%" height="100%">
  <tr>
    <td><table width="650" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
      <tr>
            <td width="650">
                <img src="https://www.horizonsetfs.com/horizons/media/emails/2020/202002_FieraWebinar/Email_Header.png" alt="2020 Preferred Share Outlook with Fiera Capital" style="border:none"/>
            </td>
       </tr>
       <tr>
          <td align="left" style="padding: 15px 20px 20px 20px;">
            <p class="title">Get the Latest Outlook from Fiera Capital on the Canadian Preferred Shares and Fixed Income Markets</p>
            <p>The Canadian preferred share market has bounced back from its lows in Q3 2019. But Fiera Capital believes there is still significant potential upside left in this asset class, since preferred shares offer higher relative yields compared to bonds, and should have less pressure from new issuances in 2020.</p>
            <p>Fiera Capital’s Nicolas Normandeau, lead portfolio manager for the <a href="http://www.horizonsetfs.com/hpr">Horizons Active Preferred Share ETF (HPR)</a> and the <a href="http://www.horizonsetfs.com/hfp">Horizons Floating Rate Preferred Share ETF (HFP)</a>, will outline his team’s outlook for Canadian preferred shares in 2020, and why he feels they remain a potentially attractive option for Canadian fixed income investors.</p>
            <p><a href="https://attendee.gotowebinar.com/register/6491065155959682573?" target="_blank"><img src="http://horizonsetfs.com/horizons/media/emails/common-images/register_en.png" alt="Register for the webinar Now" style="border:none"/></a></p>

            <table width="100%" cellspacing="10" cellpadding="10" border="0">
                <tbody>
                    <tr>
                        <td width="50%" bgcolor="#EEEEEE"><br><span class="title"><strong>Advisors and Investors Bullish in New Decade<br>
                            <a href="https://www.horizonsetfs.com/sentimentsurvey" target="_blank"><br>
                            <img src="https://www.horizonsetfs.com/horizons/media/emails/2020/202002_FieraWebinar/Sentiment-Survey.jpg" alt="Sentiment Survey Results" style="border:none"></a><br>
                            </strong></span><br>
                            <a href="https://www.horizonsetfs.com/sentimentsurvey" target="_blank">Did you miss our Q1 2020 Sentiment Survey Results?</a> See where Canadian advisors and investors stand on 14 different indices and asset classes, ranging from the NASDAQ-100® to Gold Bullion.<br> <p>Stay tuned for our Q2 2020 Sentiment Survey in March – you could win a $150 Amazon gift card!</p>
                        </td>
                        <td width="" bgcolor="#EEEEEE">
                            <span class="title"><strong>Just Launched: Three New Total Return ETFs</strong></span><br>
                            <a href="https://www.horizonsetfs.com/news/Press-Release/Horizons-ETFs-Launches-Three-New-Total-Return-ETFs" target="_blank"><br>
                            <img src="https://www.horizonsetfs.com/horizons/media/emails/2020/202002_FieraWebinar/Market-Open-pic.png" alt="Launch of new Total Return ETFs" style="border:none"></a><br>
                            On February 6, 2020, Horizons ETFs launched three new ETFs: <a href="https://www.horizonsetfs.com/etf/hulc">HULC</a>, <a href="https://www.horizonsetfs.com/etf/hsav">HSAV</a>, as well as <a href="https://www.horizonsetfs.com/etf/hxcn">HXCN</a>. With $1 billion in seed capital, HXCN is the largest ETF launch in Canadian history. <a href="https://www.horizonsetfs.com/news/Press-Release/Horizons-ETFs-Launches-Three-New-Total-Return-ETFs" target="_blank">Learn more about our new total return ETFs</a> <br> <br> <br> <br>
                        </td>
                    </tr>
                </tbody>
            </table>

            <table width="100%" border="0" cellpadding="0">
                <tbody>
                    <tr>
                    <td width="30%">
                        <img src="https://www.horizonsetfs.com/horizons/media/emails/2020/202002_FieraWebinar/Nicolas-Normandeau.png" alt="Nicolas Normandeau, CFA®, M.SC." style="border:none"/><span class="orange"><strong>Nicolas Normandeau</strong></span>
                        <br>
                        <strong><span style="font-size: 12px;">CFA®, M.SC. – Vice-President and Portfolio Manager, Fixed Income, Fiera Capital</span></strong>
                    </td>
                    <td width="70%">
                        <em>Nicolas Normandeau is a member of Fiera Capital’s Corporate Fixed Income team and a portfolio manager for the firm’s Corporate Fixed Income strategy with 10 years of industry experience. Fiera Capital is one of Canada’s largest managers of fixed income investments and is the sub-advisor for many of <a href="https://www.horizonsetfs.com/horizons/media/pdfs/library/ActiveIncomeETFs_EN.pdf" target="_blank">Horizons ETFs’ fixed income funds.</a></em>
                    </td>
                    <br>
                    </tr>
                </tbody>
            </table>

          </td>
        </tr>

       <tr>
          <td width="650"><img src="https://www.horizonsetfs.com/horizons/media/emails/common-images/footer_en.jpg" alt="Horizons Exchange Traded Funds" /></td>
       </tr>
       <tr>
           <td class="disclaimer"><p class="disclaimer1">*Plus  applicable sales taxes.</p>
             <p class="disclaimer1">Commissions, management fees and expenses all  may be associated with an investment in exchange traded products managed by  Horizons ETFs Management (Canada) Inc. (the "Horizons Exchange Traded  Products"). The Horizons Exchange Traded Products are not guaranteed,  their values change frequently and past performance may not be repeated. The  prospectus contains important detailed information about the Horizons Exchange  Traded Products. <strong>Please read the  relevant prospectus before investing.</strong></p>
             <p class="disclaimer1">Certain statements may constitute a forward looking statement, including those identified by the expressions “anticipate”, “estimate” or “expect” and similar expressions (including grammatical variations thereof) to the extent they relate to the ETFs or Horizons ETFs. The forward-looking statements are not historical facts but reflect the ETFs, the ETF’s managers or Horizons ETFs current expectations regarding future results or events. These forward-looking statements are subject to a number of risks and uncertainties that could cause actual results or events to differ materially from current expectations. These and other factors should be considered carefully and readers should not place undue reliance on the ETFs’ forward looking statements. These forward-looking statements are made as of the date hereof and the ETFs do not undertake to update any forward-looking statement that is contained herein, whether as a result of new information, future events or otherwise, unless required by applicable law.</p>
             <p class="disclaimer1"><sup>1</sup>Horizons Total Return ETFs  (“Horizons Total Return ETFs”) are generally index-tracking ETFs that use an  innovative investment structure known as a Total Return Swap to deliver the  returns of an underlying benchmark in a low-cost and tax-efficient manner.  Unlike a physical replication ETF that typically purchases the securities found  in the relevant benchmark in the same proportions as the benchmark, most  Horizons Total Return ETFs use a synthetic structure that never buys the  securities of a benchmark directly. Instead, the ETF receives the total return  of the benchmark through entering into a Total Return Swap agreement with one  or more counterparties, typically large financial institutions, which will  provide the ETF with the total return of the benchmark in exchange for the  interest earned on the cash held by the ETF. Any distributions which are paid  by the benchmark’s constituents are reflected automatically in the net asset  value (NAV) of the ETF. As a result, the Horizons Total Return ETF receives the  total return of the benchmark (before fees), which is reflected in the ETF’s  share price, and investors are not expected to receive any taxable  distributions. Certain Horizons Total Return ETFs use physical replication  instead of a total return swap, which includes HULC and HSAV. The Horizons Cash  Maximizer ETF does not track a traditional benchmark but rather a compounding  rate of interest paid on a cash deposit that can change over time.</p>
             <p class="disclaimer1">In the past you have provided Horizons ETFs with your email address or your email address is publicly available. You will receive brief news announcements regarding our ETFs and related topics. If you no longer wish to receive these announcements, you may unsubscribe by <a href="%%email_preference_center%%" target="_blank">clicking here</a> and updating your user preferences.</p>
             <p class="disclaimer1"><a href="http://www.horizonsetfs.com/legal/Privacy-of-information" target="_blank">Click here to read our Privacy Policy.</a></p>
             <p class="disclaimer1">Horizons ETFs Management (Canada) Inc.<br />
55 University Avenue, Suite 800<br />
Toronto, Ontario, M5J 2H7</p></td>
        </tr>
  </table></td>
  </tr>
</table>
</body>
</html>
</code>```

答:
Header and footer images are not being reduced at all, they are correctly displaying at 650px width.
The horizontal padding on the  containing the nested tables is causing your main table to shift from 650px to 690px (650 + 20 + 20 = 690), and so causing the images not filling the main table's width.

Changing this line

```<code><td align="left" style="padding: 15px 20px 20px 20px;">
</code>```

To, for example

```<code><td align="left" style="padding: 15px 0 20px 0;">
</code>```

Solves the issue

Title: Nested tables in email

Body:
So, I'm totally losing my mind with an email that I'm trying to format.

I think it has to do with a particular nested table.

The main table is 650px wide and the width of the nested table is set to 100%.

What's happening is that, as soon as I plug in the nested tables, the header and footer images are being reduced by 20px(10+10) on the right side(despite both images being 650 pixels wide).

When I modify the nested tables to make the cellspacing on both sides of the nested tables =0(originally 10px on both sides i.e. 20px in total), then the header and footer images line up correctly but, assuming the cellspacing is set to 10 px on each side of the nested table, then the header and footer images get reduced.

Why is the nested table cellspacing affecting my table header and footer images?

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>2020 Preferred Share Outlook with Fiera Capital</title>

Get the Latest Outlook from Fiera Capital on the Canadian Preferred Shares and Fixed Income Markets

The Canadian preferred share market has bounced back from its lows in Q3 2019. But Fiera Capital believes there is still significant potential upside left in this asset class, since preferred shares offer higher relative yields compared to bonds, and should have less pressure from new issuances in 2020.

Fiera Capital’s Nicolas Normandeau, lead portfolio manager for the Horizons Active Preferred Share ETF (HPR) and the Horizons Floating Rate Preferred Share ETF (HFP), will outline his team’s outlook for Canadian preferred shares in 2020, and why he feels they remain a potentially attractive option for Canadian fixed income investors.

Advisors and Investors Bullish in New Decade

                            Did you miss our Q1 2020 Sentiment Survey Results? See where Canadian advisors and investors stand on 14 different indices and asset classes, ranging from the NASDAQ-100® to Gold Bullion.

Stay tuned for our Q2 2020 Sentiment Survey in March – you could win a $150 Amazon gift card!

                            Just Launched: Three New Total Return ETFs

                            On February 6, 2020, Horizons ETFs launched three new ETFs: HULC, HSAV, as well as HXCN. With $1 billion in seed capital, HXCN is the largest ETF launch in Canadian history. Learn more about our new total return ETFs

                        Nicolas Normandeau

                        CFA®, M.SC. – Vice-President and Portfolio Manager, Fixed Income, Fiera Capital

                        Nicolas Normandeau is a member of Fiera Capital’s Corporate Fixed Income team and a portfolio manager for the firm’s Corporate Fixed Income strategy with 10 years of industry experience. Fiera Capital is one of Canada’s largest managers of fixed income investments and is the sub-advisor for many of Horizons ETFs’ fixed income funds.

*Plus  applicable sales taxes.

Commissions, management fees and expenses all  may be associated with an investment in exchange traded products managed by  Horizons ETFs Management (Canada) Inc. (the "Horizons Exchange Traded  Products"). The Horizons Exchange Traded Products are not guaranteed,  their values change frequently and past performance may not be repeated. The  prospectus contains important detailed information about the Horizons Exchange  Traded Products. Please read the  relevant prospectus before investing.

Certain statements may constitute a forward looking statement, including those identified by the expressions “anticipate”, “estimate” or “expect” and similar expressions (including grammatical variations thereof) to the extent they relate to the ETFs or Horizons ETFs. The forward-looking statements are not historical facts but reflect the ETFs, the ETF’s managers or Horizons ETFs current expectations regarding future results or events. These forward-looking statements are subject to a number of risks and uncertainties that could cause actual results or events to differ materially from current expectations. These and other factors should be considered carefully and readers should not place undue reliance on the ETFs’ forward looking statements. These forward-looking statements are made as of the date hereof and the ETFs do not undertake to update any forward-looking statement that is contained herein, whether as a result of new information, future events or otherwise, unless required by applicable law.

1Horizons Total Return ETFs  (“Horizons Total Return ETFs”) are generally index-tracking ETFs that use an  innovative investment structure known as a Total Return Swap to deliver the  returns of an underlying benchmark in a low-cost and tax-efficient manner.  Unlike a physical replication ETF that typically purchases the securities found  in the relevant benchmark in the same proportions as the benchmark, most  Horizons Total Return ETFs use a synthetic structure that never buys the  securities of a benchmark directly. Instead, the ETF receives the total return  of the benchmark through entering into a Total Return Swap agreement with one  or more counterparties, typically large financial institutions, which will  provide the ETF with the total return of the benchmark in exchange for the  interest earned on the cash held by the ETF. Any distributions which are paid  by the benchmark’s constituents are reflected automatically in the net asset  value (NAV) of the ETF. As a result, the Horizons Total Return ETF receives the  total return of the benchmark (before fees), which is reflected in the ETF’s  share price, and investors are not expected to receive any taxable  distributions. Certain Horizons Total Return ETFs use physical replication  instead of a total return swap, which includes HULC and HSAV. The Horizons Cash  Maximizer ETF does not track a traditional benchmark but rather a compounding  rate of interest paid on a cash deposit that can change over time.

In the past you have provided Horizons ETFs with your email address or your email address is publicly available. You will receive brief news announcements regarding our ETFs and related topics. If you no longer wish to receive these announcements, you may unsubscribe by clicking here and updating your user preferences.

Click here to read our Privacy Policy.

Horizons ETFs Management (Canada) Inc.

55 University Avenue, Suite 800

Toronto, Ontario, M5J 2H7

Body:
Header and footer images are not being reduced at all, they are correctly displaying at 650px width.
The horizontal padding on the <td> containing the nested tables is causing your main table to shift from 650px to 690px (650 + 20 + 20 = 690), and so causing the images not filling the main table's width.

Changing this line

<td align="left" style="padding: 15px 20px 20px 20px;">

To, for example

<td align="left" style="padding: 15px 0 20px 0;">

Solves the issue