text:
import calendar
import datetime
from datetime import date
import logging
import math
import time
from operator import attrgetter
from werkzeug import url_encode

from dateutil.relativedelta import relativedelta

from openerp.exceptions import UserError, AccessError
from openerp import tools
from openerp.osv import fields, osv
from openerp.tools.translate import _

_logger = logging.getLogger(__name__)

class hr_holidays_status(osv.osv):
    _name = "hr.holidays.status"
    _description = "Leave Type"

    def get_days(self, cr, uid, ids, employee_id, context=None):
        result = dict((id, dict(max_leaves=0, leaves_taken=0, remaining_leaves=0,
                                virtual_remaining_leaves=0)) for id in ids)
        holiday_ids = self.pool['hr.holidays'].search(cr, uid, [('employee_id', '=', employee_id),
                                                                ('state', 'in', ['confirm', 'validate1', 'validate']),
                                                                ('holiday_status_id', 'in', ids)
                                                                ], context=context)
        for holiday in self.pool['hr.holidays'].browse(cr, uid, holiday_ids, context=context):
            status_dict = result[holiday.holiday_status_id.id]
            if holiday.type == 'add':
                if holiday.state == 'validate':
                    # note: add only validated allocation even for the virtual
                    # count; otherwise pending then refused allocation allow
                    # the employee to create more leaves than possible
                    status_dict['virtual_remaining_leaves'] += holiday.number_of_days_temp
                    status_dict['max_leaves'] += holiday.number_of_days_temp
                    status_dict['remaining_leaves'] += holiday.number_of_days_temp
            elif holiday.type == 'remove':  # number of days is negative
                status_dict['virtual_remaining_leaves'] -= holiday.number_of_days_temp
                if holiday.state == 'validate':
                    status_dict['leaves_taken'] += holiday.number_of_days_temp
                    status_dict['remaining_leaves'] -= holiday.number_of_days_temp
        return result

    def _user_left_days(self, cr, uid, ids, name, args, context=None):
        employee_id = False
        if context and 'employee_id' in context:
            employee_id = context['employee_id']
        else:
            employee_ids = self.pool.get('hr.employee').search(cr, uid, [('user_id', '=', uid)], context=context)
            if employee_ids:
                employee_id = employee_ids[0]
        if employee_id:
            res = self.get_days(cr, uid, ids, employee_id, context=context)
        else:
            res = dict((res_id, {'leaves_taken': 0, 'remaining_leaves': 0, 'max_leaves': 0}) for res_id in ids)
        return res

    _columns = {
        'name': fields.char('Leave Type', size=64, required=True, translate=True),
        'categ_id': fields.many2one('calendar.event.type', 'Meeting Type',
            help='Once a leave is validated, Odoo will create a corresponding meeting of this type in the calendar.'),
        'color_name': fields.selection([('red', 'Red'),('blue','Blue'), ('lightgreen', 'Light Green'), ('lightblue','Light Blue'), ('lightyellow', 'Light Yellow'), ('magenta', 'Magenta'),('lightcyan', 'Light Cyan'),('black', 'Black'),('lightpink', 'Light Pink'),('brown', 'Brown'),('violet', 'Violet'),('lightcoral', 'Light Coral'),('lightsalmon', 'Light Salmon'),('lavender', 'Lavender'),('wheat', 'Wheat'),('ivory', 'Ivory')],'Color in Report', required=True, help='This color will be used in the leaves summary located in Reporting\Leaves by Department.'),
        'limit': fields.boolean('Allow to Override Limit', help='If you select this check box, the system allows the employees to take more leaves than the available ones for this type and will not take them into account for the "Remaining Legal Leaves" defined on the employee form.'),
        'active': fields.boolean('Active', help="If the active field is set to false, it will allow you to hide the leave type without removing it."),
        'max_leaves': fields.function(_user_left_days, string='Maximum Allowed', help='This value is given by the sum of all holidays requests with a positive value.', multi='user_left_days'),
        'leaves_taken': fields.function(_user_left_days, string='Leaves Already Taken', help='This value is given by the sum of all holidays requests with a negative value.', multi='user_left_days'),
        'remaining_leaves': fields.function(_user_left_days, string='Remaining Leaves', help='Maximum Leaves Allowed - Leaves Already Taken', multi='user_left_days'),
        'virtual_remaining_leaves': fields.function(_user_left_days, string='Virtual Remaining Leaves', help='Maximum Leaves Allowed - Leaves Already Taken - Leaves Waiting Approval', multi='user_left_days'),
        'double_validation': fields.boolean('Apply Double Validation', help="When selected, the Allocation/Leave Requests for this type require a second validation to be approved."),
        'company_id': fields.many2one('res.company', 'Company'),
    }
    _defaults = {
        'color_name': 'red',
        'active': True,
    }

    def name_get(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        if not context.get('employee_id'):
            # leave counts is based on employee_id, would be inaccurate if not based on correct employee
            return super(hr_holidays_status, self).name_get(cr, uid, ids, context=context)
        res = []
        for record in self.browse(cr, uid, ids, context=context):
            name = record.name
            if not record.limit:
                name = name + ('  (%g/%g)' % (record.virtual_remaining_leaves or 0.0, record.max_leaves or 0.0))
            res.append((record.id, name))
        return res

    def _search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
        """ Override _search to order the results, according to some employee.
        The order is the following

         - limit (limited leaves first, such as Legal Leaves)
         - virtual remaining leaves (higher the better, so using reverse on sorted)

        This override is necessary because those fields are not stored and depends
        on an employee_id given in context. This sort will be done when there
        is an employee_id in context and that no other order has been given
        to the method. """
        if context is None:
            context = {}
        ids = super(hr_holidays_status, self)._search(cr, uid, args, offset=offset, limit=limit, order=order, context=context, count=count, access_rights_uid=access_rights_uid)
        if not count and not order and context.get('employee_id'):
            leaves = self.browse(cr, uid, ids, context=context)
            sort_key = lambda l: (not l.limit, l.virtual_remaining_leaves)
            return map(int, leaves.sorted(key=sort_key, reverse=True))
        return ids

class hr_holidays(osv.osv):
    _name = "hr.holidays"
    _description = "Leave"
    _order = "type desc, date_from desc"
    _inherit = ['mail.thread', 'ir.needaction_mixin']

    def _employee_get(self, cr, uid, context=None):
        emp_id = context.get('default_employee_id', False)
        if emp_id:
            return emp_id
        ids = self.pool.get('hr.employee').search(cr, uid, [('user_id', '=', uid)], context=context)
        if ids:
            return ids[0]
        return False

    def _compute_number_of_days(self, cr, uid, ids, name, args, context=None):
        result = {}
        for hol in self.browse(cr, uid, ids, context=context):
            if hol.type=='remove':
                result[hol.id] = -hol.number_of_days_temp
            else:
                result[hol.id] = hol.number_of_days_temp
        return result

    def _get_can_reset(self, cr, uid, ids, name, arg, context=None):
        """User can reset a leave request if it is its own leave request or if
        he is an Hr Manager. """
        user = self.pool['res.users'].browse(cr, uid, uid, context=context)
        group_hr_manager_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'group_hr_manager')[1]
        if group_hr_manager_id in [g.id for g in user.groups_id]:
            return dict.fromkeys(ids, True)
        result = dict.fromkeys(ids, False)
        for holiday in self.browse(cr, uid, ids, context=context):
            if holiday.employee_id and holiday.employee_id.user_id and holiday.employee_id.user_id.id == uid:
                result[holiday.id] = True
        return result

    def _check_date(self, cr, uid, ids, context=None):
        for holiday in self.browse(cr, uid, ids, context=context):
            domain = [
                ('date_from', '<=', holiday.date_to),
                ('date_to', '>=', holiday.date_from),
                ('employee_id', '=', holiday.employee_id.id),
                ('id', '!=', holiday.id),
                ('state', 'not in', ['cancel', 'refuse']),
            ]
            nholidays = self.search_count(cr, uid, domain, context=context)
            if nholidays:
                return False
        return True

    _check_holidays = lambda self, cr, uid, ids, context=None: self.check_holidays(cr, uid, ids, context=context)

    _columns = {
        'name': fields.char('Description', size=64),
        'state': fields.selection([('draft', 'To Submit'), ('cancel', 'Cancelled'),('confirm', 'To Approve'), ('refuse', 'Refused'), ('validate1', 'Second Approval'), ('validate', 'Approved')],
            'Status', readonly=True, track_visibility='onchange', copy=False,
            help='The status is set to \'To Submit\', when a holiday request is created.\
            \nThe status is \'To Approve\', when holiday request is confirmed by user.\
            \nThe status is \'Refused\', when holiday request is refused by manager.\
            \nThe status is \'Approved\', when holiday request is approved by manager.'),
        'payslip_status': fields.boolean(string='Reported in last payslips',
            help='Green this button when the leave has been taken into account in the payslip.'),
        'report_note': fields.text('HR Comments'),
        'user_id':fields.related('employee_id', 'user_id', type='many2one', relation='res.users', string='User', store=True),
        'date_from': fields.datetime('Start Date', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, select=True, copy=False),
        'date_to': fields.datetime('End Date', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, copy=False),
        'holiday_status_id': fields.many2one("hr.holidays.status", "Leave Type", required=True,readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}),
        'employee_id': fields.many2one('hr.employee', "Employee", select=True, invisible=False, readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}),
        'manager_id': fields.many2one('hr.employee', 'First Approval', invisible=False, readonly=True, copy=False,
                                      help='This area is automatically filled by the user who validate the leave'),
        'notes': fields.text('Reasons',readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}),
        'number_of_days_temp': fields.float('Allocation', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, copy=False),
        'number_of_days': fields.function(_compute_number_of_days, string='Number of Days', store=True),
        'meeting_id': fields.many2one('calendar.event', 'Meeting'),
        'type': fields.selection([('remove','Leave Request'),('add','Allocation Request')], 'Request Type', required=True, readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, help="Choose 'Leave Request' if someone wants to take an off-day. \nChoose 'Allocation Request' if you want to increase the number of leaves available for someone", select=True),
        'parent_id': fields.many2one('hr.holidays', 'Parent'),
        'linked_request_ids': fields.one2many('hr.holidays', 'parent_id', 'Linked Requests',),
        'department_id':fields.related('employee_id', 'department_id', string='Department', type='many2one', relation='hr.department', readonly=True, store=True),
        'category_id': fields.many2one('hr.employee.category', "Employee Tag", help='Category of Employee', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}),
        'holiday_type': fields.selection([('employee','By Employee'),('category','By Employee Tag')], 'Allocation Mode', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, help='By Employee: Allocation/Request for individual Employee, By Employee Tag: Allocation/Request for group of employees in category', required=True),
        'manager_id2': fields.many2one('hr.employee', 'Second Approval', readonly=True, copy=False,
                                       help='This area is automaticly filled by the user who validate the leave with second level (If Leave type need second validation)'),
        'double_validation': fields.related('holiday_status_id', 'double_validation', type='boolean', relation='hr.holidays.status', string='Apply Double Validation'),
        'can_reset': fields.function(
            _get_can_reset, string="Can reset",
            type='boolean'),
    }
    _defaults = {
        'employee_id': _employee_get,
        'state': 'confirm',
        'type': 'remove',
        'user_id': lambda obj, cr, uid, context: uid,
        'holiday_type': 'employee',
        'payslip_status': False,
    }
    _constraints = [
        (_check_date, 'You can not have 2 leaves that overlaps on same day!', ['date_from', 'date_to']),
        (_check_holidays, 'The number of remaining leaves is not sufficient for this leave type.\n'
                          'Please verify also the leaves waiting for validation.', ['state', 'number_of_days_temp'])
    ]

    _sql_constraints = [
        ('type_value', "CHECK( (holiday_type='employee' AND employee_id IS NOT NULL) or (holiday_type='category' AND category_id IS NOT NULL))",
         "The employee or employee category of this request is missing. Please make sure that your user login is linked to an employee."),
        ('date_check2', "CHECK ( (type='add') OR (date_from <= date_to))", "The start date must be anterior to the end date."),
        ('date_check', "CHECK ( number_of_days_temp >= 0 )", "The number of days must be greater than 0."),
    ]

    def name_get(self, cr, uid, ids, context=None):
        res = []
        for leave in self.browse(cr, uid, ids, context=context):
            res.append((leave.id, leave.name or _("%s on %s") % (leave.employee_id.name, leave.holiday_status_id.name)))
        return res

    def _create_resource_leave(self, cr, uid, leaves, context=None):
        '''This method will create entry in resource calendar leave object at the time of holidays validated '''
        obj_res_leave = self.pool.get('resource.calendar.leaves')
        for leave in leaves:
            vals = {
                'name': leave.name,
                'date_from': leave.date_from,
                'holiday_id': leave.id,
                'date_to': leave.date_to,
                'resource_id': leave.employee_id.resource_id.id,
                'calendar_id': leave.employee_id.resource_id.calendar_id.id
            }
            obj_res_leave.create(cr, uid, vals, context=context)
        return True

    def _remove_resource_leave(self, cr, uid, ids, context=None):
        '''This method will create entry in resource calendar leave object at the time of holidays cancel/removed'''
        obj_res_leave = self.pool.get('resource.calendar.leaves')
        leave_ids = obj_res_leave.search(cr, uid, [('holiday_id', 'in', ids)], context=context)
        return obj_res_leave.unlink(cr, uid, leave_ids, context=context)

    def onchange_type(self, cr, uid, ids, holiday_type, employee_id=False, context=None):
        result = {}
        if holiday_type == 'employee' and not employee_id:
            ids_employee = self.pool.get('hr.employee').search(cr, uid, [('user_id','=', uid)])
            if ids_employee:
                result['value'] = {
                    'employee_id': ids_employee[0]
                }
        elif holiday_type != 'employee':
            result['value'] = {
                    'employee_id': False
                }
        return result

    def onchange_employee(self, cr, uid, ids, employee_id):
        result = {'value': {'department_id': False}}
        if employee_id:
            employee = self.pool.get('hr.employee').browse(cr, uid, employee_id)
            result['value'] = {'department_id': employee.department_id.id}
        return result

    # TODO: can be improved using resource calendar method
    def _get_number_of_days(self, date_from, date_to):
        """Returns a float equals to the timedelta between two dates given as string."""

        DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
        from_dt = datetime.datetime.strptime(date_from, DATETIME_FORMAT)
        to_dt = datetime.datetime.strptime(date_to, DATETIME_FORMAT)
        timedelta = to_dt - from_dt
        diff_day = timedelta.days + float(timedelta.seconds) / 86400
        return diff_day

    def unlink(self, cr, uid, ids, context=None):
        for rec in self.browse(cr, uid, ids, context=context):
            if rec.state not in ['draft', 'cancel', 'confirm']:
                raise UserError(_('You cannot delete a leave which is in %s state.') % (rec.state,))
        return super(hr_holidays, self).unlink(cr, uid, ids, context)

    def onchange_date_from(self, cr, uid, ids, date_to, date_from):
        """
        If there are no date set for date_to, automatically set one 8 hours later than
        the date_from.
        Also update the number_of_days.
        """
        # date_to has to be greater than date_from
        if (date_from and date_to) and (date_from > date_to):
            raise UserError(_('The start date must be anterior to the end date.'))

        result = {'value': {}}

        # No date_to set so far: automatically compute one 8 hours later
        if date_from and not date_to:
            date_to_with_delta = datetime.datetime.strptime(date_from, tools.DEFAULT_SERVER_DATETIME_FORMAT) + datetime.timedelta(hours=8)
            result['value']['date_to'] = str(date_to_with_delta)

        # Compute and update the number of days
        if (date_to and date_from) and (date_from <= date_to):
            diff_day = self._get_number_of_days(date_from, date_to)
            result['value']['number_of_days_temp'] = round(math.floor(diff_day))+1
        else:
            result['value']['number_of_days_temp'] = 0

        return result

    def onchange_date_to(self, cr, uid, ids, date_to, date_from):
        """
        Update the number_of_days.
        """
        # date_to has to be greater than date_from
        if (date_from and date_to) and (date_from > date_to):
            raise UserError(_('The start date must be anterior to the end date.'))

        result = {'value': {}}

        # Compute and update the number of days
        if (date_to and date_from) and (date_from <= date_to):
            diff_day = self._get_number_of_days(date_from, date_to)
            result['value']['number_of_days_temp'] = round(math.floor(diff_day))+1
        else:
            result['value']['number_of_days_temp'] = 0
        return result

    def _check_state_access_right(self, cr, uid, vals, context=None):
        if vals.get('state') and vals['state'] not in ['draft', 'confirm', 'cancel'] and not self.pool['res.users'].has_group(cr, uid, 'base.group_hr_user'):
            return False
        return True

    def add_follower(self, cr, uid, ids, employee_id, context=None):
        employee = self.pool.get('hr.employee').browse(cr, uid, employee_id, context=context)
        if employee and employee.user_id:
            self.message_subscribe_users(cr, uid, ids, user_ids=[employee.user_id.id], context=context)

    def create(self, cr, uid, values, context=None):
        """ Override to avoid automatic logging of creation """
        if context is None:
            context = {}
        employee_id = values.get('employee_id', False)
        context = dict(context, mail_create_nolog=True, mail_create_nosubscribe=True)
        if not self._check_state_access_right(cr, uid, values, context):
            raise AccessError(_('You cannot set a leave request as \'%s\'. Contact a human resource manager.') % values.get('state'))
        if not values.get('name'):
            employee_name = self.pool['hr.employee'].browse(cr, uid, employee_id, context=context).name
            holiday_type = self.pool['hr.holidays.status'].browse(cr, uid, values.get('holiday_status_id'), context=context).name
            values['name'] = _("%s on %s") % (employee_name, holiday_type)
        hr_holiday_id = super(hr_holidays, self).create(cr, uid, values, context=context)
        self.add_follower(cr, uid, [hr_holiday_id], employee_id, context=context)
        return hr_holiday_id

    def write(self, cr, uid, ids, vals, context=None):
        employee_id = vals.get('employee_id', False)
        if not self._check_state_access_right(cr, uid, vals, context):
            raise AccessError(_('You cannot set a leave request as \'%s\'. Contact a human resource manager.') % vals.get('state'))
        hr_holiday_id = super(hr_holidays, self).write(cr, uid, ids, vals, context=context)
        self.add_follower(cr, uid, ids, employee_id, context=context)
        return hr_holiday_id

    def holidays_reset(self, cr, uid, ids, context=None):
        self.write(cr, uid, ids, {
            'state': 'draft',
            'manager_id': False,
            'manager_id2': False,
        })
        to_unlink = []
        for record in self.browse(cr, uid, ids, context=context):
            for record2 in record.linked_request_ids:
                self.holidays_reset(cr, uid, [record2.id], context=context)
                to_unlink.append(record2.id)
        if to_unlink:
            self.unlink(cr, uid, to_unlink, context=context)
        return True

    def holidays_first_validate(self, cr, uid, ids, context=None):
        obj_emp = self.pool.get('hr.employee')
        ids2 = obj_emp.search(cr, uid, [('user_id', '=', uid)])
        manager = ids2 and ids2[0] or False
        return self.write(cr, uid, ids, {'state': 'validate1', 'manager_id': manager}, context=context)

    def holidays_validate(self, cr, uid, ids, context=None):
        obj_emp = self.pool.get('hr.employee')
        ids2 = obj_emp.search(cr, uid, [('user_id', '=', uid)])
        manager = ids2 and ids2[0] or False
        self.write(cr, uid, ids, {'state': 'validate'}, context=context)
        data_holiday = self.browse(cr, uid, ids)
        for record in data_holiday:
            if record.double_validation:
                self.write(cr, uid, [record.id], {'manager_id2': manager})
            else:
                self.write(cr, uid, [record.id], {'manager_id': manager})
            if record.holiday_type == 'employee' and record.type == 'remove':
                meeting_obj = self.pool.get('calendar.event')
                meeting_vals = {
                    'name': record.display_name,
                    'categ_ids': record.holiday_status_id.categ_id and [(6,0,[record.holiday_status_id.categ_id.id])] or [],
                    'duration': record.number_of_days_temp * 8,
                    'description': record.notes,
                    'user_id': record.user_id.id,
                    'start': record.date_from,
                    'stop': record.date_to,
                    'allday': False,
                    'state': 'open',            # to block that meeting date in the calendar
                    'class': 'confidential'
                }
                #Add the partner_id (if exist) as an attendee
                if record.user_id and record.user_id.partner_id:
                    meeting_vals['partner_ids'] = [(4,record.user_id.partner_id.id)]

                ctx_no_email = dict(context or {}, no_email=True)
                meeting_id = meeting_obj.create(cr, uid, meeting_vals, context=ctx_no_email)
                self._create_resource_leave(cr, uid, [record], context=context)
                self.write(cr, uid, ids, {'meeting_id': meeting_id})
            elif record.holiday_type == 'category':
                emp_ids = record.category_id.employee_ids.ids
                leave_ids = []
                batch_context = dict(context, mail_notify_force_send=False)
                for emp in obj_emp.browse(cr, uid, emp_ids, context=context):
                    vals = {
                        'name': record.name,
                        'type': record.type,
                        'holiday_type': 'employee',
                        'holiday_status_id': record.holiday_status_id.id,
                        'date_from': record.date_from,
                        'date_to': record.date_to,
                        'notes': record.notes,
                        'number_of_days_temp': record.number_of_days_temp,
                        'parent_id': record.id,
                        'employee_id': emp.id
                    }
                    leave_ids.append(self.create(cr, uid, vals, context=batch_context))
                for leave_id in leave_ids:
                    # TODO is it necessary to interleave the calls?
                    for sig in ('confirm', 'validate', 'second_validate'):
                        self.signal_workflow(cr, uid, [leave_id], sig)
        return True

    def holidays_confirm(self, cr, uid, ids, context=None):
        for record in self.browse(cr, uid, ids, context=context):
            if record.department_id:
                # Subscribe the followers of the department following the `confirmed` subtype
                # It's done manually because `message_auto_subscribe` only works on fields for which
                # the value is passed to the `create` or `write` methods,
                # it doesn't work for related/computed fields
                # This can be removed as soon as `department_id` on `hr.holidays` becomes a regular
                # fields or as soon as `message_auto_subscribe` works with related/computed fields.
                confirmed_subtype = self.pool['ir.model.data'].xmlid_to_object(cr, uid, 'hr_holidays.mt_department_holidays_confirmed', context=context)
                self.message_subscribe(cr, uid, [record.id], [
                    follower.partner_id.id for follower in record.department_id.message_follower_ids
                    if confirmed_subtype in follower.subtype_ids
                ], context=context)
        return self.write(cr, uid, ids, {'state': 'confirm'})

    def holidays_refuse(self, cr, uid, ids, context=None):
        obj_emp = self.pool.get('hr.employee')
        ids2 = obj_emp.search(cr, uid, [('user_id', '=', uid)])
        manager = ids2 and ids2[0] or False
        for holiday in self.browse(cr, uid, ids, context=context):
            if holiday.state == 'validate1':
                self.write(cr, uid, [holiday.id], {'state': 'refuse', 'manager_id': manager})
            else:
                self.write(cr, uid, [holiday.id], {'state': 'refuse', 'manager_id2': manager})
        self.holidays_cancel(cr, uid, ids, context=context)
        return True

    def holidays_cancel(self, cr, uid, ids, context=None):
        for record in self.browse(cr, uid, ids, context=context):
            # Delete the meeting
            if record.meeting_id:
                record.meeting_id.unlink()

            # If a category that created several holidays, cancel all related
            self.signal_workflow(cr, uid, map(attrgetter('id'), record.linked_request_ids or []), 'refuse')

        self._remove_resource_leave(cr, uid, ids, context=context)
        return True

    def check_holidays(self, cr, uid, ids, context=None):
        for record in self.browse(cr, uid, ids, context=context):
            if record.holiday_type != 'employee' or record.type != 'remove' or not record.employee_id or record.holiday_status_id.limit:
                continue
            leave_days = self.pool.get('hr.holidays.status').get_days(cr, uid, [record.holiday_status_id.id], record.employee_id.id, context=context)[record.holiday_status_id.id]
            if leave_days['remaining_leaves'] < 0 or leave_days['virtual_remaining_leaves'] < 0:
                return False
        return True

    def toggle_payslip_status(self, cr, uid, ids, context=None):
        ids_to_set_true = self.search(cr, uid, [('id', 'in', ids), ('payslip_status', '=', False)], context=context)
        ids_to_set_false = list(set(ids) - set(ids_to_set_true))
        return self.write(cr, uid, ids_to_set_true, {'payslip_status': True}, context=context) and self.write(cr, uid, ids_to_set_false, {'payslip_status': False}, context=context)

    def _track_subtype(self, cr, uid, ids, init_values, context=None):
        record = self.browse(cr, uid, ids[0], context=context)
        if 'state' in init_values and record.state == 'validate':
            return 'hr_holidays.mt_holidays_approved'
        elif 'state' in init_values and record.state == 'validate1':
            return 'hr_holidays.mt_holidays_first_validated'
        elif 'state' in init_values and record.state == 'confirm':
            return 'hr_holidays.mt_holidays_confirmed'
        elif 'state' in init_values and record.state == 'refuse':
            return 'hr_holidays.mt_holidays_refused'
        return super(hr_holidays, self)._track_subtype(cr, uid, ids, init_values, context=context)

    def _notification_group_recipients(self, cr, uid, ids, message, recipients, done_ids, group_data, context=None):
        """ Override the mail.thread method to handle HR users and officers
        recipients. Indeed those will have specific action in their notification
        emails. """
        group_hr_user = self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, 'base.group_hr_user')
        for recipient in recipients:
            if recipient.id in done_ids:
                continue
            if recipient.user_ids and group_hr_user in recipient.user_ids[0].groups_id.ids:
                group_data['group_hr_user'] |= recipient
                done_ids.add(recipient.id)
        return super(hr_holidays, self)._notification_group_recipients(cr, uid, ids, message, recipients, done_ids, group_data, context=context)

    def _notification_get_recipient_groups(self, cr, uid, ids, message, recipients, context=None):
        res = super(hr_holidays, self)._notification_get_recipient_groups(cr, uid, ids, message, recipients, context=context)

        app_action = '/mail/workflow?%s' % url_encode({'model': self._name, 'res_id': ids[0], 'signal': 'validate'})
        ref_action = '/mail/workflow?%s' % url_encode({'model': self._name, 'res_id': ids[0], 'signal': 'refuse'})

        holiday = self.browse(cr, uid, ids[0], context=context)
        actions = []
        if holiday.state == 'confirm':
            actions.append({'url': app_action, 'title': 'Approve'})
        if holiday.state in ['confirm', 'validate', 'validate1']:
            actions.append({'url': ref_action, 'title': 'Refuse'})

        res['group_hr_user'] = {
            'actions': actions
        }
        return res

