Update check data from action (notification for instance)

        :param check: action to get data from
        :type check: alignak.action.Action
        :return: None
547576
def get_return_from(self, check):
        
        for prop in ['exit_status', 'output', 'long_output', 'check_time', 'execution_time',
                     'perf_data', 'u_time', 's_time']:
            setattr(self, prop, getattr(check, prop))
1356255
def action_log_update(sender, instance, **kwargs):
    
    if instance.pk is not None:
        try:
            old = sender.objects.get(pk=instance.pk)
        except sender.DoesNotExist:
            pass
        else:
            new = instance

            changes = model_instance_diff(old, new)

            # Log an entry only if there are changes
            if changes:
                log_entry = LogAction.objects.create_log_action(
                    instance=instance,
                    action=LogAction.UPDATE,
                    changes=json.dumps(changes),
                )
256406
def post_check(self, check):
        

        if self.disabled is True:
            logging.error('Posting has been disabled. '
                          'See previous errors for details.')
            return(False)

        url = self.checkurl + '/' \
            + check.name + '/' \
            + check.elementId + '/' \
            + str(check.ttl)
        headers = {'User-Agent': self.agent}
        try:
            request = urllib2.Request(
                url, data='', headers=headers)
            resp = self._repeat_request(request, self.connection_timeout)
            logging.debug("Response code: %d", resp.getcode())
            resp.close()

            return(True)

        except urllib2.HTTPError as e:
            logging.debug("Response code: %d", e.code)

            if e.code in self.kill_codes:
                self.disabled = True
                logging.exception('Posting has been disabled.'
                                  'See previous errors for details.')
            else:
                logging.exception(
                    'HTTPError posting payload to api ingest endpoint'
                    + ' (%s): %s',
                    url, e)
585629
def checkbox_check(self, force_check=False):
        
        if not self.get_attribute('checked'):
            self.click(force_click=force_check)
928438
def get_action(self, action=None):
        
        if action:
            self.action = action

        if self.action not in AjaxResponseAction.choices:
            raise ValueError(
                "Invalid action selected: '{}'".format(self.action))

        return self.action
1326082
def response_action(self, request, queryset):  # noqa
        
        # There can be multiple action forms on the page (at the top
        # and bottom of the change list, for example). Get the action
        # whose button was pushed.
        try:
            action_index = int(request.POST.get('index', 0))
        except ValueError:  # pragma: no cover
            action_index = 0

        # Construct the action form.
        data = request.POST.copy()
        data.pop(helpers.ACTION_CHECKBOX_NAME, None)
        data.pop("index", None)

        # Use the action whose button was pushed
        try:
            data.update({'action': data.getlist('action')[action_index]})
        except IndexError:  # pragma: no cover
            # If we didn't get an action from the chosen form that's invalid
            # POST data, so by deleting action it'll fail the validation check
            # below. So no need to do anything here
            pass

        action_form = self.action_form(data, auto_id=None)
        action_form.fields['action'].choices = self.get_action_choices(request)

        # If the form's valid we can handle the action.
        if action_form.is_valid():
            action = action_form.cleaned_data['action']
            func, name, description = self.get_actions(request)[action]

            # Get the list of selected PKs. If nothing's selected, we can't
            # perform an action on it, so bail.
            if action_form.cleaned_data['select_across']:
                selected = ALL
            else:
                selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)

            if not selected:
                return None

            revision_field = self.model._concurrencymeta.field

            if self.check_concurrent_action:
                self.delete_selected_confirmation_template = self.get_confirmation_template()

                # If select_across we have to avoid the use of concurrency
                if selected is not ALL:
                    filters = []
                    for x in selected:
                        try:
                            pk, version = x.split(",")
                        except ValueError:  # pragma: no cover
                            raise ImproperlyConfigured('`ConcurrencyActionMixin` error.'
                                                       'A tuple with `primary_key, version_number` '
                                                       'expected:  `%s` found' % x)
                        filters.append(Q(**{'pk': pk,
                                            revision_field.attname: version}))

                    queryset = queryset.filter(reduce(operator.or_, filters))
                    if len(selected) != queryset.count():
                        messages.error(request, 'One or more record were updated. '
                                                '(Probably by other user) '
                                                'The execution was aborted.')
                        return HttpResponseRedirect(".")
                else:
                    messages.warning(request, 'Selecting all records, you will avoid the concurrency check')

            response = func(self, request, queryset)

            # Actions may return an HttpResponse, which will be used as the
            # response from the POST. If not, we'll be a good little HTTP
            # citizen and redirect back to the changelist page.
            if isinstance(response, HttpResponse):
                return response
            else:
                return HttpResponseRedirect(".")
