text:
import {Mastery} from './Mastery';

export class Page {
  public sums: number[] = [0, 0, 0];
  public max: number = 30;
  public masteries: Mastery[] = [];
  public rank: any = {};
  constructor(public name: string) { }

  addMastery(id: number, category: number) {
    const mastery = this.masteries.filter(mastery => mastery.id === id)[0];

    if (typeof mastery === 'undefined') {
      this.masteries.push(new Mastery(id, 1));
      this.rank[id] = 1;
    } else {
      this.updateMastery(1, mastery);
    }

    this.updateCounters(1, category);
  }

  removeMastery(id: number, category: number) {
    const mastery = this.masteries.filter(mastery => mastery.id === id)[0];

    if (mastery.rank > 1) {
      this.updateMastery(-1, mastery);
    } else {
      const index = this.masteries.indexOf(mastery);

      this.masteries.splice(index, 1);
      delete this.rank[id];
    }

    this.updateCounters(-1, category);
  }

  updateCounters(ammount: number, category: number): void {
    this.sums[category - 1] += ammount;
    this.max -= ammount;
  }

  updateMastery(ammount:number, mastery: Mastery): void {
    mastery.rank += ammount;
    this.rank[mastery.id] += ammount;
  }
}


text:
package org.apache.ambari.server.controller.internal;

import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;

import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.controller.AmbariManagementController;
import org.apache.ambari.server.controller.ConfigurationRequest;
import org.apache.ambari.server.controller.ConfigurationResponse;
import org.apache.ambari.server.controller.spi.NoSuchParentResourceException;
import org.apache.ambari.server.controller.spi.NoSuchResourceException;
import org.apache.ambari.server.controller.spi.Predicate;
import org.apache.ambari.server.controller.spi.Request;
import org.apache.ambari.server.controller.spi.RequestStatus;
import org.apache.ambari.server.controller.spi.Resource;
import org.apache.ambari.server.controller.spi.ResourceAlreadyExistsException;
import org.apache.ambari.server.controller.spi.SystemException;
import org.apache.ambari.server.controller.spi.UnsupportedPropertyException;
import org.apache.ambari.server.controller.utilities.PropertyHelper;
import org.apache.ambari.server.security.authorization.AuthorizationException;
import org.apache.ambari.server.security.authorization.RoleAuthorization;

/**
 * Resource provider for configuration resources.
 */
public class ConfigurationResourceProvider extends
    AbstractControllerResourceProvider {

  private static final Pattern PROPERTIES_ATTRIBUTES_PATTERN = Pattern.compile("^"
      + PROPERTIES_ATTRIBUTES_REGEX);

  // ----- Property ID constants ---------------------------------------------
  protected static final String CONFIGURATION_CLUSTER_NAME_PROPERTY_ID = PropertyHelper.getPropertyId("Config", "cluster_name");
  protected static final String CONFIGURATION_STACK_ID_PROPERTY_ID = PropertyHelper.getPropertyId("Config", "stack_id");

  // !!! values are part of query strings and body post, so they
  // don't have defined categories (like Config)
  public static final String CONFIGURATION_CONFIG_TYPE_PROPERTY_ID = PropertyHelper.getPropertyId(null, "type");
  public static final String CONFIGURATION_CONFIG_TAG_PROPERTY_ID = PropertyHelper.getPropertyId(null, "tag");
  public static final String CONFIGURATION_CONFIG_VERSION_PROPERTY_ID = PropertyHelper.getPropertyId(null, "version");

  /**
   * The property ids for a configuration resource.
   */
  private static final Set<String> PROPERTY_IDS = new HashSet<>();

  /**
   * The key property ids for a configuration resource.
   */
  private static final Map<Resource.Type, String> KEY_PROPERTY_IDS = new HashMap<>();

  static {
    // properties
    PROPERTY_IDS.add(CONFIGURATION_CLUSTER_NAME_PROPERTY_ID);
    PROPERTY_IDS.add(CONFIGURATION_STACK_ID_PROPERTY_ID);
    PROPERTY_IDS.add(CONFIGURATION_CONFIG_TYPE_PROPERTY_ID);
    PROPERTY_IDS.add(CONFIGURATION_CONFIG_TAG_PROPERTY_ID);
    PROPERTY_IDS.add(CONFIGURATION_CONFIG_VERSION_PROPERTY_ID);

    // keys
    KEY_PROPERTY_IDS.put(Resource.Type.Configuration,CONFIGURATION_CONFIG_TYPE_PROPERTY_ID);
    KEY_PROPERTY_IDS.put(Resource.Type.Cluster,CONFIGURATION_CLUSTER_NAME_PROPERTY_ID);
  }

  /**
   * The primary key property ids for the configuration resource type.
   */
  private static Set<String> pkPropertyIds =
    new HashSet<>(Arrays.asList(new String[]{
      CONFIGURATION_CLUSTER_NAME_PROPERTY_ID,
      CONFIGURATION_CONFIG_TYPE_PROPERTY_ID}));

  // ----- Constructors ------------------------------------------------------

  /**
   * Constructor
   *
   * @param managementController  the associated management controller
   */
  ConfigurationResourceProvider(AmbariManagementController managementController) {
    super(PROPERTY_IDS, KEY_PROPERTY_IDS, managementController);

    // creating configs requires authorizations based on the type of changes being performed, therefore
    // checks need to be performed inline.
    // update and delete are not supported for configs

    setRequiredGetAuthorizations(EnumSet.of(RoleAuthorization.CLUSTER_VIEW_CONFIGS));
  }

  // ----- ResourceProvider --------------------------------------------------

  @Override
  public RequestStatus createResources(Request request)
      throws SystemException,
             UnsupportedPropertyException,
             ResourceAlreadyExistsException,
             NoSuchParentResourceException {

    for (Map<String, Object> map : request.getProperties()) {
      String cluster = (String) map.get(CONFIGURATION_CLUSTER_NAME_PROPERTY_ID);
      String type = (String) map.get(CONFIGURATION_CONFIG_TYPE_PROPERTY_ID);
      String tag  = (String) map.get(CONFIGURATION_CONFIG_TAG_PROPERTY_ID);

      Map<String, String> configMap = new HashMap<>();
      Map<String, Map<String, String>> configAttributesMap = null;

      for (Entry<String, Object> entry : map.entrySet()) {
        String propertyCategory = PropertyHelper.getPropertyCategory(entry.getKey());
        if (propertyCategory != null && propertyCategory.equals("properties") && null != entry.getValue()) {
          configMap.put(PropertyHelper.getPropertyName(entry.getKey()), entry.getValue().toString());
        }
        if (propertyCategory != null
            && PROPERTIES_ATTRIBUTES_PATTERN.matcher(propertyCategory).matches()
            && null != entry.getValue()) {
          if (null == configAttributesMap) {
            configAttributesMap = new HashMap<>();
          }
          String attributeName = propertyCategory.substring(propertyCategory.lastIndexOf('/') + 1);
          Map<String, String> attributesMap = configAttributesMap.get(attributeName);
          if (attributesMap == null) {
            attributesMap = new HashMap<>();
            configAttributesMap.put(attributeName, attributesMap);
          }
          attributesMap.put(PropertyHelper.getPropertyName(entry.getKey()), entry.getValue().toString());
        }
      }

      final ConfigurationRequest configRequest = new ConfigurationRequest(cluster, type, tag, configMap, configAttributesMap);

      createResources(new Command<Void>() {
        @Override
        public Void invoke() throws AmbariException, AuthorizationException {
          getManagementController().createConfiguration(configRequest);
          return null;
        }
      });

    }
    return getRequestStatus(null);
  }

  @Override
  public Set<Resource> getResourcesAuthorized(Request request, Predicate predicate)
    throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {

    final Set<ConfigurationRequest> requests = new HashSet<>();

    for (Map<String, Object> propertyMap : getPropertyMaps(predicate)) {
      requests.add(getRequest(request, propertyMap));
    }

    Set<ConfigurationResponse> responses = getResources(new Command<Set<ConfigurationResponse>>() {
      @Override
      public Set<ConfigurationResponse> invoke() throws AmbariException {
        return getManagementController().getConfigurations(requests);
      }
    });

    Set<Resource> resources = new HashSet<>();
    for (ConfigurationResponse response : responses) {
      // don't use the StackId object here; we just want the stack ID string
      String stackId = response.getStackId().getStackId();

      Resource resource = new ResourceImpl(Resource.Type.Configuration);
      resource.setProperty(CONFIGURATION_CLUSTER_NAME_PROPERTY_ID, response.getClusterName());
      resource.setProperty(CONFIGURATION_STACK_ID_PROPERTY_ID, stackId);
      resource.setProperty(CONFIGURATION_CONFIG_TYPE_PROPERTY_ID, response.getType());
      resource.setProperty(CONFIGURATION_CONFIG_TAG_PROPERTY_ID, response.getVersionTag());
      resource.setProperty(CONFIGURATION_CONFIG_VERSION_PROPERTY_ID, response.getVersion());

      if (null != response.getConfigs() && response.getConfigs().size() > 0) {
        Map<String, String> configs = response.getConfigs();

        for (Entry<String, String> entry : configs.entrySet()) {
          String id = PropertyHelper.getPropertyId("properties", entry.getKey());
          resource.setProperty(id, entry.getValue());
        }
      }
      if (null != response.getConfigAttributes() && response.getConfigAttributes().size() > 0) {
        Map<String, Map<String, String>> configAttributes = response.getConfigAttributes();
        for (Entry<String, Map<String, String>> configAttribute : configAttributes.entrySet()) {
          String id = PropertyHelper.getPropertyId("properties_attributes", configAttribute.getKey());
          resource.setProperty(id, configAttribute.getValue());
        }
      }
      resources.add(resource);
    }
    return resources;
  }

  /**
   * Throws an exception, as Configurations cannot be updated.
   */
  @Override
  public RequestStatus updateResources(Request request, Predicate predicate)
      throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
    throw new UnsupportedOperationException("Cannot update a Configuration resource.");
  }

  /**
   * Throws an exception, as Configurations cannot be deleted.
   */
  @Override
  public RequestStatus deleteResources(Request request, Predicate predicate) throws SystemException,
      UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
    throw new UnsupportedOperationException("Cannot delete a Configuration resource.");
  }

  @Override
  public Set<String> checkPropertyIds(Set<String> propertyIds) {
    propertyIds = super.checkPropertyIds(propertyIds);

    if (propertyIds.isEmpty()) {
      return propertyIds;
    }
    Set<String> unsupportedProperties = new HashSet<>();

    for (String propertyId : propertyIds) {

      // TODO : hack to allow for inconsistent property names
      // for example, the tag property can come here as Config/tag, /tag or tag
      if (!propertyId.equals("tag") && !propertyId.equals("type") &&
          !propertyId.equals("/tag") && !propertyId.equals("/type") &&
          !propertyId.equals("properties") && !propertyId.equals("properties_attributes")) {

        String propertyCategory = PropertyHelper.getPropertyCategory(propertyId);

        if (propertyCategory == null
            || !(propertyCategory.equals("properties") || PROPERTIES_ATTRIBUTES_PATTERN.matcher(
                propertyCategory).matches())) {
          unsupportedProperties.add(propertyId);
        }
      }
    }
    return unsupportedProperties;
  }

  // ----- AbstractResourceProvider ------------------------------------------

  @Override
  protected Set<String> getPKPropertyIds() {
    return pkPropertyIds;
  }

  // ----- utility methods ---------------------------------------------------

  /**
   * Get a configuration request object from the given map of properties.
   *
   * @param properties  the map of properties
   *
   * @return a configuration request
   */
  private ConfigurationRequest getRequest(Request request, Map<String, Object> properties) {
    String type = (String) properties.get(CONFIGURATION_CONFIG_TYPE_PROPERTY_ID);
    String tag  = (String) properties.get(CONFIGURATION_CONFIG_TAG_PROPERTY_ID);

    ConfigurationRequest configRequest = new ConfigurationRequest(
        (String) properties.get(CONFIGURATION_CLUSTER_NAME_PROPERTY_ID),
        type, tag, new HashMap<>(), new HashMap<>());

    Set<String> requestedIds = request.getPropertyIds();
    if (requestedIds.contains("properties") || requestedIds.contains("*")) {
      configRequest.setIncludeProperties(true);
    }

    return configRequest;
  }
}