class resource_calendar_leaves(osv.osv):
    _inherit = "resource.calendar.leaves"
    _description = "Leave Detail"
    _columns = {
        'holiday_id': fields.many2one("hr.holidays", "Leave Request"),
    }

class hr_employee(osv.Model):
    _inherit = "hr.employee"

    def _set_remaining_days(self, cr, uid, empl_id, name, value, arg, context=None):
        if value:
            employee = self.browse(cr, uid, empl_id, context=context)
            diff = value - employee.remaining_leaves
            type_obj = self.pool.get('hr.holidays.status')
            holiday_obj = self.pool.get('hr.holidays')
            # Find for holidays status
            status_ids = type_obj.search(cr, uid, [('limit', '=', False)], context=context)
            if len(status_ids) != 1 :
                raise UserError(_("The feature behind the field 'Remaining Legal Leaves' can only be used when there is only one leave type with the option 'Allow to Override Limit' unchecked. (%s Found). Otherwise, the update is ambiguous as we cannot decide on which leave type the update has to be done. \nYou may prefer to use the classic menus 'Leave Requests' and 'Allocation Requests' located in 'Human Resources \ Leaves' to manage the leave days of the employees if the configuration does not allow to use this field.") % (len(status_ids)))
            status_id = status_ids and status_ids[0] or False
            if not status_id:
                return False
            if diff > 0:
                leave_id = holiday_obj.create(cr, uid, {'name': _('Allocation for %s') % employee.name, 'employee_id': employee.id, 'holiday_status_id': status_id, 'type': 'add', 'holiday_type': 'employee', 'number_of_days_temp': diff}, context=context)
            elif diff < 0:
                raise UserError(_('You cannot reduce validated allocation requests'))
            else:
                return False
            for sig in ('confirm', 'validate', 'second_validate'):
                holiday_obj.signal_workflow(cr, uid, [leave_id], sig)
            return True
        return False

    def _get_remaining_days(self, cr, uid, ids, name, args, context=None):
        cr.execute("""SELECT
                sum(h.number_of_days) as days,
                h.employee_id
            from
                hr_holidays h
                join hr_holidays_status s on (s.id=h.holiday_status_id)
            where
                h.state='validate' and
                s.limit=False and
                h.employee_id in %s
            group by h.employee_id""", (tuple(ids),))
        res = cr.dictfetchall()
        remaining = {}
        for r in res:
            remaining[r['employee_id']] = r['days']
        for employee_id in ids:
            if not remaining.get(employee_id):
                remaining[employee_id] = 0.0
        return remaining

    def _get_leave_status(self, cr, uid, ids, name, args, context=None):
        holidays_obj = self.pool.get('hr.holidays')
        holidays_id = holidays_obj.search(cr, uid,
           [('employee_id', 'in', ids), ('date_from','<=',time.strftime('%Y-%m-%d %H:%M:%S')),
           ('date_to','>=',time.strftime('%Y-%m-%d %H:%M:%S')),('type','=','remove'),('state','not in',('cancel','refuse'))],
           context=context)
        result = {}
        for id in ids:
            result[id] = {
                'current_leave_state': False,
                'current_leave_id': False,
                'leave_date_from':False,
                'leave_date_to':False,
            }
        for holiday in self.pool.get('hr.holidays').browse(cr, uid, holidays_id, context=context):
            result[holiday.employee_id.id]['leave_date_from'] = holiday.date_from
            result[holiday.employee_id.id]['leave_date_to'] = holiday.date_to
            result[holiday.employee_id.id]['current_leave_state'] = holiday.state
            result[holiday.employee_id.id]['current_leave_id'] = holiday.holiday_status_id.id
        return result

    def _leaves_count(self, cr, uid, ids, field_name, arg, context=None):
        res = {}
        leaves = self.pool['hr.holidays'].read_group(cr, uid, [
            ('employee_id', 'in', ids),
            ('holiday_status_id.limit', '=', False), ('state', '=', 'validate')], fields=['number_of_days', 'employee_id'], groupby=['employee_id'])
        res.update(dict([(leave['employee_id'][0], leave['number_of_days']) for leave in leaves ]))
        return res

    def _show_approved_remaining_leave(self, cr, uid, ids, name, args, context=None):
        if self.pool['res.users'].has_group(cr, uid, 'base.group_hr_user'):
            return dict([(employee_id, True) for employee_id in ids])
        return dict([(employee.id, True) for employee in self.browse(cr, uid, ids, context=context) if employee.user_id.id == uid])

    def _absent_employee(self, cr, uid, ids, field_name, arg, context=None):
        today_date = datetime.datetime.utcnow().date()
        today_start = today_date.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT) # get the midnight of the current utc day
        today_end = (today_date + relativedelta(hours=23, minutes=59, seconds=59)).strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT)
        data = self.pool['hr.holidays'].read_group(cr, uid,
            [('employee_id', 'in', ids), ('state', 'not in', ['cancel', 'refuse']),
             ('date_from', '<=', today_end), ('date_to', '>=', today_start), ('type', '=', 'remove')],
            ['employee_id'], ['employee_id'], context=context)
        result = dict.fromkeys(ids, False)
        for d in data:
            if d['employee_id_count'] >= 1:
                result[d['employee_id'][0]] = True
        return result

    def _search_absent_employee(self, cr, uid, obj, name, args, context=None):
        today_date = datetime.datetime.utcnow().date()
        today_start = today_date.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT) # get the midnight of the current utc day
        today_end = (today_date + relativedelta(hours=23, minutes=59, seconds=59)).strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT)
        holiday_ids = self.pool['hr.holidays'].search_read(cr, uid, [
            ('state', 'not in', ['cancel', 'refuse']),
            ('date_from', '<=', today_end),
            ('date_to', '>=', today_start),
            ('type', '=', 'remove')], ['employee_id'], context=context)
        absent_employee_ids = [holiday['employee_id'][0] for holiday in holiday_ids if holiday['employee_id']]
        return [('id', 'in', absent_employee_ids)]

    _columns = {
        'remaining_leaves': fields.function(_get_remaining_days, string='Remaining Legal Leaves', fnct_inv=_set_remaining_days, type="float", help='Total number of legal leaves allocated to this employee, change this value to create allocation/leave request. Total based on all the leave types without overriding limit.'),
        'current_leave_state': fields.function(
            _get_leave_status, multi="leave_status", string="Current Leave Status", type="selection",
            selection=[('draft', 'New'), ('confirm', 'Waiting Approval'), ('refuse', 'Refused'),
                       ('validate1', 'Waiting Second Approval'), ('validate', 'Approved'), ('cancel', 'Cancelled')]),
        'current_leave_id': fields.function(_get_leave_status, multi="leave_status", string="Current Leave Type", type='many2one', relation='hr.holidays.status'),
        'leave_date_from': fields.function(_get_leave_status, multi='leave_status', type='date', string='From Date'),
        'leave_date_to': fields.function(_get_leave_status, multi='leave_status', type='date', string='To Date'),
        'leaves_count': fields.function(_leaves_count, type='integer', string='Number of Leaves'),
        'show_leaves': fields.function(_show_approved_remaining_leave, type='boolean', string="Able to see Remaining Leaves"),
        'is_absent_totay': fields.function(_absent_employee, fnct_search=_search_absent_employee, type="boolean", string="Absent Today", default=False)
    }