1302774
def check_update(ctx, forced=False):
    
    try:
        if ctx.update_checked and not forced:
            return
    except AttributeError:
        update_check_file = os.path.join(dir_path, 'update_check.txt')
        today = datetime.date.today().strftime("%m/%d/%Y")
        if os.path.exists(update_check_file):
            date = open(update_check_file, 'r').read()
        else:
            date = []
        if forced or today != date:
            ctx.update_checked = True
            date = today
            with open(update_check_file, 'w') as f:
                f.write(date)
            r = requests.get("https://pypi.org/pypi/keep/json").json()
            version = r['info']['version']
            curr_version = about.__version__
            if version > curr_version:
                click.secho("Keep seems to be outdated. Current version = "
                            "{}, Latest version = {}".format(curr_version, version) +
                            "\n\nPlease update with ", bold=True, fg='red')
                click.secho("\tpip3 --no-cache-dir install -U keep==" + str(version), fg='green')
                click.secho("\n\n")
25334
async def process_update(self, update: types.Update):
        
        types.Update.set_current(update)

        try:
            if update.message:
                types.User.set_current(update.message.from_user)
                types.Chat.set_current(update.message.chat)
                return await self.message_handlers.notify(update.message)
            if update.edited_message:
                types.User.set_current(update.edited_message.from_user)
                types.Chat.set_current(update.edited_message.chat)
                return await self.edited_message_handlers.notify(update.edited_message)
            if update.channel_post:
                types.Chat.set_current(update.channel_post.chat)
                return await self.channel_post_handlers.notify(update.channel_post)
            if update.edited_channel_post:
                types.Chat.set_current(update.edited_channel_post.chat)
                return await self.edited_channel_post_handlers.notify(update.edited_channel_post)
            if update.inline_query:
                types.User.set_current(update.inline_query.from_user)
                return await self.inline_query_handlers.notify(update.inline_query)
            if update.chosen_inline_result:
                types.User.set_current(update.chosen_inline_result.from_user)
                return await self.chosen_inline_result_handlers.notify(update.chosen_inline_result)
            if update.callback_query:
                if update.callback_query.message:
                    types.Chat.set_current(update.callback_query.message.chat)
                types.User.set_current(update.callback_query.from_user)
                return await self.callback_query_handlers.notify(update.callback_query)
            if update.shipping_query:
                types.User.set_current(update.shipping_query.from_user)
                return await self.shipping_query_handlers.notify(update.shipping_query)
            if update.pre_checkout_query:
                types.User.set_current(update.pre_checkout_query.from_user)
                return await self.pre_checkout_query_handlers.notify(update.pre_checkout_query)
            if update.poll:
                return await self.poll_handlers.notify(update.poll)
        except Exception as e:
            err = await self.errors_handlers.notify(update, e)
            if err:
                return err
            raise
677205
def call_action(condition, action)
      # Before.
      before_items = self.behaviors
      before_items += [condition] if condition
      before_items.each do |b|
        info = b.send("before_#{action}")
        if info
          msg = "#{self.name} before_#{action}: #{info} (#{b.base_name})"
          applog(self, :info, msg)
        end
      end

      # Log.
      if self.send(action)
        msg = "#{self.name} #{action}: #{self.send(action).to_s}"
        applog(self, :info, msg)
      end

      # Execute.
      @process.call_action(action)

      # After.
      after_items = self.behaviors
      after_items += [condition] if condition
      after_items.each do |b|
        info = b.send("after_#{action}")
        if info
          msg = "#{self.name} after_#{action}: #{info} (#{b.base_name})"
          applog(self, :info, msg)
        end
      end
    end
380537
function(action) {
		this._updates.filter(function(update) {
			return (
				update.type === edbml.Update.TYPE_HARD ||
				Object.keys(update.ids).every(function(id) {
					return !this._hardupdates[id];
				}, this)
			);
		}, this).forEach(function(update) {
			action(update);
		});
	}
403068
def set_checked(self, checked):
        
        if not checked:
            self.widget.clearCheck()
        else:
            #: Checked is a reference to the radio declaration
            #: so we need to get the ID of it
            rb = checked.proxy.widget
            if not rb:
                return
            self.widget.check(rb.getId())