redpajama_set_name: RedPajamaGithub


text:
extern "Java"
{
  namespace javax
  {
    namespace sound
    {
      namespace midi
      {
          class Instrument;
          class Patch;
          class Soundbank;
      }
    }
  }
}

class javax::sound::midi::Instrument : public ::javax::sound::midi::SoundbankResource
{

public: // actually protected
  Instrument(::javax::sound::midi::Soundbank *, ::javax::sound::midi::Patch *, ::java::lang::String *, ::java::lang::Class *);
public:
  virtual ::javax::sound::midi::Patch * getPatch();
private:
  ::javax::sound::midi::Patch * __attribute__((aligned(__alignof__( ::javax::sound::midi::SoundbankResource)))) patch;
public:
  static ::java::lang::Class class$;
};

#endif // __javax_sound_midi_Instrument__


text:
<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\UcenterMember;

/**
 * UcenterMemberSearch represents the model behind the search form about `common\models\UcenterMember`.
 */
class UcenterMemberSearch extends UcenterMember
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'status','lock', 'type','created_at', 'updated_at', 'create_channel', 'error_num', 'parent_member_id', 'vip'], 'integer'],
            [['username', 'auth_key', 'password_hash', 'password_reset_token', 'phone', 'email', 'idcard', 'real_name', 'create_ip', 'create_area', 'login_ip', 'login_area'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = UcenterMember::find()->orderBy('id DESC');

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 10,
            ],
        ]);

        $this->load($params);

        if(\App::$app->request->post()) {
            $time = \App::$app->request->post()['time'];
            if ($time) {
                $arr = explode('至', \App::$app->request->post()['time']);
                //var_dump($arr);
//            var_dump(strtotime($arr[0].' 00:00:00'));
//            var_dump(strtotime($arr[1].' 23:59:59'));
                $query->andWhere(['between', 'created_at', strtotime($arr[0] . ' 00:00:00'), strtotime($arr[1] . ' 23:59:59')]);
            }
        }
        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'status' => $this->status,
            'lock' => $this->lock,
            'type' => $this->type,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
            'create_channel' => $this->create_channel,
            'error_num' => $this->error_num,
            'parent_member_id' => $this->parent_member_id,
            'vip' => $this->vip,
        ]);

        $query->andFilterWhere(['like', 'username', $this->username])
            ->andFilterWhere(['like', 'auth_key', $this->auth_key])
            ->andFilterWhere(['like', 'password_hash', $this->password_hash])
            ->andFilterWhere(['like', 'password_reset_token', $this->password_reset_token])
            ->andFilterWhere(['like', 'phone', $this->phone])
            ->andFilterWhere(['like', 'email', $this->email])
            ->andFilterWhere(['like', 'idcard', $this->idcard])
            ->andFilterWhere(['like', 'real_name', $this->real_name])
            ->andFilterWhere(['like', 'create_ip', $this->create_ip])
            ->andFilterWhere(['like', 'create_area', $this->create_area])
            ->andFilterWhere(['like', 'login_ip', $this->login_ip])
            ->andFilterWhere(['like', 'login_area', $this->login_area]);

        return $dataProvider;
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using Inbox2.Framework;
using Inbox2.Framework.Interfaces.Enumerations;
using Inbox2.Framework.Interfaces.Plugins;
using Inbox2.Framework.VirtualMailBox.Entities;
using Inbox2.Plugins.Documents.Helpers;

namespace Inbox2.Plugins.Documents
{
	[Export(typeof(PluginPackage))]
	public class DocumentsPlugin : PluginPackage
	{
		private readonly DocumentsState state;

		public override string Name
		{
			get { return "Documents"; }
		}

		public override IStatePlugin State
		{
			get { return state; }
		}

		public override IColumnPlugin Colomn
		{
			get { return new PluginHelper(state); }
		}

		public override IEnumerable<IOverviewPlugin> Overviews
		{
			get { return new IOverviewPlugin[] { new DocumentsViewHelper(state), new ImagesViewHelper(state) }; }
		}

		public DocumentsPlugin()
		{
			state = new DocumentsState();

			EventBroker.Subscribe(AppEvents.View, delegate(Document document)
				{
					string sourceFilename = ClientState.Current.Storage.ResolvePhysicalFilename(".", document.StreamName);
					string targetFileName = document.Filename;

					int i = 0;

					while (true)
					{
						if (i > 0)
						{
							targetFileName = String.Format("{0} ({1}){2}",
								Path.GetFileNameWithoutExtension(document.Filename), i,
								Path.GetExtension(document.Filename));
						}

						if (File.Exists(Path.Combine(Path.GetTempPath(), targetFileName)))
						{
							i++;
							continue;
						}

						break;
					}

					var targetFilename = Path.Combine(Path.GetTempPath(), targetFileName);

					File.Copy(sourceFilename, targetFilename);

					new Process { StartInfo = new ProcessStartInfo(targetFilename) }.Start();
				});

			EventBroker.Subscribe(AppEvents.Save, delegate(Document document)
			{
				var dialog = new System.Windows.Forms.SaveFileDialog();
				dialog.FileName = document.Filename;
				dialog.Filter = String.Format("{0} files (*.{0})|*.{0}|All files (*.*)|*.*",
					Path.GetExtension(document.Filename));

				var result = dialog.ShowDialog();

				if (result == System.Windows.Forms.DialogResult.OK)
				{
					string filename = ClientState.Current.Storage.ResolvePhysicalFilename(".", document.StreamName);
					File.Copy(filename, dialog.FileName);
				}
			});
		}
	}
}


text:
RailsInvitable::Engine.routes.draw do

  namespace :api, defaults: { format: 'json' } do
    namespace :v1 do
      resources :user_accepted_referrals, only: [:index, :create]
      resources :referrals, only: [:show]
      resources :withdraws, only: [:create] do
        collection do
          post :succeed
        end
      end
      resources :red_pocket_records, only: [:index]
    end
  end

end


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>DTAdventure</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="./css/global.css">


text:
import webapp2, numpy
from collections import defaultdict
from google.appengine.ext import ndb

class GridConfig(ndb.Model):
    grid_config_id = ndb.IntegerProperty()
    num_server_instances = ndb.IntegerProperty()
    server_instance_type = ndb.StringProperty()
    num_servers = ndb.IntegerProperty()
    server_disk = ndb.StringProperty()
    server_version = ndb.StringProperty()
    server_latencies = ndb.FloatProperty(repeated=True)
    avg_server_latency = ndb.FloatProperty()
    max_server_latency = ndb.FloatProperty()
    client_instance_type = ndb.StringProperty()
    client_version = ndb.StringProperty()

class UploadPerf(ndb.Model):
   grid_config_id = ndb.IntegerProperty()
   trial_id = ndb.IntegerProperty()
   filetype = ndb.StringProperty()
   filesize = ndb.IntegerProperty()
   k = ndb.IntegerProperty()
   N = ndb.IntegerProperty()
   max_segsize = ndb.IntegerProperty(default=128*1024)
   #"max_segsize":default", # use no-such-key to mean default
   filecap = ndb.StringProperty()
   elapsed = ndb.FloatProperty()

class DownloadTrial(ndb.Model):
    trial_id = ndb.IntegerProperty()
    perf_test_git_hash = ndb.StringProperty()
    notes = ndb.StringProperty()
    client_tahoe_appname = ndb.StringProperty()
    client_tahoe_version = ndb.StringProperty()
    client_tahoe_branch = ndb.StringProperty()
    client_tahoe_git_hash = ndb.StringProperty()

class DownloadPerf(ndb.Model):
    grid_config_id = ndb.IntegerProperty()
    trial_id = ndb.IntegerProperty()
    filetype = ndb.StringProperty()
    filesize = ndb.IntegerProperty()
    offset = ndb.IntegerProperty()
    readsize = ndb.IntegerProperty()
    k = ndb.IntegerProperty()
    N = ndb.IntegerProperty()
    filecap = ndb.StringProperty()
    download_time = ndb.FloatProperty()

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.headers["Content-Type"] = "text/plain"
        self.response.write("Hello, World!\n")

class DownloadTrialData(webapp2.RequestHandler):
    def process(self, trial_id):
        if trial_id is None:
            q = DownloadTrial.query()
            trials = [t.trial_id
                      for t in q.fetch(projection=[DownloadTrial.trial_id])]
            return {"trials": trials}
        trial_data = DownloadTrial.query(DownloadTrial.trial_id == trial_id).get()
        if not trial_data:
            return {"error": "no DownloadTrial for trial_id=%d" % trial_id}
        perfs = [p.to_dict()
                 for p in DownloadPerf.query(DownloadPerf.trial_id == trial_id).fetch()
                 ]
        if trial_id in (1,2,3,5,6,7,8,9,10):
            by = "k"
        else:
            by = "readsize"
        return {"trial_data": trial_data.to_dict(),
                "perfs": perfs,
                "rates": self.calc_rates(by, perfs),
                }

    def calc_rates(self, by, perfs):
        series = defaultdict(list)
        rates = []
        for p in perfs:
            if by == "readsize":
                s = (p["k"], p["filesize"])
            else:
                s = p["filesize"]
            series[s].append(p)

        for key in sorted(series.keys()):
            data = series[key]
            x_data = [p[by] for p in data]
            max_x = max(x_data)
            y_data = [p["download_time"] for p in data]
            x = numpy.array(x_data)
            y = numpy.array(y_data)
            A = numpy.vstack([x, numpy.ones(len(x))]).T
            m,c = numpy.linalg.lstsq(A, y)[0]
            if by == "readsize":
                k,filesize = key
                speed = 1.0/m / 1e6 # MBps
                text = "%dMB k=%d: %.2f MBps + %.3f sec" \
                       % (int(filesize/1e6), k, speed, c)
                rates.append({"k": k,
                              "filesize": filesize,
                              "speed": speed,
                              "c": c,
                              "p0": [0,c],
                              "p1": [max_x, m*max_x+c],
                              "text": text,
                              })
            elif by == "k":
                filesize = key
                slope = m # sec/k
                text = "%dMB: %.02f sec/k + %.3f sec" \
                       % (int(filesize/1e6), slope, c)
                rates.append({"filesize": filesize,
                              "slope": slope,
                              "c": c,
                              "p0": [0,c],
                              "p1": [max_x, m*max_x+c],
                              "text": text,
                              })

            #print "time = %.2f MBps + %.3f s" % (speed, c)
        return rates

    def get(self):
        trial_id = self.request.get("trial_id", None)
        if trial_id is not None:
            trial_id = int(trial_id)
        self.response.json = self.process(trial_id)
        self.response.headers["Content-Type"] = "application/json; charset=utf-8"

class TestModel(ndb.Model):
    foo = ndb.IntegerProperty()

