text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.cdn.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/** Metric specification of operation. */
@Fluent
public final class MetricSpecification {
    /*
     * Name of metric specification.
     */
    @JsonProperty(value = "name")
    private String name;

    /*
     * Display name of metric specification.
     */
    @JsonProperty(value = "displayName")
    private String displayName;

    /*
     * Display description of metric specification.
     */
    @JsonProperty(value = "displayDescription")
    private String displayDescription;

    /*
     * The metric unit. Possible values include: 'Bytes', 'Count', 'Milliseconds'.
     */
    @JsonProperty(value = "unit")
    private String unit;

    /*
     * The metric aggregation type. Possible values include: 'Average', 'Count', 'Total'.
     */
    @JsonProperty(value = "aggregationType")
    private String aggregationType;

    /*
     * Retention policies of a resource metric.
     */
    @JsonProperty(value = "availabilities")
    private List<MetricAvailability> availabilities;

    /*
     * The supported time grain types for the metrics.
     */
    @JsonProperty(value = "supportedTimeGrainTypes")
    private List<String> supportedTimeGrainTypes;

    /*
     * The dimensions of metric
     */
    @JsonProperty(value = "dimensions")
    private List<DimensionProperties> dimensions;

    /*
     * Property to specify whether to fill gap with zero.
     */
    @JsonProperty(value = "fillGapWithZero")
    private Boolean fillGapWithZero;

    /*
     * Pattern to filter based on name
     */
    @JsonProperty(value = "metricFilterPattern")
    private String metricFilterPattern;

    /*
     * Property to specify metric is internal or not.
     */
    @JsonProperty(value = "isInternal")
    private Boolean isInternal;

    /**
     * Get the name property: Name of metric specification.
     *
     * @return the name value.
     */
    public String name() {
        return this.name;
    }

    /**
     * Set the name property: Name of metric specification.
     *
     * @param name the name value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get the displayName property: Display name of metric specification.
     *
     * @return the displayName value.
     */
    public String displayName() {
        return this.displayName;
    }

    /**
     * Set the displayName property: Display name of metric specification.
     *
     * @param displayName the displayName value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withDisplayName(String displayName) {
        this.displayName = displayName;
        return this;
    }

    /**
     * Get the displayDescription property: Display description of metric specification.
     *
     * @return the displayDescription value.
     */
    public String displayDescription() {
        return this.displayDescription;
    }

    /**
     * Set the displayDescription property: Display description of metric specification.
     *
     * @param displayDescription the displayDescription value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withDisplayDescription(String displayDescription) {
        this.displayDescription = displayDescription;
        return this;
    }

    /**
     * Get the unit property: The metric unit. Possible values include: 'Bytes', 'Count', 'Milliseconds'.
     *
     * @return the unit value.
     */
    public String unit() {
        return this.unit;
    }

    /**
     * Set the unit property: The metric unit. Possible values include: 'Bytes', 'Count', 'Milliseconds'.
     *
     * @param unit the unit value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withUnit(String unit) {
        this.unit = unit;
        return this;
    }

    /**
     * Get the aggregationType property: The metric aggregation type. Possible values include: 'Average', 'Count',
     * 'Total'.
     *
     * @return the aggregationType value.
     */
    public String aggregationType() {
        return this.aggregationType;
    }

    /**
     * Set the aggregationType property: The metric aggregation type. Possible values include: 'Average', 'Count',
     * 'Total'.
     *
     * @param aggregationType the aggregationType value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withAggregationType(String aggregationType) {
        this.aggregationType = aggregationType;
        return this;
    }

    /**
     * Get the availabilities property: Retention policies of a resource metric.
     *
     * @return the availabilities value.
     */
    public List<MetricAvailability> availabilities() {
        return this.availabilities;
    }

    /**
     * Set the availabilities property: Retention policies of a resource metric.
     *
     * @param availabilities the availabilities value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withAvailabilities(List<MetricAvailability> availabilities) {
        this.availabilities = availabilities;
        return this;
    }

    /**
     * Get the supportedTimeGrainTypes property: The supported time grain types for the metrics.
     *
     * @return the supportedTimeGrainTypes value.
     */
    public List<String> supportedTimeGrainTypes() {
        return this.supportedTimeGrainTypes;
    }

    /**
     * Set the supportedTimeGrainTypes property: The supported time grain types for the metrics.
     *
     * @param supportedTimeGrainTypes the supportedTimeGrainTypes value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withSupportedTimeGrainTypes(List<String> supportedTimeGrainTypes) {
        this.supportedTimeGrainTypes = supportedTimeGrainTypes;
        return this;
    }

    /**
     * Get the dimensions property: The dimensions of metric.
     *
     * @return the dimensions value.
     */
    public List<DimensionProperties> dimensions() {
        return this.dimensions;
    }

    /**
     * Set the dimensions property: The dimensions of metric.
     *
     * @param dimensions the dimensions value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withDimensions(List<DimensionProperties> dimensions) {
        this.dimensions = dimensions;
        return this;
    }

    /**
     * Get the fillGapWithZero property: Property to specify whether to fill gap with zero.
     *
     * @return the fillGapWithZero value.
     */
    public Boolean fillGapWithZero() {
        return this.fillGapWithZero;
    }

    /**
     * Set the fillGapWithZero property: Property to specify whether to fill gap with zero.
     *
     * @param fillGapWithZero the fillGapWithZero value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withFillGapWithZero(Boolean fillGapWithZero) {
        this.fillGapWithZero = fillGapWithZero;
        return this;
    }

    /**
     * Get the metricFilterPattern property: Pattern to filter based on name.
     *
     * @return the metricFilterPattern value.
     */
    public String metricFilterPattern() {
        return this.metricFilterPattern;
    }

    /**
     * Set the metricFilterPattern property: Pattern to filter based on name.
     *
     * @param metricFilterPattern the metricFilterPattern value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withMetricFilterPattern(String metricFilterPattern) {
        this.metricFilterPattern = metricFilterPattern;
        return this;
    }

    /**
     * Get the isInternal property: Property to specify metric is internal or not.
     *
     * @return the isInternal value.
     */
    public Boolean isInternal() {
        return this.isInternal;
    }