167385
def process_actions(self, actions):
        
        notices = {}
        notification_contacts = {}
        for action in actions:
            resource = action['resource']
            action_status = ActionStatus.SUCCEED

            try:
                if action['action'] == AuditActions.REMOVE:
                    action_status = self.process_action(
                        resource,
                        AuditActions.REMOVE
                    )
                    if action_status == ActionStatus.SUCCEED:
                        db.session.delete(action['issue'].issue)

                elif action['action'] == AuditActions.STOP:
                    action_status = self.process_action(
                        resource,
                        AuditActions.STOP
                    )
                    if action_status == ActionStatus.SUCCEED:
                        action['issue'].update({
                            'missing_tags': action['missing_tags'],
                            'notes': action['notes'],
                            'last_alert': action['last_alert'],
                            'state': action['action']
                        })

                elif action['action'] == AuditActions.FIXED:
                    db.session.delete(action['issue'].issue)

                elif action['action'] == AuditActions.ALERT:
                    action['issue'].update({
                        'missing_tags': action['missing_tags'],
                        'notes': action['notes'],
                        'last_alert': action['last_alert'],
                        'state': action['action']
                    })

                db.session.commit()

                if action_status == ActionStatus.SUCCEED:
                    for owner in [
                        dict(t) for t in {tuple(d.items()) for d in (action['owners'] + self.permanent_emails)}
                    ]:
                        if owner['value'] not in notification_contacts:
                            contact = NotificationContact(type=owner['type'], value=owner['value'])
                            notification_contacts[owner['value']] = contact
                            notices[contact] = {
                                'fixed': [],
                                'not_fixed': []
                            }
                        else:
                            contact = notification_contacts[owner['value']]

                        if action['action'] == AuditActions.FIXED:
                            notices[contact]['fixed'].append(action)
                        else:
                            notices[contact]['not_fixed'].append(action)
            except Exception as ex:
                self.log.exception('Unexpected error while processing resource {}/{}/{}/{}'.format(
                    action['resource'].account.account_name,
                    action['resource'].id,
                    action['resource'],
                    ex
                ))

        return notices
836016
def update_check(self, existing, new):
        
        old_state = existing.state
        if 'NowPlayingItem' in existing.session_raw:
            try:
                old_theme = existing.session_raw['NowPlayingItem']['IsThemeMedia']
            except KeyError:
                old_theme = False
        else:
            old_theme = False

        if 'NowPlayingItem' in new:
            if new['PlayState']['IsPaused']:
                new_state = STATE_PAUSED
            else:
                new_state = STATE_PLAYING

            try:
                new_theme = new['NowPlayingItem']['IsThemeMedia']
            except KeyError:
                new_theme = False

        else:
            new_state = STATE_IDLE
            new_theme = False

        if old_theme or new_theme:
            return False
        elif old_state == STATE_PLAYING or new_state == STATE_PLAYING:
            return True
        elif old_state != new_state:
            return True
        else:
            return False
386766
@Transactional(propagation = Propagation.REQUIRES_NEW)
    public void check() {
        LOGGER.debug("Auto assigned check call");

        final PageRequest pageRequest = PageRequest.of(0, PAGE_SIZE);

        final Page<TargetFilterQuery> filterQueries = targetFilterQueryManagement.findWithAutoAssignDS(pageRequest);

        for (final TargetFilterQuery filterQuery : filterQueries) {
            checkByTargetFilterQueryAndAssignDS(filterQuery);
        }

    }
978914
def setCurrentAction(self, action):
        
        self._actionGroup.blockSignals(True)
        for act in self._actionGroup.actions():
            act.setChecked(act == action or act.text() == action)
        self._actionGroup.blockSignals(False)
238555
public void check(TreePath tp, boolean check) {
        CheckedNode cn = nodesCheckingState.get(tp);
        cn.isSelected = check;
        if (check) {
            checkedPaths.add(tp);
        } else {
            checkedPaths.remove(tp);
        }
        updatePredecessorsAllChildrenSelectedState(tp);
    }
919944
def _can_refresh_check(self, check_id):
        
        try:
            refresh_status = \
                self.conn.describe_trusted_advisor_check_refresh_statuses(
                    checkIds=[check_id]
                )
            logger.debug("TA Check %s refresh status: %s", check_id,
                         refresh_status['statuses'][0])
            ms = refresh_status['statuses'][0]['millisUntilNextRefreshable']
            if ms > 0:
                logger.warning("Trusted Advisor check cannot be refreshed for "
                               "another %d milliseconds; skipping refresh and "
                               "getting check results now", ms)
                return False
            return True
        except Exception:
            logger.warning("Could not get refresh status for TA check %s",
                           check_id, exc_info=True)
        # default to True if we don't know...
        return True