class Test(webapp2.RequestHandler):
    def log(self, msg):
        print msg
        self.response.write(msg+"\n")

    def do_import(self, data, klass, old_plural_names=[]):
        self.log("%s: %d old records, %d new" % (klass.__name__,
                                                 klass.query().count(),
                                                 len(data)))
        total = 0
        q = klass.query()
        if False:
            offset = 0
            while True:
                keys = q.fetch(500, keys_only=True, offset=offset)
                if not keys:
                    break
                offset += 500
                total += len(keys)
                ndb.delete_multi(keys)
        elif False:
            keys, next_cursor, more = klass.query().fetch_page(500,
                                                               keys_only=True)
            ndb.delete_multi(keys)
        else:
            #ndb.delete(klass.all(keys_only=True))
            q = klass.query()
            q.keys_only()
            ndb.delete_multi(q)

        self.log(" deleted %d records" % total)
        if not self.request.get("discard", None):
            for start in range(0, len(data), 50):
                entities = []
                for d in data[start:start+50]:
                    for name in old_plural_names:
                        names = name+"s"
                        if names in d:
                            d[name] = d[names][0]
                            del d[names]
                    for name in d:
                        if isinstance(getattr(klass,name), ndb.IntegerProperty):
                            d[name] = int(d[name])
                    e = klass(parent=ndb.Key("Parent", "?"))
                    e.populate(**d)
                    entities.append(e)
                ndb.put_multi(entities)
                entities[:] = []
            self.log(" populated %d records" % len(data))
        else:
            self.log(" discarded")
        self.log(" now have %d records" % klass.query().count())

    def get(self):
        import os, json
        self.response.headers["Content-Type"] = "text/plain"
        self.response.write(os.getcwd()+"\n")
        data = json.load(open("all-data.json", "rb"))
        self.response.write(str(data.keys())+"\n")
        self.do_import(data["GridConfig"], GridConfig,
                       ["server_version", "server_instance_type"])
        self.do_import(data["UploadPerf"], UploadPerf)
        self.do_import(data["DownloadTrial"], DownloadTrial)
        self.do_import(data["DownloadPerf"], DownloadPerf)
        self.response.write("done\n")

    def OFFget(self):
        #print "in txn", ndb.in_transaction()
        t = TestModel(foo=12)
        t.put()
        print "len(TestModel):", TestModel.query().count()
        rows = TestModel.query().fetch()
        print "len(TestModel):", len(rows)
        t1 = rows[0]
        print "row[0]:", t1, type(t1)
        print "to_dict", t1.to_dict()
        self.response.write("ok")