redpajama_set_name: RedPajamaGithub


text:
Rococo Theatre
140 N 13th St, Lincoln NE 68508
Barrymore's
Tour the Theatre
On Monday, June 10, 1929, the Stuart Theatre opened its doors to the public for the first time. The first show to be performed on the historic stage was "The Rainbow Man."
The original structure occupied six floors in the 13-story building. Seating capacity was 1,850. The theater's architecture boasted influences resembling that of Italian Romanesque, with a slight Moorish influence. Strains of other architectural types were also evident in the beamed and panel designed ceiling, two balconies and six chandeliers. The interior walls, consisting of stone and terra cotta, were rich in history and designed like that of an Old Italian Palace.
In 1971, the Dubinsky Brothers purchased the theater. Despite community efforts to "Save the Stuart," it was transformed into a modern movie theater. A false ceiling was created, which covered the ornate design, magnificent chandeliers and the top balcony. The orchestra pit was covered, the marble walls and floors carpeted and the stage was bricked off.
In 1977, the University of Nebraska Foundation was bestowed the first five floors of the Stuart Building, including the theater, but eventually decided that renovation of the theater was neither realistic nor affordable.
In March 1986, floors two through ten of the Stuart Building were transformed into condominiums.
In July of 2000, The Stuart Theatre once again changed hands and was purchased by Doug Deeter, as majority owner. His goal was to create a state-of-the-art entertainment facility, without compromising the original, grandiose design of the theater. To achieve this, the false ceiling was torn down, the carpet was ripped from the walls and floors, the marble was restored and the chandeliers were lowered to their original height.
In June of 2001, the Stuart Theatre's new identity was unveiled. With the new name, Rococo Theatre, comes a new look – the theater seats have been replaced with Vegas-style booths and tables. When not hosting live musical acts, the Rococo Theatre showcases classic and cult-classic movies and sporting events on their state-of-the-art equipment.
Join our mailing list for contests, announcements, ticket information, and much more!

