Obtain sleep fragmentation parameter, ie number of stage shifts to 
        a lighter stage.
491947
def slp_frag(self, time=None):
        """"""
        epochs = self.get_epochs(time=time)
        stage_int = {'Wake': 0, 'NREM1': 1, 'NREM2': 2, 'NREM3': 3, 'REM': 2}
        
        hypno_str = [x['stage'] for x in epochs \
                     if x['stage'] in stage_int.keys()]
        hypno_int = [stage_int[x] for x in hypno_str]
        frag = sum(asarray(clip(diff(hypno_int), a_min=None, a_max=0), 
                           dtype=bool))
            
        # N3 to REM doesn't count
        n3_to_rem = 0
        for i, j in enumerate(hypno_str[:-1]):
            if j == 'NREM3':
                if hypno_str[i + 1] == 'REM':
                    n3_to_rem += 1
        
        return frag - n3_to_rem
1108733
async def get_sleep_timer_settings(self) -> List[Setting]:
        """"""
        return [
            Setting.make(**x)
            for x in await self.services["system"]["getSleepTimerSettings"]({})
        ]
335417
def segment(f, output, target_duration, mpegts):
    """"""
    try:
        target_duration = int(target_duration)
    except ValueError:
        exit('Error: Invalid target duration.')

    try:
        mpegts = int(mpegts)
    except ValueError:
        exit('Error: Invalid MPEGTS value.')

    WebVTTSegmenter().segment(f, output, target_duration, mpegts)
1011413
def switch(self, time=None):
        """"""
        stag_to_int = {'NREM1': 1, 'NREM2': 2, 'NREM3': 3, 'REM': 5, 'Wake': 0}
        hypno = [stag_to_int[x['stage']] for x in self.get_epochs(time=time) \
                 if x['stage'] in stag_to_int.keys()]
        
        return sum(asarray(diff(hypno), dtype=bool))
574637
def on_batch_end(self, last_target, train, **kwargs):
        ""
        if train: return
        bs = last_target.size(0)
        for name in self.names:
            self.metrics[name] += bs * self.learn.loss_func.metrics[name].detach().cpu()
        self.nums += bs
192772
def _transition_loop(self):
        """"""
        while self._transitions:
            start = time.time()
            for transition in self._transitions:
                transition.step()
                if transition.finished:
                    self._transitions.remove(transition)

            time_delta = time.time() - start
            sleep_time = max(0, self.MIN_STEP_TIME - time_delta)
            time.sleep(sleep_time)
332704
function () {
    var firstObject = beatmap.hitObjects[0];
    var lastObject  = beatmap.hitObjects[beatmap.hitObjects.length - 1];

    var totalBreakTime = 0;

    beatmap.breakTimes.forEach(function (breakTime) {
      totalBreakTime += (breakTime.endTime - breakTime.startTime);
    });

    if (firstObject && lastObject) {
      beatmap.totalTime    = Math.floor(lastObject.startTime / 1000);
      beatmap.drainingTime = Math.floor((lastObject.startTime - firstObject.startTime - totalBreakTime) / 1000);
    } else {
      beatmap.totalTime    = 0;
      beatmap.drainingTime = 0;
    }
  }
230539
def __stage2(self, img, total_boxes, stage_status:StageStatus):
        

        num_boxes = total_boxes.shape[0]
        if num_boxes == 0:
            return total_boxes, stage_status

        # second stage
        tempimg = np.zeros(shape=(24, 24, 3, num_boxes))

        for k in range(0, num_boxes):
            tmp = np.zeros((int(stage_status.tmph[k]), int(stage_status.tmpw[k]), 3))

            tmp[stage_status.dy[k] - 1:stage_status.edy[k], stage_status.dx[k] - 1:stage_status.edx[k], :] = \
                img[stage_status.y[k] - 1:stage_status.ey[k], stage_status.x[k] - 1:stage_status.ex[k], :]

            if tmp.shape[0] > 0 and tmp.shape[1] > 0 or tmp.shape[0] == 0 and tmp.shape[1] == 0:
                tempimg[:, :, :, k] = cv2.resize(tmp, (24, 24), interpolation=cv2.INTER_AREA)

            else:
                return np.empty(shape=(0,)), stage_status


        tempimg = (tempimg - 127.5) * 0.0078125
        tempimg1 = np.transpose(tempimg, (3, 1, 0, 2))

        out = self.__rnet.feed(tempimg1)

        out0 = np.transpose(out[0])
        out1 = np.transpose(out[1])

        score = out1[1, :]

        ipass = np.where(score > self.__steps_threshold[1])

        total_boxes = np.hstack([total_boxes[ipass[0], 0:4].copy(), np.expand_dims(score[ipass].copy(), 1)])

        mv = out0[:, ipass[0]]

        if total_boxes.shape[0] > 0:
            pick = self.__nms(total_boxes, 0.7, 'Union')
            total_boxes = total_boxes[pick, :]
            total_boxes = self.__bbreg(total_boxes.copy(), np.transpose(mv[:, pick]))
            total_boxes = self.__rerec(total_boxes.copy())

        return total_boxes, stage_status