app = webapp2.WSGIApplication([
    ("/api", MainPage),
    ("/api/downloads", DownloadTrialData),
    #("/api/test", Test),
], debug=True)


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>no.cantara.blitz</groupId>
    <artifactId>client-basic</artifactId>
    <version>0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>Blitz Client Basic</name>
    <url>https://wiki.cantara.no/display/blitz/Basic+Blitz+Client</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <river.version>2.2.1</river.version>
    </properties>

    <parent>
        <groupId>no.cantara.emi</groupId>
        <artifactId>parent</artifactId>
        <version>3</version>
    </parent>

    <repositories>
        <!--Temporary needed for fixing Serialization error-->
        <repository>
            <id>cantara-releases</id>
            <name>Cantara Release Repository</name>
            <url>http://mvnrepo.cantara.no/content/repositories/releases/</url>
        </repository>
    </repositories>

    <dependencies>

	<!--Temporary needed for fixing Serialization error-->
        <dependency>
            <groupId>org.dancres.blitz</groupId>
            <artifactId>blitz-provided</artifactId>
            <version>2.1.7</version>
        </dependency>

        <dependency>
            <groupId>net.jini</groupId>
            <artifactId>jsk-lib</artifactId>
            <version>${river.version}</version>
        </dependency>

        <dependency>
            <groupId>net.jini</groupId>
            <artifactId>jsk-dl</artifactId>
            <version>${river.version}</version>
        </dependency>

        <dependency>
            <groupId>net.jini</groupId>
            <artifactId>jsk-platform</artifactId>
            <version>${river.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.river</groupId>
            <artifactId>reggie-dl</artifactId>
            <version>${river.version}</version>
        </dependency>

        <dependency>
            <groupId>net.jini.lookup</groupId>
            <artifactId>serviceui</artifactId>
            <version>${river.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.river</groupId>
            <artifactId>outrigger</artifactId>
            <version>${river.version}</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.2</version>
        </dependency>

        <!--Test dependencies -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
/*

  C-Interface for the AVFoundation webcam grabber.

 */
#ifndef VIDEO_CAPTURE_AV_FOUNDATION_INTERFACE_H
#define VIDEO_CAPTURE_AV_FOUNDATION_INTERFACE_H

#include <vector>
#include <camera_information.h>
#include <capability.h>
#include "av_foundation_utils.h"
#include <camera_interface.h>

void* webcam_capture_av_alloc(std::string deviceId);       /* Allocate the AVFoundation implementation. */
void webcam_capture_av_dealloc(void* cap);                 /* Deallocate the AVFoundation implementation */
int webcam_capture_av_get_devices(std::vector<webcam_capture::AVFoundationDeviceInfo>& result); /* Get available devices. */
int webcam_capture_av_get_capabilities(void* cap, std::vector<webcam_capture::AVFoundationCapability>& result); /* Get available capability formats */
int webcam_capture_av_start_capturing(void *cap, webcam_capture::PixelFormat pixelFormat,
                                      int width,
                                      int height, float fps,
                                      webcam_capture::FrameCallback cb);
int webcam_capture_av_stop_capturing(void *cap);
#endif


text:
package org.jetbrains.android.actions;

import com.android.tools.idea.ddms.adb.AdbService;
import com.intellij.execution.ExecutionManager;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Pair;
import org.jetbrains.android.run.AndroidDebugRunner;
import org.jetbrains.android.run.AndroidSessionInfo;
import org.jetbrains.android.util.AndroidBundle;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.must.android.module.extension.AndroidModuleExtension;
import org.mustbe.consulo.module.extension.ModuleExtensionHelper;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Eugene.Kudelevsky
 */
public class AndroidEnableAdbServiceAction extends ToggleAction {
  private static final String ENABLE_ADB_SERVICE_PROPERTY_NAME = "AndroidEnableDdms";

  @SuppressWarnings({"UnusedDeclaration"})
  public AndroidEnableAdbServiceAction() {
    this(null);
  }

  public AndroidEnableAdbServiceAction(@Nullable Icon icon) {
    super(AndroidBundle.message("android.enable.adb.service.action.title"),
          AndroidBundle.message("android.enable.adb.service.action.description"), icon);
  }

  @Override
  public boolean isSelected(AnActionEvent e) {
    return isAdbServiceEnabled();
  }

  public static boolean isAdbServiceEnabled() {
    String enableDdmsProperty = PropertiesComponent.getInstance().getValue(ENABLE_ADB_SERVICE_PROPERTY_NAME);
    return enableDdmsProperty == null || Boolean.parseBoolean(enableDdmsProperty);
  }

  @Override
  public void setSelected(AnActionEvent e, boolean state) {
    Project project = e.getData(CommonDataKeys.PROJECT);
    if (state) {
      setAdbServiceEnabled(project, true);
    }
    else {
      disableAdbService(project);
    }
  }

  public static boolean disableAdbService(Project project) {
    ApplicationManager.getApplication().assertIsDispatchThread();

    if (!askForClosingDebugSessions(project)) {
      return false;
    }
    setAdbServiceEnabled(project, false);
    return true;
  }

  public static void setAdbServiceEnabled(Project project, boolean state) {
    boolean oldState = isAdbServiceEnabled();
    PropertiesComponent.getInstance().setValue(ENABLE_ADB_SERVICE_PROPERTY_NAME, Boolean.toString(state));
    if (oldState != state) {
      AdbService.getInstance().restartDdmlib(project);
    }
  }

  private static boolean askForClosingDebugSessions(@NotNull Project project) {
    final List<Pair<ProcessHandler, RunContentDescriptor>> pairs = new ArrayList<Pair<ProcessHandler, RunContentDescriptor>>();

    for (Project p : ProjectManager.getInstance().getOpenProjects()) {
      final ProcessHandler[] processes = ExecutionManager.getInstance(p).getRunningProcesses();

      for (ProcessHandler process : processes) {
        if (!process.isProcessTerminated()) {
          final AndroidSessionInfo info = process.getUserData(AndroidDebugRunner.ANDROID_SESSION_INFO);
          if (info != null) {
            pairs.add(Pair.create(process, info.getDescriptor()));
          }
        }
      }
    }

    if (pairs.size() == 0) {
      return true;
    }

    final StringBuilder s = new StringBuilder();

    for (Pair<ProcessHandler, RunContentDescriptor> pair : pairs) {
      if (s.length() > 0) {
        s.append('\n');
      }
      s.append(pair.getSecond().getDisplayName());
    }

    final int r = Messages.showYesNoDialog(project, AndroidBundle.message("android.debug.sessions.will.be.closed", s),
                                           AndroidBundle.message("android.disable.adb.service.title"), Messages.getQuestionIcon());
    return r == Messages.YES;
  }

  @Override
  public void update(AnActionEvent e) {
    super.update(e);
    final Project project = e.getData(CommonDataKeys.PROJECT);
    e.getPresentation().setEnabled(project != null && ModuleExtensionHelper.getInstance(project).getModuleExtensions(AndroidModuleExtension.class).size() > 0);
  }
}


text:
#ifndef SIM_TMXR_H_
#define SIM_TMXR_H_    0

#ifdef  __cplusplus
extern "C" {
#endif

#ifndef SIMH_SERHANDLE_DEFINED
#define SIMH_SERHANDLE_DEFINED 0
typedef struct SERPORT *SERHANDLE;
#endif

#include "sim_sock.h"

#define TMXR_V_VALID    15
#define TMXR_VALID      (1 << TMXR_V_VALID)
#define TMXR_MAXBUF     256                             /* buffer size */

#define TMXR_DTR_DROP_TIME 500                          /* milliseconds to drop DTR for 'pseudo' modem control */
#define TMXR_MODEM_RING_TIME 3                          /* seconds to wait for DTR for incoming connections */
#define TMXR_DEFAULT_CONNECT_POLL_INTERVAL 1            /* seconds between connection polls */

#define TMXR_DBG_XMT    0x0010000                        /* Debug Transmit Data */
#define TMXR_DBG_RCV    0x0020000                        /* Debug Received Data */
#define TMXR_DBG_RET    0x0040000                        /* Debug Returned Received Data */
#define TMXR_DBG_MDM    0x0080000                        /* Debug Modem Signals */
#define TMXR_DBG_CON    0x0100000                        /* Debug Connection Activities */
#define TMXR_DBG_ASY    0x0200000                        /* Debug Asynchronous Activities */
#define TMXR_DBG_TRC    0x0400000                        /* Debug trace routine calls */
#define TMXR_DBG_PXMT   0x0800000                        /* Debug Transmit Packet Data */
#define TMXR_DBG_PRCV   0x1000000                        /* Debug Received Packet Data */
#define TMXR_DBG_EXP    0x2000000                        /* Debug Expect Activities */
#define TMXR_DBG_SEND   0x4000000                        /* Debug Send Activities */

/* Modem Control Bits */

#define TMXR_MDM_DTR        0x01    /* Data Terminal Ready */
#define TMXR_MDM_RTS        0x02    /* Request To Send     */
#define TMXR_MDM_DCD        0x04    /* Data Carrier Detect */
#define TMXR_MDM_RNG        0x08    /* Ring Indicator      */
#define TMXR_MDM_CTS        0x10    /* Clear To Send       */
#define TMXR_MDM_DSR        0x20    /* Data Set Ready      */
#define TMXR_MDM_INCOMING   (TMXR_MDM_DCD|TMXR_MDM_RNG|TMXR_MDM_CTS|TMXR_MDM_DSR)  /* Settable Modem Bits */
#define TMXR_MDM_OUTGOING   (TMXR_MDM_DTR|TMXR_MDM_RTS)  /* Settable Modem Bits */

/* Unit flags */

#define TMUF_V_NOASYNCH   (UNIT_V_UF + 12)              /* Asynch Disabled unit */
#define TMUF_NOASYNCH     (1u << TMUF_V_NOASYNCH)       /* This flag can be defined */
                                                        /* statically in a unit's flag field */
                                                        /* This will disable the unit from */
                                                        /* supporting asynchronmous mux behaviors */
/* Receive line speed limits */

#define TMLN_SPD_50_BPS     200000 /* usec per character */
#define TMLN_SPD_75_BPS     133333 /* usec per character */
#define TMLN_SPD_110_BPS     90909 /* usec per character */
#define TMLN_SPD_134_BPS     74626 /* usec per character */
#define TMLN_SPD_150_BPS     66666 /* usec per character */
#define TMLN_SPD_300_BPS     33333 /* usec per character */
#define TMLN_SPD_600_BPS     16666 /* usec per character */
#define TMLN_SPD_1200_BPS     8333 /* usec per character */
#define TMLN_SPD_1800_BPS     5555 /* usec per character */
#define TMLN_SPD_2000_BPS     5000 /* usec per character */
#define TMLN_SPD_2400_BPS     4166 /* usec per character */
#define TMLN_SPD_3600_BPS     2777 /* usec per character */
#define TMLN_SPD_4800_BPS     2083 /* usec per character */
#define TMLN_SPD_7200_BPS     1388 /* usec per character */
#define TMLN_SPD_9600_BPS     1041 /* usec per character */
#define TMLN_SPD_19200_BPS     520 /* usec per character */
#define TMLN_SPD_38400_BPS     260 /* usec per character */
#define TMLN_SPD_57600_BPS     173 /* usec per character */
#define TMLN_SPD_76800_BPS     130 /* usec per character */
#define TMLN_SPD_115200_BPS     86 /* usec per character */

typedef struct tmln TMLN;
typedef struct tmxr TMXR;
struct loopbuf {
    int32               bpr;                          /* xmt buf remove */
    int32               bpi;                          /* xmt buf insert */
    int32               size;
    };

struct tmln {
    int                 conn;                           /* line connected flag */
    SOCKET              sock;                           /* connection socket */
    char                *ipad;                          /* IP address */
    SOCKET              master;                         /* line specific master socket */
    char                *port;                          /* line specific listening port */
    int32               sessions;                       /* count of tcp connections received */
    uint32              cnms;                           /* conn time */
    int32               tsta;                           /* Telnet state */
    int32               rcve;                           /* rcv enable */
    int32               xmte;                           /* xmt enable */
    int32               dstb;                           /* disable Telnet binary mode */
    t_bool              notelnet;                       /* raw binary data (no telnet interpretation) */
    uint8               *telnet_sent_opts;              /* Telnet Options which we have sent a DON'T/WON'T */
    int32               rxbpr;                          /* rcv buf remove */
    int32               rxbpi;                          /* rcv buf insert */
    int32               rxbsz;                          /* rcv buffer size */
    int32               rxcnt;                          /* rcv count */
    int32               rxpcnt;                         /* rcv packet count */
    int32               txbpr;                          /* xmt buf remove */
    int32               txbpi;                          /* xmt buf insert */
    int32               txcnt;                          /* xmt count */
    int32               txpcnt;                         /* xmt packet count */
    int32               txdrp;                          /* xmt drop count */
    int32               txstall;                        /* xmt stall count */
    int32               txbsz;                          /* xmt buffer size */
    int32               txbfd;                          /* xmt buffered flag */
    t_bool              modem_control;                  /* line supports modem control behaviors */
    t_bool              port_speed_control;             /* line programmatically sets port speed */
    int32               modembits;                      /* modem bits which are currently set */
    FILE                *txlog;                         /* xmt log file */
    FILEREF             *txlogref;                      /* xmt log file reference */
    char                *txlogname;                     /* xmt log file name */
    char                *rxb;                           /* rcv buffer */
    char                *rbr;                           /* rcv break */
    char                *txb;                           /* xmt buffer */
    uint8               *rxpb;                          /* rcv packet buffer */
    uint32              rxpbsize;                       /* rcv packet buffer size */
    uint32              rxpboffset;                     /* rcv packet buffer offset */
    uint32              rxbps;                          /* rcv bps speed (0 - unlimited) */
    double              rxbpsfactor;                    /* receive speed factor (scaled to usecs) */
#define TMXR_RX_BPS_UNIT_SCALE 1000000.0
    uint32              rxdelta;                        /* rcv inter character min time (usecs) */
    double              rxnexttime;                     /* min time for next receive character */
    uint32              txbps;                          /* xmt bps speed (0 - unlimited) */
    uint32              txdelta;                        /* xmt inter character min time (usecs) */
    double              txnexttime;                     /* min time for next transmit character */
    uint8               *txpb;                          /* xmt packet buffer */
    uint32              txpbsize;                       /* xmt packet buffer size */
    uint32              txppsize;                       /* xmt packet packet size */
    uint32              txppoffset;                     /* xmt packet buffer offset */
    TMXR                *mp;                            /* back pointer to mux */
    char                *serconfig;                     /* line config */
    SERHANDLE           serport;                        /* serial port handle */
    t_bool              ser_connect_pending;            /* serial connection notice pending */
    SOCKET              connecting;                     /* Outgoing socket while connecting */
    char                *destination;                   /* Outgoing destination address:port */
    t_bool              loopback;                       /* Line in loopback mode */
    t_bool              halfduplex;                     /* Line in half-duplex mode */
    t_bool              datagram;                       /* Line is datagram packet oriented */
    t_bool              packet;                         /* Line is packet oriented */
    int32               lpbpr;                          /* loopback buf remove */
    int32               lpbpi;                          /* loopback buf insert */
    int32               lpbcnt;                         /* loopback buf used count */
    int32               lpbsz;                          /* loopback buffer size */
    char                *lpb;                           /* loopback buffer */
    UNIT                *uptr;                          /* input polling unit (default to mp->uptr) */
    UNIT                *o_uptr;                        /* output polling unit (default to lp->uptr)*/
    DEVICE              *dptr;                          /* line specific device */
    EXPECT              expect;                         /* Expect rules */
    SEND                send;                           /* Send input state */
    };

struct tmxr {
    int32               lines;                          /* # lines */
    char                *port;                          /* listening port */
    SOCKET              master;                         /* master socket */
    TMLN                *ldsc;                          /* line descriptors */
    int32               *lnorder;                       /* line connection order */
    DEVICE              *dptr;                          /* multiplexer device */
    UNIT                *uptr;                          /* polling unit (connection) */
    char                logfiletmpl[FILENAME_MAX];      /* template logfile name */
    int32               txcount;                        /* count of transmit bytes */
    int32               buffered;                       /* Buffered Line Behavior and Buffer Size Flag */
    int32               sessions;                       /* count of tcp connections received */
    uint32              poll_interval;                  /* frequency of connection polls (seconds) */
    uint32              last_poll_time;                 /* time of last connection poll */
    uint32              ring_start_time;                /* time ring signal was raised */
    char                *ring_ipad;                     /* incoming connection address awaiting DTR */
    SOCKET              ring_sock;                      /* incoming connection socket awaiting DTR */
    t_bool              notelnet;                       /* default telnet capability for incoming connections */
    t_bool              modem_control;                  /* multiplexer supports modem control behaviors */
    t_bool              port_speed_control;             /* multiplexer programmatically sets port speed */
    t_bool              packet;                         /* Lines are packet oriented */
    t_bool              datagram;                       /* Lines use datagram packet transport */
    };

int32 tmxr_poll_conn (TMXR *mp);
t_stat tmxr_reset_ln (TMLN *lp);
t_stat tmxr_detach_ln (TMLN *lp);
int32 tmxr_input_pending_ln (TMLN *lp);
int32 tmxr_getc_ln (TMLN *lp);
t_stat tmxr_get_packet_ln (TMLN *lp, const uint8 **pbuf, size_t *psize);
t_stat tmxr_get_packet_ln_ex (TMLN *lp, const uint8 **pbuf, size_t *psize, uint8 frame_byte);
void tmxr_poll_rx (TMXR *mp);
t_stat tmxr_putc_ln (TMLN *lp, int32 chr);
t_stat tmxr_put_packet_ln (TMLN *lp, const uint8 *buf, size_t size);
t_stat tmxr_put_packet_ln_ex (TMLN *lp, const uint8 *buf, size_t size, uint8 frame_byte);
void tmxr_poll_tx (TMXR *mp);
int32 tmxr_send_buffered_data (TMLN *lp);
t_stat tmxr_open_master (TMXR *mp, CONST char *cptr);
t_stat tmxr_close_master (TMXR *mp);
t_stat tmxr_connection_poll_interval (TMXR *mp, uint32 seconds);
t_stat tmxr_attach_ex (TMXR *mp, UNIT *uptr, CONST char *cptr, t_bool async);
t_stat tmxr_detach (TMXR *mp, UNIT *uptr);
t_stat tmxr_attach_help(FILE *st, DEVICE *dptr, UNIT *uptr, int32 flag, const char *cptr);
char *tmxr_line_attach_string(TMLN *lp);
t_stat tmxr_set_modem_control_passthru (TMXR *mp);
t_stat tmxr_clear_modem_control_passthru (TMXR *mp);
t_stat tmxr_set_port_speed_control (TMXR *mp);
t_stat tmxr_clear_port_speed_control (TMXR *mp);
t_stat tmxr_set_line_port_speed_control (TMXR *mp, int line);
t_stat tmxr_clear_line_port_speed_control (TMXR *mp, int line);
t_stat tmxr_set_get_modem_bits (TMLN *lp, int32 bits_to_set, int32 bits_to_clear, int32 *incoming_bits);
t_stat tmxr_set_line_loopback (TMLN *lp, t_bool enable_loopback);
t_bool tmxr_get_line_loopback (TMLN *lp);
t_stat tmxr_set_line_halfduplex (TMLN *lp, t_bool enable_loopback);
t_bool tmxr_get_line_halfduplex (TMLN *lp);
t_stat tmxr_set_line_speed (TMLN *lp, CONST char *speed);
t_stat tmxr_set_config_line (TMLN *lp, CONST char *config);
t_stat tmxr_set_line_unit (TMXR *mp, int line, UNIT *uptr_poll);
t_stat tmxr_set_line_output_unit (TMXR *mp, int line, UNIT *uptr_poll);
t_stat tmxr_set_console_units (UNIT *rxuptr, UNIT *txuptr);
t_stat tmxr_ex (t_value *vptr, t_addr addr, UNIT *uptr, int32 sw);
t_stat tmxr_dep (t_value val, t_addr addr, UNIT *uptr, int32 sw);
void tmxr_msg (SOCKET sock, const char *msg);
void tmxr_linemsg (TMLN *lp, const char *msg);
void tmxr_linemsgf (TMLN *lp, const char *fmt, ...);
void tmxr_linemsgvf (TMLN *lp, const char *fmt, va_list args);
void tmxr_fconns (FILE *st, const TMLN *lp, int32 ln);
void tmxr_fstats (FILE *st, const TMLN *lp, int32 ln);
t_stat tmxr_set_log (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat tmxr_set_nolog (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat tmxr_show_log (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat tmxr_dscln (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
int32 tmxr_rqln (const TMLN *lp);
int32 tmxr_tqln (const TMLN *lp);
int32 tmxr_tpqln (const TMLN *lp);
t_bool tmxr_tpbusyln (const TMLN *lp);
t_stat tmxr_set_lnorder (UNIT *uptr, int32 val, CONST char *cptr, void *desc);
t_stat tmxr_show_lnorder (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat tmxr_show_summ (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat tmxr_show_cstat (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat tmxr_show_lines (FILE *st, UNIT *uptr, int32 val, CONST void *desc);
t_stat tmxr_show_open_devices (FILE* st, DEVICE *dptr, UNIT* uptr, int32 val, CONST char* desc);
t_stat tmxr_activate (UNIT *uptr, int32 interval);
t_stat tmxr_activate_abs (UNIT *uptr, int32 interval);
t_stat tmxr_activate_after (UNIT *uptr, uint32 usecs_walltime);
t_stat tmxr_activate_after_abs (UNIT *uptr, uint32 usecs_walltime);
t_stat tmxr_clock_coschedule (UNIT *uptr, int32 interval);
t_stat tmxr_clock_coschedule_abs (UNIT *uptr, int32 interval);
t_stat tmxr_clock_coschedule_tmr (UNIT *uptr, int32 tmr, int32 ticks);
t_stat tmxr_clock_coschedule_tmr_abs (UNIT *uptr, int32 tmr, int32 ticks);
t_stat tmxr_change_async (void);
t_stat tmxr_locate_line_send (const char *dev_line, SEND **snd);
t_stat tmxr_locate_line_expect (const char *dev_line, EXPECT **exp);
const char *tmxr_send_line_name (const SEND *snd);
const char *tmxr_expect_line_name (const EXPECT *exp);
t_stat tmxr_startup (void);
t_stat tmxr_shutdown (void);
t_stat tmxr_start_poll (void);
t_stat tmxr_stop_poll (void);
void _tmxr_debug (uint32 dbits, TMLN *lp, const char *msg, char *buf, int bufsize);
#define tmxr_debug(dbits, lp, msg, buf, bufsize) do {if (sim_deb && (lp)->mp && (lp)->mp->dptr && ((dbits) & (lp)->mp->dptr->dctrl)) _tmxr_debug (dbits, lp, msg, buf, bufsize); } while (0)
#define tmxr_debug_msg(dbits, lp, msg) do {if (sim_deb && (lp)->mp && (lp)->mp->dptr && ((dbits) & (lp)->mp->dptr->dctrl)) sim_debug (dbits, (lp)->mp->dptr, "%s", msg); } while (0)
#define tmxr_debug_return(lp, val) do {if (sim_deb && (val) && (lp)->mp && (lp)->mp->dptr && (TMXR_DBG_RET & (lp)->mp->dptr->dctrl)) { if ((lp)->rxbps) sim_debug (TMXR_DBG_RET, (lp)->mp->dptr, "Ln%d: 0x%x - Next after: %.0f\n", (int)((lp)-(lp)->mp->ldsc), val, (lp)->rxnexttime); else sim_debug (TMXR_DBG_RET, (lp)->mp->dptr, "Ln%d: 0x%x\n", (int)((lp)-(lp)->mp->ldsc), val); } } while (0)
#define tmxr_debug_trace(mp, msg) do {if (sim_deb && (mp)->dptr && (TMXR_DBG_TRC & (mp)->dptr->dctrl)) sim_debug (TMXR_DBG_TRC, mp->dptr, "%s\n", (msg)); } while (0)
#define tmxr_debug_trace_line(lp, msg) do {if (sim_deb && (lp)->mp && (lp)->mp->dptr && (TMXR_DBG_TRC & (lp)->mp->dptr->dctrl)) sim_debug (TMXR_DBG_TRC, (lp)->mp->dptr, "Ln%d:%s\n", (int)((lp)-(lp)->mp->ldsc), (msg)); } while (0)
#define tmxr_debug_connect(mp, msg) do {if (sim_deb && (mp)->dptr && (TMXR_DBG_CON & (mp)->dptr->dctrl)) sim_debug (TMXR_DBG_CON, mp->dptr, "%s\n", (msg)); } while (0)
#define tmxr_debug_connect_line(lp, msg) do {if (sim_deb && (lp)->mp && (lp)->mp->dptr && (TMXR_DBG_CON & (lp)->mp->dptr->dctrl)) sim_debug (TMXR_DBG_CON, (lp)->mp->dptr, "Ln%d:%s\n", (int)((lp)-(lp)->mp->ldsc), (msg)); } while (0)

#if defined(SIM_ASYNCH_MUX) && !defined(SIM_ASYNCH_IO)
#undef SIM_ASYNCH_MUX
#endif /* defined(SIM_ASYNCH_MUX) && !defined(SIM_ASYNCH_IO) */

#if defined(SIM_ASYNCH_MUX)
#define tmxr_attach(mp, uptr, cptr) tmxr_attach_ex(mp, uptr, cptr, TRUE)
#else
#define tmxr_attach(mp, uptr, cptr) tmxr_attach_ex(mp, uptr, cptr, FALSE)
#endif
#if (!defined(NOT_MUX_USING_CODE))
#define sim_activate tmxr_activate
#define sim_activate_abs tmxr_activate_abs
#define sim_activate_after tmxr_activate_after
#define sim_activate_after_abs tmxr_activate_after_abs
#define sim_clock_coschedule tmxr_clock_coschedule
#define sim_clock_coschedule_abs tmxr_clock_coschedule_abs
#define sim_clock_coschedule_tmr tmxr_clock_coschedule_tmr
#define sim_clock_coschedule_tmr_abs tmxr_clock_coschedule_tmr_abs
#endif

#ifdef  __cplusplus
}
#endif

#endif /* _SIM_TMXR_H_ */


text:
<?php

namespace app\models;

use Yii;
use \yii\db\ActiveRecord;
use yii\web\UploadedFile;

/**
 * This is the model class for table "book".
 *
 * @property integer $id
 * @property string $name
 * @property integer $date_create
 * @property integer $date_update
 * @property integer $date_release
 * @property integer $author_id
 * @property string $preview
 *
 * @property Author $author
 */
class Book extends ActiveRecord
{
    /**
     * @var UploadedFile
     */
    public $imageFile;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'book';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'author_id'], 'required'],
            [['date_create', 'date_update', 'author_id'], 'integer'],
            [['name'], 'string', 'max' => 161],
            [['preview'], 'string', 'max' => 255],
            [['date_release'], 'safe'],
//            [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'date_create' => 'Date Create',
            'date_update' => 'Date Update',
            'date_release' => 'Date Release',
            'author_id' => 'Author ID',
            'preview' => 'Preview',
        ];
    }

    public function behaviors()
    {
        return [
            'timestamp' => [
                'class' => 'yii\behaviors\TimestampBehavior',
                'createdAtAttribute' => 'date_create',
                'updatedAtAttribute' => 'date_update',
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['date_create', 'date_update'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['date_update'],
                ],
            ],
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAuthor()
    {
        return $this->hasOne(Author::className(), ['id' => 'author_id']);
    }

    public function beforeValidate()
    {
        if (parent::beforeValidate()) {
            $this->date_release = \Yii::$app->formatter->asDate($this->date_release, 'php:U');
            $this->imageFile = UploadedFile::getInstance($this, 'imageFile');
            if ($this->imageFile) {
                $name = md5(microtime());
                $this->imageFile->saveAs(\Yii::getAlias('@webroot') . '/uploads/' . $name . '.' . $this->imageFile->extension);
                $this->preview = $name . '.' . $this->imageFile->extension;
            }
            return true;
        } else {
            return false;
        }
    }

    public function getImageurl()
    {
        return \Yii::getAlias('@webroot') . '/uploads/' . $this->preview;
    }

    public function getAuthorName()
    {
        $author = $this->getAuthor()->one();
        return $author->first_name . ' ' . $author->last_name;
    }
}


text:
app.controller('ProductController', ['$scope', function($scope) {

	console.log('This is user controller');

}]);


text:
TESTSIZE=$1
DIR=ext/PracRand

$DIR/RNG_test stdin8 -tlmin $TESTSIZE -tlmax $TESTSIZE


text:
#define LOG_LEVEL CONFIG_IVSHMEM_LOG_LEVEL
#include <logging/log.h>
LOG_MODULE_REGISTER(ivshmem);

#include <errno.h>

#include <kernel.h>
#include <arch/cpu.h>

#include <soc.h>
#include <device.h>
#include <init.h>

#include <drivers/virtualization/ivshmem.h>
#include "virt_ivshmem.h"

#ifdef CONFIG_IVSHMEM_DOORBELL

static void ivshmem_doorbell(const void *arg)
{
	const struct ivshmem_param *param = arg;

	LOG_DBG("Interrupt received on vector %u", param->vector);

	if (param->signal != NULL) {
		k_poll_signal_raise(param->signal, param->vector);
	}
}

static bool ivshmem_configure_interrupts(const struct device *dev)
{
	struct ivshmem *data = dev->data;
	bool ret = false;
	uint8_t n_vectors;
	uint32_t key;
	int i;

	key = irq_lock();

	n_vectors = pcie_msi_vectors_allocate(data->bdf,
					      CONFIG_IVSHMEM_INT_PRIORITY,
					      data->vectors,
					      CONFIG_IVSHMEM_MSI_X_VECTORS);
	if (n_vectors == 0) {
		LOG_ERR("Could not allocate %u MSI-X vectors",
			CONFIG_IVSHMEM_MSI_X_VECTORS);
		goto out;
	}

	LOG_DBG("Allocated %u vectors", n_vectors);

	for (i = 0; i < n_vectors; i++) {
		data->params[i].dev = dev;
		data->params[i].vector = i;

		if (!pcie_msi_vector_connect(data->bdf,
					     &data->vectors[i],
					     ivshmem_doorbell,
					     &data->params[i], 0)) {
			LOG_ERR("Failed to connect MSI-X vector %u", i);
			goto out;
		}
	}

	LOG_DBG("%u MSI-X Vectors connected", n_vectors);

	if (!pcie_msi_enable(data->bdf, data->vectors, n_vectors)) {
		LOG_ERR("Could not enable MSI-X");
		goto out;
	}

	data->n_vectors = n_vectors;
	ret = true;

	LOG_DBG("MSI-X configured");
out:
	irq_unlock(key);

	return ret;
}

static void register_signal(const struct device *dev,
			    struct k_poll_signal *signal,
			    uint16_t vector)
{
	struct ivshmem *data = dev->data;

	data->params[vector].signal = signal;
}

#else

static const struct ivshmem_reg no_reg;

#define ivshmem_configure_interrupts(...) true
#define register_signal(...)

#endif /* CONFIG_IVSHMEM_DOORBELL */

static bool ivshmem_configure(const struct device *dev)
{
	struct ivshmem *data = dev->data;
	struct pcie_mbar mbar_regs, mbar_mem;

	if (!pcie_get_mbar(data->bdf, IVSHMEM_PCIE_REG_BAR_IDX, &mbar_regs)) {
#ifdef CONFIG_IVSHMEM_DOORBELL
		LOG_ERR("ivshmem regs bar not found");
		return false;
#else
		LOG_DBG("ivshmem regs bar not found");
		device_map(DEVICE_MMIO_RAM_PTR(dev), (uintptr_t)&no_reg,
			   sizeof(struct ivshmem_reg), K_MEM_CACHE_NONE);
#endif /* CONFIG_IVSHMEM_DOORBELL */
	} else {
		pcie_set_cmd(data->bdf, PCIE_CONF_CMDSTAT_MEM, true);

		device_map(DEVICE_MMIO_RAM_PTR(dev), mbar_regs.phys_addr,
			   mbar_regs.size, K_MEM_CACHE_NONE);
	}

	if (!pcie_get_mbar(data->bdf, IVSHMEM_PCIE_SHMEM_BAR_IDX, &mbar_mem)) {
		LOG_ERR("ivshmem mem bar not found");
		return false;
	}

	data->size = mbar_mem.size;

	z_phys_map((uint8_t **)&data->shmem,
		   mbar_mem.phys_addr, data->size,
		   K_MEM_CACHE_WB | K_MEM_PERM_RW | K_MEM_PERM_USER);

	LOG_DBG("ivshmem configured:");
	LOG_DBG("- Registers at 0x%lx (mapped to 0x%lx)",
		mbar_regs.phys_addr, DEVICE_MMIO_GET(dev));
	LOG_DBG("- Shared memory of %lu bytes at 0x%lx (mapped to 0x%lx)",
		data->size, mbar_mem.phys_addr, data->shmem);

	return ivshmem_configure_interrupts(dev);
}

static size_t ivshmem_api_get_mem(const struct device *dev,
				  uintptr_t *memmap)
{
	struct ivshmem *data = dev->data;

	*memmap = data->shmem;

	return data->size;
}

static uint32_t ivshmem_api_get_id(const struct device *dev)
{
	struct ivshmem_reg *regs = (struct ivshmem_reg *)DEVICE_MMIO_GET(dev);

	return regs->iv_position;
}

static uint16_t ivshmem_api_get_vectors(const struct device *dev)
{
#if CONFIG_IVSHMEM_DOORBELL
	struct ivshmem *data = dev->data;

	return data->n_vectors;
#else
	return 0;
#endif
}

static int ivshmem_api_int_peer(const struct device *dev,
				uint32_t peer_id, uint16_t vector)
{
#if CONFIG_IVSHMEM_DOORBELL
	struct ivshmem_reg *regs = (struct ivshmem_reg *)DEVICE_MMIO_GET(dev);
	struct ivshmem *data = dev->data;
	uint32_t doorbell;

	if (vector >= data->n_vectors) {
		return -EINVAL;
	}

	doorbell = IVSHMEM_GEN_DOORBELL(peer_id, vector);
	regs->doorbell = doorbell;

	return 0;
#else
	return -ENOSYS;
#endif
}

static int ivshmem_api_register_handler(const struct device *dev,
					struct k_poll_signal *signal,
					uint16_t vector)
{
#if CONFIG_IVSHMEM_DOORBELL
	struct ivshmem *data = dev->data;

	if (vector >= data->n_vectors) {
		return -EINVAL;
	}

	register_signal(dev, signal, vector);

	return 0;
#else
	return -ENOSYS;
#endif
}

static const struct ivshmem_driver_api ivshmem_api = {
	.get_mem = ivshmem_api_get_mem,
	.get_id = ivshmem_api_get_id,
	.get_vectors = ivshmem_api_get_vectors,
	.int_peer = ivshmem_api_int_peer,
	.register_handler = ivshmem_api_register_handler
};

static int ivshmem_init(const struct device *dev)
{
	struct ivshmem *data = dev->data;

	data->bdf = pcie_bdf_lookup(PCIE_ID(IVSHMEM_VENDOR_ID,
					    IVSHMEM_DEVICE_ID));
	if (data->bdf == PCIE_BDF_NONE) {
		LOG_WRN("ivshmem device not found");
		return -ENOTSUP;
	}

	LOG_DBG("ivshmem found at bdf 0x%x", data->bdf);

	if (!ivshmem_configure(dev)) {
		return -EIO;
	}

	return 0;
}

static struct ivshmem ivshmem_data;

DEVICE_DEFINE(ivshmem, CONFIG_IVSHMEM_DEV_NAME,
	      ivshmem_init, device_pm_control_nop, &ivshmem_data, NULL,
	      POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &ivshmem_api);


text:
.. _fatiando_gravmag_transform:

Potential field transformations (``fatiando.gravmag.transform``)
============================================================================

.. automodule:: fatiando.gravmag.transform
   :members:
   :show-inheritance:


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Entolomatoid fungi of the Western United States and Alaska (Eureka) 262 (1994)

#### Original name
Nolanea proxima f. inodorata Largent

### Remarks
null


text:
from flask import render_template

from . import main_blueprint

@main_blueprint.app_errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404


text:
require 'vk/api/objects'
require 'vk/schema/namespace'

module Vk
  module API
    class Newsfeed < Vk::Schema::Namespace
      # @see https://github.com/VKCOM/vk-api-schema/blob/master/objects.json
      class ItemFriend < Vk::Schema::Object
        # @return [Object] @see https://github.com/VKCOM/vk-api-schema/blob/master/objects.json
        attribute :friends, API::Types::Coercible::Hash.optional.default(nil)
      end
    end
  end
end


text:
namespace SnagitJiraOutputAccessory.Commands
{
    using System.Windows.Forms;
    using SnagitJiraOutputAccessory.Models;
    using SnagitJiraOutputAccessory.ViewModels;
    using SnagitJiraOutputAccessory.Views;
    using SNAGITLib;

    public class ConfigureSettingsCommand : ICommand
    {
        private readonly ISnagIt _snagit;
        private OutputPreferencesRepository _outputPreferencesRepo;

        public ConfigureSettingsCommand(ISnagIt snagit, OutputPreferencesRepository outputPreferencesRepo)
        {
            _snagit = snagit;
            _outputPreferencesRepo = outputPreferencesRepo;
        }

        public void Execute()
        {
            OutputOptionsView view = new OutputOptionsView();
            var windowHelper = new System.Windows.Interop.WindowInteropHelper(view);
            windowHelper.Owner = (System.IntPtr)(_snagit.TopLevelHWnd);
            view.DataContext = new OutputOptionsViewModel(_outputPreferencesRepo);
            view.ShowDialog();
        }
    }
}


text:
using System;
using System.Collections.Generic;

namespace DDDHandsOn.Core
{
    public static class EnumerableExtensions
    {
        public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
        {
            foreach (var current in source)
                action(current);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Mime;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Cocoa
{
    static class Cocoa
    {
        public static void Version()
        {
            Console.WriteLine(
                @"Cocoa v" +
                Assembly.GetExecutingAssembly().GetName().Version.ToString());

            using (var choco = new ChocolateyHost())
            {
                choco.Exec();
            }
        }

        public static void Help()
        {
            using (var sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("Cocoa.Help.txt")))
            {
                Console.WriteLine(sr.ReadToEnd());
            }
        }

        public static void Install(IEnumerable<string> packages)
        {
            var sb = new StringBuilder();
            sb.Append(@"install");
            packages.ToList().ForEach(x => sb.Append(@" " + x));

            using (var choco = new ChocolateyHost())
            {
                choco.ExecInteractive(sb.ToString());
            }
        }

        public static void Uninstall(IEnumerable<string> packages)
        {
            var sb = new StringBuilder();
            sb.Append(@"uninstall");
            packages.ToList().ForEach(x => sb.Append(@" " + x));

            using (var choco = new ChocolateyHost())
            {
                choco.ExecInteractive(sb.ToString());
            }
        }

        public static void Upgrade(IEnumerable<string> packages)
        {
            var sb = new StringBuilder();
            sb.Append(@"upgrade");
            packages.ToList().ForEach(x => sb.Append(@" " + x));

            using (var choco = new ChocolateyHost())
            {
                choco.ExecInteractive(sb.ToString());
            }
        }

        public static void ShowPackagesList(IEnumerable<string> packages, bool isLocalPackages = false)
        {
            var sb = new StringBuilder();
            sb.Append(@"list");
            packages.ToList().ForEach(x => sb.Append(@" " + x));
            if (isLocalPackages)
            {
                sb.Append(@" --localonly");
            }

            using (var choco = new ChocolateyHost())
            {
                choco.ExecInteractive(sb.ToString());
            }
        }

        public static void ShowNonApprovedPackagesList(IEnumerable<string> packages)
        {
            var count = 0;
            packages.ToList().ForEach(x =>
            {
                var packageInfo = Crawler.GetPackageInfos(x);
                if (packageInfo != null && packageInfo.Count() != 0)
                {
                    Console.WriteLine(packageInfo.ToList()[0].ToString());
                    count++;
                }
            });

            Console.WriteLine(count + @" packages found.");
        }

        public static async Task InstallNonApprovedPackages(IEnumerable<string> packages)
        {
            var tempDir = Path.Combine(Path.GetTempPath(), @"cocoa");
            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }

            var availablePackages = new List<string>();
            var args = new List<string>();

            foreach(var package in packages)
            {
                if (package.StartsWith(@"-"))
                {
                    args.Add(package);
                    continue;
                }

                var packageInfos = Crawler.GetPackageInfos(package);
                if (packageInfos == null || !packageInfos.Any())
                {
                    Console.WriteLine(@"'" + package + @"' was not found.");
                    continue;
                }

                availablePackages.Add(package);

                var packageInfo = packageInfos.ToList()[0];
                string fileName;
                string filePath;
                using (var hc = new HttpClient())
                {
                    var res = hc.GetAsync(packageInfo.DownloadUri, HttpCompletionOption.ResponseHeadersRead).Result;
                    fileName = Path.GetFileName(res.RequestMessage.RequestUri.ToString());
                    filePath = Path.Combine(tempDir, fileName);

                    using (var fs = File.Create(filePath))
                    {
                        using (var s = res.Content.ReadAsStreamAsync().Result)
                        {
                            s.CopyTo(fs);
                            fs.Flush();
                        }
                    }
                }
            }

            if (availablePackages.Count != 0)
            {
                var sb = new StringBuilder();
                sb.Append(@"install");
                availablePackages.ForEach(x => sb.Append(@" " + x));
                args.ForEach(x => sb.Append(@" " + x));
                sb.Append(@" -source " + tempDir);

                using (var choco = new ChocolateyHost())
                {
                    choco.ExecInteractive(sb.ToString());
                }
            }
        }
    }
}


text:
package org.jetbrains.jps.backwardRefs.index;

import com.intellij.openapi.util.io.DataInputOutputUtilRt;
import com.intellij.util.indexing.DataIndexer;
import com.intellij.util.indexing.IndexExtension;
import com.intellij.util.indexing.IndexId;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.DataInputOutputUtil;
import com.intellij.util.io.KeyDescriptor;
import com.intellij.util.io.VoidDataExternalizer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.backwardRefs.LightRef;
import org.jetbrains.jps.backwardRefs.LightRefDescriptor;
import org.jetbrains.jps.backwardRefs.SignatureData;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public class CompilerIndices {
  //TODO manage version separately
  public final static int VERSION = 6;

  public final static IndexId<LightRef, Integer> BACK_USAGES = IndexId.create("back.refs");
  public final static IndexId<LightRef, Collection<LightRef>> BACK_HIERARCHY = IndexId.create("back.hierarchy");
  public final static IndexId<LightRef, Void> BACK_CLASS_DEF = IndexId.create("back.class.def");
  public final static IndexId<SignatureData, Collection<LightRef>> BACK_MEMBER_SIGN = IndexId.create("back.member.sign");
  public final static IndexId<LightRef, Collection<LightRef>> BACK_CAST = IndexId.create("back.cast");

  public static List<IndexExtension<?, ?, CompiledFileData>> getIndices() {
    return Arrays.asList(createBackwardClassDefinitionExtension(),
                         createBackwardUsagesExtension(),
                         createBackwardHierarchyExtension(),
                         createBackwardSignatureExtension(),
                         createBackwardCastExtension());
  }

  private static IndexExtension<LightRef, Collection<LightRef>, CompiledFileData> createBackwardCastExtension() {
    return new IndexExtension<LightRef, Collection<LightRef>, CompiledFileData>() {
      @NotNull
      @Override
      public IndexId<LightRef, Collection<LightRef>> getName() {
        return BACK_CAST;
      }

      @NotNull
      @Override
      public DataIndexer<LightRef, Collection<LightRef>, CompiledFileData> getIndexer() {
        return CompiledFileData::getCasts;
      }

      @NotNull
      @Override
      public KeyDescriptor<LightRef> getKeyDescriptor() {
        return LightRefDescriptor.INSTANCE;
      }

      @NotNull
      @Override
      public DataExternalizer<Collection<LightRef>> getValueExternalizer() {
        return createLightRefSeqExternalizer();
      }

      @Override
      public int getVersion() {
        return VERSION;
      }
    };
  }

  private static IndexExtension<LightRef, Integer, CompiledFileData> createBackwardUsagesExtension() {
    return new IndexExtension<LightRef, Integer, CompiledFileData>() {
      @Override
      public int getVersion() {
        return VERSION;
      }

      @NotNull
      public IndexId<LightRef, Integer> getName() {
        return BACK_USAGES;
      }

      @NotNull
      public DataIndexer<LightRef, Integer, CompiledFileData> getIndexer() {
        return CompiledFileData::getReferences;
      }

      @NotNull
      public KeyDescriptor<LightRef> getKeyDescriptor() {
        return LightRefDescriptor.INSTANCE;
      }

      @NotNull
      public DataExternalizer<Integer> getValueExternalizer() {
        return new UnsignedByteExternalizer();
      }
    };
  }

  private static class UnsignedByteExternalizer implements DataExternalizer<Integer> {
    @Override
    public void save(@NotNull DataOutput out, Integer value) throws IOException {
      int v = value;
      if (v > 255) {
        v = 255;
      }
      out.writeByte(v);
    }

    @Override
    public Integer read(@NotNull DataInput in) throws IOException {
      return in.readByte() & 0xFF;
    }
  }

  private static IndexExtension<LightRef, Collection<LightRef>, CompiledFileData> createBackwardHierarchyExtension() {
    return new IndexExtension<LightRef, Collection<LightRef>, CompiledFileData>() {
      @Override
      public int getVersion() {
        return VERSION;
      }

      @NotNull
      public IndexId<LightRef, Collection<LightRef>> getName() {
        return BACK_HIERARCHY;
      }

      @NotNull
      public DataIndexer<LightRef, Collection<LightRef>, CompiledFileData> getIndexer() {
        return CompiledFileData::getBackwardHierarchy;
      }

      @NotNull
      public KeyDescriptor<LightRef> getKeyDescriptor() {
        return LightRefDescriptor.INSTANCE;
      }

      @NotNull
      public DataExternalizer<Collection<LightRef>> getValueExternalizer() {
        return createLightRefSeqExternalizer();
      }
    };
  }

  private static IndexExtension<LightRef, Void, CompiledFileData> createBackwardClassDefinitionExtension() {
    return new IndexExtension<LightRef, Void, CompiledFileData>() {
      @Override
      public int getVersion() {
        return VERSION;
      }

      @NotNull
      public IndexId<LightRef, Void> getName() {
        return BACK_CLASS_DEF;
      }

      @NotNull
      public DataIndexer<LightRef, Void, CompiledFileData> getIndexer() {
        return CompiledFileData::getDefinitions;
      }

      @NotNull
      public KeyDescriptor<LightRef> getKeyDescriptor() {
        return LightRefDescriptor.INSTANCE;
      }

      @NotNull
      public DataExternalizer<Void> getValueExternalizer() {
        return VoidDataExternalizer.INSTANCE;
      }
    };
  }

  private static IndexExtension<SignatureData, Collection<LightRef>, CompiledFileData> createBackwardSignatureExtension() {
    return new IndexExtension<SignatureData, Collection<LightRef>, CompiledFileData>() {
      @NotNull
      @Override
      public IndexId<SignatureData, Collection<LightRef>> getName() {
        return BACK_MEMBER_SIGN;
      }

      @NotNull
      @Override
      public DataIndexer<SignatureData, Collection<LightRef>, CompiledFileData> getIndexer() {
        return CompiledFileData::getSignatureData;
      }

      @NotNull
      @Override
      public KeyDescriptor<SignatureData> getKeyDescriptor() {
        return createSignatureDataDescriptor();
      }

      @NotNull
      @Override
      public DataExternalizer<Collection<LightRef>> getValueExternalizer() {
        return createLightRefSeqExternalizer();
      }

      @Override
      public int getVersion() {
        return VERSION;
      }
    };
  }

  @NotNull
  private static DataExternalizer<Collection<LightRef>> createLightRefSeqExternalizer() {
    return new DataExternalizer<Collection<LightRef>>() {
      @Override
      public void save(@NotNull final DataOutput out, Collection<LightRef> value) throws IOException {
        DataInputOutputUtilRt.writeSeq(out, value, lightRef -> LightRefDescriptor.INSTANCE.save(out, lightRef));
      }

      @Override
      public Collection<LightRef> read(@NotNull final DataInput in) throws IOException {
        return DataInputOutputUtilRt.readSeq(in, () -> LightRefDescriptor.INSTANCE.read(in));
      }
    };
  }

  private static KeyDescriptor<SignatureData> createSignatureDataDescriptor() {
    return new KeyDescriptor<SignatureData>() {
      @Override
      public int getHashCode(SignatureData value) {
        return value.hashCode();
      }

      @Override
      public boolean isEqual(SignatureData val1, SignatureData val2) {
        return val1.equals(val2);
      }

      @Override
      public void save(@NotNull DataOutput out, SignatureData value) throws IOException {
        DataInputOutputUtil.writeINT(out, value.getRawReturnType());
        out.writeByte(value.getIteratorKind());
        out.writeBoolean(value.isStatic());
      }

      @Override
      public SignatureData read(@NotNull DataInput in) throws IOException {
        return new SignatureData(DataInputOutputUtil.readINT(in), in.readByte(), in.readBoolean());
      }
    };
  }
}


text:
IMPLEMENT_CLIENTCLASS_DT(C_SDK_PlayerResource, DT_SDKPlayerResource, CSDKPlayerResource)
#if defined ( SDK_USE_PLAYERCLASSES )
	RecvPropArray3( RECVINFO_ARRAY(m_iPlayerClass), RecvPropInt( RECVINFO(m_iPlayerClass[0]))),
#endif
END_RECV_TABLE()

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
C_SDK_PlayerResource::C_SDK_PlayerResource()
{
#if defined ( SDK_USE_TEAMS )
	m_Colors[SDK_TEAM_BLUE] = COLOR_BLUE;
	m_Colors[SDK_TEAM_RED] = COLOR_RED;
#endif

	m_Colors[TEAM_UNASSIGNED] = COLOR_YELLOW;
	m_Colors[TEAM_SPECTATOR] = COLOR_GREY;
}

//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
C_SDK_PlayerResource::~C_SDK_PlayerResource()
{
}

#if defined ( SDK_USE_PLAYERCLASSES )
int C_SDK_PlayerResource::GetPlayerClass( int iIndex )
{
	if ( !IsConnected( iIndex ) )
		return PLAYERCLASS_UNDEFINED;

	return m_iPlayerClass[iIndex];
}

#endif // SDK_USE_PLAYERCLASSES

C_SDK_PlayerResource * SDKGameResources( void )
{
	return dynamic_cast<C_SDK_PlayerResource *>(GameResources());
}


text:
A set of common configuration files I use under macOS for things like customizing
the shell, ruby, node, git, etc.

## Usage

  1. create `.env` file (`cp .env.example .env`) and fill in secrets
  2. run `./install.sh`

## Terminal Prompt

  * git status (if dir is a repo)
  * current ruby & node versions (if any)
  * current aws profile & region (if any)
  * duration of last command
  * zsh autcompletion & suggestions
  * zsh syntax highlighting
  * iTerm CPU/MEM/NET usage
  * summon on any display or virtual desktop with cmd + ~

### Examples

#### Hotkey

![Terminal Prompt - Hotkey](./examples/prompt-01-hotkey.gif)

#### Suggestions

![Terminal Prompt - Suggestions](./examples/prompt-02-suggestions.gif)

#### Syntax highlighting and errors

![Terminal Prompt - Syntax and Errors](./examples/prompt-03-syntax.gif)


text:
@interface CCMeViewController : UIViewController

@end


text:
set -e

################################################################################

SCRIPTDIR="$( cd -P "$( dirname "$0" )" && pwd )"
SCRIPTNAME=$( echo $0 | sed 's#.*/##g' )

################################################################################

version="v84"

EMAIL=""
PASSWORD=""

################################################################################

function usage() {
	echo "This script creates the cosmic data sources for the Funcotator GATK tool."
	echo "It will download the raw data files from the COSMIC SFTP repository and "
	echo "create 3 folders in the current working directory, one for each data"
	echo "source:"
	echo "    cosmic"
	echo "    cosmic_tissue"
	echo "    cosmic_fusion"
	echo "Note: This script requires an account with COSMIC and will prompt the "
	echo "      user to input these credentials in order to download the raw data."
}

################################################################################

function createConfigFile() {

    dataSourceName=$1
    version=$2
    srcFile=$3
    originLocation=$4
    preprocessors=$5
    type=$6
    key=$7
    col=$8
    delim=$9

    echo "name = ${dataSourceName}"
    echo "version = ${version}"
    echo "src_file = ${srcFile}"
    echo "origin_location = ${originLocation}"
    echo "preprocessing_script = ${preprocessors}"
    echo ""
    echo "# Supported types:"
    echo "# simpleXSV    -- Arbitrary separated value table (e.g. CSV), keyed off Gene Name OR Transcript ID"
    echo "# locatableXSV -- Arbitrary separated value table (e.g. CSV), keyed off a genome location"
    echo "# gencode      -- Custom datasource class for GENCODE"
    echo "# cosmic       -- Custom datasource class for COSMIC"
    echo "type = ${type}"
    echo ""
    echo "# Required field for GENCODE files."
    echo "# Path to the FASTA file from which to load the sequences for GENCODE transcripts:"
    echo "gencode_fasta_path ="
    echo ""
    echo "# Required field for simpleXSV files."
    echo "# Valid values:"
    echo "#     GENE_NAME"
    echo "#     TRANSCRIPT_ID"
    echo "xsv_key = ${key}"
    echo ""
    echo "# Required field for simpleXSV files."
    echo "# The 0-based index of the column containing the key on which to match"
    echo "xsv_key_column = ${col}"
    echo ""
    echo "# Required field for simpleXSV AND locatableXSV files."
    echo "# The delimiter by which to split the XSV file into columns."
    echo "xsv_delimiter = ${delim}"
    echo ""
    echo "# Required field for simpleXSV files."
    echo "# Whether to permissively match the number of columns in the header and data rows"
    echo "# Valid values:"
    echo "#     true"
    echo "#     false"
    echo "xsv_permissive_cols = ${PERMISSIVE_COLS}"
    echo ""
    echo "# Required field for locatableXSV files."
    echo "# The 0-based index of the column containing the contig for each row"
    echo "contig_column ="
    echo ""
    echo "# Required field for locatableXSV files."
    echo "# The 0-based index of the column containing the start position for each row"
    echo "start_column ="
    echo ""
    echo "# Required field for locatableXSV files."
    echo "# The 0-based index of the column containing the end position for each row"
    echo "end_column ="
    echo ""

}

################################################################################

if [[ $# -gt 0 ]] ; then
	usage
	exit 0
fi

################################################################################

echo "This script creates the cosmic data sources for the Funcotator GATK tool."
echo ""
echo "For usage information run with the '-h' option"
echo ""
echo "To retrieve the COSMIC data sources you must have a COSMIC account."
echo "Please enter your COSMIC account credentials:"

while [[ ${#EMAIL} -eq 0 ]] ; do
    echo -n "Enter your email address: "
    read EMAIL
done

while [[ ${#PASSWORD} -eq 0 ]] ; do
    echo -n "Enter your password: "
    read -s PASSWORD
done
echo

################################################################################
# Setup the Directory:

echo "Creating folders: ..."

mkdir -vp cosmic/hg19 cosmic/hg38 cosmic_fusion/hg19 cosmic_fusion/hg38 cosmic_tissue/hg19 cosmic_tissue/hg38

################################################################################
# Get the data files:

echo "Getting files ... "
lftp --norc -u "${EMAIL}","${PASSWORD}" sftp://sftp-cancer.sanger.ac.uk <<EOF

get cosmic/grch37/cosmic/${version}/CosmicCompleteTargetedScreensMutantExport.tsv.gz -o cosmic/hg19/CosmicCompleteTargetedScreensMutantExport.tsv.gz
get cosmic/grch37/cosmic/${version}/CosmicFusionExport.tsv.gz -o cosmic_fusion/hg19/CosmicFusionExport.tsv.gz
get cosmic/grch38/cosmic/${version}/CosmicCompleteTargetedScreensMutantExport.tsv.gz -o cosmic/hg38/CosmicCompleteTargetedScreensMutantExport.tsv.gz
get cosmic/grch38/cosmic/${version}/CosmicFusionExport.tsv.gz -o cosmic_fusion/hg38/CosmicFusionExport.tsv.gz
bye

EOF

echo "Retrieved COSMIC version ${version} on $(date) from sftp-cancer.sanger.ac.uk by: ${SCRIPTNAME}:" >  cosmic/metadata.txt
echo "User: ${EMAIL}" >> cosmic/metadata.txt
echo "    cosmic/grch37/cosmic/${version}/CosmicCompleteTargetedScreensMutantExport.tsv.gz" >> cosmic/metadata.txt
echo "    cosmic/grch38/cosmic/${version}/CosmicCompleteTargetedScreensMutantExport.tsv.gz" >> cosmic/metadata.txt
echo "" >> cosmic/metadata.txt

echo "Retrieved COSMIC version ${version} on $(date) from sftp-cancer.sanger.ac.uk by: ${SCRIPTNAME}:" >  cosmic_fusion/metadata.txt
echo "User: ${EMAIL}" >> cosmic_fusion/metadata.txt
echo "    cosmic/grch37/cosmic/${version}/CosmicFusionExport.tsv.gz" >> cosmic_fusion/metadata.txt
echo "    cosmic/grch38/cosmic/${version}/CosmicFusionExport.tsv.gz" >> cosmic_fusion/metadata.txt
echo "" >> cosmic_fusion/metadata.txt

echo "Retrieved COSMIC version ${version} on $(date) from sftp-cancer.sanger.ac.uk by: ${SCRIPTNAME}:" >  cosmic_tissue/metadata.txt
echo "User: ${EMAIL}" >> cosmic_tissue/metadata.txt
echo "    cosmic/grch37/cosmic/${version}/CosmicCompleteTargetedScreensMutantExport.tsv.gz" >> cosmic_tissue/metadata.txt
echo "    cosmic/grch38/cosmic/${version}/CosmicCompleteTargetedScreensMutantExport.tsv.gz" >> cosmic_tissue/metadata.txt
echo "" >> cosmic_tissue/metadata.txt

################################################################################
# Unzip the files, process into usable files for funcotator, and create
# config files for these data sources:

for d in "hg19" "hg38" ; do

    echo "Unzipping data for ${d} ..."

    gunzip cosmic/${d}/CosmicCompleteTargetedScreensMutantExport.tsv.gz
    gunzip cosmic_fusion/${d}/CosmicFusionExport.tsv.gz

    echo "Processing data source for Cosmic ${d} ..."
    ${SCRIPTDIR}/createSqliteCosmicDb.sh cosmic/${d}/CosmicCompleteTargetedScreensMutantExport.tsv cosmic/${d}/Cosmic.db

    echo "Processing data source for Cosmic Fusion ${d} ..."
    ${SCRIPTDIR}/createCosmicFusionGeneTsv.py cosmic_fusion/${d}/CosmicFusionExport.tsv cosmic_fusion/${d}/cosmic_fusion.tsv

    echo "Processing data source for Cosmic Tissue ${d} ..."
    ${SCRIPTDIR}/createCosmicGeneTsv.py cosmic/${d}/CosmicCompleteTargetedScreensMutantExport.tsv cosmic_tissue/${d}/cosmic_tissue.tsv

    ref="grch37"
    if [[ "${d}" == "hg38" ]] ; then
        ref="grch38"
    fi

    echo "Creating config file for Cosmic Fusion ${d} ..."
    PERMISSIVE_COLS="true"
    createConfigFile \
        "CosmicFusion" \
        "${version}" \
        "cosmic_fusion.tsv" \
        "sftp://sftp-cancer.sanger.ac.uk/cosmic/${ref}/cosmic/${version}/CosmicFusionExport.tsv.gz" \
        "${SCRIPTNAME}, createCosmicFusionGeneTsv.py" \
        "simpleXSV" \
        "GENE_NAME" \
        "0" \
        '\t' > cosmic_fusion/${d}/cosmic_fusion.config

    echo "Creating config file for Cosmic Tissue ${d} ..."
    PERMISSIVE_COLS="true"
    createConfigFile \
        "CosmicTissue" \
        "${version}" \
        "cosmic_tissue.tsv" \
        "sftp://sftp-cancer.sanger.ac.uk/cosmic/${ref}/cosmic/${version}/CosmicCompleteTargetedScreensMutantExport.tsv.gz" \
        "${SCRIPTNAME}, createCosmicGeneTsv.py" \
        "simpleXSV" \
        "GENE_NAME" \
        "0" \
        '\t' > cosmic_tissue/${d}/cosmic_tissue.config

    echo "Creating config file for Cosmic ${d} ..."
    PERMISSIVE_COLS=""
    createConfigFile \
        "Cosmic" \
        "${version}" \
        "Cosmic.db" \
        "sftp://sftp-cancer.sanger.ac.uk/cosmic/${ref}/cosmic/${version}/CosmicCompleteTargetedScreensMutantExport.tsv.gz" \
        "${SCRIPTNAME}, createSqliteCosmicDb.sh" \
        "cosmic" \
        "" \
        "" \
        ''  > cosmic/${d}/cosmic.config

    echo "Cleaning up raw files ..."
    rm -v cosmic/${d}/CosmicCompleteTargetedScreensMutantExport.tsv
    rm -v cosmic_fusion/${d}/CosmicFusionExport.tsv
done

echo "DONE."


text:
package org.apache.mahout.clustering.meanshift;

public interface MeanShiftCanopyConfigKeys {

	// keys used by Driver, Mapper, Combiner & Reducer
	String DISTANCE_MEASURE_KEY = "org.apache.mahout.clustering.canopy.measure";
	String KERNEL_PROFILE_KEY = "org.apache.mahout.clustering.canopy.kernelprofile";
	String T1_KEY = "org.apache.mahout.clustering.canopy.t1";
	String T2_KEY = "org.apache.mahout.clustering.canopy.t2";
	String CONTROL_PATH_KEY = "org.apache.mahout.clustering.control.path";
	String CLUSTER_CONVERGENCE_KEY = "org.apache.mahout.clustering.canopy.convergence";
	String CLUSTER_POINTS_KEY = "org.apache.mahout.clustering.meanshift.clusterPointsKey";

}


text:
import unittest
from copy import deepcopy
from unittest.mock import Mock, patch
from datetime import timezone, timedelta, datetime, date
from ..reply.Reply import Reply
from ..reply import ReplyCRUD
from ..scheduler import Scheduler

class TestReply(unittest.TestCase):
    def test_replyObjectCreatesCorrectly(self):
        d = datetime.now(tz = timezone(timedelta(hours=5, minutes=30)))
        replyToTest = Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292)
        self.assertEqual(replyToTest.userId, 1)
        self.assertEqual(replyToTest.message, "@example an example message")
        self.assertEqual(replyToTest.scheduledTime, d)
        self.assertEqual(replyToTest.timeZone, timezone(timedelta(hours=5, minutes=30)))
        self.assertEqual(replyToTest.tweetId, 134953292)
        self.assertEqual(replyToTest.replyId, None)
        self.assertEqual(replyToTest.sentStatus, "unsent")
        replyToTest = Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292, sentStatus = "sent", replyId = 1)
        self.assertEqual(replyToTest.sentStatus, "sent")
        self.assertEqual(replyToTest.replyId, 1)

class TestReplyCRUD(unittest.TestCase):
    @patch.object(Scheduler, 'scheduleReply')
    def test_replyObjectSavesCorrectly(self, scheduleReplyPatch):
        d = datetime.now(tz = timezone(timedelta(hours=5, minutes=30))) + timedelta(minutes=20)
        replyToSave = Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292)
        mockReplyDataStrategy = Mock()
        mockReplyDataStrategyAttrs = {"saveReply.return_value": 1}
        mockReplyDataStrategy.configure_mock(**mockReplyDataStrategyAttrs)
        self.assertEqual(ReplyCRUD.saveReply(replyToSave, mockReplyDataStrategy), {"result": "success", "value": 1})
        scheduleReplyPatch.assert_called_once_with(1, d)

    def test_replyObjectCannotBeSavedIfTimeIsBeforeCurrentTime(self):
        d = datetime.now(tz = timezone(timedelta(hours=5, minutes=30))) - timedelta(minutes=40)
        replyToSave = Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292)
        mockReplyDataStrategy = Mock()
        self.assertEqual(ReplyCRUD.saveReply(replyToSave, mockReplyDataStrategy), {"result": "error", "value": "Scheduled time cannot be earlier than current time"})

    def test_replyCanBeRetrievedById(self):
        d = datetime.now(tz = timezone(timedelta(hours=5, minutes=30))) + timedelta(minutes=20)
        replyToRetrieve = Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId = 1)
        mockReplyDataStrategy = Mock()
        mockReplyDataStrategyAttrs = {"getReplyByReplyId.return_value": replyToRetrieve}
        mockReplyDataStrategy.configure_mock(**mockReplyDataStrategyAttrs)
        self.assertEqual(ReplyCRUD.getReplyByReplyId(1, mockReplyDataStrategy), replyToRetrieve)
        self.assertTrue(mockReplyDataStrategy.getReplyByReplyId.called)

    @patch.object(Scheduler, 'updateReply')
    def test_replyCanBeUpdatedCorrectly(self, updateReplyPatch):
        d = datetime.now(tz = timezone(timedelta(hours=5, minutes=30))) + timedelta(minutes=20)
        replyToUpdate = Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId = 1)
        newVersionOfReply = deepcopy(replyToUpdate)
        mockReplyDataStrategy = Mock()
        mockReplyDataStrategyAttrs = {"getReplyByReplyId.return_value": newVersionOfReply,
                "updateReply.return_value": True}
        mockReplyDataStrategy.configure_mock(**mockReplyDataStrategyAttrs)
        replyToUpdate.message = "@example an updated message"
        self.assertEqual(ReplyCRUD.updateReply(replyToUpdate, mockReplyDataStrategy), {"result": "success"})
        updateReplyPatch.assert_called_once_with(1, d)

        newVersionOfReply.sentStatus = "sent"
        self.assertEqual(ReplyCRUD.updateReply(replyToUpdate, mockReplyDataStrategy), {"result": "error", "value": "Reply has already been sent"})

    @patch.object(Scheduler, 'removeReply')
    def test_repliesCanBeCancelled(self, removeReplyPatch):
        d = datetime.now(tz = timezone(timedelta(hours=5, minutes=30))) + timedelta(minutes=20)
        replyToUpdate = Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId = 1)
        newVersionOfReply = deepcopy(replyToUpdate)
        mockReplyDataStrategy = Mock()
        mockReplyDataStrategyAttrs = {"getReplyByReplyId.return_value": newVersionOfReply,
                "cancelReply.return_value": True,
                }
        mockReplyDataStrategy.configure_mock(**mockReplyDataStrategyAttrs)
        self.assertEqual(ReplyCRUD.cancelReply(replyToUpdate, mockReplyDataStrategy), {"result": "success"})
        self.assertEqual(replyToUpdate.sentStatus, "cancelled")
        removeReplyPatch.assert_called_once_with(1)

    def test_repliesCanBeRetrievedByUserId(self):
        d = datetime.now(tz = timezone(timedelta(hours=5, minutes=30))) + timedelta(minutes=20)
        replies = [
                Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId = 1),
                Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId = 2)
                ]
        mockReplyDataStrategy = Mock()
        mockReplyDataStrategyAttrs = {"getRepliesByUserId.return_value": replies}
        mockReplyDataStrategy.configure_mock(**mockReplyDataStrategyAttrs)
        self.assertEqual(ReplyCRUD.getRepliesByUserId(1, mockReplyDataStrategy), replies)

    def test_repliesCanBeRetrievedByUserIdAndStatus(self):
        d = datetime.now(tz = timezone(timedelta(hours=5, minutes=30))) + timedelta(minutes=20)
        replies = [
                Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId = 1),
                Reply(1, "@example an example message", d, timezone(timedelta(hours=5, minutes=30)), 134953292, replyId = 2)
                ]
        mockReplyDataStrategy = Mock()
        mockReplyDataStrategyAttrs = {"getRepliesByUserIdAndStatus.return_value": replies}
        mockReplyDataStrategy.configure_mock(**mockReplyDataStrategyAttrs)
        self.assertEqual(ReplyCRUD.getRepliesByUserIdAndStatus(1, "unsent", mockReplyDataStrategy), replies)

if __name__ == "__main__":
    unittest.main()


text:
title: The OctoSnowCat
date: '2015-01-05T12:43:08.000Z'
author: Ionică Bizău
tags:
  - GitHub
  - Octocat
---
It's a snowy weather here... And I had a lot of fun by building a 3D octocat of snow: actually an *OctoSnowCat*. Yeps, here is the result:

![The OctoSnowCat](/images/posts/19/1.jpg)

The GitHubbers will understand. If you didn't get it, watch the following video with the 3D octocat figurine:

...and [buy it](https://github.myshopify.com/products/5-inch-octocat-figurine), if you like it and have enough money.

I chose to build it from source.