redpajama_set_name: RedPajamaCommonCrawl


text:
Damascus () steht für:

 in der Antike der Name von Damaskus in Syrien
 Titularerzbistum Damascus, zurückgehend auf ein erloschenes Erzbistum Damaskus

Orte in den Vereinigten Staaten:
 Damaskus (Alabama)
 Damascus (Arkansas)
 Damascus (Georgia)
 Damascus (Illinois)
 Damascus (Maryland)
 Damascus (New York)
 Damascus (Ohio)
 Damascus (Oregon)
 Damascus (Virginia)
 Damascus Township (Ohio)
 Damascus Township (Pennsylvania)

im NRHP gelistete Objekte:
 Damascus Baptist Church Arbor, in Harmony, North Carolina, ID-Nr. 80002850
 Damascus CCC Camp, Co. No. 3781 Historic District, in Damascus, Arkansas, ID-Nr. 02001631
 Damascus Grade School, in Damascus, Ohio, ID-Nr. 89001456
 Damascus Gymnasium, in Damascus, Arkansas, ID-Nr. 92001122
 Damascus Historic District, in Damascus, Pennsylvania, ID-Nr. 92001000
 Damascus School, in Damascus, Oregon, ID-Nr. 80003304

Siehe auch:
 Damaskus (Begriffsklärung)

redpajama_set_name: RedPajamaWikipedia


Bathrooms are not just bathrooms anymore and some principles of modern bathroom need to be incorporated in designing a bathroom space using modern design. Modern bathroom design has lines that are bold and clean, décor to a minimum and the use of white color abundantly. The bathroom in today's world is not just a place to do what is typically done in a bathroom but also a room that is elegant as well. In designing a modern bathroom, the following are the tips that may be followed.