    /**
     * Set the isInternal property: Property to specify metric is internal or not.
     *
     * @param isInternal the isInternal value to set.
     * @return the MetricSpecification object itself.
     */
    public MetricSpecification withIsInternal(Boolean isInternal) {
        this.isInternal = isInternal;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (availabilities() != null) {
            availabilities().forEach(e -> e.validate());
        }
        if (dimensions() != null) {
            dimensions().forEach(e -> e.validate());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
Identification of the requirement to run a WebDAV server should be
considered. If it is not required then it should be disabled. However,
if it is required to meet the application functionality, then it
should be protected by SSL/TLS as well as the implementation of a
strong authentication mechanism.


text:
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { CoreConstants, ModPurpose } from '@/core/constants';
import { Injectable, Type } from '@angular/core';
import { CoreModuleHandlerBase } from '@features/course/classes/module-base-handler';
import { CoreCourseModuleData } from '@features/course/services/course-helper';
import { CoreCourseModuleHandler, CoreCourseModuleHandlerData } from '@features/course/services/module-delegate';
import { CoreSitePluginsModuleHandler } from '@features/siteplugins/classes/handlers/module-handler';
import { CoreSitePlugins } from '@features/siteplugins/services/siteplugins';
import { makeSingleton } from '@singletons';
import { AddonModBBBIndexComponent } from '../../components/index';
import { AddonModBBB } from '../bigbluebuttonbn';

export const ADDON_MOD_BBB_MAIN_MENU_PAGE_NAME = 'mod_bigbluebuttonbn';

/**
 * Handler to support Big Blue Button activities.
 */
@Injectable({ providedIn: 'root' })
export class AddonModBBBModuleHandlerService extends CoreModuleHandlerBase implements CoreCourseModuleHandler {

    name = 'AddonModBBB';
    modName = 'bigbluebuttonbn';
    protected pageName = ADDON_MOD_BBB_MAIN_MENU_PAGE_NAME;
    protected sitePluginHandler?: CoreSitePluginsModuleHandler;

    supportedFeatures = {
        [CoreConstants.FEATURE_GROUPS]: true,
        [CoreConstants.FEATURE_GROUPINGS]: true,
        [CoreConstants.FEATURE_MOD_INTRO]: true,
        [CoreConstants.FEATURE_COMPLETION_TRACKS_VIEWS]: true,
        [CoreConstants.FEATURE_GRADE_HAS_GRADE]: false,
        [CoreConstants.FEATURE_GRADE_OUTCOMES]: true,
        [CoreConstants.FEATURE_BACKUP_MOODLE2]: true,
        [CoreConstants.FEATURE_SHOW_DESCRIPTION]: true,
        [CoreConstants.FEATURE_MOD_PURPOSE]: ModPurpose.MOD_PURPOSE_OTHER,
    };

    /**
     * @inheritdoc
     */
    async isEnabled(): Promise<boolean> {
        const enabled = await AddonModBBB.isPluginEnabled();

        if (enabled) {
            delete this.sitePluginHandler;
            this.name = 'AddonModBBB';

            return true;
        }

        // Native support not available in this site. Check if it's supported by site plugin.
        this.sitePluginHandler = CoreSitePlugins.getModuleHandlerInstance(this.modName);
        // Change the handler name to be able to retrieve the plugin data in component.
        this.name = this.sitePluginHandler?.name || this.name;

        return !!this.sitePluginHandler;
    }

    /**
     * @inheritdoc
     */
    async getData(
        module: CoreCourseModuleData,
        courseId: number,
        sectionId?: number,
        forCoursePage?: boolean,
    ): Promise<CoreCourseModuleHandlerData> {
        if (this.sitePluginHandler) {
            return this.sitePluginHandler.getData(module, courseId, sectionId, forCoursePage);
        }

        const data = await super.getData(module, courseId, sectionId, forCoursePage);

        data.showDownloadButton = false;

        return data;
    }

    /**
     * @inheritdoc
     */
    async getMainComponent(): Promise<Type<unknown>> {
        if (this.sitePluginHandler) {
            return this.sitePluginHandler.getMainComponent();
        }

        return AddonModBBBIndexComponent;
    }

}

export const AddonModBBBModuleHandler = makeSingleton(AddonModBBBModuleHandlerService);


text:
import WS from 'ws';
import runLog from './run-log.js';
import crypto from 'crypto';
import { AssertionError } from 'assert';
import Anser from "anser";
import { CordovaBuilder } from '../cordova/builder.js';

export class HMRServer {
  constructor({
    proxy, hmrPath, secret, projectContext, cordovaServerPort
}) {
    this.proxy = proxy;
    this.projectContext = projectContext;

    this.hmrPath = hmrPath;
    this.secret = secret;

    this.wsServer = null;
    this.connByArch = Object.create(null);
    this.started = false;

    this.changeSetsByArch = Object.create(null);

    this.maxChangeSets = 300;
    this.cacheKeys = Object.create(null);
    this.trimmedArchUntil = Object.create(null);
    this.firstBuild = null;

    if (!cordovaServerPort) {
     cordovaServerPort = CordovaBuilder.createCordovaServerPort(
          projectContext.appIdentifier
        );
    }

    this.cordovaOrigin = `http://localhost:${cordovaServerPort}`;
  }

  start() {
    if (!this.proxy.started) {
      throw new Error('Proxy must be started before HMR Server');
    }

    this.wsServer = new WS.Server({
      noServer: true,
    });
    this.proxy.server.on('upgrade', (req, res, head) => {
      if (req.url === this.hmrPath) {
        this.wsServer.handleUpgrade(req, res, head, (conn) => {
          this._handleWsConn(conn, req);
        });
      }
    });

    this.started = true;
  }

  stop() {
    this.wsServer.close();
    this.connByArch = Object.create(null);
  }

  _handleWsConn(conn, req) {
    let registered = false;
    let connArch = null;
    let fromCordova = this.cordovaOrigin && req.headers.origin === this.cordovaOrigin;

    conn.on('message', (_message) => {
      const message = JSON.parse(_message);

      switch (message.type) {
        case 'register': {
          const { arch, appId, secret = '' } = message;

          if (appId !== this.projectContext.appIdentifier) {
            // A different app is trying to request changes
            conn.send(JSON.stringify({
              type: 'register-failed',
              reason: 'wrong-app'
            }));
          }

          let secretsMatch = secret.length === this.secret.length &&
            crypto.timingSafeEqual(Buffer.from(secret), Buffer.from(this.secret));

          if (
            !fromCordova &&
            !secretsMatch
          ) {
            conn.send(JSON.stringify({
              type: 'register-failed',
              reason: 'wrong-secret'
            }));
            conn.close();
            return;
          }

          this.connByArch[arch] = this.connByArch[arch] || [];
          this.connByArch[arch].push(conn);
          connArch = arch;
          registered = true;
          break;
        }

        case 'request-changes': {
          if (!registered) {
            // Might have sent the wrong secret or be the wrong app
            // Even if we closed the connection, it might still handle
            // this message.
            return;
          }
          const { after, arch } = message;

          const trimmedUntil = this.trimmedArchUntil[arch] || Math.Infinity;
          if (trimmedUntil > after) {
            // We've removed changeSets needed for the client to update with HMR
            conn.send(
              JSON.stringify({
                type: 'changes',
                changeSets: [
                  { reloadable: false }
                ]
              })
            );
            return;
          }

          const archChangeSets = this.changeSetsByArch[arch] || [];
          const newChanges = archChangeSets.filter(({ linkedAt }) => {
            return linkedAt > after;
          });

          conn.send(JSON.stringify({
            type: 'changes',
            changeSets: newChanges
          }));

          break;
        }

        default:
          throw new Error(`Unknown HMR message ${message.type}`);
      }
    });

    // TODO: should use pings to detect disconnected sockets
    conn.on('close', () => {
      if (!connArch) {
        return;
      }

      const archConns = this.connByArch[connArch] || [];
      const index = archConns.indexOf(conn);
      if (index > -1) {
        archConns.splice(
          index,
          1
        );
      }
    });
  }

  _sendAll(message) {
    Object.values(this.connByArch).forEach(conns => {
      conns.forEach(conn => {
        conn.send(JSON.stringify(message));
      });
    });
  }

  setAppState(state) {
    if (state === 'error') {
      const lines = runLog.getLog().map(line => {
        return Anser.ansiToHtml(Anser.escapeForHtml(line.message))
      });
      this._sendAll({
        type: 'app-state',
        state: 'error',
        log: lines
      });
    } else if (state === 'okay') {
      this._sendAll({
        type: 'app-state',
        state: 'okay'
      });
    }
  }

  compare({ name, arch, hmrAvailable, files, cacheKey }, getFileOutput) {
    if (this.firstBuild = null) {
      this.firstBuild = Date.now();
    }

    this.changeSetsByArch[arch] = this.changeSetsByArch[arch] || [];
    const previousCacheKey = this.cacheKeys[`${arch}-${name}`];

    if (previousCacheKey === cacheKey) {
      return;
    }

    // Try to do HMR without waiting for the build to finish
    // If it fails, the client will retry after the build finishes so
    // it can fall back to hot code push
    const sendEagerUpdate = (changeset) => {
      if (!this.connByArch[arch]) {
        return;
      }

      this.connByArch[arch].forEach(conn => {
        conn.send(JSON.stringify({
          type: 'changes',
          changeSets: [changeset],
          eager: true
        }));
      });
    }

    this.cacheKeys[`${arch}-${name}`] = cacheKey;
    const previous = this.findLastChangeset(name, arch) || {};

    if (!hmrAvailable) {
      let changeset = {
        name,
        reloadable: false,
        cacheKey,
        // TODO: use more accurate name
        linkedAt: Date.now()
      };
      this.changeSetsByArch[arch].push(changeset);
      this._trimChangeSets(arch);
      sendEagerUpdate(changeset);
      return;
    }

    const {
      addedFiles,
      changedFiles,
      removedFilePaths,
      unreloadable,
      onlyReplaceableChanges,
      fileHashes
    } = this.compareFiles(
      previous.fileHashes,
      previous.unreloadableHashes,
      files
    );

    const couldCompare = !!previous.fileHashes
    const reloadable = couldCompare &&
      onlyReplaceableChanges &&
      removedFilePaths.length === 0;

    function saveFileDetails(file) {
      return {
        content: getFileOutput(file).toStringWithSourceMap({}),
        path: file.absModuleId,
        meteorInstallOptions: file.meteorInstallOptions
      };
    }

    const result = {
      fileHashes,
      unreloadableHashes: unreloadable,
      reloadable,
      addedFiles: reloadable ? addedFiles.map(saveFileDetails) : [],
      changedFiles: reloadable ? changedFiles.map(saveFileDetails) : [],
      linkedAt: Date.now(),
      id: this._createId(),
      name
    };

    // TODO: we should also store the latest change set
    // for each arch and name someplace else so it doesn't
    // get removed when trimming changesets
    this.changeSetsByArch[arch].push(result);
    this._trimChangeSets(arch);

    if (!arch in this.trimmedArchUntil) {
      this.trimmedArchUntil[arch] = this.firstBuild - 1;
    }

    sendEagerUpdate(result);
  }

  _trimChangeSets(arch) {
    if (this.changeSetsByArch[arch].length > this.maxChangeSets) {
      const removed = this.changeSetsByArch[arch].splice(
        0,
        this.changeSetsByArch[arch].length - this.maxChangeSets
      );
      this.trimmedArchUntil[arch] = removed[removed.length - 1].linkedAt;
    }
  }

  _createId() {
    return `${Date.now()}-${Math.random()}`;
  }

  _checkReloadable(file) {
    return file.absModuleId &&
      !file.bare &&
      // TODO: support jsonData
      !file.jsonData &&
      file.meteorInstallOptions
  }

  compareFiles(previousHashes = new Map(), previousUnreloadable = [], currentFiles) {
    const unreloadable = [];
    const currentHashes = new Map();
    const unseenModules = new Map(previousHashes);

    const changedFiles = [];
    const addedFiles = [];
    let onlyReplaceableChanges = true;

    currentFiles.forEach(file => {
      let fileConfig;
      let ignoreHash = false;

      if (file.targetPath !== file.sourcePath && file.implicit) {
        // The import scanner created this file as an alias to the target path
        // This file's content does not change when the hash does, only the
        // content of the new file created at the target path.
        ignoreHash = true;
        fileConfig = JSON.stringify({
          implicit: file.implicit,
          sourcePath: file.sourcePath,
          targetPath: file.targetPath
        });
      } else {
        fileConfig = JSON.stringify({
          meteorInstallOptions: file.meteorInstallOptions,
          absModuleId: file.absModuleId,
          sourceMap: !!file.sourceMap,
          mainModule: file.mainModule,
          imported: file.imported,
          alias: file.alias,
          lazy: file.lazy,
          bare: file.bare
        })
      }

      if (
        !this._checkReloadable(file)
      ) {
        unreloadable.push(`${fileConfig}-${file._inputHash}`);
        return;
      }

      currentHashes.set(file.absModuleId, {
        inputHash: file._inputHash,
        config: fileConfig
      });

      const {
        inputHash: previousInputHash,
        config: previousConfig
      } = previousHashes.get(file.absModuleId) || {};

      if (!previousInputHash) {
        addedFiles.push(file);
      } else if (previousConfig !== fileConfig) {
        onlyReplaceableChanges = false;
      } else if (!ignoreHash && previousInputHash !== file._inputHash) {
        changedFiles.push(file);
      }

      unseenModules.delete(file.absModuleId);
    });

    const removedFilePaths = Array.from(unseenModules.keys());
    if (onlyReplaceableChanges) {
      const unreloadableChanged = unreloadable.length !== previousUnreloadable.length ||
        unreloadable.some((hash, i) => hash !== previousUnreloadable[i]);
      onlyReplaceableChanges = !unreloadableChanged;
    }

    return {
      fileHashes: currentHashes,
      addedFiles,
      changedFiles,
      removedFilePaths,
      unreloadable,
      onlyReplaceableChanges,
    };
  }

  findLastChangeset(name, arch) {
    const changeSets = this.changeSetsByArch[arch] || [];
    for (let i = changeSets.length - 1; i >= 0; i--) {
      if (changeSets[i].name === name) {
        return changeSets[i];
      }
    }
  }
}


text:
import json

from keras.applications.inception_v3 import InceptionV3
from keras.models import Model, model_from_json
from keras.layers import Input, Dense, Dropout, Flatten, GlobalAveragePooling2D
from keras.optimizers import SGD, RMSprop
from keras.regularizers import l2, activity_l2
from keras import regularizers

# load the initial pre-trained model
def build_model(nb_classes):
    initial_model = InceptionV3(weights='imagenet', include_top=False, input_tensor=Input(shape=(3,224,224)))

    last = initial_model.output
    x = Flatten()(last)

    # let's add a fully-connected layer
    x = Dense(1024, activation='relu')(x)
    x = Dropout(0.5)(x)
    predictions = Dense(nb_classes, activation='softmax',  W_regularizer = l2(0.1) )(x)
    model = Model(input=initial_model.input, output=predictions)

    # first we freeze all convolutional InceptionV3 layers
    for layer in initial_model.layers:
        layer.trainable = False

    print "starting model compile"
    compile(model)
    print "model compile done"
    return model

def save(model, tags, prefix):
    model.save_weights(prefix+".h5")
    # serialize model to JSON
    model_json = model.to_json()
    with open(prefix+".json", "w") as json_file:
        json_file.write(model_json)
    with open(prefix+"-labels.json", "w") as json_file:
        json.dump(tags, json_file)

def load(prefix):
    # load json and create model
    with open(prefix+".json") as json_file:
        model_json = json_file.read()
    model = model_from_json(model_json)
    # load weights into new model
    model.load_weights(prefix+".h5")
    with open(prefix+"-labels.json") as json_file:
        tags = json.load(json_file)
    return model, tags

def compile(model):
	model.compile(loss = "categorical_crossentropy", optimizer ="adam", metrics=["accuracy"])


text:
from __future__ import absolute_import, print_function

from datetime import timedelta
from django.utils import timezone

from sentry.models import CheckInStatus, Monitor, MonitorCheckIn, MonitorStatus, MonitorType
from sentry.testutils import TestCase
from sentry.tasks.check_monitors import check_monitors

class CheckMonitorsTest(TestCase):
    def test_missing_checkin(self):
        org = self.create_organization()
        project = self.create_project(organization=org)

        monitor = Monitor.objects.create(
            organization_id=org.id,
            project_id=project.id,
            next_checkin=timezone.now() - timedelta(minutes=1),
            type=MonitorType.CRON_JOB,
            config={"schedule": "* * * * *"},
            status=MonitorStatus.OK,
        )

        check_monitors()

        assert Monitor.objects.filter(id=monitor.id, status=MonitorStatus.ERROR).exists()

    def test_missing_checkin_but_disabled(self):
        org = self.create_organization()
        project = self.create_project(organization=org)

        monitor = Monitor.objects.create(
            organization_id=org.id,
            project_id=project.id,
            next_checkin=timezone.now() - timedelta(minutes=1),
            type=MonitorType.CRON_JOB,
            config={"schedule": "* * * * *"},
            status=MonitorStatus.DISABLED,
        )

        check_monitors()

        assert Monitor.objects.filter(id=monitor.id, status=MonitorStatus.DISABLED).exists()

    def test_missing_checkin_but_pending_deletion(self):
        org = self.create_organization()
        project = self.create_project(organization=org)

        monitor = Monitor.objects.create(
            organization_id=org.id,
            project_id=project.id,
            next_checkin=timezone.now() - timedelta(minutes=1),
            type=MonitorType.CRON_JOB,
            config={"schedule": "* * * * *"},
            status=MonitorStatus.PENDING_DELETION,
        )

        check_monitors()

        assert Monitor.objects.filter(id=monitor.id, status=MonitorStatus.PENDING_DELETION).exists()

    def test_missing_checkin_but_deletion_in_progress(self):
        org = self.create_organization()
        project = self.create_project(organization=org)

        monitor = Monitor.objects.create(
            organization_id=org.id,
            project_id=project.id,
            next_checkin=timezone.now() - timedelta(minutes=1),
            type=MonitorType.CRON_JOB,
            config={"schedule": "* * * * *"},
            status=MonitorStatus.DELETION_IN_PROGRESS,
        )

        check_monitors()

        assert Monitor.objects.filter(
            id=monitor.id, status=MonitorStatus.DELETION_IN_PROGRESS
        ).exists()

    def test_not_missing_checkin(self):
        org = self.create_organization()
        project = self.create_project(organization=org)

        monitor = Monitor.objects.create(
            organization_id=org.id,
            project_id=project.id,
            next_checkin=timezone.now() + timedelta(minutes=1),
            type=MonitorType.CRON_JOB,
            config={"schedule": "* * * * *"},
            status=MonitorStatus.OK,
        )
        MonitorCheckIn.objects.create(
            monitor=monitor, project_id=project.id, status=CheckInStatus.OK
        )

        check_monitors()

        assert Monitor.objects.filter(id=monitor.id, status=MonitorStatus.OK).exists()

    def test_timeout_with_no_future_complete_checkin(self):
        org = self.create_organization()
        project = self.create_project(organization=org)

        current_datetime = timezone.now() - timedelta(hours=24)

        monitor = Monitor.objects.create(
            organization_id=org.id,
            project_id=project.id,
            next_checkin=current_datetime + timedelta(hours=12, minutes=1),
            last_checkin=current_datetime + timedelta(hours=12),
            type=MonitorType.CRON_JOB,
            config={"schedule": "0 0 * * *"},
            status=MonitorStatus.OK,
            date_added=current_datetime,
        )
        checkin = MonitorCheckIn.objects.create(
            monitor=monitor,
            project_id=project.id,
            status=CheckInStatus.IN_PROGRESS,
            date_added=current_datetime,
            date_updated=current_datetime,
        )
        checkin2 = MonitorCheckIn.objects.create(
            monitor=monitor,
            project_id=project.id,
            status=CheckInStatus.IN_PROGRESS,
            date_added=monitor.last_checkin,
            date_updated=monitor.last_checkin,
        )

        assert checkin.date_added == checkin.date_updated == current_datetime

        check_monitors(current_datetime=current_datetime + timedelta(hours=12, minutes=1))

        assert MonitorCheckIn.objects.filter(id=checkin.id, status=CheckInStatus.ERROR).exists()

        assert MonitorCheckIn.objects.filter(
            id=checkin2.id, status=CheckInStatus.IN_PROGRESS
        ).exists()

        assert Monitor.objects.filter(id=monitor.id, status=MonitorStatus.ERROR).exists()

    def test_timeout_with_future_complete_checkin(self):
        org = self.create_organization()
        project = self.create_project(organization=org)

        current_datetime = timezone.now() - timedelta(hours=24)

        monitor = Monitor.objects.create(
            organization_id=org.id,
            project_id=project.id,
            next_checkin=current_datetime + timedelta(hours=12, minutes=1),
            last_checkin=current_datetime + timedelta(hours=12),
            type=MonitorType.CRON_JOB,
            config={"schedule": "0 0 * * *"},
            status=MonitorStatus.OK,
            date_added=current_datetime,
        )
        checkin = MonitorCheckIn.objects.create(
            monitor=monitor,
            project_id=project.id,
            status=CheckInStatus.IN_PROGRESS,
            date_added=current_datetime,
            date_updated=current_datetime,
        )
        checkin2 = MonitorCheckIn.objects.create(
            monitor=monitor,
            project_id=project.id,
            status=CheckInStatus.OK,
            date_added=monitor.last_checkin,
            date_updated=monitor.last_checkin,
        )

        assert checkin.date_added == checkin.date_updated == current_datetime

        check_monitors(current_datetime=current_datetime + timedelta(hours=12, minutes=1))

        assert MonitorCheckIn.objects.filter(id=checkin.id, status=CheckInStatus.ERROR).exists()

        assert MonitorCheckIn.objects.filter(id=checkin2.id, status=CheckInStatus.OK).exists()

        assert Monitor.objects.filter(id=monitor.id, status=MonitorStatus.OK).exists()

    def test_timeout_with_via_configuration(self):
        org = self.create_organization()
        project = self.create_project(organization=org)

        current_datetime = timezone.now() - timedelta(hours=24)

        monitor = Monitor.objects.create(
            organization_id=org.id,
            project_id=project.id,
            next_checkin=current_datetime + timedelta(hours=1, minutes=1),
            last_checkin=current_datetime + timedelta(hours=1),
            type=MonitorType.CRON_JOB,
            config={"schedule": "0 0 * * *", "max_runtime": 60},
            status=MonitorStatus.OK,
            date_added=current_datetime,
        )
        checkin = MonitorCheckIn.objects.create(
            monitor=monitor,
            project_id=project.id,
            status=CheckInStatus.IN_PROGRESS,
            date_added=current_datetime,
            date_updated=current_datetime,
        )

        assert checkin.date_added == checkin.date_updated == current_datetime

        check_monitors(current_datetime=current_datetime + timedelta(hours=1, minutes=1))

        assert MonitorCheckIn.objects.filter(id=checkin.id, status=CheckInStatus.ERROR).exists()

        assert Monitor.objects.filter(id=monitor.id, status=MonitorStatus.ERROR).exists()


text:
package fs

import (
	"github.com/opencontainers/runc/libcontainer/cgroups"
	"github.com/opencontainers/runc/libcontainer/configs"
)

type PerfEventGroup struct{}

func (s *PerfEventGroup) Name() string {
	return "perf_event"
}

func (s *PerfEventGroup) Apply(path string, d *cgroupData) error {
	return join(path, d.pid)
}

func (s *PerfEventGroup) Set(_ string, _ *configs.Resources) error {
	return nil
}

func (s *PerfEventGroup) GetStats(path string, stats *cgroups.Stats) error {
	return nil
}


text:
package com.garrapeta.jumplings.ui.preferences;

import android.os.Bundle;
import android.preference.PreferenceActivity;

import com.garrapeta.jumplings.JumplingsApplication;
import com.garrapeta.jumplings.R;
import com.garrapeta.jumplings.util.FlurryHelper;

/**
 * Actividad de preferencias
 *
 * @author GaRRaPeTa
 */
public class PreferencesActivity extends PreferenceActivity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        if (JumplingsApplication.isDebugBuild(this)) {
            addPreferencesFromResource(R.xml.preferences_debug);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        FlurryHelper.onStartSession(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        FlurryHelper.onEndSession(this);
    }
}


text:
@implementation ZFQDocument

- (instancetype)initWithDocInfo:(NSDictionary *)docInfo
{
    self = [super init];
    if (self) {
        self.name = docInfo[@"file_name"];

        NSNumber *sizeNum = docInfo[@"file_size"];
        self.fileSize = sizeNum.doubleValue;

        NSString *extention = [self.name pathExtension];

        if ([extention rangeOfString:@"doc"].length > 0) {  //doc docx
            self.documentType = ZFQDocumentTypeDOC;
        } else if ([extention rangeOfString:@"ppt"].length > 0) {   //ppt pptx
            self.documentType = ZFQDocumentTypePPT;
        } else if ([extention rangeOfString:@"xls"].length > 0) {   //xls xlsx
            self.documentType = ZFQDocumentTypeXLS;
        } else if ([extention isEqualToString:@"pdf"]) {
            self.documentType = ZFQDocumentTypePDF;
        } else if ([extention isEqualToString:@"txt"]) {
            self.documentType = ZFQDocumentTypeTXT;
        } else {
            self.documentType = ZFQDocumentTypeOther;
        }

    }
    return self;
}

- (NSString *)docPath
{
    NSString *path = [ZFQGeneralService documentURLString];
    //创建doc文件夹
    NSString *docPath = [path stringByAppendingPathComponent:@"doc"];
    //判断doc文件夹是否存在
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = NO;
    BOOL result = [fileManager fileExistsAtPath:docPath isDirectory:&isDirectory];
    if (isDirectory == YES) {
        return docPath;
    } else {
        result = [fileManager createDirectoryAtPath:docPath withIntermediateDirectories:NO attributes:nil error:NULL];
        if (result == YES) {
            return docPath;
        } else {
            return nil;
        }
    }
}

- (NSURL *)previewItemURL
{
//    NSString *docPath = [self docPath];
//    if (docPath != nil) {
        //判断文件是否存在
//        NSString *filePath
        NSString *filePath = [ZFQGeneralService docFilePathWithName:self.name];
//        NSString *filePath = [docPath stringByAppendingPathComponent:self.name];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL result = [fileManager fileExistsAtPath:filePath isDirectory:NULL];
        if (result == YES) {
            return [NSURL fileURLWithPath:filePath];
        } else {
            return nil;
        }
//    } else {
//        return nil;
//    }
}

- (NSString *)previewItemTitle
{
    return self.name;
}
@end


text:
// https://www.hackerrank.com/challenges/java-exception-handling
class MyCalculator {
    /*
    * Create the method long power(int, int) here.
    */
    public long power(int n, int p) throws Exception {
        if (n == 0 && p == 0)
            throw new Exception("n and p should not be zero.");
        if (n < 0 || p < 0)
            throw new Exception("n or p should not be negative.");
        return (long) Math.pow(n, p);
    }
}


text:
/* $Id$ */

/*
 * Copyright (c) 2010-2011 SURFnet bv
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of SURFnet bv nor the names of its contributors
 *    may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

/*
 * The Extensible Ethernet Monitor (EEMO)
 * DNS query packet handling
 */

#include "config.h"
#include <stdlib.h>
#include <string.h>
#include "eemo.h"
#include "utlist.h"
#include "eemo_handlefactory.h"
#include "eemo_log.h"
#include "udp_handler.h"
#include "tcp_handler.h"
#include "dns_handler.h"
#include "dns_parser.h"
#include "dns_types.h"

/* The linked list of DNS query handlers */
static eemo_dns_handler* dns_handlers = NULL;

/* UDP and TCP DNS handler handles */
static unsigned long udp_dns_in_handler_handle = 0;
static unsigned long udp_dns_out_handler_handle = 0;
static unsigned long tcp_dns_in_handler_handle = 0;
static unsigned long tcp_dns_out_handler_handle = 0;

/* DNS parser flags */
static unsigned long dns_parser_flags = PARSE_NONE;

/* Handle DNS payload */
eemo_rv eemo_handle_dns_payload(eemo_packet_buf* packet, eemo_ip_packet_info ip_info, int is_tcp, unsigned short udp_len, int is_fragmented)
{
	eemo_rv			rv 		= ERV_SKIPPED;
	eemo_dns_handler*	handler_it 	= NULL;
	eemo_dns_packet		dns_packet;

	/* Parse the packet */
	rv = eemo_parse_dns_packet(packet, &dns_packet, dns_parser_flags, udp_len, is_fragmented);

	if ((rv == ERV_OK) || (rv == ERV_PARTIAL))
	{
		/* Call the registerd handlers with this packet */
		LL_FOREACH(dns_handlers, handler_it)
		{
			eemo_rv handler_rv = ERV_SKIPPED;

			handler_rv = (handler_it->handler_fn)(ip_info, is_tcp, &dns_packet);

			if (rv != ERV_HANDLED)
			{
				rv = handler_rv;
			}
		}
	}
	else
	{
		switch(rv)
		{
		case ERV_DNS_NAME_LOOPS:
			WARNING_MSG("DNS message from %s to %s contains a looping DNS name", ip_info.ip_src, ip_info.ip_dst);
			break;
		default:
			break;
		}
	}

	eemo_free_dns_packet(&dns_packet);

	return rv;
}

/* Handle a UDP DNS packet */
eemo_rv eemo_handle_dns_udp_packet(eemo_packet_buf* packet, eemo_ip_packet_info ip_info, u_short srcport, u_short dstport, u_short length)
{
	/* Skip packets that are not coming from or going to port 53 */
	if ((srcport != DNS_PORT) && (dstport != DNS_PORT)) return ERV_SKIPPED;

	return eemo_handle_dns_payload(packet, ip_info, 0, length, ip_info.is_fragment);
}

/* Handle a TCP DNS packet */
eemo_rv eemo_handle_dns_tcp_packet(eemo_packet_buf* packet, eemo_ip_packet_info ip_info, eemo_tcp_packet_info tcp_info)
{
	eemo_packet_buf* dns_data = NULL;
	eemo_rv rv = ERV_OK;
	u_short dns_length = 0;

	/* Skip packets that are not coming from or going to port 53 */
	if ((tcp_info.srcport != DNS_PORT) && (tcp_info.dstport != DNS_PORT)) return ERV_SKIPPED;

	/* Skip SYN, RST and FIN packets */
	if (FLAG_SET(tcp_info.flags, TCP_SYN) ||
	    FLAG_SET(tcp_info.flags, TCP_RST) ||
	    FLAG_SET(tcp_info.flags, TCP_FIN))
	{
		return ERV_SKIPPED;
	}

	/* Check minimal length */
	if (packet->len < 2)
	{
		/* Malformed packet */
		return ERV_MALFORMED;
	}

	/* Take length field */
	dns_length = ntohs(*((u_short*) packet->data));

	/* Check length */
	if ((packet->len - 2) != dns_length)
	{
		/* Packet data is truncated and we currently don't do reassembly */
		return ERV_MALFORMED;
	}

	dns_data = eemo_pbuf_new(&packet->data[2], packet->len - 2);

	if (dns_data == NULL)
	{
		/* Out of memory! */
		return ERV_MEMORY;
	}

	rv = eemo_handle_dns_payload(dns_data, ip_info, 1, 0, 0);

	eemo_pbuf_free(dns_data);

	return rv;
}

/* Register a DNS handler */
eemo_rv eemo_reg_dns_handler(eemo_dns_handler_fn handler_fn, unsigned long parser_flags, unsigned long* handle)
{
	eemo_dns_handler* new_handler = NULL;

	/* Check parameters */
	if ((handler_fn == NULL) || (handle == NULL))
	{
		return ERV_PARAM_INVALID;
	}

	/* Create a new handler entry */
	new_handler = (eemo_dns_handler*) malloc(sizeof(eemo_dns_handler));

	if (new_handler == NULL)
	{
		/* Not enough memory */
		return ERV_MEMORY;
	}

	new_handler->handler_fn = handler_fn;
	new_handler->handle = eemo_get_new_handle();

	/* Update parser flags */
	dns_parser_flags |= parser_flags;

	/* Register the new handler */
	LL_APPEND(dns_handlers, new_handler);

	*handle = new_handler->handle;

	DEBUG_MSG("Registered DNS handler with handle 0x%08X and handler function at 0x%08X", *handle, handler_fn);

	return ERV_OK;
}

/* Unregister a DNS handler */
eemo_rv eemo_unreg_dns_handler(unsigned long handle)
{
	eemo_dns_handler* to_delete = NULL;

	LL_SEARCH_SCALAR(dns_handlers, to_delete, handle, handle);

	if (to_delete != NULL)
	{
		LL_DELETE(dns_handlers, to_delete);

		DEBUG_MSG("Unregistered DNS handler with handle 0x%08X and handler function at 0x%08X", handle, to_delete->handler_fn);

		free(to_delete);

		eemo_recycle_handle(handle);

		return ERV_OK;
	}
	else
	{
		return ERV_NOT_FOUND;
	}
}

/* Initialise DNS query handling */
eemo_rv eemo_init_dns_handler(void)
{
	eemo_rv rv = ERV_OK;
	dns_handlers = NULL;
	dns_parser_flags = PARSE_NONE;

	/* Register UDP packet handlers */
	rv = eemo_reg_udp_handler(UDP_ANY_PORT, UDP_ANY_PORT, &eemo_handle_dns_udp_packet, &udp_dns_in_handler_handle);

	if (rv != ERV_OK)
	{
		return rv;
	}

	/* Register DNS packet handler */
	rv = eemo_reg_tcp_handler(TCP_ANY_PORT, TCP_ANY_PORT, &eemo_handle_dns_tcp_packet, &tcp_dns_in_handler_handle);

	if (rv != ERV_OK)
	{
		eemo_unreg_udp_handler(udp_dns_in_handler_handle);
		eemo_unreg_udp_handler(udp_dns_out_handler_handle);

		return rv;
	}

	INFO_MSG("Initialised DNS query handling");

	return rv;
}

/* Clean up */
void eemo_dns_handler_cleanup(void)
{
	eemo_dns_handler* handler_it = NULL;
	eemo_dns_handler* handler_tmp = NULL;

	/* Clean up list of DNS query handlers */
	LL_FOREACH_SAFE(dns_handlers, handler_it, handler_tmp)
	{
		LL_DELETE(dns_handlers, handler_it);

		free(handler_it);
	}

	/* Unregister the DNS UDP and TCP handler */
	eemo_unreg_udp_handler(udp_dns_in_handler_handle);
	eemo_unreg_udp_handler(udp_dns_out_handler_handle);
	eemo_unreg_tcp_handler(tcp_dns_in_handler_handle);
	eemo_unreg_tcp_handler(tcp_dns_out_handler_handle);

	INFO_MSG("Uninitialised DNS query handling");
}


text:
"use strict";

angular

.module("yoda.routes", ["ui.router"])

.config(function config($stateProvider) {
    $stateProvider
        .state("home", {
            url: "/",
            views: {
                "main@": {
                    templateUrl: "home/tpls/content.tpl.html",
                    controller: "yoda.home.controllers.profile"
                }
            }
        });
});


text:
from django.contrib import admin
from guardian.admin import GuardedModelAdmin
from profiles.models import Profile

admin.site.register(Profile, GuardedModelAdmin)


text:
// Copyright © 2010-2016 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

namespace CefSharp
{
    public interface IFocusHandler
    {
        /// <summary>
        /// Called when the browser component has received focus.
        /// </summary>
        void OnGotFocus();

        /// <summary>
        /// Called when the browser component is requesting focus.
        /// </summary>
        /// <param name="source">Indicates where the focus request is originating from.</param>
        /// <returns>Return false to allow the focus to be set or true to cancel setting the focus.</returns>
        bool OnSetFocus(CefFocusSource source);

        /// <summary>
        /// Called when the browser component is about to lose focus.
        /// For instance, if focus was on the last HTML element and the user pressed the TAB key.
        /// </summary>
        /// <param name="next">Will be true if the browser is giving focus to the next component
        /// and false if the browser is giving focus to the previous component.</param>
        void OnTakeFocus(bool next);
    }
}


text:
<?php
	## Set the timezone to your location
	ini_set("date.timezone", "America/Chicago");

	require_once('includes/connection.php');
	require_once('includes/utility_funcs.php');

	set_include_path('includes');
	# Install PSR-0-compatible class autoloader
	spl_autoload_register(function($class){
		require preg_replace('{\\\\|_(?!.*\\\\)}', DIRECTORY_SEPARATOR, ltrim($class, '\\')).'.php';
	});
	# Get Markdown class
	use \Michelf\MarkdownExtra;

	// create database connection
	$conn = dbConnect('read');

	//prepare sql
	$sql = "SELECT title, page_content, html_content, DATE_FORMAT( created,  '%W, %M %e, %Y' ) AS created_date, filename, caption, category FROM php_pages
		LEFT JOIN php_images
		USING (image_id)
		JOIN php_categories
		USING (cat_id)
		WHERE php_pages.page_id = 4";

	$result = $conn->query($sql);
	$row = $result->fetch_assoc();

	//prepare sql for random post
	$sql = "SELECT filename, title, postername FROM php_videos
			ORDER BY RAND()
			LIMIT 1";

	$rand = $conn->query($sql);
	$randRow = $rand->fetch_assoc();

	$title_section = "Home";
	include('includes/title-page-name.php');
	include('includes/header.php');
?>

<?php if ($row) {
				echo $row['title'];
				} else {
				echo 'No record found';
				} ?>

				<?php
			if ($row && !empty($row['filename'])) {
				$filename = "/images/{$row['filename']}";
				$imageSize = getimagesize($_SERVER['DOCUMENT_ROOT'] . $filename);
			 ?>

			 	<img src="<?php echo $filename; ?>" alt="<?php echo $row['caption']; ?>" <?php echo $imageSize[3]; ?>>

<?php echo $row['caption']; ?>

			<?php } if ($row) {
				$htmleArticle = htmlentities($row['page_content'], ENT_COMPAT, 'utf-8');
				echo MarkdownExtra::defaultTransform($htmleArticle);
				if ($row['html_content']) echo $row['html_content'];
			} ?>

		<?php
		include('includes/footer.php');
		?>


text:
import { createReducer }     from '../utils/redux';
import APIClient from '../utils/APIClient';
import {repoName} from '../utils/github';
import {REHYDRATE_COMPLETE} from 'redux-persist/constants';

const assign = Object.assign;

const client = new APIClient();

// Action types
const ns = 'sir/should-i-release';
export const LOAD = `${ns}/LOAD`;
export const LOAD_SUCCESS = `${ns}/LOAD_SUCCESS`;
export const LOAD_FAIL = `${ns}/LOAD_FAIL`;

export const REMOVE = `${ns}/REMOVE`;
export const REMOVE_ALL = `${ns}/REMOVE_ALL`;

export const REFRESH_START = `${ns}/REFRESH_START`;
export const REFRESH_ALL_START = `${ns}/REFRESH_ALL_START`;

export const DISMISS_ERROR = `${ns}/DISMISS_ERROR`;

// Reducer

const initialState = {
  error: null,
  // Each result is an object of the form
  // {
  //   username: <string>,
  //   repo: <string>,
  //   shouldRelease: <bool>,
  //   latestTag: <string>,
  //   aheadBy: <bool>,
  //   requestPending: <bool>,
  //   lastUpdated: <Date>
  // }
  results: []
};

/**
 * Helper to return an updated array of SIR results.
 * Does not modify results in-place.
 *
 * @return array Array of updated results
 */
function updatedResults(oldResults, username, repo, data) {
  return oldResults.map((result) => {
    // Use repo name as unique identifier
    if (repoName(username, repo, true) === repoName(result.username, result.repo, true)) {
      return assign({}, result, data);
    } else {
      return result;
    }
  });
}

/**
 * Find first result that matches the given username and repo
 */
function findResult(results, username, repo) {
  for (let i = 0, len = results.length; i < len; i++) {
    const result = results[i];
    if (repoName(result.username, result.repo, true) === repoName(username, repo, true)) {
      return result;
    }
  }
}

export default createReducer(initialState, {
  [LOAD]: (state, {username, repo}) => {
    const inList = (username && repo && state.results.filter((result) => {
      return repoName(result.username, result.repo) === repoName(username, repo);
    }).length);
    // Add new result if repo isn't in list
    if (!inList) {
      const result = {
        username: username,
        repo: repo,
        aheadBy: null,
        shouldRelease: null,
        requestPending: true,
        latestTag: null,
        lastUpdated: null
      };
      return assign({}, state, {
        results: [
          result,
          ...state.results
        ]
      });
    } else {
      // Move the existing result in front of all the others
      const oldResult = findResult(state.results, username, repo);
      const rest = state.results.filter((result) => {
        return repoName(result.username, result.repo, true) !== repoName(username, repo, true);
      });
      // Also set requestPending to true
      const newResults = [
        assign({}, oldResult, {requestPending: true}),
        ...rest
      ];
      return assign({}, state, {
        results: newResults
      });
    }
  },
  [LOAD_SUCCESS]: (state, {username, repo, response}) => {
    return assign({}, state, {
      results: updatedResults(state.results, username, repo,
        {
          requestPending: false,
          shouldRelease: response.should_release,
          aheadBy: response.ahead_by,
          latestTag: response.latest_tag,
          lastUpdated: new Date()
        }
      )
    });
  },
  [LOAD_FAIL]: (state, {error, username, repo}) => {
    return assign({}, state, {
      error: {
        error,
        username,
        repo
      },
      // Remove result that errored
      results: state.results.filter((result) => {
        return repoName(username, repo, true) !== repoName(result.username, result.repo, true);
      })
    });
  },
  [REMOVE]: (state, {username, repo}) => {
    return assign({}, state, {
      results: state.results.filter((result) => {
        return repoName(username, repo, true) !== repoName(result.username, result.repo, true);
      })
    });
  },
  [DISMISS_ERROR]: (state) => {
    return assign({}, state, {
      error: null
    });
  },
  [REMOVE_ALL]: (state) => {
    return assign({}, state, {
      results: [],
      error: null
    });
  },
  [REFRESH_START]: (state, {username, repo}) => {
    return assign({}, state, {
      results: updatedResults(state.results, username, repo, {
        requestPending: true,
      })
    });
  },
  [REFRESH_ALL_START]: (state) => { return state; },
  [REHYDRATE_COMPLETE]: (state) => {
    // Clear error when reloading state from local storage
    return assign({}, state, {error: null});
  },
});

// Actions

function request(username, repo) {
  return {
    type: LOAD, payload: {username, repo}
  };
}

function success(username, repo, response) {
  return {
    type: LOAD_SUCCESS, payload: {username, repo, response}
  };
}

function fail(error, username, repo) {
  return {
    type: LOAD_FAIL, payload: {error, username, repo}
  };
}

export function fetch(username, repo) {
  return (dispatch) => {
    dispatch(request(username, repo));
    client.get(`/should_i_release/${username}/${repo}/`)
      .then((res) => {
        dispatch(success(username, repo, res));
      })
      .catch((err) => {
        dispatch(fail(err, username, repo));
      });
  };
}

function refreshStart(username, repo) {
  return {type: REFRESH_START, payload: {username, repo}};
}

export function refresh(username, repo) {
  return (dispatch) => {
    dispatch(refreshStart(username, repo));
    client.get(`/should_i_release/${username}/${repo}/`)
      .then((res) => {
        dispatch(success(username, repo, res));
      })
      .catch((err) => {
        dispatch(fail(err, username, repo));
      });
  };
}

export function remove(username, repo) {
  return {
    type: REMOVE, payload: {username, repo}
  };
}

export function removeAll() {
  return {type: REMOVE_ALL};
}

export function dismissError() {
  return {type: DISMISS_ERROR};
}

function refreshAllStart() {
  return {type: REFRESH_ALL_START};
}

export function refreshAll() {
  return (dispatch, getState) => {
    dispatch(refreshAllStart());
    const {shouldIRelease} = getState();
    const {results} = shouldIRelease;
    results.forEach((result) => {
      dispatch(refresh(result.username, result.repo));
    });
  };
}


text:
var net = require('net');
var Agent = require('smith').Agent;
var Transport = require('smith').Transport;

// Create our client agent.
var agent = new Agent();

var backoff = 1000;
var add;

// Query the API to test the connection
function query() {
  var a = Math.floor(Math.random() * 10) + 1;
  var b = Math.floor(Math.random() * 10) + 1;
  console.log("%s + %s = ...", a, b);
  add(a, b, function (err, result) {
    if (err) console.error(err.stack);
    else console.log("%s + %s = %s", a, b, result);
  });
}

// On the first connect, store a reference to the add function and start
// calling it on an interval
agent.once("connect", function (api) {
  add = api.add;
  console.log("Running query() every 3000 ms");
  setInterval(query, 3000);
  query();
});

// On every connect, log the connection and reset the backoff time.
agent.on("connect", function () {
  console.log("Connected!");
  if (backoff > 1000) {
    console.log(" Resetting backoff to 1000ms.");
    backoff = 1000;
  }
});

// Set up auto-reconnect and do initial connection
agent.on("disconnect", onError);
connect();

function connect() {
  var socket = net.connect(1337, function () {
    agent.connect(new Transport(socket));
  });
  socket.on("error", onError);
}

function onError(err) {
  if (err) console.error(err.stack);
  console.log("Reconnecting in %s ms", backoff);
  setTimeout(connect, backoff);
  backoff *= 2;
}