251813
def NOAJS_metric(bpmn_graph):
    

    activities_count = all_activities_count(bpmn_graph)
    gateways_count = all_gateways_count(bpmn_graph)

    return activities_count + gateways_count
1294793
synchronized Weight getMaximumDuration() {
        if (calcMaxDuration == null) {
            Weight max = WeightFactory.ZERO;
            for (int i = 0, n = intervals.size(); i < n; i++) {
                Object start = intervals.get(i).getStart();
                Map<?, Weight> d = BellmanFord.calcShortestDistances(start,
                        directedGraph, BellmanFord.Mode.SOURCE);
                if (d == null) {
                    throw new IllegalStateException("Negative cycle detected!");
                }
                for (int j = 0; j < n; j++) {
                    Object finish = intervals.get(j).getFinish();
                    max = Weight.max(max, d.get(finish));
                }
            }
            calcMaxDuration = max;
        }

        return calcMaxDuration;
    }
584030
def hourly_values(self):
        """"""
        return [self._dry_bulb_max - self._dry_bulb_range * x for
                x in self.temp_multipliers]
533782
function(range) {
      var stats = {};
      stats.total = 0;

      if (!this.timeSlices)
        return stats;

      function addStatsForSlice(threadTimeSlice) {
        var freqRange = tr.b.Range.fromExplicitRange(threadTimeSlice.start,
            threadTimeSlice.end);
        var intersection = freqRange.findIntersection(range);

        if (threadTimeSlice.schedulingState ==
            tr.model.SCHEDULING_STATE.RUNNING) {
          var cpu = threadTimeSlice.cpuOnWhichThreadWasRunning;
          if (!(cpu.cpuNumber in stats))
            stats[cpu.cpuNumber] = 0;

          stats[cpu.cpuNumber] += intersection.duration;
          stats.total += intersection.duration;
        }
      }

      tr.b.iterateOverIntersectingIntervals(this.timeSlices,
                                            function(x) { return x.start; },
                                            function(x) { return x.end; },
                                            range.min,
                                            range.max,
                                            addStatsForSlice);
      return stats;
    }
843000
def get_stages(self):
        '''
        
        '''
        sequence = self.get_sequence()
        stages = {}
        for seq in self._sequences:
            for e in seq:
                if e.src.get_name() not in stages:
                    stages[e.src.get_name()] = []
                if e.dst.get_name() not in stages[e.src.get_name()]:
                    stages[e.src.get_name()].append(e.dst.get_name())
        return {
            'current': [e.dst.get_name() for e in sequence],
            'stages': stages
        }
620739
public ManagementStage getStage(final int index) {

		if (index >= 0 && index < this.stages.size()) {
			return this.stages.get(index);
		}

		return null;
	}