The etiology of pre-eclampsia (PE) is not yet fully understood, though current literature indicates an upregulation of inflammatory mediators produced by the placenta as a potential causal mechanism. Vitamin D is known to have anti-inflammatory properties and there is evidence of an inverse relationship between dietary calcium intake and the incidence of PE. Evidence of the role of vitamin D status and supplementation in the etiology and prevention of PE is reviewed in this article along with identification of research gaps to inform future studies.
We conducted a structured literature search using MEDLINE electronic databases to identify published studies until February 2015. These sources were retrieved, collected, indexed, and assessed for availability of pregnancy-related data on PE and vitamin D.
Several case-control studies and cross-sectional studies have shown an association between vitamin D status and PE, although evidence has been inconsistent. Clinical trials to date have been unable to show an independent effect of vitamin D supplementation in preventing PE.
The included clinical trials do not show an independent effect of vitamin D supplementation in preventing PE; however, issues with dose, timing, and duration of supplementation have not been completely addressed.
Each day, 830 women die from preventable pregnancy-related causes; low- and middle-income countries bear the greatest burden of disease . Hypertensive disorders of pregnancy, including gestational hypertension, pre-eclampsia (PE), and eclampsia, are among the major complications that account for approximately 14% of maternal mortality [1, 2]. Pregnancy induced hypertension, defined as blood pressure greater than 140/90 mmHg on two consecutive occasions ≥6 h apart occurring after 20 weeks of pregnancy, complicates approximately 10% of all pregnancies worldwide. Pre-eclampsia (PE) is hypertension and proteinuria (protein in urine ≥0.3 g/24 h (1+ dipstick) on two occasions ≥6 h apart) or edema [3, 4]. It is a major cause of maternal and perinatal morbidity and mortality and complicates 2% to 8% of pregnancies [3, 5]. Early onset severe PE (EOSPE) is diagnosed between 20 to 34 weeks gestation and is associated with a 20-fold increased risk for maternal mortality compared to PE after 34 weeks gestation  called late onset severe PE (LOSPE). Pregnant women who show signs of pregnancy induced hypertension or PE can develop eclampsia, which is the occurrence of unexplained seizures .
The complications of PE include eclampsia, disseminated intravascular coagulation and the HELLP syndrome (hemolytic anemia, elevated liver enzymes, and low platelets ). Risks to the fetus include intrauterine growth restriction (IUGR) and fetal death . Pathognomonic features shared by PE and IUGR include abnormal placental implantation and reduced trophoblastic invasion . Similarly, EOSPE and LOSPE are associated with fetal death, perinatal death, and severe neonatal morbidity. For example, in an analysis of 456,668 singleton births in Washington state, EOSPE was associated with high risk of fetal death; the adjusted odds ratio (aOR) was 5.8 (95% Confidence Interval (CI): 4.0–8.3 vs. 1.3 for LOSPE (95% CI: 0.8–2.0). The aOR for perinatal death/severe neonatal morbidity was 16.4 (95% CI: 14.5–18.6) in EOSPE and 2.0 (95% CI: 1.8–2.3) in LOSPE . Women with a history of PE also have a higher risk of cardiovascular disease later in life [11, 12].
For years, PE has been hypothesized to be a two-stage disorder . In the first stage, placental perfusion is reduced resulting in defective placental implantation. In the second stage, reduced vascularization at the placental site activates a maternal inflammatory response. This leads to generalized endothelial dysfunction and the release of excessive anti-angiogenic factors into the maternal bloodstream resulting in hypertension. In PE, higher amounts of soluble fms-like tyrosine kinase 1 (sFLT-1) are produced in the placenta. sFLT-1 competitively binds to placental growth factor (PIGF) and vascular endothelial growth factor (VEGF) creating an angiogenically imbalanced vascular environment that prevents proper endothelial preservation [14, 15]. More recently, a modified version of the two-stage hypothesis has been developed, which proposes that maternal constitutional factors (genetics, obesity, diet, co-morbid disease) in combination with normal inflammatory changes in pregnancy can lead directly to endothelial dysfunction with or without the contribution of reduced placental perfusion [16, 17].
Hypovitaminosis D has been associated with PE . While the pathogenesis of PE involves a number of biological processes, there are several hypotheses to suggest how vitamin D levels may affect these processes (Table 1). These include vitamin D's role in modulating pro-inflammatory responses and decreasing oxidative stress in PE, promoting angiogenesis through VEGF and gene modulation, and decreasing blood pressure through the renin-angiotensin system (RAS) [19–25].
Vitamin D3, or cholecalciferol, is formed endogenously when 7-dehydrocholesterol in keratinocytes is converted to a seco-steroid pro-hormone upon irradiation by UV-B light. This is followed by two successive hydroxylations - first at the 25 position to form 25-hydroxyvitamin D [25(OH)D], which occurs in the liver, and second to form the active hormonal metabolite 1,25-dihydroxyvitamin D [1,25(OH)2D], also called calcitriol, which is largely carried out in the kidney. Calcitriol binds to its cognate nuclear receptor and modulates gene expression mainly related to calcium absorption in the intestine. Calcitriol can also modulate immune function through a rapid action pathway by binding to receptors on the plasma membrane when the active hormone is synthesized in situ by several extra-renal tissues, namely macrophages, endothelium, cells in the prostate, and keratinocytes, as all of them express the vitamin D receptor .
Vitamin D status is determined by the measurement of its circulating form, 25-hydroxyvitamin D [25(OH)D] . Vitamin D is considered adequate when 25(OH)D levels are above 50 nmol/L, as defined by the Institute of Medicine. A level between 30 and 50 nmol/L is considered insufficient, and less than 30 nmol/L, deficient .
In the past decade, maternal vitamin D insufficiency and deficiency have increasingly been recognized as a public health concern. Insufficiency has been linked to adverse maternal and fetal outcomes, including poor fetal and infant bone mineralization [28, 29], hypocalcemia and rickets in neonates . A number of prospective observational studies have shown a high prevalence of hypovitaminosis D during pregnancy in developing and developed countries . Risk factors that affect vitamin D status include season, time of the day, latitude, clothing and skin color . Vitamin D deficiency is commonly found among pregnant women in various ethnic populations [33–37]. African American women of reproductive age have been found to be at particularly high risk for vitamin D deficiency in the United States . Clothing with minimal skin exposure [38, 39], increased urbanization, skin pigmentation , and vegetarian diets  are all believed to have contributed to a vitamin D deficiency epidemic worldwide.
During the course of pregnancy, evidence from observational studies shows divergent data on the concentration of serum 25(OH)D levels in different trimesters of pregnancy, with either decline , increase , or absence of change in vitamin D levels with progression [43, 44].
It is plausible that a deficiency in vitamin D and its downstream products can play a role in the etiology of PE. Human decidual cells at the fetal-maternal interface synthesize active 1,25(OH)2D via 1alpha-hydroxlyase (CYP72B1) [45–47]. Syncytial trophoblasts responsible for invading the uterine wall for fetal implantation also express active CYP27B1, in addition to vitamin D receptor (VDR), vitamin D binding protein (VDBP), 25-hydroxylase, and 24-hydroxlyase. Metabolic homeostasis of these proteins has been shown to be significantly altered in placental tissue from pregnancies with PE compared to controls [48, 49]. In a study in which human extravillous trophoblasts were treated in vitro with 1,25(OH)2D or 25(OH)D, there was a significant increase in EVT invasion into cell cultures when compared with untreated controls (p < 0.01) .
Additionally, vitamin D likely plays a key role in the pathology of pre-eclamptic conditions by affecting blood pressure through calcium homeostasis and/or modulating inflammation and immunity, which are examined further in this review.
Vitamin D is thought to play a significant role in PE as an immune modulator [20, 50]. It may help mount an appropriate maternal immune response to the placenta preventing the release of anti-angiogenic factors into the bloodstream and modulating hypertension . For example, 1,25(OH)2D suppresses T cell receptor-induced T cell proliferation, altering the cytokine expression profile and diminishing the production of γ-interferon and interleukin-2 . 1,25(OH)2D down regulated pro-inflammatory cytokines, tumor necrosis factor-α, and interleukin-6 secretions (p < 0.05) in trophoblastic preparations from placentas of pre-eclamptic women collected after delivery and cultured in the presence of calcitriol compared to pre-eclamptic placentas cultured in the absence of 1,25(OH)2D . In a study conducted on 100 normotensive and 100 pre-eclamptic women, both plasma vitamin D deficiency (OR 4.2, 95% CI: 1.4–12.8, p = 0.04) and interleukin-6 elevation (OR 4.4, 95% CI: 1.8–10.8, p < 0.01) were independently associated with PE. However there was no association between plasma vitamin D deficiency and interleukin-6 elevation .
1,25(OH)2D is also suspected to be involved in the regulation of IL-10, which has an inhibitory effect on pro-inflammatory cytokines expression in the human placenta. For example, 1,25(OH)2D may undertake the anti-inflammatory effects of IL-10 by itself to inhibit expression of placental Th1-cytokines, which are increased in PE. Barerra et al. showed that calcitriol down-regulates IL-10 under normal, natural and experimental inflammatory conditions in cultured human trophoblasts . Calcitriol has also been shown to decrease TNF-a and IL-6 expression .
In addition to down-regulating the release of anti-angiogenic factors, vitamin D has been shown to promote angiogenesis in endothelial progenitor cells, by possibly increasing VEGF expression and pro-matrix metalloproteinase (pro-MMP-2) activity . MMPs are implicated in the pathogenesis of vascular dysfunction associated with PE [56, 57]. There is evidence that 1,25(OH)2D is synthesized in the vascular endothelial cells  and induces vascular smooth muscle cell (VSMC) proliferation . Brodowski et al. showed that supplemented 1,25(OH)2D on endothelial progenitor cells reversed endothelial dysfunction seen in preeclampsia . Cardus et al. found that the effect of 1,25(OH)2D on VSMC proliferation is mediated by increased VEGF expression, while others find no relation between vitamin D and pro-angiogenic factors . There is currently not enough data to strongly support the hypothesis that impaired angiogenesis explains the association between vitamin D deficiency and PE .
An inverse relationship between plasma 1,25(OH)2D and plasma renin activity has been observed. The RAS plays an important role in regulation of blood pressure. During normal pregnancy, RAS is stimulated so that there is an increase in circulating levels of renin, angiotensinogen and angiotensin II . In PE, circulating serum angiotensin I, angiotensin II and aldosterone are lower compared to normotensive women, while plasma active renin levels and autoantibodies to the Angiotensin II type 1 receptor, which stimulate receptor signaling to increase systemic blood pressure, are higher [62–64]. These findings suggest a hemodynamic dysregulation in PE involving the RAS. Vitamin D metabolites may suppress renin gene transcription by a vitamin D receptor (VDR) dependent pathway  or reduce autoantibodies to the Angiotensin II type I receptor . In one study, oral vitamin D2 (VD2, 270 IU/day) and vitamin D3 (VD3, 15 IU/day) lowered mean arterial blood pressure (mm Hg) in pregnant rats infused with autoantibodies to Angiotensin II type I receptor (VD2: 105 +/−2, VD3: 109 +/− 2) versus rats that were infused with autoantibodies to Angiotensin II type I receptor but did not receive oral VD2 or VD3 (121 +/− 4) . Studies have shown an inverse relationship between plasma 1,25(OH)2D levels and blood pressure , and plasma 1,25(OH)2D levels and essential hypertension . In vitro and in vivo studies have found receptors for calcitriol in vascular smooth muscle  and heart muscle . A study of mice found receptors for calcitriol in regions of the spinal cord and brain stem that are associated with blood pressure regulation .
The effects of calcium supplementation on pregnancy-induced hypertensive disorders are well characterized. A Cochrane meta-analysis of 13 randomized trials involving 15,730 women found that at least 1 g daily calcium supplementation lowers the average risk of PE by approximately half (relative risk [RR]: 0.45, 95% CI: 0.31–0.65) . Low calcium levels may lead to hypertension by stimulating either the parathyroid hormone (PTH) or renin release, resulting in vasoconstriction due to increased intracellular calcium in vascular smooth muscle [72, 73]. Further calcium absorption has been found to be positively associated with serum 1,25(OH)2D concentrations in late pregnancy [74, 75]. The high concentration of this metabolite inhibits serum PTH synthesis and secretion, promoting the active intestinal absorption of calcium.
It is also observed that calcium sufficiency may occur independently of vitamin D sufficiency. In a study of female mice with a VDR null mutation and rickets, intestinal absorption of calcium and whole-body mineral content was significantly reduced compared to wild type mice before pregnancy (0.381 ± 0.026 vs. 0.529 ± 0.023, p < 0.001). During pregnancy, 1,25(OH)2D levels doubled in both groups and VDR null mice gained 158% of bone mineral content from baseline. By day 16.5 of pregnancy, intestinal calcium absorption in VDR null mice was equivalent to non-pregnant wild type mice, but did not reach levels of pregnant wild type mice .
Given the role of vitamin D in modulation of inflammation and immune function, placental implantation, angiogenesis and adverse birth outcomes such as low birth weight and SGA, we examined the evidence that vitamin D may play a role in the etiology and prevention of PE in this manuscript.
The review protocol was designed a priori to answer the question, "What are the effects of vitamin D concentrations and supplementation during pregnancy on pre-eclampsia in women?" We conducted a literature search using MEDLINE electronic databases (via PubMed) to identify published studies until February 2015. Search terms: (preeclampsia OR pre-eclampsia) AND (vitamin D OR hypovitaminosis D OR 1,25 dihydroxyvitamin D OR (vitamin D AND (supplementation OR supplement)) OR dihydroxyvitamin D OR 25 hydroxyvitamin D). The search was confined to peer-reviewed articles that were published in English and contained an abstract. Reference lists of journal articles were also screened for additional citations fitting our search criteria.
Articles were screened independently by two authors (JP and PG) for relevance based on the title and abstract. In the event that the number of RCTs returned by the search was insufficient to conduct a meta-analysis of PIH outcomes, authors planned to give a structured review of both experimental and observational studies. Considering retrospective and observational designs are more prone to bias than experimental design, results of clinical trials are presented separately and given more weight in conclusions and interpretations. An individual Risk of Bias assessment was not done given structured review design. Selected journal articles were then retrieved, collected, indexed, and assessed for availability of pregnancy-related data on PE and vitamin D by JP and PG. The inclusion criteria for this review were availability of an abstract, clinical data on vitamin D concentrations and/or supplementation in association with PIH outcomes in any global setting, and subjects that included pregnant participants aged 18 years and above without other medical co-morbidities. Studies were excluded if they were reviews, commentaries, editorials, letters, non-human studies, didn't include maternal vitamin D measured during gestation as a primary or secondary variable, or did not include PE as a primary or secondary outcome.
Selected studies were read and desired data were extracted independently by two authors (JP and PG). A third author, PD cross-checked data extraction to establish 100% agreement between the two independent reviewers. The following elements were extracted for each study: Author; year of publication; country; study design; objective, methods, exposure and outcome measures, sample size and key findings. All authors reviewed the final summary of selected studies and resolved any data discrepancies through discussion. Principal summary measures included risk of PIH outcomes and change in means of continuous PIH indicators such as hypertension.
The structured literature search resulted in 233 articles. 200 studies were excluded (60 reviews, 55 non-human studies, 85 studies that didn't meet the inclusion criteria described above (Fig. 1). A total of 33 studies were extracted for further review. The reviewed studies included 3 cross-sectional studies, 20 case control studies, 2 retrospective cohort studies, 6 prospective cohort studies and 2 randomized controlled trials.
A detailed summary of the search strategy and results is presented in Fig. 1. The PRISMA Checklist for this review can be found in Additional file 1.
Several cohort and case control studies measuring vitamin D before the development of PE show an association between vitamin D and PE (Tables 2 and 3). In a large cohort study of 22 057 nulliparous women, no association was found between vitamin D intake from diet alone and the incidence of PE. However, when considering total vitamin D intake (diet + supplement) of 15–20 μg/d compared to less than 5 μg/d, there was an adjusted OR of 0.76 (95% CI 0.60–0.95) for diagnosis with PE . There was an adjusted OR of 0.72 (95% CI 0.58–0.92) in women with vitamin D intake of 10–15 μg/d from supplementation of vitamin D alone when compared with no supplementation. A limitation of this study was that it was unable to adjust for intake of long chain n-3 fatty acids, which correlated with vitamin D intake in a Norwegian diet. Another prospective cohort study of nulliparous women with singleton pregnancies found no significant association between vitamin D deficiency in the 1st trimester and risk for PE; however, at 24–26 weeks of gestation mean maternal 25(OH)D was significantly lower in women who developed PE compared with those who did not (p = 0.03) . The adjusted OR was 3.24 for PE (95% CI:1.37–7.69) in women with 25(OH)D levels less than 50 nmol/l. Strengths of this study were that vitamin D was measured in both high and low risk women, representing a realistic clinical scenario. A retrospective cohort study showed that at entry to care (13.7 ± 5.7 weeks) there was an increased risk of PE in women with 25(OH)D levels less than 49.9 nmol/L and high parathyroid hormone (> 62 pg/mL) (aOR 2.86; 95% CI: 1.28–6.41) . However, there was no association in women with vitamin D insufficiency who did not also have high PTH.
A case-cohort study of women from 12 different United States (US) sites whose vitamin D levels were measured at ≤26 weeks of gestation showed that 25(OH)D levels greater than 50 nmol/L were associated with a 40% reduction in risk for severe PE (0.65 [95% CI 0.43 to 0.98]), although there was no reduction in absolute and relative risk for the milder clinical subtypes of PE when 25(OH)D levels were greater than 50 nmol/L . In a nested case control study of 274 nulliparous pregnant women conducted previously by the same investigator, there was an OR of 5.0 for PE in early pregnancy (<22 weeks) when maternal 25(OH)D was less than 37.5 nmol/l after controlling for education in addition to the common confounders (95% CI: 1.7–14.1). Interestingly, it was reported that newborns of pre-eclamptic mothers were more than twice as likely to have 25(OH)D levels less than 37.5 nmol/L (aOR = 2.2, 95% CI: 1.2–4.1) than newborns of healthy controls . Another nested case control study of 225 women with singleton pregnancies reported an OR of 5.41 for severe PE among women with mid-gestation vitamin D deficiency after controlling for multi-parity (95% CI: 2.02–14.52) compared to women with vitamin D levels of at least 75 nmol/L . A larger Canadian case control study reported a more than twice as likely odds for PE in women with 25(OH)D less than 30 nmol/L compared to women with at least 50 nmol/L (95% CI: 1.29–3.83). There was a dose response relationship between maternal 25(OH)D and risk of PE with a threshold of effect at 50 nmol/L .
Observational studies which measured vitamin D status after the onset of PE [53, 82] near delivery  or at delivery [84, 85] suggest an inverse association with PE. A US case control study reported a trend toward increased risk of PE with 25(OH)D levels less than 15.0 nmol/L (OR = 2.5 [95% CI: 0.89-6.9]) when compared to the controls (chosen randomly from among women who remained normotensive throughout pregnancy, and did not have gestational diabetes mellitus or gave birth to SGA infants). However, this trend was not significant after adjusting for BMI and other covariates. The investigators observed a trend towards increased risk of PE at very low levels of 25(OH)D, suggesting that there may be an association at the low extreme . A recent North Indian case control study of nulliparous women with PE and singleton pregnancies reported serum vitamin D to be significantly lower among PE cases vs. controls at the time of delivery (24.2 +/− 12.4 nmol/L, 36.9 +/− 16.7 nmol/L, respectively; p = 0.0001). Similar vitamin D levels were found in women with mild and severe PE . Two cross-sectional studies report 25(OH)D and 1,25(OH)2D levels to be lower in women with PE in the third trimester. Although these studies find an inverse association between vitamin D levels and PE, this association may be confounded by the gestational age at serum collection. These studies are also limited in that odds ratios are not reported [83, 88].
Correlation between low serum vitamin D in women with established PE was also found in studies in which populations had specific risk factors for vitamin D deficiency such as race or seasonal sun exposure. A nested case control study showed an association between EOSPE and vitamin D deficiency after the diagnosis of EOSPE. Serum 25(OH)D was measured at the time of diagnosis of EOSPE (~ 29 weeks of gestation). Controls were matched to cases according to gestational age at diagnosis with EOSPE and race. In patients with EOSPE (n = 50), 25(OH)D was significantly lower compared to the controls (n = 100) (44.9 vs. 79.9 nmol/L; p < 0.001). There was an adjusted odds ratio (aOR) of 3.6 [(95% CI 1.71–7.58), p < 0.001] for EOSPE when maternal 25(OH)D was less than or equal to 19.6 nmol/L. There was also a 12-fold increase in odds of diagnosis with EOSPE in African American women, who had the lowest mean 25(OH)D concentration among groups categorized by race . In an Iranian case control study conducted in the fall and winter months, 25(OH)D levels were measured at the time of delivery in 41 pre-eclamptic women, 50 normal women and from their umbilical cord samples immediately after birth. This study found mean 25(OH)D levels to be significantly lower in pre-eclamptic women versus normal women (37.9 ± 33.9 nmol/L vs. 58.2 ± 38.2 nmol/L, respectively, p = 0.001). There was a significant relationship between vitamin D levels in pre-eclamptic women with levels in their neonates (r = 0.901, p = 0.0001) .
Two studies of vitamin D in PE cases have evaluated the possible relationship with angiogenic factors. In a small nested case control study that matched cases of severe PE by race and ethnicity to healthy controls, 25(OH)D levels were found to be an independent predictor for severe PE. In women with a 10 nmol/L increase in maternal 25(OH)D, there was a 38% reduction in the odds of severe PE (aOR = 0.62, 95% CI: 0.51–0.76). Women with severe PE had significantly lower levels of PIGF (p = 0.03) and VEGF (p = 0.0007) and a higher sFLT-1/PlGF ratio (p = 0.02) compared to controls. However, there were no independent correlations reported between 25(OH)D levels and these angiogenic markers. A limitation of this study was heterogeneity of parity, a potentially confounding variable, in pre-eclamptic cases (44% multiparous) . A retrospective fully blinded cohort study of 257 pregnant women in an obstetric emergency service in Spain also found no association between SFlt-1/PIGF and 25(OH)D levels in women with PE. However, this study found a greater risk of late-onset PE among women with low 25(OH)D level (<50 nmol/L) (OR 4.6, 95% CI 1.4–15) and increased risk of both early- and late-onset PE when sFlt-1/PIGF ratios were above corresponding cut-points (ORs 58 [95% CI 11–312] and 12 [95% CI 5.0–27], respectively) .
There have been a small number of clinical trials studying associations between maternal vitamin D and hypertensive disorders in pregnancy (Table 4). In a 50-year-old controlled trial of 5644 women, Olsen & Secher assessed the preventive effect of a multi-vitamin mineral supplement, which included iron, calcium, iodine, manganese, copper, vitamin B complex, vitamin C, and 260 mg/day of calcium and halibut liver oil containing 2500 IU/g vitamin D per day. Among women who were given supplementation from week 20 of gestation onwards, there was a 31.5% reduction in the odds of PE (p < 0.005). No significant effect was observed in the odds of developing gestational hypertension . Of note, omega-3 fatty acids found along with vitamin D in cod liver oil are likely to play an independent role in preventing PE [92, 93].
While the preceding studies support a link between vitamin D deficiency during pregnancy and risk of PE, some studies present conflicting evidence (Tables 2 and 3). Most of these studies were observational, and measured maternal vitamin D concentration before the diagnosis of PE as opposed to measuring at the time of diagnosis or delivery.
A 2010 prospective cohort study did not find an association between low serum 25(OH)D levels (<37.5 nmol/L) in the first half of pregnancy and the development of PE (aOR = 0.91 CI: 0.31–2.62) or gestational hypertension (aOR = 1.55 CI: 0.58–4.17) in women who were at high-risk for PE after controlling for smoking and parity. This study used high-risk women, both nulliparous and multiparous, who did not develop PE as controls . Another cohort study in 2014 found no association between low plasma 25(OH)D concentration (<25 nmol/L) and PE in women at 16.4–36.9 weeks of gestation (aOR = 0.60 95% CI:0.14–2.56). Rather, investigators found for every 25 nmol/L increase in 25(OH)D, the aOR for PE was 1.14 (95% CI, 0.77–1.67) .
In 2012, Wei et al. retrospectively analyzed vitamin D status and the risk of PE in 697 nulliparous women with singleton pregnancies in a randomized, placebo-controlled trial of Vitamin C and E supplementation for the prevention of PE. After controlling for smoking, the study showed that in the first trimester (mean 11 weeks), vitamin D deficiency was not significantly associated with an increased risk of PE (aOR = 1.24 95% CI: 0.58–2.67; p = 0.58) . In a 2013 follow-up study of women from the same cohort, Wei et al. found that PIGF level was inversely associated with PE (p < 0.05) . In a multivariate logistic model to control for PIGF there was an aOR of 2.97 (95% CI: 1.23–7.20) for PE among women with 25(OH)D levels less than 50 nmol/l. This was only an 8.3% reduction in the risk for PE compared to when PIGF levels were not considered. There was no statistical evidence of interaction between PIGF and vitamin D (p = 0.54) .
In 2004, a longitudinal case control study did not find altered circulating 1,25(OH)2D during mid-pregnancy in those who developed PE compared to healthy, normotensive women . In 2010, Powe et al. suggested that earlier studies have measured total 25(OH)D as a vitamin D/Vitamin D Binding Protein (VDP) complex, and not the free vitamin. Therefore, Powe et al. conducted a study measuring levels of both total and free 25(OH)D in the first trimester of PE and normotensive pregnancies. They found total and free 25(OH)D levels were similar in cases and controls (68.4 ± 4.7 nmol/L versus 71.9 ± 2.0 nmol/L, p = 0.435). There was no association between 25(OH)D levels <15.0 nmol/L and risk of PE (aOR = 1.35 95% CI: 0.40 to 4.50) . In a nested case control study of women with singleton pregnancies, 100 pregnant women with PE were matched to 200 healthy controls who delivered at 39–40 weeks. 25(OH)D levels were assessed from stored blood samples drawn between 15 and 21 weeks gestation for multiple marker screening. After adjusting for covariates, vitamin D insufficiency and deficiency were not significantly associated with PE (aOR = 1.1 95% CI: 0.6–2.0; aOR = 1.4 95% CI: 0.7–3.0, respectively) .
In a cross-sectional study of 466 pregnant women attending an outpatient clinic in Spain, serum 25(OH)D was measured between 11 and 14 weeks of pregnancy. No associations were found between maternal 25(OH)D less than 49.9 nmol/L or 25(OH)D between 49.9 and 74.9 nmol/L in cases of PE and gestational hypertension identified during follow-up .
In 2000, a double-blind, randomized, placebo-controlled trial evaluated the effects of 2.7 g fish oil supplementation given prophylactically from 20 weeks until delivery in women who had previously experienced Pregnancy Induced Hypertension (PIH) (n = 386). Supplementation with fish oil did not affect the recurrence risk for PIH in the prophylactic trial (OR = 0.98 CI: 0.63–1.53). Vitamin D concentrations were not reported .
Observational studies evaluating the association between vitamin D and PE have shown inconsistent results and must be interpreted cautiously. This may be a result of issues with study design and methodology, including lack of adjustment of key confounding variables and methods of measuring vitamin D levels.
Study findings must be interpreted in the context of study design. Most previous studies were based on cohort studies that collected clinical data and stored blood in repositories at regular intervals. Many researchers utilized a case-control study design within these cohorts, or performed cross-sectional studies. Residual confounding and differences between groups may explain the association between vitamin D deficiency and PE.
Most studies controlled for maternal age, body mass index, season, and gestational trimester at sample collection. In addition, some studies also controlled for smoking [14, 37]. Smoking has consistently been shown to reduce the risk of PE and gestational hypertension [99, 100]. This could be due to an association between smoking and lower circulating concentrations of anti-angiogenic proteins and higher concentration of pro-angiogenic proteins . Smoking has also been linked to lower vitamin D concentrations . Smoking may be an important confounder and should be considered in studies linking vitamin D to PE. The pathophysiology of PE may also vary by parity . Wetta et al., , Shand et al.,  and Bodnar et al.,  have controlled for parity in their studies.
Individuals receive the majority of their vitamin D from sunlight, linking seasonality to the development of PE. Seasonality is also considered a confounder, particularly in studies related to causal effects of vitamin D on PE. Seasonal and latitudinal variation has an effect on vitamin D3 production in the skin . According to a study by Magnus and Eskild , in Norway, mothers of children born in August had the lowest risk of PE. Risk in this study was highest in the winter months (for December, aOR: 1.26, 95% CI: 1.20–1.31) . Similarly, Bodnar et al.  found that the incidence PE among white women in the United States was highest in the winter, when production of cutaneous vitamin D3 is limited in temperate zones and serum 25(OH)D are at their lowest levels. However, despite this known association, not all studies looking at PE as an outcome report information on seasonal, latitudinal variation, sun exposure and lifestyle differences—all of which may differentially expose individuals to sunlight in the sample population.
Maternal dietary intake of vitamin D from foods or supplements may also vary. Oily fish and cod liver oil (n-3 fatty acids) are a rich source of vitamin D. In the Norwegian diet, intake of vitamin D is correlated with intake of long chain n-3 fatty acids . The use of cod liver oil as a food supplement in some diets presents a challenge in determining an isolated effect of vitamin D supplementation. This was noted by Haugen et al. , who were unable to control for the intake of fatty acids in their analysis. In their secondary analysis with intake of long chain n-3 fatty acids and vitamin D, a weaker association with the incidence of PE was observed .
Although randomized clinical trials (RCTs) offer the opportunity to design studies with power to provide definitive evidence, few have been performed in this field. RCTs reviewed in this article were not able to study vitamin D supplementation independently of calcium and/or other multivitamin/micronutrient supplementation. In a Cochrane review of Vitamin D supplementation for women during pregnancy, women who received vitamin D and calcium supplementation had a lower risk of pre-eclampsia than those not receiving any intervention (RR 0.51; 95% CI 0.32 to 0.80; three trials, 1114 women, moderate quality), yet an increased risk for preterm birth (RR = 1.57; 95% CI: 1.02–2.43; three studies, 798 women, moderate quality). In trials with an intervention of vitamin D without calcium, women who received vitamin D supplements had a statistically nonsignificant lower risk of pre-eclampsia than those receiving no intervention or placebo (8.9% versus 15.5%; risk ratio (RR) 0.52; 95% CI 0.25 to 1.05; low quality) with no adverse outcomes . The role of fish oils in PE remains uncertain and similarly poses a challenge in determining an isolated effect of vitamin D supplementation, unless studies are designed such that they consider this. In the RCTs reviewed, no conclusions can be made regarding the independent effects of vitamin D in preventing or treating PE.
Studies must also be interpreted according to how vitamin D exposure is defined and measured. "The free hormone hypothesis" postulates that hormones that are free from their binding proteins may enter cells to perform biological functions . During pregnancy, VDBP increases by 2-fold . Future investigations should consider concurrently measuring VDBP levels and calculated free vitamin D levels when considering the role of vitamin D in PE . Additionally, investigators should attempt to assess preconception and early pregnancy dietary intake, sun exposure or baseline vitamin D status.
Studies that find a role early in pregnancy, before the clinical onset of PE, suggest that vitamin D may play a role in the modulation of a pro-inflammatory response or regulation of angiogenic factors. It is possible that biomarkers for PE, such as angiogenic factors VEGF and PIGF, may serve as mediators in the pathway linking vitamin D metabolites to PE. Despite evidence that low vitamin D levels increase risk for PE early in pregnancy, very few studies have tried to relate this effect with the regulation of angiogenic or anti-angiogenic factors. Although current evidence supports an association between angiogenic factors and PE, these studies have not found an association between vitamin D levels and angiogenic factors [14, 15]. Studies with longitudinal study design carefully controlling for temporal sequences of changes in vitamin D levels in women with PE are needed to identify the role of vitamin D and any potential mediators in the pathway linking vitamin D to PE.
There are important clinical considerations that necessitate the need for further research on this topic. There is limited data on the most efficacious dose of vitamin D to prevent pre-eclampsia while avoiding toxicity. The doses of vitamin D supplements in the studies reviewed ranged from 400 to 2500 IU daily . These studies reported no major adverse effects of supplementation at these doses [107–109]. Recently, participants in the Vitamin D for Antenatal Asthma (VDAART) randomized double-blind placebo controlled trial took a daily dose of 4000 IU vitamin D supplementation plus a multivitamin with 400 IU vitamin D or placebo (placebo pill plus a multi-vitamin with 400 IU vitamin D daily) to assess the effect of vitamin D supplementation on the frequency of PE among pregnant women with a high risk for atopic disease .
The investigation by Haugen et al. suggests a potential for a role for the frequency and timing of vitamin D supplementation and risk for PE, given that the total intake greater than 800 IU/day did not reduce risk. However, Haugen et al. found that women who took supplements at all three points of pregnancy (before pregnancy, early pregnancy and in late pregnancy) were at a lower risk for PE compared with women who took supplements in only early or late pregnancy or did not take any supplements . In the VDAART, frequency of PE among pregnant women with a high risk for atopic disease was not lower when a supplementation of 4400 IU vitamin D daily was given in early pregnancy (10–18 weeks). However, women with a serum vitamin D status of ≥75 nmol/L that was maintained from enrollment through late pregnancy had a significantly lower risk of PE versus women who had <75 nmol/L (P = 0.04). But this vitamin D level was maintained in only 74% of pregnancies in the supplementation group by weeks 32 to 38 of gestation, suggesting that supplementation at even earlier time-points or before pregnancy may be necessary to maintain sufficient vitamin D levels that are protective against PE. This was further supported by peripheral blood gene expression patterns relating to immune and inflammatory processes identified as early as the 10th week of pregnancy that were unique in women who went on to develop PE .
Additionally, early-onset and late-onset PE have unique clinical features, biomarkers and prognoses that may guide clinical dose recommendations. Studies reported varying degrees of risk for clinical subtypes of PE among women with low vitamin D levels [79, 90]. In order to guide the clinical recommendations, investigators must use a standard set of definitions for the disease and clinical subtypes in future research. In the current literature, the definition of PE was not consistent across studies, limiting our ability to draw generalizations. For example, clinical cutoffs for proteinuria varied slightly among studies [86, 87]. Replication of findings using a uniform set of definitions for PE and clinical subtypes can inform the use of vitamin D supplementation for the prevention of PE.
Robinson et al.  suggest that vitamin D deficiency may be a factor in the disproportionate incidence of adverse pregnancy outcomes in African American women since this group had the lowest vitamin D levels among the populations they studied. While some studies have been able to capture an adequate representation of African American women , there is a need for further research on populations with very low vitamin D levels to understand this observation and identify factors that predispose high-risk groups to PE and its more threatening clinical subtypes.
Despite the clear association of serum deficiency with PE, a better understanding of the variable impact of supplementation is needed to identify potential of genetic and environmental interactions, as well as pre-conception data to identify the critical time window for therapeutic potential of vitamin D, if any.
There is consistent evidence of an association between low vitamin D concentrations and adverse PIH outcomes. Results from vitamin D supplementation during pregnancy did not show a statistically significant independent effect of vitamin D on the risk of PE and PIH.
At this time, our understanding of an ideal supplementation dose of vitamin D to reduce PIH remains incomplete. Future studies should include follow up from the pre-conception period until delivery to elucidate the mechanisms and interactions which drive vitamin D status, response, and onset of PE to inform population-specific dose recommendations.
The authors would like to thank Dr. Julia Finkelstein, Assistant Professor of Epidemiology and Nutrition for her essential comments during the drafting of this review. We are grateful to the Division of Nutritional Sciences, Cornell University and the Hunter R. Rawlings III Cornell Presidential Research Scholars program for academic support to Juhi Purswani as an undergraduate research scholar.
No funds were used for this student project.
JP and PG wrote the initial draft of the manuscript. PD helped revise the manuscript and contributed to interpretation of the included studies. HL consulted on review methodology, contributed to writing, and interpretation of results. SM and AK contributed to conception and design, acquisition of data, analysis and interpretation of data. All authors have read and approved the final version of this manuscript.
SM has equity interest in a startup focusing on point-of-care diagnostic platforms for nutritional status that were developed as part of his research program as a faculty member at Cornell University.
World Health Organization. Fact Sheet - Maternal Mortality. http://www.who.int/mediacentre/factsheets/fs348/en/. Accessed 23 July 2016.


text:
Q: android sdk google analytics track events with metadata in the link: https://developers.google.com/analytics/devguides/collection/android/v4/events
google explains how to send events.
However I didn't see any mention of a way to send events with extra  pairs.
for example if I want to send an event of uploading images, and I would like to also send something like
    <"number_of_images_uploaded", 4>
    <"location_of_upload", "Italy">
    <"was_registered_user", false>
etc..
is there a way to do this?

A: EDIT: Apparently you can do it with custom dimensions
https://developers.google.com/analytics/devguides/collection/android/v4/customdimsmets
ORIGINAL ANSWER
Can't do it. The link you provided shows that you can only send events with categories, actions, labels, and values.
The only way to store this meta data in combination with google analytics is to do it yourself.
e.g.

*

*Send an HTTP request to your own server to create a record (or records) in a database with the meta information and return an identifier in the response.

*When you receive a response from the server, send the google analytics event information to google along with your event ID that you received from your server.

This allows you to use google analytics for general user-interaction information and also allows you to link specific events in google analytics to their metadata on your server.

redpajama_set_name: RedPajamaStackExchange


text:
North Florida Roofing Is Now Model City Roofing
by TechBear | Jan 15, 2019 | News | 0 comments
Rebecca Currie
rebecca@northfloridaroofing.com
The company positions for growth and expansion into new markets.
Wednesday, January 2nd, 2019 – North Florida Roofing is now operating as Model City Roofing, positioning to grow and expand across multiple markets. The company went through an ownership change about 3 ½ years ago with the intent to expand across the Southeast to become a regional leader in the roofing industry. "The intent of the expansion was in the forefront of the ownership's mind when considering the company for purchase. Prior to the launch of the new brand and expansion into new markets, company leadership wanted to optimize some things on the operations side before starting an extensive growth plan. "We are now positioned strongly to grow the business in multiple states and markets," says Chris Canipe, MCR President. The company headquarters is in Jacksonville, Florida. The North Florida Roofing brand, regarding both past ownership and new, only operated in the Jacksonville and North Florida markets. The company has
now launched into several key markets including: Tampa/St. Pete, the Florida Panhandle, Orlando, and the Tri-Cities market in Northeast Tennessee. "We have some vital business relationships in the additional Florida markets that were encouraging us to grow so that we could service properties in markets outside of our current footprint," states Canipe. The MCR branding story is two-fold. First, the company obviously needed a brand that would carry over into markets across the U.S. and not be one with geographic ties. Secondly, the name of the company was opportunity for Chris Canipe to pay homage to his roots. Kingsport, known as the Model City and Canipe's hometown, is one of the three cities that make up the Tri-Cities, Tennessee. The market has just over 500,000 people in its population. "I loved growing up in the Tri-Cities market, plain and simple. Kingsport is where I grew up and additionally where Brian Ritz (Model City's National Sales Director) currently resides. It was an easy decision for our company when considering our first out-of-state operation," says Canipe Model City Roofing is already selling and installing roofs in all additional markets. The company has completely revamped the Jacksonville warehouse to accommodate growth and will have an additional warehouse in one of its recently opened markets. MCR has an aggressive sales and marketing plan which will include the hire of 15-20 additional staff members.


text:
Man arraigned from Albany Med bed on murder charges
Subrina Dhammi
The main suspect in a crime spree from Greene to Saratoga counties that included murder was arraigned in his hospital room at Albany Med on Tuesday.
NewsChannel 13 was the only station there, as Greene County District Attorney Joseph Stanzione came out of Jeffrey Field's arraignment.
Stanzione said he had never conducted a hospital room arraignment until Tuesday.
Field is now officially charged with murder and attempted murder.
The alleged crime spree happened Aug. 22 just before 1:30 a.m. in Catskill. Police say Field stabbed Adam White and Christopher Gere at 31 Summit Ave. and then drove to Saratoga County, where the crime spree continued. They say he broke into a home on Allen Road in Greenfield, assaulted the homeowner with a weapon, and tried to steal his car. When that didn't work, they say Field went to a neighbor's house, allegedly stole that car and then led officers on a chase that carried on to Locust Grove Road.
NewsChannel 13 was there for the tail end of that chase, which ended in a crash right near Greene Road.
Field was seriously injured and airlifted to Albany Medical Center.
The district attorney says a woman, Jennifer Hall, told Field a man put his hands on her. The district attorney says Field thought it was one of the two men he is accused of attacking. Turns out, according to Stanzione, that's not the case.
"It's just a terrible situation where a totally innocent person has died, and had no relation to these individuals at all," he said.
One of the two men stabbed, Adam White, did not survive. The other victim is still recovering.
Stanzione says a companion part of all of this is bail reform.
Learn how that plays into this case by watching the video of Subrina Dhammi's story.


I managed to figure out a fix so the controls work in Super Mario All-Stars and also doesn't break other games (Mario Kart, Super Bomberman etc). This problem has been bugging me for ages and I had to figure out a way to play this game for nostalgia sake. This fix will unfortunately mean player two controls wont work for other games (but I play alone anyway and this is for people with one controller). Simply post this in your blank retroarch.cfg in the snes folder. P.S Remember to change the button numbers/axis for you own controller. Also remember to do a reboot after this.
Last edited by KitchUK on Wed Jun 18, 2014 10:30 am, edited 3 times in total.
What am i supposed to replace?
field where "nul" is or the other ones?
To be honest this fix is way outdated now. It's much easier just to use the libretro-Snes9x-next core as this doesn't have any problems with All-Stars and it has better sound/performance for snes games.
If your using Retropie press 'x' when you load up the game and change the core.
okej, so no other way?
eway wrote: okej, so no other way?
Sorry no. I think this method was somehow patched out with an update. I remember trying it a while back and it stopped working. It would be much easier just using Snes9x-next. It's a much better core.
is there a guide to where to change core?
cant find Snes9x-next in my retropie 3.0 RC1 options.
lr-armsnes="/opt/retropie/emulators/retroarch/bin/retroarch -L /opt/retropie/libretrocores/lr-armsnes/libpocketsnes.so --config /opt/retropie/configs/snes/retroarch.cfg %ROM%"
lr-catsfc="/opt/retropie/emulators/retroarch/bin/retroarch -L /opt/retropie/libretrocores/lr-catsfc/catsfc_libretro.so --config /opt/retropie/configs/snes/retroarch.cfg %ROM%"
lr-pocketsnes="/opt/retropie/emulators/retroarch/bin/retroarch -L /opt/retropie/libretrocores/lr-pocketsnes/libretro.so --config /opt/retropie/configs/snes/retroarch.cfg %ROM%"
May I ask a question? Why do you fix the control while it is played normally. I tried Super Mario All-Star and Super Mario 63 on FREEGAMES66 and there is not any change.


All in One SEO Pack generates a Google XML Sitemap dynamically by default. If you're getting this error, this indicates headers have already been sent, usually caused by another PHP file outputting blank lines. Normally this happens when another PHP file is incorrectly outputting a closing PHP ?> tag, followed by some extra lines.
Another plugin – You can use these instructions to narrow down the offending plugin/plugins. Once you find the plugin, you can either deactivate it, look for the file(s) with a closing PHP tag followed by blank lines and remove it, and/or contact the developer with the bug report.
Your theme – Similar to #2, use these instructions to determine if it's your theme that's the problem. Install a fresh and unmodified copy of one of the default themes (Twenty Fifteen, Twenty Sixteen, etc). If the problem goes away, you know it was your theme.
WordPress core – This would only be a problem if either you're on a really old version of WP (upgrade!) or else you've modified core files (don't!).
Prior to WordPress 2.8, wp-config.php ended with a closing PHP tag.
Wherever you find this closing PHP tag, remove it.


Miss Sri Lanka 2009' Gamya Wijayadasa makes her debut in Manish Manikpuri's Aalaap with an item song called Chadhti Jawaani.
The music of the item song has been composed by the band Agnee and the song is already a rage all over Chattisgarh where Gamya performed recently at a promotional event organised by the producers Nishant Tripathi and Abhishek Mishra of Sri Shankaracharya Arts.
Gamya, who has an MBA from the University of Melbourne, says that she flew down to Raipur to shoot this song even without having heard it. "It's a situational number that has been picturised at an engagement party of one of the pivotal characters in the film," she says.
The song has been sung by Kanika Joshi and Bonnie Chakraborty. Being a Sri Lankan, Gamya didn't understand most of the lyrics. "But that wasn't an issue. The film deals with how music is used to quell Naxalism in Chattisgarh," she adds. The film stars Amit Purohit, Pitobash, Rituparna Sengupta, Raghuvir Yadav, Omkar Das Manikpuri, Murli Sharma, Aabid Shamim and Abhimanyu Singh.