771276
def cli(ctx, monitor, full, stage):
    """"""
    if not ctx.bubble:
        msg = 'There is no bubble present, will not search stats'
        if monitor:
            ctx.say_yellow('Unknown - ' + msg, 0)
            raise SystemExit(3)
        else:
            ctx.say_yellow(msg)
        raise click.Abort()

    stats = {}
    stats_found = False
    flowing_full = False
    flowing_decrease = False
    flowing_increase = False
    errors = False

    loader = bubble_lod_load(ctx, 'stats', stage)
    lod_gen = _find_lod_gen(ctx, loader)
    if lod_gen:
        last_stats = {}
        ctx.say('lod_gen', stuff=lod_gen)
        for stats_data in lod_gen:
            last_stats = stats_data
        if last_stats:
            ctx.say('found last_stats:', stuff=last_stats, verbosity=10)

    try:
        ctx.say('trying:last stats:', stuff=last_stats, verbosity=10)
        if last_stats:
            l = last_stats
            stats['pull_err'] = k0(l, 'pulled_stat_error_count')
            stats['pull_total'] = k0(l, 'pulled_stat_total_count')

            stats['trans_err'] = k0(l, 'transformed_stat_error_count')
            stats['trans_total'] = k0(l, 'transformed_stat_total_count')

            stats['push_err'] = k0(l, 'pushed_stat_error_count')
            stats['push_total'] = k0(l, 'pushed_stat_total_count')
            stats_found = True
        else:
            stats_found = False

        ctx.say('stats:', stuff=stats, verbosity=10)

        if stats_found and stats['pull_err'] > 0 or \
                stats['trans_err'] > 0 or \
                stats['push_err'] > 0:
            errors = True
        if stats_found and stats['pull_total'] == stats['trans_total'] and \
                stats['trans_total'] == stats['push_total']:
            flowing_full = True
        if stats_found and stats['pull_total'] >= stats['trans_total'] >= stats['push_total']:
            flowing_decrease = True
        if stats_found and stats['pull_total'] <= stats['trans_total'] <= stats['push_total']:
            flowing_increase = True
    except KeyError as stat_key_error:
        errors = True
        ctx.gbc.cry('cannot create status from last stats', stuff=stat_key_error)

    if full:
        ctx.say_yellow('Stats full')
        ctx.say_yellow('Full flow:' + str(flowing_full))
        ctx.say_yellow('Flowing decrease:' + str(flowing_decrease))
        ctx.say_yellow('Flowing increase:' + str(flowing_increase))
        ctx.say_yellow('Errors:' + str(errors))
        ctx.say_yellow('totals:')
        ctx.say_yellow(pf(stats, indent=8))

    if monitor == 'nagios' or full:

        """
        for Numeric Value Service Status Status Description, please see:
        https://nagios-plugins.org/doc/guidelines.html#AEN78
        0 OK The plugin was able to check the service and
          it appeared to be functioning properly
        1 Warning The plugin was able to check the service,
          but it appeared to be above some "warning" threshold or did not appear to be working properly
        2 Critical The plugin detected that either the service was not running or
          it was above some "critical" threshold
        3 Unknown Invalid command line arguments were supplied to the plugin or
          low-level failures internal to the plugin (such as unable to fork, or open a tcp socket)
          that prevent it from performing the specified operation. Higher-level errors (such as name resolution errors,
          socket timeouts, etc) are outside of the control of plugins and
          should generally NOT be reported as UNKNOWN states.

        http://nagios.sourceforge.net/docs/3_0/perfdata.html
        http://nagios.sourceforge.net/docs/3_0/pluginapi.html
        """
        if stats_found:
            templ_nagios = 'pull: %d %d transform: %d  %d push: %d %d '
            res_nagios = templ_nagios % (stats['pull_total'],
                                         stats['pull_err'],
                                         stats['trans_total'],
                                         stats['trans_err'],
                                         stats['push_total'],
                                         stats['push_err']
                                         )
        else:
            res_nagios = 'Cannot find or read stats'

        if not stats_found:
            print('Unknown - ' + res_nagios)
            raise SystemExit(3)
            # return

        if not errors and flowing_full:
            print('Ok - ' + res_nagios)
            return

        # magister and databyte with amount
        if not errors and flowing_decrease:
            print('Ok - ' + res_nagios)
            return

        if not errors and not flowing_full:
            print('Warning - ' + res_nagios)
            raise SystemExit(1)
            # return

        if errors:
            print('Critical - ' + res_nagios)
            raise SystemExit(2)
            # return
    return False
151884
def _adapt_sleep_interval(self, sent, received, queue, now):
        
        Global.LOGGER.debug("adjusting sleep interval")

        dispatched_since_last_check = sent - self.last_queue_check_count
        seconds_since_last_check = (
            now - self.last_queue_check_date).total_seconds()

        Global.LOGGER.debug(
            str(dispatched_since_last_check) + " dispatched in the last " + str(seconds_since_last_check))
        sleep_time = (seconds_since_last_check /
                      (dispatched_since_last_check + queue + 1)) * 0.75

        if sleep_time > 0.5:
            sleep_time = 0.5

        if sleep_time < 0.0001:
            sleep_time = 0.0001

        self.last_queue_check_date = now
        self.last_queue_check_count = sent

        Global.CONFIG_MANAGER.message_fetcher_sleep_interval = sleep_time

        sleep_interval_log_string = f"new sleep_interval = {sleep_time}"
        Global.LOGGER.debug(sleep_interval_log_string)

        if Global.CONFIG_MANAGER.show_stats:
            Global.LOGGER.info(sleep_interval_log_string)
724777
def bbox(self):
        """"""
        bbs = [seg.bbox() for seg in self._segments]
        xmins, xmaxs, ymins, ymaxs = list(zip(*bbs))
        xmin = min(xmins)
        xmax = max(xmaxs)
        ymin = min(ymins)
        ymax = max(ymaxs)
        return xmin, xmax, ymin, ymax